]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
Win32 BackupRead/Write, begin adding Base, Jmsg knows about console, autochanger...
[bacula/bacula] / bacula / src / dird / backup.c
1 /*
2  *
3  *   Bacula Director -- backup.c -- responsible for doing backup jobs
4  *
5  *     Kern Sibbald, March MM
6  *
7  *  Basic tasks done here:
8  *     Open DB and create records for this job.
9  *     Open Message Channel with Storage daemon to tell him a job will be starting.
10  *     Open connection with File daemon and pass him commands
11  *       to do the backup.
12  *     When the File daemon finishes the job, update the DB.
13  *
14  *   Version $Id$
15  */
16
17 /*
18    Copyright (C) 2000-2003 Kern Sibbald and John Walker
19
20    This program is free software; you can redistribute it and/or
21    modify it under the terms of the GNU General Public License as
22    published by the Free Software Foundation; either version 2 of
23    the License, or (at your option) any later version.
24
25    This program is distributed in the hope that it will be useful,
26    but WITHOUT ANY WARRANTY; without even the implied warranty of
27    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28    General Public License for more details.
29
30    You should have received a copy of the GNU General Public
31    License along with this program; if not, write to the Free
32    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
33    MA 02111-1307, USA.
34
35  */
36
37 #include "bacula.h"
38 #include "dird.h"
39 #include "ua.h"
40
41 /* Commands sent to File daemon */
42 static char backupcmd[] = "backup\n";
43 static char storaddr[]  = "storage address=%s port=%d ssl=%d\n";
44 static char levelcmd[]  = "level = %s%s\n";
45
46 /* Responses received from File daemon */
47 static char OKbackup[]  = "2000 OK backup\n";
48 static char OKstore[]   = "2000 OK storage\n";
49 static char OKlevel[]   = "2000 OK level\n";
50 static char EndBackup[] = "2801 End Backup Job TermCode=%d JobFiles=%u ReadBytes=%" lld " JobBytes=%" lld "\n";
51
52
53 /* Forward referenced functions */
54 static void backup_cleanup(JCR *jcr, int TermCode, char *since);
55 static int wait_for_job_termination(JCR *jcr);               
56
57 /* External functions */
58
59 /* 
60  * Do a backup of the specified FileSet
61  *    
62  *  Returns:  0 on failure
63  *            1 on success
64  */
65 int do_backup(JCR *jcr) 
66 {
67    char since[MAXSTRING];
68    int stat;
69    BSOCK   *fd;
70    POOL_DBR pr;
71    FILESET_DBR fsr;
72
73    since[0] = 0;
74
75    if (!get_or_create_client_record(jcr)) {
76       Jmsg(jcr, M_ERROR, 0, _("Could not get/create Client record. ERR=%s\n"), 
77          db_strerror(jcr->db));
78       goto bail_out;
79    }
80
81    /*
82     * Get or Create FileSet record
83     */
84    memset(&fsr, 0, sizeof(fsr));
85    strcpy(fsr.FileSet, jcr->fileset->hdr.name);
86    if (jcr->fileset->have_MD5) {
87       struct MD5Context md5c;
88       unsigned char signature[16];
89       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
90       MD5Final(signature, &md5c);
91       bin_to_base64(fsr.MD5, (char *)signature, 16); /* encode 16 bytes */
92       strcpy(jcr->fileset->MD5, fsr.MD5);
93    } else {
94       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
95    }
96    if (!db_create_fileset_record(jcr, jcr->db, &fsr)) {
97       Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet record. ERR=%s\n"), 
98          db_strerror(jcr->db));
99       goto bail_out;
100    }   
101    jcr->jr.FileSetId = fsr.FileSetId;
102    Dmsg2(119, "Created FileSet %s record %d\n", jcr->fileset->hdr.name, 
103       jcr->jr.FileSetId);
104
105    /* Look up the last
106     * FULL backup job to get the time/date for a 
107     * differential or incremental save.
108     */
109    jcr->stime = get_pool_memory(PM_MESSAGE);
110    jcr->stime[0] = 0;
111    since[0] = 0;
112    switch (jcr->JobLevel) {
113       case L_DIFFERENTIAL:
114       case L_INCREMENTAL:
115          /* Look up start time of last job */
116          jcr->jr.JobId = 0;
117          if (!db_find_job_start_time(jcr, jcr->db, &jcr->jr, &jcr->stime)) {
118             Jmsg(jcr, M_INFO, 0, _("Last FULL backup time not found. Doing FULL backup.\n"));
119             jcr->JobLevel = jcr->jr.Level = L_FULL;
120          } else {
121             strcpy(since, ", since=");
122             bstrncat(since, jcr->stime, sizeof(since));
123          }
124          Dmsg1(115, "Last start time = %s\n", jcr->stime);
125          break;
126    }
127
128    jcr->jr.JobId = jcr->JobId;
129    jcr->jr.StartTime = jcr->start_time;
130    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
131       Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
132       goto bail_out;
133    }
134
135    jcr->fname = (char *) get_pool_memory(PM_FNAME);
136
137    /* Print Job Start message */
138    Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %d, Job=%s\n"),
139         jcr->JobId, jcr->Job);
140
141    /* 
142     * Get the Pool record  
143     */
144    memset(&pr, 0, sizeof(pr));
145    strcpy(pr.Name, jcr->pool->hdr.name);
146    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
147       /* Try to create the pool */
148       if (create_pool(jcr, jcr->db, jcr->pool, 1) < 0) {
149          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name, 
150             db_strerror(jcr->db));
151          goto bail_out;
152       } else {
153          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
154       }
155    }
156    jcr->PoolId = pr.PoolId;               /****FIXME**** this can go away */
157    jcr->jr.PoolId = pr.PoolId;
158
159    /*
160     * Open a message channel connection with the Storage
161     * daemon. This is to let him know that our client
162     * will be contacting him for a backup  session.
163     *
164     */
165    Dmsg0(110, "Open connection with storage daemon\n");
166    set_jcr_job_status(jcr, JS_WaitSD);
167    /*
168     * Start conversation with Storage daemon  
169     */
170    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
171       goto bail_out;
172    }
173    /*
174     * Now start a job with the Storage daemon
175     */
176    if (!start_storage_daemon_job(jcr)) {
177       goto bail_out;
178    }
179    /*
180     * Now start a Storage daemon message thread
181     */
182    if (!start_storage_daemon_message_thread(jcr)) {
183       goto bail_out;
184    }
185    Dmsg0(150, "Storage daemon connection OK\n");
186
187    set_jcr_job_status(jcr, JS_WaitFD);
188    if (!connect_to_file_daemon(jcr, 10, FDConnectTimeout, 1)) {
189       goto bail_out;
190    }
191
192    set_jcr_job_status(jcr, JS_Running);
193    fd = jcr->file_bsock;
194
195    if (!send_include_list(jcr)) {
196       goto bail_out;
197    }
198
199    if (!send_exclude_list(jcr)) {
200       goto bail_out;
201    }
202
203    /* 
204     * send Storage daemon address to the File daemon
205     */
206    if (jcr->store->SDDport == 0) {
207       jcr->store->SDDport = jcr->store->SDport;
208    }
209    bnet_fsend(fd, storaddr, jcr->store->address, jcr->store->SDDport,
210               jcr->store->enable_ssl);
211    if (!response(fd, OKstore, "Storage", 1)) {
212       goto bail_out;
213    }
214
215    /* 
216     * Send Level command to File daemon
217     */
218    switch (jcr->JobLevel) {
219       case L_BASE:
220          bnet_fsend(fd, levelcmd, "base", " ");
221          break;
222       case L_FULL:
223          bnet_fsend(fd, levelcmd, "full", " ");
224          break;
225       case L_DIFFERENTIAL:
226       case L_INCREMENTAL:
227          bnet_fsend(fd, levelcmd, "since ", jcr->stime);
228          free_pool_memory(jcr->stime);
229          jcr->stime = NULL;
230          break;
231       case L_SINCE:
232       default:
233          Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"), 
234             jcr->JobLevel, jcr->JobLevel);
235          goto bail_out;
236    }
237    Dmsg1(120, ">filed: %s", fd->msg);
238    if (!response(fd, OKlevel, "Level", 1)) {
239       goto bail_out;
240    }
241
242    /* Send backup command */
243    bnet_fsend(fd, backupcmd);
244    if (!response(fd, OKbackup, "backup", 1)) {
245       goto bail_out;
246    }
247
248    /* Pickup Job termination data */        
249    stat = wait_for_job_termination(jcr);
250    backup_cleanup(jcr, stat, since);
251    return 1;
252
253 bail_out:
254    if (jcr->stime) {
255       free_pool_memory(jcr->stime);
256       jcr->stime = NULL;
257    }
258    backup_cleanup(jcr, JS_ErrorTerminated, since);
259    return 0;
260
261 }
262
263 /*
264  * Here we wait for the File daemon to signal termination,
265  *   then we wait for the Storage daemon.  When both
266  *   are done, we return the job status.
267  */
268 static int wait_for_job_termination(JCR *jcr)
269 {
270    int32_t n = 0;
271    BSOCK *fd = jcr->file_bsock;
272    int fd_ok = FALSE;
273
274    set_jcr_job_status(jcr, JS_Running);
275    /* Wait for Client to terminate */
276    while ((n = bget_dirmsg(fd)) >= 0) {
277       if (sscanf(fd->msg, EndBackup, &jcr->FDJobStatus, &jcr->JobFiles,
278           &jcr->ReadBytes, &jcr->JobBytes) == 4) {
279          fd_ok = TRUE;
280          set_jcr_job_status(jcr, jcr->FDJobStatus);
281          Dmsg1(100, "FDStatus=%c\n", (char)jcr->JobStatus);
282       }
283       if (job_canceled(jcr)) {
284          break;
285       }
286    }
287    if (is_bnet_error(fd)) {
288       Jmsg(jcr, M_FATAL, 0, _("<filed: network error during BACKUP command. ERR=%s\n"),
289           bnet_strerror(fd));
290    }
291    bnet_sig(fd, BNET_TERMINATE);   /* tell Client we are terminating */
292
293    wait_for_storage_daemon_termination(jcr);
294
295    /* Return the first error status we find FD or SD */
296    if (fd_ok && jcr->JobStatus != JS_Terminated) {
297       return jcr->JobStatus;
298    }
299    if (!fd_ok || is_bnet_error(fd)) {                          
300       return JS_ErrorTerminated;
301    }
302    return jcr->SDJobStatus;
303 }
304
305 /*
306  * Release resources allocated during backup.
307  */
308 static void backup_cleanup(JCR *jcr, int TermCode, char *since)
309 {
310    char sdt[50], edt[50];
311    char ec1[30], ec2[30], ec3[30], compress[50];
312    char term_code[100], fd_term_msg[100], sd_term_msg[100];
313    char *term_msg;
314    int msg_type;
315    MEDIA_DBR mr;
316    double kbps, compression;
317    utime_t RunTime;
318
319    Dmsg0(100, "Enter backup_cleanup()\n");
320    memset(&mr, 0, sizeof(mr));
321    set_jcr_job_status(jcr, TermCode);
322
323    update_job_end_record(jcr);        /* update database */
324    
325    if (!db_get_job_record(jcr, jcr->db, &jcr->jr)) {
326       Jmsg(jcr, M_WARNING, 0, _("Error getting job record for stats: %s"), 
327          db_strerror(jcr->db));
328       set_jcr_job_status(jcr, JS_ErrorTerminated);
329    }
330
331    strcpy(mr.VolumeName, jcr->VolumeName);
332    if (!db_get_media_record(jcr, jcr->db, &mr)) {
333       Jmsg(jcr, M_WARNING, 0, _("Error getting Media record for Volume \"%s\": ERR=%s"), 
334          mr.VolumeName, db_strerror(jcr->db));
335       set_jcr_job_status(jcr, JS_ErrorTerminated);
336    }
337
338    /* Now update the bootstrap file if any */
339    if (jcr->JobStatus == JS_Terminated && jcr->job->WriteBootstrap) {
340       FILE *fd;
341       BPIPE *bpipe = NULL;
342       int got_pipe = 0;
343       char *fname = jcr->job->WriteBootstrap;
344       VOL_PARAMS *VolParams = NULL;
345       int VolCount;
346
347       if (*fname == '|') {
348          fname++;
349          got_pipe = 1;
350          bpipe = open_bpipe(fname, 0, "w");
351          fd = bpipe ? bpipe->wfd : NULL;
352       } else {
353          /* ***FIXME*** handle BASE */
354          fd = fopen(fname, jcr->JobLevel==L_FULL?"w+":"a+");
355       }
356       if (fd) {
357          VolCount = db_get_job_volume_parameters(jcr, jcr->db, jcr->JobId,
358                     &VolParams);
359          if (VolCount == 0) {
360             Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters. ERR=%s\n"),
361                  db_strerror(jcr->db));
362          }
363          for (int i=0; i < VolCount; i++) {
364             /* Write the record */
365             fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
366             fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
367             fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
368             fprintf(fd, "VolFile=%u-%u\n", VolParams[i].StartFile,
369                          VolParams[i].EndFile);
370             fprintf(fd, "VolBlock=%u-%u\n", VolParams[i].StartBlock,
371                          VolParams[i].EndBlock);
372             fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
373                          VolParams[i].LastIndex);
374          }
375          if (VolParams) {
376             free(VolParams);
377          }
378          if (got_pipe) {
379             close_bpipe(bpipe);
380          } else {
381             fclose(fd);
382          }
383       } else {
384          Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
385               "%s: ERR=%s\n"), fname, strerror(errno));
386          set_jcr_job_status(jcr, JS_ErrorTerminated);
387       }
388    }
389
390    msg_type = M_INFO;                 /* by default INFO message */
391    switch (jcr->JobStatus) {
392       case JS_Terminated:
393          term_msg = _("Backup OK");
394          break;
395       case JS_FatalError:
396       case JS_ErrorTerminated:
397          term_msg = _("*** Backup Error ***"); 
398          msg_type = M_ERROR;          /* Generate error message */
399          if (jcr->store_bsock) {
400             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
401             pthread_cancel(jcr->SD_msg_chan);
402          }
403          break;
404       case JS_Canceled:
405          term_msg = _("Backup Canceled");
406          if (jcr->store_bsock) {
407             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
408             pthread_cancel(jcr->SD_msg_chan);
409          }
410          break;
411       default:
412          term_msg = term_code;
413          sprintf(term_code, _("Inappropriate term code: %c\n"), jcr->JobStatus);
414          break;
415    }
416    bstrftime(sdt, sizeof(sdt), jcr->jr.StartTime);
417    bstrftime(edt, sizeof(edt), jcr->jr.EndTime);
418    RunTime = jcr->jr.EndTime - jcr->jr.StartTime;
419    if (RunTime <= 0) {
420       kbps = 0;
421    } else {
422       kbps = (double)jcr->jr.JobBytes / (1000 * RunTime);
423    }
424    if (!db_get_job_volume_names(jcr, jcr->db, jcr->jr.JobId, &jcr->VolumeName)) {
425       /*
426        * Note, if the job has erred, most likely it did not write any
427        *  tape, so suppress this "error" message since in that case
428        *  it is normal.  Or look at it the other way, only for a
429        *  normal exit should we complain about this error.
430        */
431       if (jcr->JobStatus == JS_Terminated) {                                
432          Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
433       }
434       jcr->VolumeName[0] = 0;         /* none */
435    }
436
437    if (jcr->ReadBytes == 0) {
438       strcpy(compress, "None");
439    } else {
440       compression = (double)100 - 100.0 * ((double)jcr->JobBytes / (double)jcr->ReadBytes);
441       if (compression < 0.5) {
442          strcpy(compress, "None");
443       } else {
444          sprintf(compress, "%.1f %%", (float)compression);
445       }
446    }
447    jobstatus_to_ascii(jcr->FDJobStatus, fd_term_msg, sizeof(fd_term_msg));
448    jobstatus_to_ascii(jcr->SDJobStatus, sd_term_msg, sizeof(sd_term_msg));
449
450    Jmsg(jcr, msg_type, 0, _("Bacula " VERSION " (" LSMDATE "): %s\n\
451 JobId:                  %d\n\
452 Job:                    %s\n\
453 FileSet:                %s\n\
454 Backup Level:           %s%s\n\
455 Client:                 %s\n\
456 Start time:             %s\n\
457 End time:               %s\n\
458 Files Written:          %s\n\
459 Bytes Written:          %s\n\
460 Rate:                   %.1f KB/s\n\
461 Software Compression:   %s\n\
462 Volume names(s):        %s\n\
463 Volume Session Id:      %d\n\
464 Volume Session Time:    %d\n\
465 Last Volume Bytes:      %s\n\
466 FD termination status:  %s\n\
467 SD termination status:  %s\n\
468 Termination:            %s\n\n"),
469         edt,
470         jcr->jr.JobId,
471         jcr->jr.Job,
472         jcr->fileset->hdr.name,
473         level_to_str(jcr->JobLevel), since,
474         jcr->client->hdr.name,
475         sdt,
476         edt,
477         edit_uint64_with_commas(jcr->jr.JobFiles, ec1),
478         edit_uint64_with_commas(jcr->jr.JobBytes, ec2),
479         (float)kbps,
480         compress,
481         jcr->VolumeName,
482         jcr->VolSessionId,
483         jcr->VolSessionTime,
484         edit_uint64_with_commas(mr.VolBytes, ec3),
485         fd_term_msg,
486         sd_term_msg,
487         term_msg);
488
489    Dmsg0(100, "Leave backup_cleanup()\n");
490 }