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