]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
b2736bf6457ee5c4b281dd1ed80e6e3167cf1cad
[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-2005 Kern Sibbald
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    STORE *store;
71
72    since[0] = 0;
73
74    if (!get_or_create_fileset_record(jcr, &fsr)) {
75       goto bail_out;
76    }
77
78    get_level_since_time(jcr, since, sizeof(since));
79
80    /*
81     * Get the Pool record -- first apply any level defined pools
82     */
83    switch (jcr->JobLevel) {
84    case L_FULL:
85       if (jcr->full_pool) {
86          jcr->pool = jcr->full_pool;
87       }
88       break;
89    case L_INCREMENTAL:
90       if (jcr->inc_pool) {
91          jcr->pool = jcr->inc_pool;
92       }
93       break;
94    case L_DIFFERENTIAL:
95       if (jcr->dif_pool) {
96          jcr->pool = jcr->dif_pool;
97       }
98       break;
99    }
100    memset(&pr, 0, sizeof(pr));
101    bstrncpy(pr.Name, jcr->pool->hdr.name, sizeof(pr.Name));
102
103    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
104       /* Try to create the pool */
105       if (create_pool(jcr, jcr->db, jcr->pool, POOL_OP_CREATE) < 0) {
106          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name,
107             db_strerror(jcr->db));
108          goto bail_out;
109       } else {
110          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
111       }
112    }
113    jcr->PoolId = pr.PoolId;               /****FIXME**** this can go away */
114    jcr->jr.PoolId = pr.PoolId;
115
116
117    /* Print Job Start message */
118    Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %u, Job=%s\n"),
119         jcr->JobId, jcr->Job);
120
121    set_jcr_job_status(jcr, JS_Running);
122    Dmsg2(100, "JobId=%d JobLevel=%c\n", jcr->jr.JobId, jcr->jr.JobLevel);
123    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
124       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
125       goto bail_out;
126    }
127
128    /*
129     * Open a message channel connection with the Storage
130     * daemon. This is to let him know that our client
131     * will be contacting him for a backup  session.
132     *
133     */
134    Dmsg0(110, "Open connection with storage daemon\n");
135    set_jcr_job_status(jcr, JS_WaitSD);
136    /*
137     * Start conversation with Storage daemon
138     */
139    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
140       goto bail_out;
141    }
142    /*
143     * Now start a job with the Storage daemon
144     */
145    if (!start_storage_daemon_job(jcr, jcr->storage, SD_APPEND)) {
146       goto bail_out;
147    }
148    /*
149     * Now start a Storage daemon message thread
150     */
151    if (!start_storage_daemon_message_thread(jcr)) {
152       goto bail_out;
153    }
154    Dmsg0(150, "Storage daemon connection OK\n");
155
156    set_jcr_job_status(jcr, JS_WaitFD);
157    if (!connect_to_file_daemon(jcr, 10, FDConnectTimeout, 1)) {
158       goto bail_out;
159    }
160
161    set_jcr_job_status(jcr, JS_Running);
162    fd = jcr->file_bsock;
163
164    if (!send_include_list(jcr)) {
165       goto bail_out;
166    }
167
168    if (!send_exclude_list(jcr)) {
169       goto bail_out;
170    }
171
172    if (!send_level_command(jcr)) {
173       goto bail_out;
174    }
175
176    /*
177     * send Storage daemon address to the File daemon
178     */
179    store = jcr->store;
180    if (store->SDDport == 0) {
181       store->SDDport = store->SDport;
182    }
183    bnet_fsend(fd, storaddr, store->address, store->SDDport,
184               store->enable_ssl);
185    if (!response(jcr, fd, OKstore, "Storage", DISPLAY_ERROR)) {
186       goto bail_out;
187    }
188
189
190    if (!send_run_before_and_after_commands(jcr)) {
191       goto bail_out;
192    }
193
194    /* Send backup command */
195    bnet_fsend(fd, backupcmd);
196    if (!response(jcr, fd, OKbackup, "backup", DISPLAY_ERROR)) {
197       goto bail_out;
198    }
199
200    /* Pickup Job termination data */
201    stat = wait_for_job_termination(jcr);
202    backup_cleanup(jcr, stat, since, &fsr);
203    return 1;
204
205 bail_out:
206    backup_cleanup(jcr, JS_ErrorTerminated, since, &fsr);
207    return 0;
208 }
209
210 /*
211  * Here we wait for the File daemon to signal termination,
212  *   then we wait for the Storage daemon.  When both
213  *   are done, we return the job status.
214  * Also used by restore.c
215  */
216 int wait_for_job_termination(JCR *jcr)
217 {
218    int32_t n = 0;
219    BSOCK *fd = jcr->file_bsock;
220    bool fd_ok = false;
221    uint32_t JobFiles, Errors;
222    uint64_t ReadBytes, JobBytes;
223
224    set_jcr_job_status(jcr, JS_Running);
225    /* Wait for Client to terminate */
226    while ((n = bget_dirmsg(fd)) >= 0) {
227       if (!fd_ok && sscanf(fd->msg, EndJob, &jcr->FDJobStatus, &JobFiles,
228           &ReadBytes, &JobBytes, &Errors) == 5) {
229          fd_ok = true;
230          set_jcr_job_status(jcr, jcr->FDJobStatus);
231          Dmsg1(100, "FDStatus=%c\n", (char)jcr->JobStatus);
232       } else {
233          Jmsg(jcr, M_WARNING, 0, _("Unexpected Client Job message: %s\n"),
234             fd->msg);
235       }
236       if (job_canceled(jcr)) {
237          break;
238       }
239    }
240    if (is_bnet_error(fd)) {
241       Jmsg(jcr, M_FATAL, 0, _("Network error with FD during %s: ERR=%s\n"),
242           job_type_to_str(jcr->JobType), bnet_strerror(fd));
243    }
244    bnet_sig(fd, BNET_TERMINATE);   /* tell Client we are terminating */
245
246    /* Note, the SD stores in jcr->JobFiles/ReadBytes/JobBytes/Errors */
247    wait_for_storage_daemon_termination(jcr);
248
249
250    /* Return values from FD */
251    if (fd_ok) {
252       jcr->JobFiles = JobFiles;
253       jcr->Errors = Errors;
254       jcr->ReadBytes = ReadBytes;
255       jcr->JobBytes = JobBytes;
256    } else {
257       Jmsg(jcr, M_FATAL, 0, _("No Job status returned from FD.\n"));
258    }
259
260 // Dmsg4(100, "fd_ok=%d FDJS=%d JS=%d SDJS=%d\n", fd_ok, jcr->FDJobStatus,
261 //   jcr->JobStatus, jcr->SDJobStatus);
262
263    /* Return the first error status we find Dir, FD, or SD */
264    if (!fd_ok || is_bnet_error(fd)) {
265       jcr->FDJobStatus = JS_ErrorTerminated;
266    }
267    if (jcr->JobStatus != JS_Terminated) {
268       return jcr->JobStatus;
269    }
270    if (jcr->FDJobStatus != JS_Terminated) {
271       return jcr->FDJobStatus;
272    }
273    return jcr->SDJobStatus;
274 }
275
276 /*
277  * Release resources allocated during backup.
278  */
279 static void backup_cleanup(JCR *jcr, int TermCode, char *since, FILESET_DBR *fsr)
280 {
281    char sdt[50], edt[50];
282    char ec1[30], ec2[30], ec3[30], ec4[30], ec5[30], compress[50];
283    char term_code[100], fd_term_msg[100], sd_term_msg[100];
284    const char *term_msg;
285    int msg_type;
286    MEDIA_DBR mr;
287    double kbps, compression;
288    utime_t RunTime;
289
290    Dmsg2(100, "Enter backup_cleanup %d %c\n", TermCode, TermCode);
291    dequeue_messages(jcr);             /* display any queued messages */
292    memset(&mr, 0, sizeof(mr));
293    set_jcr_job_status(jcr, TermCode);
294
295    update_job_end_record(jcr);        /* update database */
296
297    if (!db_get_job_record(jcr, jcr->db, &jcr->jr)) {
298       Jmsg(jcr, M_WARNING, 0, _("Error getting job record for stats: %s"),
299          db_strerror(jcr->db));
300       set_jcr_job_status(jcr, JS_ErrorTerminated);
301    }
302
303    bstrncpy(mr.VolumeName, jcr->VolumeName, sizeof(mr.VolumeName));
304    if (!db_get_media_record(jcr, jcr->db, &mr)) {
305       Jmsg(jcr, M_WARNING, 0, _("Error getting Media record for Volume \"%s\": ERR=%s"),
306          mr.VolumeName, db_strerror(jcr->db));
307       set_jcr_job_status(jcr, JS_ErrorTerminated);
308    }
309
310    /* Now update the bootstrap file if any */
311    if (jcr->JobStatus == JS_Terminated && jcr->jr.JobBytes &&
312        jcr->job->WriteBootstrap) {
313       FILE *fd;
314       BPIPE *bpipe = NULL;
315       int got_pipe = 0;
316       char *fname = jcr->job->WriteBootstrap;
317       VOL_PARAMS *VolParams = NULL;
318       int VolCount;
319
320       if (*fname == '|') {
321          fname++;
322          got_pipe = 1;
323          bpipe = open_bpipe(fname, 0, "w");
324          fd = bpipe ? bpipe->wfd : NULL;
325       } else {
326          /* ***FIXME*** handle BASE */
327          fd = fopen(fname, jcr->JobLevel==L_FULL?"w+":"a+");
328       }
329       if (fd) {
330          VolCount = db_get_job_volume_parameters(jcr, jcr->db, jcr->JobId,
331                     &VolParams);
332          if (VolCount == 0) {
333             Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters to "
334                  "update Bootstrap file. ERR=%s\n"), db_strerror(jcr->db));
335              if (jcr->SDJobFiles != 0) {
336                 set_jcr_job_status(jcr, JS_ErrorTerminated);
337              }
338
339          }
340          for (int i=0; i < VolCount; i++) {
341             /* Write the record */
342             fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
343             fprintf(fd, "MediaType=\"%s\"\n", VolParams[i].MediaType);
344             fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
345             fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
346             fprintf(fd, "VolFile=%u-%u\n", VolParams[i].StartFile,
347                          VolParams[i].EndFile);
348             fprintf(fd, "VolBlock=%u-%u\n", VolParams[i].StartBlock,
349                          VolParams[i].EndBlock);
350             fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
351                          VolParams[i].LastIndex);
352          }
353          if (VolParams) {
354             free(VolParams);
355          }
356          if (got_pipe) {
357             close_bpipe(bpipe);
358          } else {
359             fclose(fd);
360          }
361       } else {
362          berrno be;
363          Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
364               "%s: ERR=%s\n"), fname, be.strerror());
365          set_jcr_job_status(jcr, JS_ErrorTerminated);
366       }
367    }
368
369    msg_type = M_INFO;                 /* by default INFO message */
370    switch (jcr->JobStatus) {
371       case JS_Terminated:
372          if (jcr->Errors || jcr->SDErrors) {
373             term_msg = _("Backup OK -- with warnings");
374          } else {
375             term_msg = _("Backup OK");
376          }
377          break;
378       case JS_FatalError:
379       case JS_ErrorTerminated:
380          term_msg = _("*** Backup Error ***");
381          msg_type = M_ERROR;          /* Generate error message */
382          if (jcr->store_bsock) {
383             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
384             if (jcr->SD_msg_chan) {
385                pthread_cancel(jcr->SD_msg_chan);
386             }
387          }
388          break;
389       case JS_Canceled:
390          term_msg = _("Backup Canceled");
391          if (jcr->store_bsock) {
392             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
393             if (jcr->SD_msg_chan) {
394                pthread_cancel(jcr->SD_msg_chan);
395             }
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    bstrftimes(sdt, sizeof(sdt), jcr->jr.StartTime);
404    bstrftimes(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 // bmicrosleep(15, 0);                /* for debugging SIGHUP */
438
439    Jmsg(jcr, msg_type, 0, _("Bacula " VERSION " (" LSMDATE "): %s\n"
440 "  JobId:                  %d\n"
441 "  Job:                    %s\n"
442 "  Backup Level:           %s%s\n"
443 "  Client:                 %s\n"
444 "  FileSet:                \"%s\" %s\n"
445 "  Pool:                   \"%s\"\n"
446 "  Storage:                \"%s\"\n"
447 "  Start time:             %s\n"
448 "  End time:               %s\n"
449 "  FD Files Written:       %s\n"
450 "  SD Files Written:       %s\n"
451 "  FD Bytes Written:       %s\n"
452 "  SD Bytes Written:       %s\n"
453 "  Rate:                   %.1f KB/s\n"
454 "  Software Compression:   %s\n"
455 "  Volume name(s):         %s\n"
456 "  Volume Session Id:      %d\n"
457 "  Volume Session Time:    %d\n"
458 "  Last Volume Bytes:      %s\n"
459 "  Non-fatal FD errors:    %d\n"
460 "  SD Errors:              %d\n"
461 "  FD termination status:  %s\n"
462 "  SD termination status:  %s\n"
463 "  Termination:            %s\n\n"),
464         edt,
465         jcr->jr.JobId,
466         jcr->jr.Job,
467         level_to_str(jcr->JobLevel), since,
468         jcr->client->hdr.name,
469         jcr->fileset->hdr.name, fsr->cCreateTime,
470         jcr->pool->hdr.name,
471         jcr->store->hdr.name,
472         sdt,
473         edt,
474         edit_uint64_with_commas(jcr->jr.JobFiles, ec1),
475         edit_uint64_with_commas(jcr->SDJobFiles, ec4),
476         edit_uint64_with_commas(jcr->jr.JobBytes, ec2),
477         edit_uint64_with_commas(jcr->SDJobBytes, ec5),
478         (float)kbps,
479         compress,
480         jcr->VolumeName,
481         jcr->VolSessionId,
482         jcr->VolSessionTime,
483         edit_uint64_with_commas(mr.VolBytes, ec3),
484         jcr->Errors,
485         jcr->SDErrors,
486         fd_term_msg,
487         sd_term_msg,
488         term_msg);
489
490    Dmsg0(100, "Leave backup_cleanup()\n");
491 }