]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/backup.c
Implement Auto Prune and Auto Recycle
[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  *    This routine is called as a thread. It may not yet be totally
8  *      thread reentrant!!!
9  *
10  *  Basic tasks done here:
11  *     Open DB and create records for this job.
12  *     Open Message Channel with Storage daemon to tell him a job will be starting.
13  *     Open connection with File daemon and pass him commands
14  *       to do the backup.
15  *     When the File daemon finishes the job, update the DB.
16  *
17  *   Version $Id$
18  */
19
20 /*
21    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
22
23    This program is free software; you can redistribute it and/or
24    modify it under the terms of the GNU General Public License as
25    published by the Free Software Foundation; either version 2 of
26    the License, or (at your option) any later version.
27
28    This program is distributed in the hope that it will be useful,
29    but WITHOUT ANY WARRANTY; without even the implied warranty of
30    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
31    General Public License for more details.
32
33    You should have received a copy of the GNU General Public
34    License along with this program; if not, write to the Free
35    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
36    MA 02111-1307, USA.
37
38  */
39
40 #include "bacula.h"
41 #include "dird.h"
42 #include "ua.h"
43
44 /* Commands sent to File daemon */
45 static char backupcmd[] = "backup\n";
46 static char storaddr[]  = "storage address=%s port=%d\n";
47 static char levelcmd[]  = "level = %s%s\n";
48
49 /* Responses received from File daemon */
50 static char OKbackup[] = "2000 OK backup\n";
51 static char OKstore[]  = "2000 OK storage\n";
52 static char OKlevel[]  = "2000 OK level\n";
53
54 /* Forward referenced functions */
55 static void backup_cleanup(JCR *jcr, int TermCode, char *since);
56 static int wait_for_job_termination(JCR *jcr);               
57
58 /* External functions */
59
60 /* 
61  * Do a backup of the specified FileSet
62  *    
63  *  Returns:  0 on failure
64  *            1 on success
65  */
66 int do_backup(JCR *jcr) 
67 {
68    char since[MAXSTRING];
69    int stat;
70    BSOCK   *fd;
71    POOL_DBR pr;
72    FILESET_DBR fsr;
73
74    since[0] = 0;
75
76    if (!get_or_create_client_record(jcr)) {
77       backup_cleanup(jcr, JS_ErrorTerminated, since);
78    }
79
80
81    /*
82     * Get or Create FileSet record
83     */
84    memset(&fsr, 0, sizeof(fsr));
85    strcpy(fsr.FileSet, jcr->fileset->hdr.name);
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    } else {
93       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
94    }
95    if (!db_create_fileset_record(jcr->db, &fsr)) {
96       Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet record. %s"), 
97          db_strerror(jcr->db));
98       backup_cleanup(jcr, JS_ErrorTerminated, since);
99       return 0;
100    }   
101    jcr->jr.FileSetId = fsr.FileSetId;
102    Dmsg2(9, "Created FileSet %s record %d\n", jcr->fileset->hdr.name, 
103       jcr->jr.FileSetId);
104
105
106    /* Look up the last
107     * FULL backup job to get the time/date for a 
108     * differential or incremental save.
109     */
110    jcr->stime = (char *) get_pool_memory(PM_MESSAGE);
111    jcr->stime[0] = 0;
112    since[0] = 0;
113    switch (jcr->level) {
114       case L_DIFFERENTIAL:
115       case L_INCREMENTAL:
116          /* Look up start time of last job */
117          jcr->jr.JobId = 0;
118          if (!db_find_job_start_time(jcr->db, &jcr->jr, jcr->stime)) {
119             Jmsg(jcr, M_INFO, 0, _("Last FULL backup time not found. Doing FULL backup.\n"));
120             jcr->level = L_FULL;
121             jcr->jr.Level = L_FULL;
122          } else {
123             strcpy(since, ", since=");
124             strcat(since, jcr->stime);
125          }
126          Dmsg1(15, "Last start time = %s\n", jcr->stime);
127          break;
128    }
129
130    jcr->jr.JobId = jcr->JobId;
131    jcr->jr.StartTime = jcr->start_time;
132    if (!db_update_job_start_record(jcr->db, &jcr->jr)) {
133       Jmsg(jcr, M_ERROR, 0, "%s", db_strerror(jcr->db));
134       backup_cleanup(jcr, JS_ErrorTerminated, since);
135       return 0;
136    }
137
138    jcr->fname = (char *) get_pool_memory(PM_FNAME);
139
140    /* Print Job Start message */
141    Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %d, Job=%s\n"),
142         jcr->JobId, jcr->Job);
143
144    /* 
145     * Get the Pool record  
146     */
147    memset(&pr, 0, sizeof(pr));
148    strcpy(pr.Name, jcr->pool->hdr.name);
149    while (!db_get_pool_record(jcr->db, &pr)) { /* get by Name */
150       /* Try to create the pool */
151       if (create_pool(jcr->db, jcr->pool) < 0) {
152          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name, 
153             db_strerror(jcr->db));
154          backup_cleanup(jcr, JS_ErrorTerminated, since);
155          return 0;
156       } else {
157          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
158       }
159    }
160    jcr->PoolId = pr.PoolId;               /****FIXME**** this can go away */
161    jcr->jr.PoolId = pr.PoolId;
162
163 #ifdef needed
164    /* NOTE, THIS IS NOW DONE BY THE STORAGE DAEMON
165     *
166     * Find at least one Volume associated with this Pool
167     *  It must be marked Append, and be of the correct Media Type
168     *  for the storage type.
169     */
170    memset(&mr, 0, sizeof(mr));
171    mr.PoolId = pr.PoolId;
172    strcpy(mr.VolStatus, "Append");
173    strcpy(mr.MediaType, jcr->store->media_type);
174    if (!db_find_next_volume(jcr->db, 1, &mr)) {
175       if (!newVolume(jcr)) {
176          Jmsg(jcr, M_FATAL, 0, _("No writable %s media in Pool %s.\n\
177       Please use the Console program to add available Volumes.\n"), mr.MediaType, pr.Name);
178          backup_cleanup(jcr, JS_ErrorTerminated, since);
179          return 0;
180       }
181    }
182 #endif
183
184    /*
185     * Open a message channel connection with the Storage
186     * daemon. This is to let him know that our client
187     * will be contacting him for a backup  session.
188     *
189     */
190    Dmsg0(10, "Open connection with storage daemon\n");
191    jcr->JobStatus = JS_Blocked;
192    /*
193     * Start conversation with Storage daemon  
194     */
195    if (!connect_to_storage_daemon(jcr, 10, SDConnectTimeout, 1)) {
196       backup_cleanup(jcr, JS_ErrorTerminated, since);
197       return 0;
198    }
199    /*
200     * Now start a job with the Storage daemon
201     */
202    if (!start_storage_daemon_job(jcr)) {
203       backup_cleanup(jcr, JS_ErrorTerminated, since);
204       return 0;
205    }
206    /*
207     * Now start a Storage daemon message thread
208     */
209    if (!start_storage_daemon_message_thread(jcr)) {
210       backup_cleanup(jcr, JS_ErrorTerminated, since);
211       return 0;
212    }
213
214    Dmsg0(50, "Storage daemon connection OK\n");
215
216    if (!connect_to_file_daemon(jcr, 10, FDConnectTimeout, 1)) {
217       backup_cleanup(jcr, JS_ErrorTerminated, since);
218       return 0;
219    }
220
221    jcr->JobStatus = JS_Running;
222    fd = jcr->file_bsock;
223
224    if (!send_include_list(jcr)) {
225       backup_cleanup(jcr, JS_ErrorTerminated, since);
226       return 0;
227    }
228
229    if (!send_exclude_list(jcr)) {
230       backup_cleanup(jcr, JS_ErrorTerminated, since);
231       return 0;
232    }
233
234    /* 
235     * send Storage daemon address to the File daemon
236     */
237    if (jcr->store->SDDport == 0) {
238       jcr->store->SDDport = jcr->store->SDport;
239    }
240    bnet_fsend(fd, storaddr, jcr->store->address, jcr->store->SDDport);
241    if (!response(fd, OKstore, "Storage")) {
242       backup_cleanup(jcr, JS_ErrorTerminated, since);
243       return 0;
244    }
245
246    /* 
247     * Send Level command to File daemon
248     */
249    switch (jcr->level) {
250       case L_FULL:
251          bnet_fsend(fd, levelcmd, "full", " ");
252          break;
253       case L_DIFFERENTIAL:
254       case L_INCREMENTAL:
255          bnet_fsend(fd, levelcmd, "since ", jcr->stime);
256          free_pool_memory(jcr->stime);
257          jcr->stime = NULL;
258          break;
259       case L_SINCE:
260       default:
261          Emsg1(M_FATAL, 0, _("Unimplemented backup level %d\n"), jcr->level);
262          backup_cleanup(jcr, JS_ErrorTerminated, since);
263          return 0;
264    }
265    Dmsg1(20, ">filed: %s", fd->msg);
266    if (!response(fd, OKlevel, "Level")) {
267       backup_cleanup(jcr, JS_ErrorTerminated, since);
268       return 0;
269    }
270
271    /* Send backup command */
272    bnet_fsend(fd, backupcmd);
273    if (!response(fd, OKbackup, "backup")) {
274       backup_cleanup(jcr, JS_ErrorTerminated, since);
275       return 0;
276    }
277
278    /* Pickup Job termination data */        
279    stat = wait_for_job_termination(jcr);
280    backup_cleanup(jcr, stat, since);
281    return 1;
282 }
283
284 /*
285  *  NOTE! This is no longer really needed as the Storage
286  *        daemon now passes this information directly
287  *        back to us.   
288  */
289 static int wait_for_job_termination(JCR *jcr)
290 {
291    int32_t n = 0;
292    BSOCK *fd = jcr->file_bsock;
293
294    jcr->JobStatus = JS_WaitFD;
295    /* Wait for Client to terminate */
296    while ((n = bget_msg(fd, 0)) > 0 && !job_cancelled(jcr)) {
297       /* get and discard Client output */
298    }
299    bnet_sig(fd, BNET_TERMINATE);      /* tell Client we are terminating */
300    if (n < 0) {
301       Jmsg(jcr, M_FATAL, 0, _("<filed: network error during BACKUP command. ERR=%s\n"),
302           bnet_strerror(fd));
303    }
304
305    /* Now wait for Storage daemon to terminate our message thread */
306    P(jcr->mutex);
307    jcr->JobStatus = JS_WaitSD;
308    while (!jcr->msg_thread_done && !job_cancelled(jcr)) {
309       struct timeval tv;
310       struct timezone tz;
311       struct timespec timeout;
312
313       gettimeofday(&tv, &tz);
314       timeout.tv_nsec = 0;
315       timeout.tv_sec = tv.tv_sec + 10; /* wait 10 seconds */
316       Dmsg0(300, "I'm waiting for message thread termination.\n");
317       pthread_cond_timedwait(&jcr->term_wait, &jcr->mutex, &timeout);
318    }
319    V(jcr->mutex);
320    if (n < 0) {                                     
321       return JS_ErrorTerminated;
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)
330 {
331    char sdt[50], edt[50];
332    char ec1[30], ec2[30], ec3[30];
333    char term_code[100];
334    char *term_msg;
335    int msg_type;
336    MEDIA_DBR mr;
337
338    Dmsg0(100, "Enter backup_cleanup()\n");
339    memset(&mr, 0, sizeof(mr));
340    jcr->JobStatus = TermCode;
341
342    update_job_end_record(jcr);        /* update database */
343    
344    if (!db_get_job_record(jcr->db, &jcr->jr)) {
345       Jmsg(jcr, M_WARNING, 0, _("Error getting job record for stats: %s"), 
346          db_strerror(jcr->db));
347    }
348
349    strcpy(mr.VolumeName, jcr->VolumeName);
350    if (!db_get_media_record(jcr->db, &mr)) {
351       Jmsg(jcr, M_WARNING, 0, _("Error getting Media record for stats: %s"), 
352          db_strerror(jcr->db));
353    }
354
355       
356    msg_type = M_INFO;                 /* by default INFO message */
357    switch (TermCode) {
358       case JS_Terminated:
359          term_msg = _("Backup OK");
360          break;
361       case JS_FatalError:
362       case JS_ErrorTerminated:
363          term_msg = _("*** Backup Error ***"); 
364          msg_type = M_ERROR;          /* Generate error message */
365          if (jcr->store_bsock) {
366             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
367             pthread_cancel(jcr->SD_msg_chan);
368          }
369          break;
370       case JS_Cancelled:
371          term_msg = _("Backup Cancelled");
372          if (jcr->store_bsock) {
373             bnet_sig(jcr->store_bsock, BNET_TERMINATE);
374             pthread_cancel(jcr->SD_msg_chan);
375          }
376          break;
377       default:
378          term_msg = term_code;
379          sprintf(term_code, _("Inappropriate term code: %c\n"), TermCode);
380          break;
381    }
382    bstrftime(sdt, sizeof(sdt), jcr->jr.StartTime);
383    bstrftime(edt, sizeof(edt), jcr->jr.EndTime);
384    if (!db_get_job_volume_names(jcr->db, jcr->jr.JobId, jcr->VolumeName)) {
385       jcr->VolumeName[0] = 0;         /* none */
386    }
387
388    Jmsg(jcr, msg_type, 0, _("%s\n\
389 JobId:                  %d\n\
390 Job:                    %s\n\
391 FileSet:                %s\n\
392 Backup Level:           %s%s\n\
393 Client:                 %s\n\
394 Start time:             %s\n\
395 End time:               %s\n\
396 Bytes Written:          %s\n\
397 Files Written:          %s\n\
398 Volume names(s):        %s\n\
399 Volume Session Id:      %d\n\
400 Volume Session Time:    %d\n\
401 Volume Bytes:           %s\n\
402 Termination:            %s\n\n"),
403         edt,
404         jcr->jr.JobId,
405         jcr->jr.Job,
406         jcr->fileset->hdr.name,
407         level_to_str(jcr->level), since,
408         jcr->client->hdr.name,
409         sdt,
410         edt,
411         edit_uint64_with_commas(jcr->jr.JobBytes, ec1),
412         edit_uint64_with_commas(jcr->jr.JobFiles, ec2),
413         jcr->VolumeName,
414         jcr->VolSessionId,
415         jcr->VolSessionTime,
416         edit_uint64_with_commas(mr.VolBytes, ec3),
417         term_msg);
418
419    Dmsg0(100, "Leave backup_cleanup()\n");
420 }