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