]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
Last major change for 1.27 code -- see kes13Nov02
[bacula/bacula] / bacula / src / dird / job.c
1 /*
2  *
3  *   Bacula Director Job processing routines
4  *
5  *     Kern Sibbald, October MM
6  *
7  *    Version $Id$
8  */
9 /*
10    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "dird.h"
31
32 /* Forward referenced subroutines */
33 static void job_thread(void *arg);
34 static char *edit_run_codes(JCR *jcr, char *omsg, char *imsg);
35
36 /* Exported subroutines */
37 void run_job(JCR *jcr);
38 void init_job_server(int max_workers);
39
40
41 /* Imported subroutines */
42 extern void term_scheduler();
43 extern void term_ua_server();
44 extern int do_backup(JCR *jcr);
45 extern int do_restore(JCR *jcr);
46 extern int do_verify(JCR *jcr);
47 extern void backup_cleanup(void);
48
49 /* Queue of jobs to be run */
50 static workq_t job_wq;                /* our job work queue */
51
52
53 void init_job_server(int max_workers)
54 {
55    int stat;
56
57    if ((stat = workq_init(&job_wq, max_workers, job_thread)) != 0) {
58       Emsg1(M_ABORT, 0, _("Could not init job work queue: ERR=%s\n"), strerror(stat));
59    }
60    return;
61 }
62
63 /*
64  * Run a job -- typically called by the scheduler, but may also
65  *              be called by the UA (Console program).
66  *
67  */
68 void run_job(JCR *jcr)
69 {
70    int stat, errstat;
71
72    init_msg(jcr, jcr->messages);
73    create_unique_job_name(jcr, jcr->job->hdr.name);
74    jcr->jr.SchedTime = jcr->sched_time;
75    jcr->jr.StartTime = jcr->start_time;
76    jcr->jr.Type = jcr->JobType;
77    jcr->jr.Level = jcr->JobLevel;
78    jcr->jr.JobStatus = jcr->JobStatus;
79    strcpy(jcr->jr.Name, jcr->job->hdr.name);
80    strcpy(jcr->jr.Job, jcr->Job);
81
82    /* Initialize termination condition variable */
83    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
84       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
85       jcr->JobStatus = JS_ErrorTerminated;
86       free_jcr(jcr);
87       return;
88    }
89
90    /*
91     * Open database
92     */
93    Dmsg0(50, "Open database\n");
94    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
95                             jcr->catalog->db_password);
96    if (!db_open_database(jcr->db)) {
97       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
98       db_close_database(jcr->db);
99       jcr->JobStatus = JS_ErrorTerminated;
100       free_jcr(jcr);
101       return;
102    }
103    Dmsg0(50, "DB opened\n");
104
105    /*
106     * Create Job record  
107     */
108    jcr->jr.JobStatus = jcr->JobStatus;
109    if (!db_create_job_record(jcr->db, &jcr->jr)) {
110       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
111       db_close_database(jcr->db);
112       jcr->JobStatus = JS_ErrorTerminated;
113       free_jcr(jcr);
114       return;
115    }
116    jcr->JobId = jcr->jr.JobId;
117    ASSERT(jcr->jr.JobId > 0);
118
119    Dmsg4(30, "Created job record JobId=%d Name=%s Type=%c Level=%c\n", 
120        jcr->JobId, jcr->Job, jcr->jr.Type, jcr->jr.Level);
121    Dmsg0(200, "Add jrc to work queue\n");
122
123
124    /* Queue the job to be run */
125    if ((stat = workq_add(&job_wq, (void *)jcr)) != 0) {
126       Emsg1(M_ABORT, 0, _("Could not add job to work queue: ERR=%s\n"), strerror(stat));
127    }
128    Dmsg0(200, "Done run_job()\n");
129 }
130
131 /* 
132  * This is the engine called by workq_add() when we were pulled                
133  *  from the work queue.
134  *  At this point, we are running in our own thread 
135  */
136 static void job_thread(void *arg)
137 {
138    time_t now;
139    JCR *jcr = (JCR *)arg;
140
141    time(&now);
142
143    Dmsg0(100, "=====Start Job=========\n");
144    jcr->start_time = now;             /* set the real start time */
145    if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
146        (utime_t)(jcr->start_time - jcr->sched_time)) {
147       Jmsg(jcr, M_FATAL, 0, _("Job cancelled because max delay time exceeded.\n"));
148       jcr->JobStatus = JS_ErrorTerminated;
149       update_job_end_record(jcr);
150    } else {
151
152       /* Run Job */
153       jcr->JobStatus = JS_Running;
154
155       if (jcr->job->RunBeforeJob) {
156          POOLMEM *before = get_pool_memory(PM_FNAME);
157          int status;
158          
159          before = edit_run_codes(jcr, before, jcr->job->RunBeforeJob);
160          status = run_program(before, 0, NULL);
161          free_pool_memory(before);
162       }
163       switch (jcr->JobType) {
164          case JT_BACKUP:
165             do_backup(jcr);
166             if (jcr->JobStatus == JS_Terminated) {
167                do_autoprune(jcr);
168             }
169             break;
170          case JT_VERIFY:
171             do_verify(jcr);
172             if (jcr->JobStatus == JS_Terminated) {
173                do_autoprune(jcr);
174             }
175             break;
176          case JT_RESTORE:
177             do_restore(jcr);
178             if (jcr->JobStatus == JS_Terminated) {
179                do_autoprune(jcr);
180             }
181             break;
182          case JT_ADMIN:
183             /* No actual job */
184             do_autoprune(jcr);
185             jcr->JobStatus = JS_Terminated;
186             break;
187          default:
188             Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
189             break;
190          }
191    }
192    if (jcr->job->RunAfterJob) {
193       POOLMEM *after = get_pool_memory(PM_FNAME);
194       int status;
195       
196       after = edit_run_codes(jcr, after, jcr->job->RunAfterJob);
197       status = run_program(after, 0, NULL);
198       free_pool_memory(after);
199    }
200    Dmsg0(50, "Before free jcr\n");
201    free_jcr(jcr);
202    Dmsg0(50, "======== End Job ==========\n");
203 }
204
205 /*
206  * Get or create a Client record for this Job
207  */
208 int get_or_create_client_record(JCR *jcr)
209 {
210    CLIENT_DBR cr;
211
212    memset(&cr, 0, sizeof(cr));
213    strcpy(cr.Name, jcr->client->hdr.name);
214    cr.AutoPrune = jcr->client->AutoPrune;
215    cr.FileRetention = jcr->client->FileRetention;
216    cr.JobRetention = jcr->client->JobRetention;
217    if (jcr->client_name) {
218       free_pool_memory(jcr->client_name);
219    }
220    jcr->client_name = get_memory(strlen(jcr->client->hdr.name) + 1);
221    strcpy(jcr->client_name, jcr->client->hdr.name);
222    if (!db_create_client_record(jcr->db, &cr)) {
223       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. %s"), 
224          db_strerror(jcr->db));
225       return 0;
226    }
227    jcr->jr.ClientId = cr.ClientId;
228    if (cr.Uname[0]) {
229       if (jcr->client_uname) {
230          free_pool_memory(jcr->client_uname);
231       }
232       jcr->client_uname = get_memory(strlen(cr.Uname) + 1);
233       strcpy(jcr->client_uname, cr.Uname);
234    }
235    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name, 
236       jcr->jr.ClientId);
237    return 1;
238 }
239
240
241 /*
242  * Write status and such in DB
243  */
244 void update_job_end_record(JCR *jcr)
245 {
246    if (jcr->jr.EndTime == 0) {
247       jcr->jr.EndTime = time(NULL);
248    }
249    jcr->end_time = jcr->jr.EndTime;
250    jcr->jr.JobId = jcr->JobId;
251    jcr->jr.JobStatus = jcr->JobStatus;
252    jcr->jr.JobFiles = jcr->JobFiles;
253    jcr->jr.JobBytes = jcr->JobBytes;
254    jcr->jr.VolSessionId = jcr->VolSessionId;
255    jcr->jr.VolSessionTime = jcr->VolSessionTime;
256    if (!db_update_job_end_record(jcr->db, &jcr->jr)) {
257       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"), 
258          db_strerror(jcr->db));
259    }
260 }
261
262 /*
263  * Takes base_name and appends (unique) current
264  *   date and time to form unique job name.
265  *
266  *  Returns: unique job name in jcr->Job
267  *    date/time in jcr->start_time
268  */
269 void create_unique_job_name(JCR *jcr, char *base_name)
270 {
271    /* Job start mutex */
272    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
273    static time_t last_start_time = 0;
274    time_t now;
275    struct tm tm;
276    char dt[MAX_TIME_LENGTH];
277    char name[MAX_NAME_LENGTH];
278    char *p;
279
280    /* Guarantee unique start time -- maximum one per second, and
281     * thus unique Job Name 
282     */
283    P(mutex);                          /* lock creation of jobs */
284    now = time(NULL);
285    while (now == last_start_time) {
286       sleep(1);
287       now = time(NULL);
288    }
289    last_start_time = now;
290    V(mutex);                          /* allow creation of jobs */
291    jcr->start_time = now;
292    /* Form Unique JobName */
293    localtime_r(&now, &tm);
294    /* Use only characters that are permitted in Windows filenames */
295    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm); 
296    strncpy(name, base_name, sizeof(name));
297    name[sizeof(name)-22] = 0;          /* truncate if too long */
298    sprintf(jcr->Job, "%s.%s", name, dt); /* add date & time */
299    /* Convert spaces into underscores */
300    for (p=jcr->Job; *p; p++) {
301       if (*p == ' ') {
302          *p = '_';
303       }
304    }
305 }
306
307 /*
308  * Free the Job Control Record if no one is still using it.
309  *  Called from main free_jcr() routine in src/lib/jcr.c so
310  *  that we can do our Director specific cleanup of the jcr.
311  */
312 void dird_free_jcr(JCR *jcr)
313 {
314    Dmsg0(200, "Start dird free_jcr\n");
315
316    if (jcr->file_bsock) {
317       Dmsg0(200, "Close File bsock\n");
318       bnet_close(jcr->file_bsock);
319    }
320    if (jcr->store_bsock) {
321       Dmsg0(200, "Close Store bsock\n");
322       bnet_close(jcr->store_bsock);
323    }
324    if (jcr->fname) {  
325       Dmsg0(200, "Free JCR fname\n");
326       free_pool_memory(jcr->fname);
327    }
328    if (jcr->stime) {
329       Dmsg0(200, "Free JCR stime\n");
330       free_pool_memory(jcr->stime);
331    }
332    if (jcr->db) {
333       Dmsg0(200, "Close DB\n");
334       db_close_database(jcr->db);
335    }
336    if (jcr->RestoreWhere) {
337       free(jcr->RestoreWhere);
338    }
339    if (jcr->RestoreBootstrap) {
340       free(jcr->RestoreBootstrap);
341    }
342    Dmsg0(200, "End dird free_jcr\n");
343 }
344
345 /*
346  * Set some defaults in the JCR necessary to
347  * run. These items are pulled from the job
348  * definition as defaults, but can be overridden
349  * later either by the Run record in the Schedule resource,
350  * or by the Console program.
351  */
352 void set_jcr_defaults(JCR *jcr, JOB *job)
353 {
354    jcr->job = job;
355    jcr->JobType = job->JobType;
356    jcr->JobLevel = job->level;
357    jcr->store = job->storage;
358    jcr->client = job->client;
359    if (jcr->client_name) {
360       free_pool_memory(jcr->client_name);
361    }
362    jcr->client_name = get_memory(strlen(jcr->client->hdr.name) + 1);
363    strcpy(jcr->client_name, jcr->client->hdr.name);
364    jcr->pool = job->pool;
365    jcr->catalog = job->client->catalog;
366    jcr->fileset = job->fileset;
367    jcr->messages = job->messages; 
368    if (jcr->RestoreBootstrap) {
369       free(jcr->RestoreBootstrap);
370    }
371    /* This can be overridden by Console program */
372    if (job->RestoreBootstrap) {
373       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
374    }
375    /* If no default level given, set one */
376    if (jcr->JobLevel == 0) {
377       switch (jcr->JobType) {
378       case JT_VERIFY:
379          jcr->JobLevel = L_VERIFY_CATALOG;
380          break;
381       case JT_BACKUP:
382          jcr->JobLevel = L_INCREMENTAL;
383          break;
384       default:
385          break;
386       }
387    }
388 }
389
390 /*
391  * Edit codes into Run command
392  *  %% = %
393  *  %c = Client's name
394  *  %d = Director's name
395  *  %i = JobId
396  *  %e = Job Exit
397  *  %j = Job
398  *  %l = Job Level
399  *  %n = Job name
400  *  %t = Job type
401  *
402  *  omsg = edited output message
403  *  imsg = input string containing edit codes (%x)
404  *
405  */
406 static char *edit_run_codes(JCR *jcr, char *omsg, char *imsg) 
407 {
408    char *p;
409    const char *str;
410    char add[20];
411
412    *omsg = 0;
413    Dmsg1(200, "edit_run_codes: %s\n", imsg);
414    for (p=imsg; *p; p++) {
415       if (*p == '%') {
416          switch (*++p) {
417          case '%':
418             str = "%";
419             break;
420          case 'c':
421             str = jcr->client_name;
422             if (!str) {
423                str = "";
424             }
425             break;
426          case 'd':
427             str = my_name;
428             break;
429          case 'e':
430             str = job_status_to_str(jcr->JobStatus);
431             break;
432          case 'i':
433             sprintf(add, "%d", jcr->JobId);
434             str = add;
435             break;
436          case 'j':                    /* Job */
437             str = jcr->Job;
438             break;
439          case 'l':
440             str = job_level_to_str(jcr->JobLevel);
441             break;
442          case 'n':
443             str = jcr->job->hdr.name;
444             break;
445          case 't':
446             str = job_type_to_str(jcr->JobType);
447             break;
448          default:
449             add[0] = '%';
450             add[1] = *p;
451             add[2] = 0;
452             str = add;
453             break;
454          }
455       } else {
456          add[0] = *p;
457          add[1] = 0;
458          str = add;
459       }
460       Dmsg1(200, "add_str %s\n", str);
461       pm_strcat(&omsg, (char *)str);
462       Dmsg1(200, "omsg=%s\n", omsg);
463    }
464    return omsg;
465 }