]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
7200a043d5970ea512b0b8fdb3b1b27d5c6012bb
[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 EndJob[]     = "2800 End Job TermCode=%d JobFiles=%u "
51                            "ReadBytes=%" lld " JobBytes=%" lld " Errors=%u\n";
52
53
54 /* Forward referenced functions */
55 static void backup_cleanup(JCR *jcr, int TermCode, char *since, FILESET_DBR *fsr);
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    bstrncpy(fsr.FileSet, jcr->fileset->hdr.name, sizeof(fsr.FileSet));
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       bstrncpy(jcr->fileset->MD5, fsr.MD5, sizeof(jcr->fileset->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 \"%s\" record. ERR=%s\n"), 
98          fsr.FileSet, db_strerror(jcr->db));
99       goto bail_out;
100    }   
101    jcr->jr.FileSetId = fsr.FileSetId;
102    if (fsr.created) {
103       Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"), 
104          fsr.FileSet, fsr.cCreateTime);
105    }
106    Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name, 
107       jcr->jr.FileSetId);
108
109    /* Look up the last
110     * FULL backup job to get the time/date for a 
111     * differential or incremental save.
112     */
113    jcr->stime = get_pool_memory(PM_MESSAGE);
114    jcr->stime[0] = 0;
115    since[0] = 0;
116    switch (jcr->JobLevel) {
117       case L_DIFFERENTIAL:
118       case L_INCREMENTAL:
119          /* Look up start time of last job */
120          jcr->jr.JobId = 0;
121          if (!db_find_job_start_time(jcr, jcr->db, &jcr->jr, &jcr->stime)) {
122             Jmsg(jcr, M_INFO, 0, "%s", db_strerror(jcr->db));
123             Jmsg(jcr, M_INFO, 0, _("No prior or suitable FULL backup found. Doing FULL backup.\n"));
124             bsnprintf(since, sizeof(since), " (upgraded from %s)", 
125                level_to_str(jcr->jr.Level));
126             jcr->JobLevel = jcr->jr.Level = L_FULL;
127          } else {
128             bstrncpy(since, ", since=", sizeof(since));
129             bstrncat(since, jcr->stime, sizeof(since));
130          }
131          Dmsg1(115, "Last start time = %s\n", jcr->stime);
132          break;
133    }
134
135    jcr->jr.JobId = jcr->JobId;
136    jcr->jr.StartTime = jcr->start_time;
137    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
138       Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
139       goto bail_out;
140    }
141
142    jcr->fname = (char *) get_pool_memory(PM_FNAME);
143
144    /* Print Job Start message */
145    Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %u, Job=%s\n"),
146         jcr->JobId, jcr->Job);
147
148    /* 
149     * Get the Pool record  
150     */
151    memset(&pr, 0, sizeof(pr));
152    bstrncpy(pr.Name, jcr->pool->hdr.name, sizeof(pr.Name));
153    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
154       /* Try to create the pool */
155       if (create_pool(jcr, jcr->db, jcr->pool, POOL_OP_CREATE) < 0) {
156          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name, 
157             db_strerror(jcr->db));
158          goto bail_out;
159       } else {
160          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
161       }
162    }
163    jcr->PoolId = pr.PoolId;               /****FIXME**** this can go away */
164    jcr->jr.PoolId = pr.PoolId;
165
166    /*
167     * Open a message channel connection with the Storage
168     * daemon. This is to let him know that our client
169     * will be contacting him for a backup  session.
170     *
171     */
172    Dmsg0(110, "Open connection with storage daemon\n");
173    set_jcr_job_status(jcr, JS_WaitSD);
174    /*
175     * Start conversation with Storage daemon  
176     */
177    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
178       goto bail_out;
179    }
180    /*
181     * Now start a job with the Storage daemon
182     */
183    if (!start_storage_daemon_job(jcr)) {
184       goto bail_out;
185    }
186    /*
187     * Now start a Storage daemon message thread
188     */
189    if (!start_storage_daemon_message_thread(jcr)) {
190       goto bail_out;
191    }
192    Dmsg0(150, "Storage daemon connection OK\n");
193
194    set_jcr_job_status(jcr, JS_WaitFD);
195    if (!connect_to_file_daemon(jcr, 10, FDConnectTimeout, 1)) {
196       goto bail_out;
197    }
198
199    set_jcr_job_status(jcr, JS_Running);
200    fd = jcr->file_bsock;
201
202    if (!send_include_list(jcr)) {
203       goto bail_out;
204    }
205
206    if (!send_exclude_list(jcr)) {
207       goto bail_out;
208    }
209
210    /* 
211     * send Storage daemon address to the File daemon
212     */
213    if (jcr->store->SDDport == 0) {
214       jcr->store->SDDport = jcr->store->SDport;
215    }
216    bnet_fsend(fd, storaddr, jcr->store->address, jcr->store->SDDport,
217               jcr->store->enable_ssl);
218    if (!response(jcr, fd, OKstore, "Storage", DISPLAY_ERROR)) {
219       goto bail_out;
220    }
221
222    /* 
223     * Send Level command to File daemon
224     */
225    switch (jcr->JobLevel) {
226       case L_BASE:
227          bnet_fsend(fd, levelcmd, "base", " ");
228          break;
229       case L_FULL:
230          bnet_fsend(fd, levelcmd, "full", " ");
231          break;
232       case L_DIFFERENTIAL:
233       case L_INCREMENTAL:
234          bnet_fsend(fd, levelcmd, "since ", jcr->stime);
235          free_pool_memory(jcr->stime);
236          jcr->stime = NULL;
237          break;
238       case L_SINCE:
239       default:
240          Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"), 
241             jcr->JobLevel, jcr->JobLevel);
242          goto bail_out;
243    }
244    Dmsg1(120, ">filed: %s", fd->msg);
245    if (!response(jcr, fd, OKlevel, "Level", DISPLAY_ERROR)) {
246       goto bail_out;
247    }
248
249    /* Send backup command */
250    bnet_fsend(fd, backupcmd);
251    if (!response(jcr, fd, OKbackup, "backup", DISPLAY_ERROR)) {
252       goto bail_out;
253    }
254
255    /* Pickup Job termination data */        
256    stat = wait_for_job_termination(jcr);
257    backup_cleanup(jcr, stat, since, &fsr);
258    return 1;
259
260 bail_out:
261    if (jcr->stime) {
262       free_pool_memory(jcr->stime);
263       jcr->stime = NULL;
264    }
265    backup_cleanup(jcr, JS_ErrorTerminated, since, &fsr);
266    return 0;
267
268 }
269
270 /*
271  * Here we wait for the File daemon to signal termination,
272  *   then we wait for the Storage daemon.  When both
273  *   are done, we return the job status.
274  * Also used by restore.c 
275  */
276 int wait_for_job_termination(JCR *jcr)
277 {
278    int32_t n = 0;
279    BSOCK *fd = jcr->file_bsock;
280    int fd_ok = FALSE;
281    uint32_t JobFiles, Errors;
282    uint64_t ReadBytes, JobBytes;
283
284    set_jcr_job_status(jcr, JS_Running);
285    /* Wait for Client to terminate */
286    while ((n = bget_dirmsg(fd)) >= 0) {
287       if (!fd_ok && sscanf(fd->msg, EndJob, &jcr->FDJobStatus, &JobFiles,
288           &ReadBytes, &JobBytes, &Errors) == 5) {
289          fd_ok = TRUE;
290          set_jcr_job_status(jcr, jcr->FDJobStatus);
291          Dmsg1(100, "FDStatus=%c\n", (char)jcr->JobStatus);
292       } else {
293          Jmsg(jcr, M_WARNING, 0, _("Unexpected Client Job message: %s\n"),
294             fd->msg);
295       }
296       if (job_canceled(jcr)) {
297          break;
298       }
299    }
300    if (is_bnet_error(fd)) {
301       Jmsg(jcr, M_FATAL, 0, _("Network error with FD during %s: ERR=%s\n"),
302           job_type_to_str(jcr->JobType), bnet_strerror(fd));
303    }
304    bnet_sig(fd, BNET_TERMINATE);   /* tell Client we are terminating */
305
306    /* Note, the SD stores in jcr->JobFiles/ReadBytes/JobBytes/Errors */
307    wait_for_storage_daemon_termination(jcr);
308
309    /* Return values from FD */
310    if (fd_ok) {
311       jcr->JobFiles = JobFiles;
312       jcr->Errors = Errors;
313       jcr->ReadBytes = ReadBytes;
314       jcr->JobBytes = JobBytes;
315    }
316
317 // Dmsg4(000, "fd_ok=%d FDJS=%d JS=%d SDJS=%d\n", fd_ok, jcr->FDJobStatus,
318 //   jcr->JobStatus, jcr->SDJobStatus);
319
320    /* Return the first error status we find Dir, FD, or SD */
321    if (!fd_ok || is_bnet_error(fd)) {                          
322       jcr->FDJobStatus = JS_ErrorTerminated;
323    }
324    if (jcr->JobStatus != JS_Terminated) {
325       return jcr->JobStatus;
326    }
327    if (jcr->FDJobStatus != JS_Terminated) {
328       return jcr->FDJobStatus;
329    }
330    return jcr->SDJobStatus;
331 }
332
333 /*
334  * Release resources allocated during backup.
335  */
336 static void backup_cleanup(JCR *jcr, int TermCode, char *since, FILESET_DBR *fsr) 
337 {
338    char sdt[50], edt[50];
339    char ec1[30], ec2[30], ec3[30], compress[50];
340    char term_code[100], fd_term_msg[100], sd_term_msg[100];
341    char *term_msg;
342    int msg_type;
343    MEDIA_DBR mr;
344    double kbps, compression;
345    utime_t RunTime;
346
347    Dmsg0(100, "Enter backup_cleanup()\n");
348    memset(&mr, 0, sizeof(mr));
349    set_jcr_job_status(jcr, TermCode);
350
351    update_job_end_record(jcr);        /* update database */
352    
353    if (!db_get_job_record(jcr, jcr->db, &jcr->jr)) {
354       Jmsg(jcr, M_WARNING, 0, _("Error getting job record for stats: %s"), 
355          db_strerror(jcr->db));
356       set_jcr_job_status(jcr, JS_ErrorTerminated);
357    }
358
359    bstrncpy(mr.VolumeName, jcr->VolumeName, sizeof(mr.VolumeName));
360    if (!db_get_media_record(jcr, jcr->db, &mr)) {
361       Jmsg(jcr, M_WARNING, 0, _("Error getting Media record for Volume \"%s\": ERR=%s"), 
362          mr.VolumeName, db_strerror(jcr->db));
363       set_jcr_job_status(jcr, JS_ErrorTerminated);
364    }
365
366    /* Now update the bootstrap file if any */
367    if (jcr->JobStatus == JS_Terminated && jcr->jr.JobBytes && 
368        jcr->job->WriteBootstrap) {
369       FILE *fd;
370       BPIPE *bpipe = NULL;
371       int got_pipe = 0;
372       char *fname = jcr->job->WriteBootstrap;
373       VOL_PARAMS *VolParams = NULL;
374       int VolCount;
375
376       if (*fname == '|') {
377          fname++;
378          got_pipe = 1;
379          bpipe = open_bpipe(fname, 0, "w");
380          fd = bpipe ? bpipe->wfd : NULL;
381       } else {
382          /* ***FIXME*** handle BASE */
383          fd = fopen(fname, jcr->JobLevel==L_FULL?"w+":"a+");
384       }
385       if (fd) {
386          VolCount = db_get_job_volume_parameters(jcr, jcr->db, jcr->JobId,
387                     &VolParams);
388          if (VolCount == 0) {
389             Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters. ERR=%s\n"),
390                  db_strerror(jcr->db));
391          }
392          for (int i=0; i < VolCount; i++) {
393             /* Write the record */
394             fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
395             fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
396             fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
397             fprintf(fd, "VolFile=%u-%u\n", VolParams[i].StartFile,
398                          VolParams[i].EndFile);
399             fprintf(fd, "VolBlock=%u-%u\n", VolParams[i].StartBlock,
400                          VolParams[i].EndBlock);
401             fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
402                          VolParams[i].LastIndex);
403          }
404          if (VolParams) {
405             free(VolParams);
406          }
407          if (got_pipe) {
408             close_bpipe(bpipe);
409          } else {
410             fclose(fd);
411          }
412       } else {
413          Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
414               "%s: ERR=%s\n"), fname, strerror(errno));
415          set_jcr_job_status(jcr, JS_ErrorTerminated);
416       }
417    }
418
419    msg_type = M_INFO;                 /* by default INFO message */
420    switch (jcr->JobStatus) {
421       case JS_Terminated:
422          term_msg = _("Backup OK");
423          break;
424       case JS_FatalError:
425       case JS_ErrorTerminated:
426          term_msg = _("*** Backup Error ***"); 
427          msg_type = M_ERROR;          /* Generate error message */
428          if (jcr->store_bsock) {
429             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
430             pthread_cancel(jcr->SD_msg_chan);
431          }
432          break;
433       case JS_Canceled:
434          term_msg = _("Backup Canceled");
435          if (jcr->store_bsock) {
436             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
437             pthread_cancel(jcr->SD_msg_chan);
438          }
439          break;
440       default:
441          term_msg = term_code;
442          sprintf(term_code, _("Inappropriate term code: %c\n"), jcr->JobStatus);
443          break;
444    }
445    bstrftime(sdt, sizeof(sdt), jcr->jr.StartTime);
446    bstrftime(edt, sizeof(edt), jcr->jr.EndTime);
447    RunTime = jcr->jr.EndTime - jcr->jr.StartTime;
448    if (RunTime <= 0) {
449       kbps = 0;
450    } else {
451       kbps = (double)jcr->jr.JobBytes / (1000 * RunTime);
452    }
453    if (!db_get_job_volume_names(jcr, jcr->db, jcr->jr.JobId, &jcr->VolumeName)) {
454       /*
455        * Note, if the job has erred, most likely it did not write any
456        *  tape, so suppress this "error" message since in that case
457        *  it is normal.  Or look at it the other way, only for a
458        *  normal exit should we complain about this error.
459        */
460       if (jcr->JobStatus == JS_Terminated && jcr->jr.JobBytes) {                                
461          Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
462       }
463       jcr->VolumeName[0] = 0;         /* none */
464    }
465
466    if (jcr->ReadBytes == 0) {
467       bstrncpy(compress, "None", sizeof(compress));
468    } else {
469       compression = (double)100 - 100.0 * ((double)jcr->JobBytes / (double)jcr->ReadBytes);
470       if (compression < 0.5) {
471          bstrncpy(compress, "None", sizeof(compress));
472       } else {
473          bsnprintf(compress, sizeof(compress), "%.1f %%", (float)compression);
474       }
475    }
476    jobstatus_to_ascii(jcr->FDJobStatus, fd_term_msg, sizeof(fd_term_msg));
477    jobstatus_to_ascii(jcr->SDJobStatus, sd_term_msg, sizeof(sd_term_msg));
478
479    Jmsg(jcr, msg_type, 0, _("Bacula " VERSION " (" LSMDATE "): %s\n\
480 JobId:                  %d\n\
481 Job:                    %s\n\
482 Backup Level:           %s%s\n\
483 Client:                 %s\n\
484 FileSet:                \"%s\" %s\n\
485 Start time:             %s\n\
486 End time:               %s\n\
487 Files Written:          %s\n\
488 Bytes Written:          %s\n\
489 Rate:                   %.1f KB/s\n\
490 Software Compression:   %s\n\
491 Volume names(s):        %s\n\
492 Volume Session Id:      %d\n\
493 Volume Session Time:    %d\n\
494 Last Volume Bytes:      %s\n\
495 Non-fatal FD errors:    %d\n\
496 FD termination status:  %s\n\
497 SD termination status:  %s\n\
498 Termination:            %s\n\n"),
499         edt,
500         jcr->jr.JobId,
501         jcr->jr.Job,
502         level_to_str(jcr->JobLevel), since,
503         jcr->client->hdr.name,
504         jcr->fileset->hdr.name, fsr->cCreateTime,
505         sdt,
506         edt,
507         edit_uint64_with_commas(jcr->jr.JobFiles, ec1),
508         edit_uint64_with_commas(jcr->jr.JobBytes, ec2),
509         (float)kbps,
510         compress,
511         jcr->VolumeName,
512         jcr->VolSessionId,
513         jcr->VolSessionTime,
514         edit_uint64_with_commas(mr.VolBytes, ec3),
515         jcr->Errors,
516         fd_term_msg,
517         sd_term_msg,
518         term_msg);
519
520    Dmsg0(100, "Leave backup_cleanup()\n");
521 }