]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
Drop old semaphore and workq code
[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
35 /* Exported subroutines */
36
37
38 /* Imported subroutines */
39 extern void term_scheduler();
40 extern void term_ua_server();
41 extern int do_backup(JCR *jcr);
42 extern int do_admin(JCR *jcr);
43 extern int do_restore(JCR *jcr);
44 extern int do_verify(JCR *jcr);
45
46 jobq_t  job_queue;
47
48 void init_job_server(int max_workers)
49 {
50    int stat;
51    if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
52       Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), strerror(stat));
53    }
54    return;
55 }
56
57 /*
58  * Run a job -- typically called by the scheduler, but may also
59  *              be called by the UA (Console program).
60  *
61  */
62 void run_job(JCR *jcr)
63 {
64    int stat, errstat;
65
66    sm_check(__FILE__, __LINE__, True);
67    init_msg(jcr, jcr->messages);
68    create_unique_job_name(jcr, jcr->job->hdr.name);
69    set_jcr_job_status(jcr, JS_Created);
70    jcr->jr.SchedTime = jcr->sched_time;
71    jcr->jr.StartTime = jcr->start_time;
72    jcr->jr.Type = jcr->JobType;
73    jcr->jr.Level = jcr->JobLevel;
74    jcr->jr.JobStatus = jcr->JobStatus;
75    bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
76    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
77
78    /* Initialize termination condition variable */
79    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
80       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
81       set_jcr_job_status(jcr, JS_ErrorTerminated);
82       free_jcr(jcr);
83       return;
84    }
85
86    /*
87     * Open database
88     */
89    Dmsg0(50, "Open database\n");
90    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
91                             jcr->catalog->db_password, jcr->catalog->db_address,
92                             jcr->catalog->db_port, jcr->catalog->db_socket);
93    if (!jcr->db || !db_open_database(jcr, jcr->db)) {
94       Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
95                  jcr->catalog->db_name);
96       if (jcr->db) {
97          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
98       }
99       set_jcr_job_status(jcr, 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, jcr->db, &jcr->jr)) {
110       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
111       set_jcr_job_status(jcr, JS_ErrorTerminated);
112       free_jcr(jcr);
113       return;
114    }
115    jcr->JobId = jcr->jr.JobId;
116    ASSERT(jcr->jr.JobId > 0);
117
118    Dmsg4(50, "Created job record JobId=%d Name=%s Type=%c Level=%c\n", 
119        jcr->JobId, jcr->Job, jcr->jr.Type, jcr->jr.Level);
120    Dmsg0(200, "Add jrc to work queue\n");
121
122    /* Queue the job to be run */
123    if ((stat = jobq_add(&job_queue, jcr)) != 0) {
124       Emsg1(M_ABORT, 0, _("Could not add job queue: ERR=%s\n"), strerror(stat));
125    }
126    Dmsg0(100, "Done run_job()\n");
127 }
128
129 /* 
130  * This is the engine called by job_add() when we were pulled                
131  *  from the work queue.
132  *  At this point, we are running in our own thread and all
133  *    necessary resources are allocated -- see jobq.c
134  */
135 static void *job_thread(void *arg)
136 {
137    JCR *jcr = (JCR *)arg;
138
139    pthread_detach(pthread_self());
140    sm_check(__FILE__, __LINE__, True);
141
142    for ( ;; ) {
143
144       Dmsg0(200, "=====Start Job=========\n");
145       jcr->start_time = time(NULL);      /* set the real start time */
146       set_jcr_job_status(jcr, JS_Running);
147
148       if (job_canceled(jcr)) {
149          update_job_end_record(jcr);
150       } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
151           (utime_t)(jcr->start_time - jcr->sched_time)) {
152          Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
153          set_jcr_job_status(jcr, JS_Canceled);
154          update_job_end_record(jcr);
155       } else {
156
157          /* Run Job */
158          if (jcr->job->RunBeforeJob) {
159             POOLMEM *before = get_pool_memory(PM_FNAME);
160             int status;
161             BPIPE *bpipe;
162             char line[MAXSTRING];
163             
164             before = edit_job_codes(jcr, before, jcr->job->RunBeforeJob, "");
165             bpipe = open_bpipe(before, 0, "r");
166             free_pool_memory(before);
167             while (fgets(line, sizeof(line), bpipe->rfd)) {
168                Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
169             }
170             status = close_bpipe(bpipe);
171             if (status != 0) {
172                Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob returned non-zero status=%d\n"),
173                   status);
174                set_jcr_job_status(jcr, JS_FatalError);
175                update_job_end_record(jcr);
176                goto bail_out;
177             }
178          }
179          switch (jcr->JobType) {
180          case JT_BACKUP:
181             do_backup(jcr);
182             if (jcr->JobStatus == JS_Terminated) {
183                do_autoprune(jcr);
184             }
185             break;
186          case JT_VERIFY:
187             do_verify(jcr);
188             if (jcr->JobStatus == JS_Terminated) {
189                do_autoprune(jcr);
190             }
191             break;
192          case JT_RESTORE:
193             do_restore(jcr);
194             if (jcr->JobStatus == JS_Terminated) {
195                do_autoprune(jcr);
196             }
197             break;
198          case JT_ADMIN:
199             do_admin(jcr);
200             if (jcr->JobStatus == JS_Terminated) {
201                do_autoprune(jcr);
202             }
203             break;
204          default:
205             Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
206             break;
207          }
208          if (jcr->job->RunAfterJob) {
209             POOLMEM *after = get_pool_memory(PM_FNAME);
210             int status;
211             BPIPE *bpipe;
212             char line[MAXSTRING];
213             
214             after = edit_job_codes(jcr, after, jcr->job->RunAfterJob, "");
215             bpipe = open_bpipe(after, 0, "r");
216             free_pool_memory(after);
217             while (fgets(line, sizeof(line), bpipe->rfd)) {
218                Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
219             }
220             status = close_bpipe(bpipe);
221             if (status != 0) {
222                Jmsg(jcr, M_FATAL, 0, _("RunAfterJob returned non-zero status=%d\n"),
223                   status);
224                set_jcr_job_status(jcr, JS_FatalError);
225                update_job_end_record(jcr);
226             }
227          }
228       }
229 bail_out:
230       break;
231    }
232
233    Dmsg0(50, "======== End Job ==========\n");
234    sm_check(__FILE__, __LINE__, True);
235    return NULL;
236 }
237
238
239 /*
240  * Get or create a Client record for this Job
241  */
242 int get_or_create_client_record(JCR *jcr)
243 {
244    CLIENT_DBR cr;
245
246    memset(&cr, 0, sizeof(cr));
247    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
248    cr.AutoPrune = jcr->client->AutoPrune;
249    cr.FileRetention = jcr->client->FileRetention;
250    cr.JobRetention = jcr->client->JobRetention;
251    if (!jcr->client_name) {
252       jcr->client_name = get_pool_memory(PM_NAME);
253    }
254    pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
255    if (!db_create_client_record(jcr, jcr->db, &cr)) {
256       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"), 
257          db_strerror(jcr->db));
258       return 0;
259    }
260    jcr->jr.ClientId = cr.ClientId;
261    if (cr.Uname[0]) {
262       if (!jcr->client_uname) {
263          jcr->client_uname = get_pool_memory(PM_NAME);
264       }
265       pm_strcpy(&jcr->client_uname, cr.Uname);
266    }
267    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name, 
268       jcr->jr.ClientId);
269    return 1;
270 }
271
272
273 /*
274  * Write status and such in DB
275  */
276 void update_job_end_record(JCR *jcr)
277 {
278    if (jcr->jr.EndTime == 0) {
279       jcr->jr.EndTime = time(NULL);
280    }
281    jcr->end_time = jcr->jr.EndTime;
282    jcr->jr.JobId = jcr->JobId;
283    jcr->jr.JobStatus = jcr->JobStatus;
284    jcr->jr.JobFiles = jcr->JobFiles;
285    jcr->jr.JobBytes = jcr->JobBytes;
286    jcr->jr.VolSessionId = jcr->VolSessionId;
287    jcr->jr.VolSessionTime = jcr->VolSessionTime;
288    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
289       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"), 
290          db_strerror(jcr->db));
291    }
292 }
293
294 /*
295  * Takes base_name and appends (unique) current
296  *   date and time to form unique job name.
297  *
298  *  Returns: unique job name in jcr->Job
299  *    date/time in jcr->start_time
300  */
301 void create_unique_job_name(JCR *jcr, char *base_name)
302 {
303    /* Job start mutex */
304    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
305    static time_t last_start_time = 0;
306    time_t now;
307    struct tm tm;
308    char dt[MAX_TIME_LENGTH];
309    char name[MAX_NAME_LENGTH];
310    char *p;
311
312    /* Guarantee unique start time -- maximum one per second, and
313     * thus unique Job Name 
314     */
315    P(mutex);                          /* lock creation of jobs */
316    now = time(NULL);
317    while (now == last_start_time) {
318       bmicrosleep(0, 500000);
319       now = time(NULL);
320    }
321    last_start_time = now;
322    V(mutex);                          /* allow creation of jobs */
323    jcr->start_time = now;
324    /* Form Unique JobName */
325    localtime_r(&now, &tm);
326    /* Use only characters that are permitted in Windows filenames */
327    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm); 
328    bstrncpy(name, base_name, sizeof(name));
329    name[sizeof(name)-22] = 0;          /* truncate if too long */
330    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
331    /* Convert spaces into underscores */
332    for (p=jcr->Job; *p; p++) {
333       if (*p == ' ') {
334          *p = '_';
335       }
336    }
337 }
338
339 /*
340  * Free the Job Control Record if no one is still using it.
341  *  Called from main free_jcr() routine in src/lib/jcr.c so
342  *  that we can do our Director specific cleanup of the jcr.
343  */
344 void dird_free_jcr(JCR *jcr)
345 {
346    Dmsg0(200, "Start dird free_jcr\n");
347
348    if (jcr->sd_auth_key) {
349       free(jcr->sd_auth_key);
350       jcr->sd_auth_key = NULL;
351    }
352    if (jcr->where) {
353       free(jcr->where);
354       jcr->where = NULL;
355    }
356    if (jcr->file_bsock) {
357       Dmsg0(200, "Close File bsock\n");
358       bnet_close(jcr->file_bsock);
359       jcr->file_bsock = NULL;
360    }
361    if (jcr->store_bsock) {
362       Dmsg0(200, "Close Store bsock\n");
363       bnet_close(jcr->store_bsock);
364       jcr->store_bsock = NULL;
365    }
366    if (jcr->fname) {  
367       Dmsg0(200, "Free JCR fname\n");
368       free_pool_memory(jcr->fname);
369       jcr->fname = NULL;
370    }
371    if (jcr->stime) {
372       Dmsg0(200, "Free JCR stime\n");
373       free_pool_memory(jcr->stime);
374       jcr->stime = NULL;
375    }
376    if (jcr->RestoreBootstrap) {
377       free(jcr->RestoreBootstrap);
378       jcr->RestoreBootstrap = NULL;
379    }
380    if (jcr->client_uname) {
381       free_pool_memory(jcr->client_uname);
382       jcr->client_uname = NULL;
383    }
384    Dmsg0(200, "End dird free_jcr\n");
385 }
386
387 /*
388  * Set some defaults in the JCR necessary to
389  * run. These items are pulled from the job
390  * definition as defaults, but can be overridden
391  * later either by the Run record in the Schedule resource,
392  * or by the Console program.
393  */
394 void set_jcr_defaults(JCR *jcr, JOB *job)
395 {
396    jcr->job = job;
397    jcr->JobType = job->JobType;
398    jcr->JobLevel = job->level;
399    jcr->JobPriority = job->Priority;
400    jcr->store = job->storage;
401    jcr->client = job->client;
402    if (!jcr->client_name) {
403       jcr->client_name = get_pool_memory(PM_NAME);
404    }
405    pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
406    jcr->pool = job->pool;
407    jcr->catalog = job->client->catalog;
408    jcr->fileset = job->fileset;
409    jcr->messages = job->messages; 
410    if (jcr->RestoreBootstrap) {
411       free(jcr->RestoreBootstrap);
412    }
413    /* This can be overridden by Console program */
414    if (job->RestoreBootstrap) {
415       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
416    }
417    /* If no default level given, set one */
418    if (jcr->JobLevel == 0) {
419       switch (jcr->JobType) {
420       case JT_VERIFY:
421          jcr->JobLevel = L_VERIFY_CATALOG;
422          break;
423       case JT_BACKUP:
424          jcr->JobLevel = L_INCREMENTAL;
425          break;
426       case JT_RESTORE:
427       case JT_ADMIN:
428          jcr->JobLevel = L_FULL;
429          break;
430       default:
431          break;
432       }
433    }
434 }