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