]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
Include RunBefore/After output in job report
[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_FULL:
220          bnet_fsend(fd, levelcmd, "full", " ");
221          break;
222       case L_DIFFERENTIAL:
223       case L_INCREMENTAL:
224          bnet_fsend(fd, levelcmd, "since ", jcr->stime);
225          free_pool_memory(jcr->stime);
226          jcr->stime = NULL;
227          break;
228       case L_SINCE:
229       default:
230          Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"), 
231             jcr->JobLevel, jcr->JobLevel);
232          goto bail_out;
233    }
234    Dmsg1(120, ">filed: %s", fd->msg);
235    if (!response(fd, OKlevel, "Level", 1)) {
236       goto bail_out;
237    }
238
239    /* Send backup command */
240    bnet_fsend(fd, backupcmd);
241    if (!response(fd, OKbackup, "backup", 1)) {
242       goto bail_out;
243    }
244
245    /* Pickup Job termination data */        
246    stat = wait_for_job_termination(jcr);
247    backup_cleanup(jcr, stat, since);
248    return 1;
249
250 bail_out:
251    if (jcr->stime) {
252       free_pool_memory(jcr->stime);
253       jcr->stime = NULL;
254    }
255    backup_cleanup(jcr, JS_ErrorTerminated, since);
256    return 0;
257
258 }
259
260 /*
261  * Here we wait for the File daemon to signal termination,
262  *   then we wait for the Storage daemon.  When both
263  *   are done, we return the job status.
264  */
265 static int wait_for_job_termination(JCR *jcr)
266 {
267    int32_t n = 0;
268    BSOCK *fd = jcr->file_bsock;
269    int fd_ok = FALSE;
270
271    set_jcr_job_status(jcr, JS_Running);
272    /* Wait for Client to terminate */
273    while ((n = bget_dirmsg(fd)) >= 0) {
274       if (sscanf(fd->msg, EndBackup, &jcr->FDJobStatus, &jcr->JobFiles,
275           &jcr->ReadBytes, &jcr->JobBytes) == 4) {
276          fd_ok = TRUE;
277          set_jcr_job_status(jcr, jcr->FDJobStatus);
278          Dmsg1(100, "FDStatus=%c\n", (char)jcr->JobStatus);
279       }
280       if (job_canceled(jcr)) {
281          break;
282       }
283    }
284    if (is_bnet_error(fd)) {
285       Jmsg(jcr, M_FATAL, 0, _("<filed: network error during BACKUP command. ERR=%s\n"),
286           bnet_strerror(fd));
287    }
288    bnet_sig(fd, BNET_TERMINATE);   /* tell Client we are terminating */
289
290    wait_for_storage_daemon_termination(jcr);
291
292    /* Return the first error status we find FD or SD */
293    if (fd_ok && jcr->JobStatus != JS_Terminated) {
294       return jcr->JobStatus;
295    }
296    if (!fd_ok || is_bnet_error(fd)) {                          
297       return JS_ErrorTerminated;
298    }
299    return jcr->SDJobStatus;
300 }
301
302 /*
303  * Release resources allocated during backup.
304  */
305 static void backup_cleanup(JCR *jcr, int TermCode, char *since)
306 {
307    char sdt[50], edt[50];
308    char ec1[30], ec2[30], ec3[30], compress[50];
309    char term_code[100], fd_term_msg[100], sd_term_msg[100];
310    char *term_msg;
311    int msg_type;
312    MEDIA_DBR mr;
313    double kbps, compression;
314    utime_t RunTime;
315
316    Dmsg0(100, "Enter backup_cleanup()\n");
317    memset(&mr, 0, sizeof(mr));
318    set_jcr_job_status(jcr, TermCode);
319
320    update_job_end_record(jcr);        /* update database */
321    
322    if (!db_get_job_record(jcr, jcr->db, &jcr->jr)) {
323       Jmsg(jcr, M_WARNING, 0, _("Error getting job record for stats: %s"), 
324          db_strerror(jcr->db));
325       set_jcr_job_status(jcr, JS_ErrorTerminated);
326    }
327
328    strcpy(mr.VolumeName, jcr->VolumeName);
329    if (!db_get_media_record(jcr, jcr->db, &mr)) {
330       Jmsg(jcr, M_WARNING, 0, _("Error getting Media record for Volume \"%s\": ERR=%s"), 
331          mr.VolumeName, db_strerror(jcr->db));
332       set_jcr_job_status(jcr, JS_ErrorTerminated);
333    }
334
335    /* Now update the bootstrap file if any */
336    if (jcr->JobStatus == JS_Terminated && jcr->job->WriteBootstrap) {
337       FILE *fd;
338       BPIPE *bpipe = NULL;
339       int got_pipe = 0;
340       char *fname = jcr->job->WriteBootstrap;
341       VOL_PARAMS *VolParams = NULL;
342       int VolCount;
343
344       if (*fname == '|') {
345          fname++;
346          got_pipe = 1;
347          bpipe = open_bpipe(fname, 0, "w");
348          fd = bpipe ? bpipe->wfd : NULL;
349       } else {
350          fd = fopen(fname, jcr->JobLevel==L_FULL?"w+":"a+");
351       }
352       if (fd) {
353          VolCount = db_get_job_volume_parameters(jcr, jcr->db, jcr->JobId,
354                     &VolParams);
355          if (VolCount == 0) {
356             Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters. ERR=%s\n"),
357                  db_strerror(jcr->db));
358          }
359          for (int i=0; i < VolCount; i++) {
360             /* Write the record */
361             fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
362             fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
363             fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
364             fprintf(fd, "VolFile=%u-%u\n", VolParams[i].StartFile,
365                          VolParams[i].EndFile);
366             fprintf(fd, "VolBlock=%u-%u\n", VolParams[i].StartBlock,
367                          VolParams[i].EndBlock);
368             fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
369                          VolParams[i].LastIndex);
370          }
371          if (VolParams) {
372             free(VolParams);
373          }
374          if (got_pipe) {
375             close_bpipe(bpipe);
376          } else {
377             fclose(fd);
378          }
379       } else {
380          Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
381               "%s: ERR=%s\n"), fname, strerror(errno));
382          set_jcr_job_status(jcr, JS_ErrorTerminated);
383       }
384    }
385
386    msg_type = M_INFO;                 /* by default INFO message */
387    switch (jcr->JobStatus) {
388       case JS_Terminated:
389          term_msg = _("Backup OK");
390          break;
391       case JS_FatalError:
392       case JS_ErrorTerminated:
393          term_msg = _("*** Backup Error ***"); 
394          msg_type = M_ERROR;          /* Generate error message */
395          if (jcr->store_bsock) {
396             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
397             pthread_cancel(jcr->SD_msg_chan);
398          }
399          break;
400       case JS_Canceled:
401          term_msg = _("Backup Canceled");
402          if (jcr->store_bsock) {
403             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
404             pthread_cancel(jcr->SD_msg_chan);
405          }
406          break;
407       default:
408          term_msg = term_code;
409          sprintf(term_code, _("Inappropriate term code: %c\n"), jcr->JobStatus);
410          break;
411    }
412    bstrftime(sdt, sizeof(sdt), jcr->jr.StartTime);
413    bstrftime(edt, sizeof(edt), jcr->jr.EndTime);
414    RunTime = jcr->jr.EndTime - jcr->jr.StartTime;
415    if (RunTime <= 0) {
416       kbps = 0;
417    } else {
418       kbps = (double)jcr->jr.JobBytes / (1000 * RunTime);
419    }
420    if (!db_get_job_volume_names(jcr, jcr->db, jcr->jr.JobId, &jcr->VolumeName)) {
421       /*
422        * Note, if the job has erred, most likely it did not write any
423        *  tape, so suppress this "error" message since in that case
424        *  it is normal.  Or look at it the other way, only for a
425        *  normal exit should we complain about this error.
426        */
427       if (jcr->JobStatus == JS_Terminated) {                                
428          Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
429       }
430       jcr->VolumeName[0] = 0;         /* none */
431    }
432
433    if (jcr->ReadBytes == 0) {
434       strcpy(compress, "None");
435    } else {
436       compression = (double)100 - 100.0 * ((double)jcr->JobBytes / (double)jcr->ReadBytes);
437       if (compression < 0.5) {
438          strcpy(compress, "None");
439       } else {
440          sprintf(compress, "%.1f %%", (float)compression);
441       }
442    }
443    jobstatus_to_ascii(jcr->FDJobStatus, fd_term_msg, sizeof(fd_term_msg));
444    jobstatus_to_ascii(jcr->SDJobStatus, sd_term_msg, sizeof(sd_term_msg));
445
446    Jmsg(jcr, msg_type, 0, _("Bacula " VERSION " (" LSMDATE "): %s\n\
447 JobId:                  %d\n\
448 Job:                    %s\n\
449 FileSet:                %s\n\
450 Backup Level:           %s%s\n\
451 Client:                 %s\n\
452 Start time:             %s\n\
453 End time:               %s\n\
454 Files Written:          %s\n\
455 Bytes Written:          %s\n\
456 Rate:                   %.1f KB/s\n\
457 Software Compression:   %s\n\
458 Volume names(s):        %s\n\
459 Volume Session Id:      %d\n\
460 Volume Session Time:    %d\n\
461 Last Volume Bytes:      %s\n\
462 FD termination status:  %s\n\
463 SD termination status:  %s\n\
464 Termination:            %s\n\n"),
465         edt,
466         jcr->jr.JobId,
467         jcr->jr.Job,
468         jcr->fileset->hdr.name,
469         level_to_str(jcr->JobLevel), since,
470         jcr->client->hdr.name,
471         sdt,
472         edt,
473         edit_uint64_with_commas(jcr->jr.JobFiles, ec1),
474         edit_uint64_with_commas(jcr->jr.JobBytes, ec2),
475         (float)kbps,
476         compress,
477         jcr->VolumeName,
478         jcr->VolSessionId,
479         jcr->VolSessionTime,
480         edit_uint64_with_commas(mr.VolBytes, ec3),
481         fd_term_msg,
482         sd_term_msg,
483         term_msg);
484
485    Dmsg0(100, "Leave backup_cleanup()\n");
486 }