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