]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Jobq.c race bug fixed + minor updates
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2  *
3  *   Bacula Director daemon -- this is the main program
4  *
5  *     Kern Sibbald, March MM
6  *
7  *   Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2004 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 terminate_dird(int sig);
34 static int check_resources();
35
36 /* Exported subroutines */
37 void reload_config(int sig);
38
39
40 /* Imported subroutines */
41 JCR *wait_for_next_job(char *runjob);
42 void term_scheduler();
43 void term_ua_server();
44 int do_backup(JCR *jcr);
45 void backup_cleanup(void);
46 void start_UA_server(char *addr, int port);
47 void init_job_server(int max_workers);
48 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
49 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
50 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
51
52 static char *configfile = NULL;
53 static char *runjob = NULL;
54 static int background = 1;
55 static void init_reload(void);
56
57 /* Globals Exported */
58 DIRRES *director;                     /* Director resource */
59 int FDConnectTimeout;
60 int SDConnectTimeout;
61
62 /* Globals Imported */
63 extern int r_first, r_last;           /* first and last resources */
64 extern RES_TABLE resources[];
65 extern RES_ITEM job_items[];
66 extern URES res_all;
67
68
69 #define CONFIG_FILE "./bacula-dir.conf" /* default configuration file */
70
71 static void usage()
72 {
73    fprintf(stderr, _(
74 "\nVersion: " VERSION " (" BDATE ")\n\n"
75 "Usage: dird [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
76 "       -c <file>   set configuration file to file\n"
77 "       -dnn        set debug level to nn\n"
78 "       -f          run in foreground (for debugging)\n"
79 "       -g          groupid\n"
80 "       -r <job>    run <job> now\n"
81 "       -s          no signals\n"
82 "       -t          test - read configuration and exit\n"
83 "       -u          userid\n"
84 "       -v          verbose user messages\n"
85 "       -?          print this message.\n"  
86 "\n"));
87
88    exit(1);
89 }
90
91
92 /*********************************************************************
93  *
94  *         Main Bacula Server program
95  *
96  */
97 int main (int argc, char *argv[])
98 {
99    int ch;
100    JCR *jcr;
101    int no_signals = FALSE;
102    int test_config = FALSE;
103    char *uid = NULL;
104    char *gid = NULL;
105
106    init_stack_dump();
107    my_name_is(argc, argv, "bacula-dir");
108    textdomain("bacula");
109    init_msg(NULL, NULL);              /* initialize message handler */
110    init_reload();
111    daemon_start_time = time(NULL);
112
113    while ((ch = getopt(argc, argv, "c:d:fg:r:stu:v?")) != -1) {
114       switch (ch) {
115       case 'c':                    /* specify config file */
116          if (configfile != NULL) {
117             free(configfile);
118          }
119          configfile = bstrdup(optarg);
120          break;
121
122       case 'd':                    /* set debug level */
123          debug_level = atoi(optarg);
124          if (debug_level <= 0) {
125             debug_level = 1; 
126          }
127          Dmsg1(0, "Debug level = %d\n", debug_level);
128          break;
129
130       case 'f':                    /* run in foreground */
131          background = FALSE;
132          break;
133
134       case 'g':                    /* set group id */
135          gid = optarg;
136          break;
137
138       case 'r':                    /* run job */
139          if (runjob != NULL) {
140             free(runjob);
141          }
142          if (optarg) {
143             runjob = bstrdup(optarg);
144          }
145          break;
146
147       case 's':                    /* turn off signals */
148          no_signals = TRUE;
149          break;
150
151       case 't':                    /* test config */
152          test_config = TRUE;
153          break;
154
155       case 'u':                    /* set uid */
156          uid = optarg;
157          break;
158
159       case 'v':                    /* verbose */
160          verbose++;
161          break;
162
163       case '?':
164       default:
165          usage();
166
167       }  
168    }
169    argc -= optind;
170    argv += optind;
171
172    if (!no_signals) {
173       init_signals(terminate_dird);
174    }
175
176    if (argc) {
177       if (configfile != NULL) {
178          free(configfile);
179       }
180       configfile = bstrdup(*argv);
181       argc--; 
182       argv++;
183    }
184    if (argc) {
185       usage();
186    }
187
188    if (configfile == NULL) {
189       configfile = bstrdup(CONFIG_FILE);
190    }
191
192    parse_config(configfile);
193
194    if (!check_resources()) {
195       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
196    }
197
198    if (test_config) {
199       terminate_dird(0);
200    }
201
202    my_name_is(0, NULL, director->hdr.name);    /* set user defined name */
203
204    FDConnectTimeout = (int)director->FDConnectTimeout;
205    SDConnectTimeout = (int)director->SDConnectTimeout;
206
207    if (background) {
208       daemon_start();
209       init_stack_dump();              /* grab new pid */
210    }
211
212    /* Create pid must come after we are a daemon -- so we have our final pid */
213    create_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
214    read_state_file(director->working_directory, "bacula-dir", director->DIRport);
215
216    drop(uid, gid);                    /* reduce priveleges if requested */
217
218    signal(SIGHUP, reload_config);
219
220    init_console_msg(working_directory);
221
222    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
223       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
224
225    Dmsg0(200, "Start UA server\n");
226    start_UA_server(director->DIRaddr, director->DIRport);
227
228    start_watchdog();                  /* start network watchdog thread */
229
230    init_jcr_subsystem();              /* start JCR watchdogs etc. */
231
232    init_job_server(director->MaxConcurrentJobs);
233   
234    Dmsg0(200, "wait for next job\n");
235    /* Main loop -- call scheduler to get next job to run */
236    while ((jcr = wait_for_next_job(runjob))) {
237       run_job(jcr);                   /* run job */
238       free_jcr(jcr);                  /* release jcr */
239       if (runjob) {                   /* command line, run a single job? */
240          break;                       /* yes, terminate */
241       }
242    }
243
244    terminate_dird(0);
245 }
246
247 /* Cleanup and then exit */
248 static void terminate_dird(int sig)
249 {
250    static int already_here = FALSE;
251
252    if (already_here) {                /* avoid recursive temination problems */
253       exit(1);
254    }
255    already_here = TRUE;
256    write_state_file(director->working_directory, "bacula-dir", director->DIRport);
257    delete_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
258 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
259    term_scheduler();
260    if (runjob) {
261       free(runjob);
262    }
263    if (configfile != NULL) {
264       free(configfile);
265    }
266    if (debug_level > 5) {
267       print_memory_pool_stats(); 
268    }
269    free_config_resources();
270    term_ua_server();
271    term_msg();                        /* terminate message handler */
272    stop_watchdog();
273    close_memory_pool();               /* release free memory in pool */
274    sm_dump(false);
275    exit(sig);
276 }
277
278 struct RELOAD_TABLE {
279    int job_count;
280    RES **res_table;
281 };
282
283 static const int max_reloads = 10;
284 static RELOAD_TABLE reload_table[max_reloads];
285
286 static void init_reload(void) 
287 {
288    for (int i=0; i < max_reloads; i++) {
289       reload_table[i].job_count = 0;
290       reload_table[i].res_table = NULL;
291    }
292 }
293
294 static void free_saved_resources(int table)
295 {
296    int num = r_last - r_first + 1;
297    RES **res_tab = reload_table[table].res_table;
298    Dmsg1(000, "Freeing resources for table %d\n", table);
299    for (int j=0; j<num; j++) {
300       free_resource(res_tab[j], r_first + j);
301    }
302    free(res_tab);
303    reload_table[table].job_count = 0;
304    reload_table[table].res_table = NULL;
305 }
306
307 /*
308  * Called here at the end of every job that was
309  * hooked decrementing the active job_count. When
310  * it goes to zero, no one is using the associated
311  * resource table, so free it.
312  */
313 static void reload_job_end_cb(JCR *jcr)
314 {
315    int i = jcr->reload_id - 1;
316    Dmsg1(000, "reload job_end JobId=%d\n", jcr->JobId);
317    lock_jcr_chain();
318    LockRes();
319    if (--reload_table[i].job_count <= 0) {
320       free_saved_resources(i);
321    }
322    UnlockRes();
323    unlock_jcr_chain();
324 }
325
326 static int find_free_table()
327 {
328    int table = -1;
329    for (int i=0; i < max_reloads; i++) {
330       if (reload_table[i].res_table == NULL) {
331          table = i;
332          break;
333       }
334    }
335    return table;
336 }
337
338 /*
339  * If we get here, we have received a SIGHUP, which means to
340  *    reread our configuration file. 
341  */
342 void reload_config(int sig)
343 {
344    static bool already_here = false;
345    sigset_t set;        
346    JCR *jcr;
347    int njobs = 0;
348    int table, rtable;
349
350    if (already_here) {
351       abort();                        /* Oops, recursion -> die */
352    }
353    already_here = true;
354    sigfillset(&set);
355    sigprocmask(SIG_BLOCK, &set, NULL);
356
357    lock_jcr_chain();
358    LockRes();
359
360    table = find_free_table();
361    if (table < 0) {
362       Jmsg(NULL, M_ERROR, 0, _("Too many reload requests.\n"));
363       goto bail_out;
364    }
365
366    /*
367     * Hook all active jobs that are not already hooked (i.e.
368     *  reload_id == 0
369     */
370    foreach_jcr(jcr) {
371       if (jcr->reload_id == 0) {
372          reload_table[table].job_count++;
373          jcr->reload_id = table + 1;
374          job_end_push(jcr, reload_job_end_cb);
375          njobs++;
376       }
377       free_locked_jcr(jcr);
378    }
379    Dmsg1(000, "Reload_config njobs=%d\n", njobs);
380    reload_table[table].res_table = save_config_resources();
381    Dmsg1(000, "Saved old config in table %d\n", table);
382
383    Dmsg0(000, "Calling parse config\n");
384    parse_config(configfile);
385
386    Dmsg0(000, "Reloaded config file\n");
387    if (!check_resources()) {
388       rtable = find_free_table();     /* save new, bad table */
389       if (rtable < 0) {
390          Jmsg(NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
391       } else {
392          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
393       }
394       reload_table[rtable].res_table = save_config_resources();
395       /* Now restore old resoure values */
396       int num = r_last - r_first + 1;
397       RES **res_tab = reload_table[table].res_table;
398       for (int i=0; i<num; i++) {
399          resources[i].res_head = res_tab[i];
400       }
401       table = rtable;                 /* release new, bad, saved table below */
402    }
403
404    /* Reset globals */
405    set_working_directory(director->working_directory);
406    FDConnectTimeout = director->FDConnectTimeout;
407    SDConnectTimeout = director->SDConnectTimeout;
408    Dmsg0(0, "Director's configuration file reread.\n");
409         
410    /* Now release saved resources */
411    free_saved_resources(table);
412
413 bail_out:
414    UnlockRes();
415    unlock_jcr_chain();
416    sigprocmask(SIG_UNBLOCK, &set, NULL);
417    signal(SIGHUP, reload_config);
418    already_here = false;
419 }
420
421 /*
422  * Make a quick check to see that we have all the
423  * resources needed.
424  *
425  *  **** FIXME **** this routine could be a lot more
426  *   intelligent and comprehensive.
427  */
428 static int check_resources()
429 {
430    bool OK = true;
431    JOB *job;
432
433    LockRes();
434
435    job = (JOB *)GetNextRes(R_JOB, NULL);
436    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
437    if (!director) {
438       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n\
439 Without that I don't know who I am :-(\n"), configfile);
440       OK = false;
441    } else {
442       set_working_directory(director->working_directory);
443       if (!director->messages) {       /* If message resource not specified */
444          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
445          if (!director->messages) {
446             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
447             OK = false;
448          }
449       }
450       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
451          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
452             configfile);
453          OK = false;
454       } 
455    }
456
457    if (!job) {
458       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
459       OK = false;
460    }
461    foreach_res(job, R_JOB) {
462       int i;
463
464       if (job->jobdefs) {
465          /* Transfer default items from JobDefs Resource */
466          for (i=0; job_items[i].name; i++) {
467             char **def_svalue, **svalue;  /* string value */
468             int *def_ivalue, *ivalue;     /* integer value */
469             int64_t *def_lvalue, *lvalue; /* 64 bit values */
470             uint32_t offset;
471
472             Dmsg4(400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
473                 job->hdr.name, job_items[i].name, 
474                 bit_is_set(i, job->hdr.item_present),  
475                 bit_is_set(i, job->jobdefs->hdr.item_present));
476
477             if (!bit_is_set(i, job->hdr.item_present) &&
478                  bit_is_set(i, job->jobdefs->hdr.item_present)) { 
479                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
480                  job->hdr.name, job_items[i].name);
481                offset = (char *)(job_items[i].value) - (char *)&res_all;   
482                /*
483                 * Handle strings and directory strings
484                 */
485                if (job_items[i].handler == store_str ||
486                    job_items[i].handler == store_dir) {
487                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
488                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n", 
489                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
490                   svalue = (char **)((char *)job + offset);
491                   if (*svalue) {
492                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
493                   }
494                   *svalue = bstrdup(*def_svalue);
495                   set_bit(i, job->hdr.item_present);
496                } else if (job_items[i].handler == store_res) {
497                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
498                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n", 
499                        job->hdr.name, job_items[i].name, i, offset);
500                   svalue = (char **)((char *)job + offset);
501                   if (*svalue) {
502                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
503                   }
504                   *svalue = *def_svalue;
505                   set_bit(i, job->hdr.item_present);
506                /*
507                 * Handle integer fields 
508                 *    Note, our store_yesno does not handle bitmaped fields
509                 */
510                } else if (job_items[i].handler == store_yesno   ||
511                           job_items[i].handler == store_pint    ||
512                           job_items[i].handler == store_jobtype ||
513                           job_items[i].handler == store_level   ||
514                           job_items[i].handler == store_pint    ||
515                           job_items[i].handler == store_replace) {
516                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
517                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n", 
518                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
519                   ivalue = (int *)((char *)job + offset);
520                   *ivalue = *def_ivalue;
521                   set_bit(i, job->hdr.item_present);
522                /*
523                 * Handle 64 bit integer fields 
524                 */
525                } else if (job_items[i].handler == store_time   ||
526                           job_items[i].handler == store_size   ||
527                           job_items[i].handler == store_int64) {
528                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
529                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n", 
530                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
531                   lvalue = (int64_t *)((char *)job + offset);
532                   *lvalue = *def_lvalue;
533                   set_bit(i, job->hdr.item_present);
534                }
535             }
536          }
537       }
538       /* 
539        * Ensure that all required items are present
540        */
541       for (i=0; job_items[i].name; i++) {
542          if (job_items[i].flags & ITEM_REQUIRED) {
543                if (!bit_is_set(i, job->hdr.item_present)) {  
544                   Jmsg(NULL, M_FATAL, 0, "Field \"%s\" in Job \"%s\" resource is required, but not found.\n",
545                     job_items[i].name, job->hdr.name);
546                   OK = false;
547                 }
548          }
549          /* If this triggers, take a look at lib/parse_conf.h */
550          if (i >= MAX_RES_ITEMS) {
551             Emsg0(M_ERROR_TERM, 0, "Too many items in Job resource\n");
552          }
553       }
554       if (job->client && job->client->catalog) {
555          CAT *catalog = job->client->catalog;
556          B_DB *db;
557
558          /*
559           * Make sure we can open catalog, otherwise print a warning
560           * message because the server is probably not running.
561           */
562          db = db_init_database(NULL, catalog->db_name, catalog->db_user,
563                             catalog->db_password, catalog->db_address,
564                             catalog->db_port, catalog->db_socket);
565          if (!db || !db_open_database(NULL, db)) {
566             Jmsg(NULL, M_FATAL, 0, _("Could not open database \"%s\".\n"),
567                  catalog->db_name);
568             if (db) {
569                Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
570             }
571             OK = false;
572          } else {
573             /* If a pool is defined for this job, create the pool DB       
574              *  record if it is not already created. 
575              */
576             if (job->pool) {
577                create_pool(NULL, db, job->pool, POOL_OP_UPDATE);  /* update request */
578             }
579             /* Set default value in all counters */
580             COUNTER *counter;
581             foreach_res(counter, R_COUNTER) {
582                /* Write to catalog? */
583                if (!counter->created && counter->Catalog == catalog) {
584                   COUNTER_DBR cr;
585                   bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
586                   cr.MinValue = counter->MinValue;
587                   cr.MaxValue = counter->MaxValue;
588                   cr.CurrentValue = counter->MinValue;
589                   if (counter->WrapCounter) {
590                      bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
591                   } else {
592                      cr.WrapCounter[0] = 0;  /* empty string */
593                   }
594                   if (db_create_counter_record(NULL, db, &cr)) {
595                      counter->CurrentValue = cr.CurrentValue;
596                      counter->created = true;
597                      Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
598                   }
599                } 
600                if (!counter->created) {
601                   counter->CurrentValue = counter->MinValue;  /* default value */
602                }
603             }
604          }
605          db_close_database(NULL, db);
606       }
607    }
608
609    UnlockRes();
610    if (OK) {
611       close_msg(NULL);                /* close temp message handler */
612       init_msg(NULL, director->messages); /* open daemon message handler */
613    }
614    return OK;
615 }