]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
Add SD heartbeat
[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  *    This routine is called as a thread. It may not yet be totally
8  *      thread reentrant!!!
9  *
10  *  Basic tasks done here:
11  *     Open DB and create records for this job.
12  *     Open Message Channel with Storage daemon to tell him a job will be starting.
13  *     Open connection with File daemon and pass him commands
14  *       to do the backup.
15  *     When the File daemon finishes the job, update the DB.
16  *
17  *   Version $Id$
18  */
19
20 /*
21    Copyright (C) 2000-2003 Kern Sibbald and John Walker
22
23    This program is free software; you can redistribute it and/or
24    modify it under the terms of the GNU General Public License as
25    published by the Free Software Foundation; either version 2 of
26    the License, or (at your option) any later version.
27
28    This program is distributed in the hope that it will be useful,
29    but WITHOUT ANY WARRANTY; without even the implied warranty of
30    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
31    General Public License for more details.
32
33    You should have received a copy of the GNU General Public
34    License along with this program; if not, write to the Free
35    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
36    MA 02111-1307, USA.
37
38  */
39
40 #include "bacula.h"
41 #include "dird.h"
42 #include "ua.h"
43
44 /* Commands sent to File daemon */
45 static char backupcmd[] = "backup\n";
46 static char storaddr[]  = "storage address=%s port=%d ssl=%d\n";
47 static char levelcmd[]  = "level = %s%s\n";
48
49 /* Responses received from File daemon */
50 static char OKbackup[]  = "2000 OK backup\n";
51 static char OKstore[]   = "2000 OK storage\n";
52 static char OKlevel[]   = "2000 OK level\n";
53 static char EndBackup[] = "2801 End Backup Job TermCode=%d JobFiles=%u ReadBytes=%" lld " JobBytes=%" lld "\n";
54
55
56 /* Forward referenced functions */
57 static void backup_cleanup(JCR *jcr, int TermCode, char *since);
58 static int wait_for_job_termination(JCR *jcr);               
59
60 /* External functions */
61
62 /* 
63  * Do a backup of the specified FileSet
64  *    
65  *  Returns:  0 on failure
66  *            1 on success
67  */
68 int do_backup(JCR *jcr) 
69 {
70    char since[MAXSTRING];
71    int stat;
72    BSOCK   *fd;
73    POOL_DBR pr;
74    FILESET_DBR fsr;
75
76    since[0] = 0;
77
78    if (!get_or_create_client_record(jcr)) {
79       Jmsg(jcr, M_ERROR, 0, _("Could not get/create Client record. ERR=%s\n"), 
80          db_strerror(jcr->db));
81       goto bail_out;
82    }
83
84    /*
85     * Get or Create FileSet record
86     */
87    memset(&fsr, 0, sizeof(fsr));
88    strcpy(fsr.FileSet, jcr->fileset->hdr.name);
89    if (jcr->fileset->have_MD5) {
90       struct MD5Context md5c;
91       unsigned char signature[16];
92       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
93       MD5Final(signature, &md5c);
94       bin_to_base64(fsr.MD5, (char *)signature, 16); /* encode 16 bytes */
95       strcpy(jcr->fileset->MD5, fsr.MD5);
96    } else {
97       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
98    }
99    if (!db_create_fileset_record(jcr, jcr->db, &fsr)) {
100       Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet record. ERR=%s\n"), 
101          db_strerror(jcr->db));
102       goto bail_out;
103    }   
104    jcr->jr.FileSetId = fsr.FileSetId;
105    Dmsg2(119, "Created FileSet %s record %d\n", jcr->fileset->hdr.name, 
106       jcr->jr.FileSetId);
107
108    /* Look up the last
109     * FULL backup job to get the time/date for a 
110     * differential or incremental save.
111     */
112    jcr->stime = get_pool_memory(PM_MESSAGE);
113    jcr->stime[0] = 0;
114    since[0] = 0;
115    switch (jcr->JobLevel) {
116       case L_DIFFERENTIAL:
117       case L_INCREMENTAL:
118          /* Look up start time of last job */
119          jcr->jr.JobId = 0;
120          if (!db_find_job_start_time(jcr, jcr->db, &jcr->jr, &jcr->stime)) {
121             Jmsg(jcr, M_INFO, 0, _("Last FULL backup time not found. Doing FULL backup.\n"));
122             jcr->JobLevel = jcr->jr.Level = L_FULL;
123          } else {
124             strcpy(since, ", since=");
125             bstrncat(since, jcr->stime, sizeof(since));
126          }
127          Dmsg1(115, "Last start time = %s\n", jcr->stime);
128          break;
129    }
130
131    jcr->jr.JobId = jcr->JobId;
132    jcr->jr.StartTime = jcr->start_time;
133    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
134       Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
135       goto bail_out;
136    }
137
138    jcr->fname = (char *) get_pool_memory(PM_FNAME);
139
140    /* Print Job Start message */
141    Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %d, Job=%s\n"),
142         jcr->JobId, jcr->Job);
143
144    /* 
145     * Get the Pool record  
146     */
147    memset(&pr, 0, sizeof(pr));
148    strcpy(pr.Name, jcr->pool->hdr.name);
149    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
150       /* Try to create the pool */
151       if (create_pool(jcr, jcr->db, jcr->pool, 1) < 0) {
152          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name, 
153             db_strerror(jcr->db));
154          goto bail_out;
155       } else {
156          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
157       }
158    }
159    jcr->PoolId = pr.PoolId;               /****FIXME**** this can go away */
160    jcr->jr.PoolId = pr.PoolId;
161
162    /*
163     * Open a message channel connection with the Storage
164     * daemon. This is to let him know that our client
165     * will be contacting him for a backup  session.
166     *
167     */
168    Dmsg0(110, "Open connection with storage daemon\n");
169    set_jcr_job_status(jcr, JS_WaitSD);
170    /*
171     * Start conversation with Storage daemon  
172     */
173    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
174       goto bail_out;
175    }
176    /*
177     * Now start a job with the Storage daemon
178     */
179    if (!start_storage_daemon_job(jcr)) {
180       goto bail_out;
181    }
182    /*
183     * Now start a Storage daemon message thread
184     */
185    if (!start_storage_daemon_message_thread(jcr)) {
186       goto bail_out;
187    }
188    Dmsg0(150, "Storage daemon connection OK\n");
189
190    set_jcr_job_status(jcr, JS_WaitFD);
191    if (!connect_to_file_daemon(jcr, 10, FDConnectTimeout, 1)) {
192       goto bail_out;
193    }
194
195    set_jcr_job_status(jcr, JS_Running);
196    fd = jcr->file_bsock;
197
198    if (!send_include_list(jcr)) {
199       goto bail_out;
200    }
201
202    if (!send_exclude_list(jcr)) {
203       goto bail_out;
204    }
205
206    /* 
207     * send Storage daemon address to the File daemon
208     */
209    if (jcr->store->SDDport == 0) {
210       jcr->store->SDDport = jcr->store->SDport;
211    }
212    bnet_fsend(fd, storaddr, jcr->store->address, jcr->store->SDDport,
213               jcr->store->enable_ssl);
214    if (!response(fd, OKstore, "Storage", 1)) {
215       goto bail_out;
216    }
217
218    /* 
219     * Send Level command to File daemon
220     */
221    switch (jcr->JobLevel) {
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_msg(fd, 0)) >= 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          fd = fopen(fname, jcr->JobLevel==L_FULL?"w+":"a+");
354       }
355       if (fd) {
356          VolCount = db_get_job_volume_parameters(jcr, jcr->db, jcr->JobId,
357                     &VolParams);
358          if (VolCount == 0) {
359             Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters. ERR=%s\n"),
360                  db_strerror(jcr->db));
361          }
362          for (int i=0; i < VolCount; i++) {
363             /* Write the record */
364             fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
365             fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
366             fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
367             fprintf(fd, "VolFile=%u-%u\n", VolParams[i].StartFile,
368                          VolParams[i].EndFile);
369             fprintf(fd, "VolBlock=%u-%u\n", VolParams[i].StartBlock,
370                          VolParams[i].EndBlock);
371             fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
372                          VolParams[i].LastIndex);
373          }
374          if (VolParams) {
375             free(VolParams);
376          }
377          if (got_pipe) {
378             close_bpipe(bpipe);
379          } else {
380             fclose(fd);
381          }
382       } else {
383          Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
384               "%s: ERR=%s\n"), fname, strerror(errno));
385          set_jcr_job_status(jcr, JS_ErrorTerminated);
386       }
387    }
388
389    msg_type = M_INFO;                 /* by default INFO message */
390    switch (jcr->JobStatus) {
391       case JS_Terminated:
392          term_msg = _("Backup OK");
393          break;
394       case JS_FatalError:
395       case JS_ErrorTerminated:
396          term_msg = _("*** Backup Error ***"); 
397          msg_type = M_ERROR;          /* Generate error message */
398          if (jcr->store_bsock) {
399             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
400             pthread_cancel(jcr->SD_msg_chan);
401          }
402          break;
403       case JS_Canceled:
404          term_msg = _("Backup Canceled");
405          if (jcr->store_bsock) {
406             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
407             pthread_cancel(jcr->SD_msg_chan);
408          }
409          break;
410       default:
411          term_msg = term_code;
412          sprintf(term_code, _("Inappropriate term code: %c\n"), jcr->JobStatus);
413          break;
414    }
415    bstrftime(sdt, sizeof(sdt), jcr->jr.StartTime);
416    bstrftime(edt, sizeof(edt), jcr->jr.EndTime);
417    RunTime = jcr->jr.EndTime - jcr->jr.StartTime;
418    if (RunTime <= 0) {
419       kbps = 0;
420    } else {
421       kbps = (double)jcr->jr.JobBytes / (1000 * RunTime);
422    }
423    if (!db_get_job_volume_names(jcr, jcr->db, jcr->jr.JobId, &jcr->VolumeName)) {
424       /*
425        * Note, if the job has erred, most likely it did not write any
426        *  tape, so suppress this "error" message since in that case
427        *  it is normal.  Or look at it the other way, only for a
428        *  normal exit should we complain about this error.
429        */
430       if (jcr->JobStatus == JS_Terminated) {                                
431          Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
432       }
433       jcr->VolumeName[0] = 0;         /* none */
434    }
435
436    if (jcr->ReadBytes == 0) {
437       strcpy(compress, "None");
438    } else {
439       compression = (double)100 - 100.0 * ((double)jcr->JobBytes / (double)jcr->ReadBytes);
440       if (compression < 0.5) {
441          strcpy(compress, "None");
442       } else {
443          sprintf(compress, "%.1f %%", (float)compression);
444       }
445    }
446    jobstatus_to_ascii(jcr->FDJobStatus, fd_term_msg, sizeof(fd_term_msg));
447    jobstatus_to_ascii(jcr->SDJobStatus, sd_term_msg, sizeof(sd_term_msg));
448
449    Jmsg(jcr, msg_type, 0, _("Bacula " VERSION " (" LSMDATE "): %s\n\
450 JobId:                  %d\n\
451 Job:                    %s\n\
452 FileSet:                %s\n\
453 Backup Level:           %s%s\n\
454 Client:                 %s\n\
455 Start time:             %s\n\
456 End time:               %s\n\
457 Files Written:          %s\n\
458 Bytes Written:          %s\n\
459 Rate:                   %.1f KB/s\n\
460 Software Compression:   %s\n\
461 Volume names(s):        %s\n\
462 Volume Session Id:      %d\n\
463 Volume Session Time:    %d\n\
464 Last Volume Bytes:      %s\n\
465 FD termination status:  %s\n\
466 SD termination status:  %s\n\
467 Termination:            %s\n\n"),
468         edt,
469         jcr->jr.JobId,
470         jcr->jr.Job,
471         jcr->fileset->hdr.name,
472         level_to_str(jcr->JobLevel), since,
473         jcr->client->hdr.name,
474         sdt,
475         edt,
476         edit_uint64_with_commas(jcr->jr.JobFiles, ec1),
477         edit_uint64_with_commas(jcr->jr.JobBytes, ec2),
478         (float)kbps,
479         compress,
480         jcr->VolumeName,
481         jcr->VolSessionId,
482         jcr->VolSessionTime,
483         edit_uint64_with_commas(mr.VolBytes, ec3),
484         fd_term_msg,
485         sd_term_msg,
486         term_msg);
487
488
489    Dmsg0(100, "Leave backup_cleanup()\n");
490 }