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