]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Turn off debug code in jobq.c
[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-2006 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
14    version 2 as amended with additional clauses defined in the
15    file LICENSE in the main source directory.
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 
20    the file LICENSE for additional details.
21
22  */
23
24 #include "bacula.h"
25 #include "dird.h"
26
27 /* Forward referenced subroutines */
28 static void terminate_dird(int sig);
29 static int check_resources();
30
31 /* Exported subroutines */
32 extern "C" void reload_config(int sig);
33 extern void invalidate_schedules();
34
35
36 /* Imported subroutines */
37 JCR *wait_for_next_job(char *runjob);
38 void term_scheduler();
39 void term_ua_server();
40 void start_UA_server(dlist *addrs);
41 void init_job_server(int max_workers);
42 void term_job_server();
43 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
44 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
45 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
46 void init_device_resources();
47
48 static char *runjob = NULL;
49 static int background = 1;
50 static void init_reload(void);
51
52 /* Globals Exported */
53 DIRRES *director;                     /* Director resource */
54 int FDConnectTimeout;
55 int SDConnectTimeout;
56 char *configfile = NULL;
57
58 /* Globals Imported */
59 extern int r_first, r_last;           /* first and last resources */
60 extern RES_TABLE resources[];
61 extern RES **res_head;
62 extern RES_ITEM job_items[];
63
64 #if defined(_MSC_VER)
65 extern "C" { // work around visual compiler mangling variables
66     extern URES res_all;
67 }
68 #else
69 extern URES res_all;
70 #endif
71
72 #define CONFIG_FILE "./bacula-dir.conf" /* default configuration file */
73
74 static void usage()
75 {
76    fprintf(stderr, _(
77 "Copyright (C) 2000-2005 Kern Sibbald.\n"
78 "\nVersion: %s (%s)\n\n"
79 "Usage: dird [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
80 "       -c <file>   set configuration file to file\n"
81 "       -dnn        set debug level to nn\n"
82 "       -f          run in foreground (for debugging)\n"
83 "       -g          groupid\n"
84 "       -r <job>    run <job> now\n"
85 "       -s          no signals\n"
86 "       -t          test - read configuration and exit\n"
87 "       -u          userid\n"
88 "       -v          verbose user messages\n"
89 "       -?          print this message.\n"
90 "\n"), VERSION, BDATE);
91
92    exit(1);
93 }
94
95
96 /*********************************************************************
97  *
98  *         Main Bacula Server program
99  *
100  */
101 int main (int argc, char *argv[])
102 {
103    int ch;
104    JCR *jcr;
105    int no_signals = FALSE;
106    int test_config = FALSE;
107    char *uid = NULL;
108    char *gid = NULL;
109
110    setlocale(LC_ALL, "");
111    bindtextdomain("bacula", LOCALEDIR);
112    textdomain("bacula");
113
114    init_stack_dump();
115    my_name_is(argc, argv, "bacula-dir");
116    init_msg(NULL, NULL);              /* initialize message handler */
117    init_reload();
118    daemon_start_time = time(NULL);
119
120    while ((ch = getopt(argc, argv, "c:d:fg:r:stu:v?")) != -1) {
121       switch (ch) {
122       case 'c':                    /* specify config file */
123          if (configfile != NULL) {
124             free(configfile);
125          }
126          configfile = bstrdup(optarg);
127          break;
128
129       case 'd':                    /* set debug level */
130          debug_level = atoi(optarg);
131          if (debug_level <= 0) {
132             debug_level = 1;
133          }
134          Dmsg1(0, "Debug level = %d\n", debug_level);
135          break;
136
137       case 'f':                    /* run in foreground */
138          background = FALSE;
139          break;
140
141       case 'g':                    /* set group id */
142          gid = optarg;
143          break;
144
145       case 'r':                    /* run job */
146          if (runjob != NULL) {
147             free(runjob);
148          }
149          if (optarg) {
150             runjob = bstrdup(optarg);
151          }
152          break;
153
154       case 's':                    /* turn off signals */
155          no_signals = TRUE;
156          break;
157
158       case 't':                    /* test config */
159          test_config = TRUE;
160          break;
161
162       case 'u':                    /* set uid */
163          uid = optarg;
164          break;
165
166       case 'v':                    /* verbose */
167          verbose++;
168          break;
169
170       case '?':
171       default:
172          usage();
173
174       }
175    }
176    argc -= optind;
177    argv += optind;
178
179    if (!no_signals) {
180       init_signals(terminate_dird);
181    }
182
183    if (argc) {
184       if (configfile != NULL) {
185          free(configfile);
186       }
187       configfile = bstrdup(*argv);
188       argc--;
189       argv++;
190    }
191    if (argc) {
192       usage();
193    }
194
195    if (configfile == NULL) {
196       configfile = bstrdup(CONFIG_FILE);
197    }
198
199    parse_config(configfile);
200
201    if (init_crypto() != 0) {
202       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
203    }
204
205    if (!check_resources()) {
206       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
207    }
208
209    if (test_config) {
210       terminate_dird(0);
211    }
212
213    my_name_is(0, NULL, director->hdr.name);    /* set user defined name */
214
215    FDConnectTimeout = (int)director->FDConnectTimeout;
216    SDConnectTimeout = (int)director->SDConnectTimeout;
217
218    if (background) {
219       daemon_start();
220       init_stack_dump();              /* grab new pid */
221    }
222
223    /* Create pid must come after we are a daemon -- so we have our final pid */
224    create_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
225    read_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
226
227    drop(uid, gid);                    /* reduce priveleges if requested */
228
229    signal(SIGHUP, reload_config);
230
231    init_console_msg(working_directory);
232
233    init_python_interpreter(director->hdr.name, director->scripts_directory, 
234        "DirStartUp");
235
236    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
237       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
238
239    Dmsg0(200, "Start UA server\n");
240    start_UA_server(director->DIRaddrs);
241
242    start_watchdog();                  /* start network watchdog thread */
243
244    init_jcr_subsystem();              /* start JCR watchdogs etc. */
245
246    init_job_server(director->MaxConcurrentJobs);
247
248    Dmsg0(200, "wait for next job\n");
249    /* Main loop -- call scheduler to get next job to run */
250    while ( (jcr = wait_for_next_job(runjob)) ) {
251       run_job(jcr);                   /* run job */
252       free_jcr(jcr);                  /* release jcr */
253       if (runjob) {                   /* command line, run a single job? */
254          break;                       /* yes, terminate */
255       }
256    }
257
258    terminate_dird(0);
259
260    return 0;
261 }
262
263 /* Cleanup and then exit */
264 static void terminate_dird(int sig)
265 {
266    static bool already_here = false;
267
268    if (already_here) {                /* avoid recursive temination problems */
269       exit(1);
270    }
271    already_here = true;
272    generate_daemon_event(NULL, "Exit");
273    write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
274    delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
275 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
276    term_scheduler();
277    term_job_server();
278    if (runjob) {
279       free(runjob);
280    }
281    if (configfile != NULL) {
282       free(configfile);
283    }
284    if (debug_level > 5) {
285       print_memory_pool_stats();
286    }
287    free_config_resources();
288    term_ua_server();
289    term_msg();                        /* terminate message handler */
290    stop_watchdog();
291    cleanup_crypto();
292    close_memory_pool();               /* release free memory in pool */
293    sm_dump(false);
294    exit(sig);
295 }
296
297 struct RELOAD_TABLE {
298    int job_count;
299    RES **res_table;
300 };
301
302 static const int max_reloads = 32;
303 static RELOAD_TABLE reload_table[max_reloads];
304
305 static void init_reload(void)
306 {
307    for (int i=0; i < max_reloads; i++) {
308       reload_table[i].job_count = 0;
309       reload_table[i].res_table = NULL;
310    }
311 }
312
313 static void free_saved_resources(int table)
314 {
315    int num = r_last - r_first + 1;
316    RES **res_tab = reload_table[table].res_table;
317    if (!res_tab) {
318       Dmsg1(100, "res_tab for table %d already released.\n", table);
319       return;
320    }
321    Dmsg1(100, "Freeing resources for table %d\n", table);
322    for (int j=0; j<num; j++) {
323       free_resource(res_tab[j], r_first + j);
324    }
325    free(res_tab);
326    reload_table[table].job_count = 0;
327    reload_table[table].res_table = NULL;
328 }
329
330 /*
331  * Called here at the end of every job that was
332  * hooked decrementing the active job_count. When
333  * it goes to zero, no one is using the associated
334  * resource table, so free it.
335  */
336 static void reload_job_end_cb(JCR *jcr, void *ctx)
337 {
338    int reload_id = (int)((long int)ctx);
339    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
340       reload_id, reload_table[reload_id].job_count);
341    lock_jobs();
342    LockRes();
343    if (--reload_table[reload_id].job_count <= 0) {
344       free_saved_resources(reload_id);
345    }
346    UnlockRes();
347    unlock_jobs();
348 }
349
350 static int find_free_reload_table_entry()
351 {
352    int table = -1;
353    for (int i=0; i < max_reloads; i++) {
354       if (reload_table[i].res_table == NULL) {
355          table = i;
356          break;
357       }
358    }
359    return table;
360 }
361
362 /*
363  * If we get here, we have received a SIGHUP, which means to
364  *    reread our configuration file.
365  *
366  * The algorithm used is as follows: we count how many jobs are
367  *   running and mark the running jobs to make a callback on
368  *   exiting. The old config is saved with the reload table
369  *   id in a reload table. The new config file is read. Now, as
370  *   each job exits, it calls back to the reload_job_end_cb(), which
371  *   decrements the count of open jobs for the given reload table.
372  *   When the count goes to zero, we release those resources.
373  *   This allows us to have pointers into the resource table (from
374  *   jobs), and once they exit and all the pointers are released, we
375  *   release the old table. Note, if no new jobs are running since the
376  *   last reload, then the old resources will be immediately release.
377  *   A console is considered a job because it may have pointers to
378  *   resources, but a SYSTEM job is not since it *should* not have any
379  *   permanent pointers to jobs.
380  */
381 extern "C"
382 void reload_config(int sig)
383 {
384    static bool already_here = false;
385    sigset_t set;
386    JCR *jcr;
387    int njobs = 0;                     /* number of running jobs */
388    int table, rtable;
389    bool ok;       
390
391    if (already_here) {
392       abort();                        /* Oops, recursion -> die */
393    }
394    already_here = true;
395    sigemptyset(&set);
396    sigaddset(&set, SIGHUP);
397    sigprocmask(SIG_BLOCK, &set, NULL);
398
399    lock_jobs();
400    LockRes();
401
402    table = find_free_reload_table_entry();
403    if (table < 0) {
404       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
405       goto bail_out;
406    }
407
408    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
409    reload_table[table].res_table = save_config_resources();
410    Dmsg1(100, "Saved old config in table %d\n", table);
411
412    ok = parse_config(configfile, 0, M_ERROR);  /* no exit on error */
413
414    Dmsg0(100, "Reloaded config file\n");
415    if (!ok || !check_resources()) {
416       rtable = find_free_reload_table_entry();    /* save new, bad table */
417       if (rtable < 0) {
418          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
419          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
420       } else {
421          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
422          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
423       }
424       reload_table[rtable].res_table = save_config_resources();
425       /* Now restore old resoure values */
426       int num = r_last - r_first + 1;
427       RES **res_tab = reload_table[table].res_table;
428       for (int i=0; i<num; i++) {
429          res_head[i] = res_tab[i];
430       }
431       table = rtable;                 /* release new, bad, saved table below */
432    } else {
433       invalidate_schedules();
434       /*
435        * Hook all active jobs so that they release this table
436        */
437       foreach_jcr(jcr) {
438          if (jcr->JobType != JT_SYSTEM) {
439             reload_table[table].job_count++;
440             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
441             njobs++;
442          }
443       }
444       endeach_jcr(jcr);
445    }
446
447    /* Reset globals */
448    set_working_directory(director->working_directory);
449    FDConnectTimeout = director->FDConnectTimeout;
450    SDConnectTimeout = director->SDConnectTimeout;
451    Dmsg0(0, "Director's configuration file reread.\n");
452
453    /* Now release saved resources, if no jobs using the resources */
454    if (njobs == 0) {
455       free_saved_resources(table);
456    }
457
458 bail_out:
459    UnlockRes();
460    unlock_jobs();
461    sigprocmask(SIG_UNBLOCK, &set, NULL);
462    signal(SIGHUP, reload_config);
463    already_here = false;
464 }
465
466 /*
467  * Make a quick check to see that we have all the
468  * resources needed.
469  *
470  *  **** FIXME **** this routine could be a lot more
471  *   intelligent and comprehensive.
472  */
473 static int check_resources()
474 {
475    bool OK = true;
476    JOB *job;
477
478    LockRes();
479
480    job = (JOB *)GetNextRes(R_JOB, NULL);
481    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
482    if (!director) {
483       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
484 "Without that I don't know who I am :-(\n"), configfile);
485       OK = false;
486    } else {
487       set_working_directory(director->working_directory);
488       if (!director->messages) {       /* If message resource not specified */
489          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
490          if (!director->messages) {
491             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
492             OK = false;
493          }
494       }
495       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
496          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
497             configfile);
498          OK = false;
499       }
500       /* tls_require implies tls_enable */
501       if (director->tls_require) {
502          if (have_tls) {
503             director->tls_enable = true;
504          } else {
505             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
506             OK = false;
507          }
508       }
509
510       if (!director->tls_certfile && director->tls_enable) {
511          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
512             director->hdr.name, configfile);
513          OK = false;
514       }
515
516       if (!director->tls_keyfile && director->tls_enable) {
517          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
518             director->hdr.name, configfile);
519          OK = false;
520       }
521
522       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && director->tls_enable && director->tls_verify_peer) {
523          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
524               " Certificate Dir\" are defined for Director \"%s\" in %s."
525               " At least one CA certificate store is required"
526               " when using \"TLS Verify Peer\".\n"),
527               director->hdr.name, configfile);
528          OK = false;
529       }
530
531       /* If everything is well, attempt to initialize our per-resource TLS context */
532       if (OK && (director->tls_enable || director->tls_require)) {
533          /* Initialize TLS context:
534           * Args: CA certfile, CA certdir, Certfile, Keyfile,
535           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
536          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
537             director->tls_ca_certdir, director->tls_certfile,
538             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
539             director->tls_verify_peer);
540          
541          if (!director->tls_ctx) {
542             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
543                  director->hdr.name, configfile);
544             OK = false;
545          }
546       }
547    }
548
549    if (!job) {
550       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
551       OK = false;
552    }
553    foreach_res(job, R_JOB) {
554       int i;
555
556       if (job->jobdefs) {
557          /* Handle Storage alists specifically */
558          JOB *jobdefs = job->jobdefs;
559          if (jobdefs->storage && !job->storage) {
560             STORE *st;
561             job->storage = New(alist(10, not_owned_by_alist));
562             foreach_alist(st, jobdefs->storage) {
563                job->storage->append(st);
564             }
565          }
566          /* Handle RunScripts alists specifically */
567          if (jobdefs->RunScripts) {
568             RUNSCRIPT *rs, *elt;
569             
570             if (!job->RunScripts) {
571                job->RunScripts = New(alist(10, not_owned_by_alist));
572             }
573            
574             foreach_alist(rs, jobdefs->RunScripts) {
575                elt = copy_runscript(rs);
576                job->RunScripts->append(elt); /* we have to free it */
577             }
578          }
579
580          /* Transfer default items from JobDefs Resource */
581          for (i=0; job_items[i].name; i++) {
582             char **def_svalue, **svalue;  /* string value */
583             int *def_ivalue, *ivalue;     /* integer value */
584             bool *def_bvalue, *bvalue;    /* bool value */
585             int64_t *def_lvalue, *lvalue; /* 64 bit values */
586             uint32_t offset;
587
588             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
589                 job->hdr.name, job_items[i].name,
590                 bit_is_set(i, job->hdr.item_present),
591                 bit_is_set(i, job->jobdefs->hdr.item_present));
592
593             if (!bit_is_set(i, job->hdr.item_present) &&
594                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
595                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
596                  job->hdr.name, job_items[i].name);
597                offset = (char *)(job_items[i].value) - (char *)&res_all;
598                /*
599                 * Handle strings and directory strings
600                 */
601                if (job_items[i].handler == store_str ||
602                    job_items[i].handler == store_dir) {
603                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
604                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
605                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
606                   svalue = (char **)((char *)job + offset);
607                   if (*svalue) {
608                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
609                   }
610                   *svalue = bstrdup(*def_svalue);
611                   set_bit(i, job->hdr.item_present);
612                /*
613                 * Handle resources
614                 */
615                } else if (job_items[i].handler == store_res) {
616                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
617                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
618                        job->hdr.name, job_items[i].name, i, offset);
619                   svalue = (char **)((char *)job + offset);
620                   if (*svalue) {
621                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
622                   }
623                   *svalue = *def_svalue;
624                   set_bit(i, job->hdr.item_present);
625                /*
626                 * Handle alist resources
627                 */
628                } else if (job_items[i].handler == store_alist_res) {
629                   if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
630                      set_bit(i, job->hdr.item_present);
631                   }
632                /*
633                 * Handle integer fields
634                 *    Note, our store_bit does not handle bitmaped fields
635                 */
636                } else if (job_items[i].handler == store_bit     ||
637                           job_items[i].handler == store_pint    ||
638                           job_items[i].handler == store_jobtype ||
639                           job_items[i].handler == store_level   ||
640                           job_items[i].handler == store_pint    ||
641                           job_items[i].handler == store_replace) {
642                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
643                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
644                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
645                   ivalue = (int *)((char *)job + offset);
646                   *ivalue = *def_ivalue;
647                   set_bit(i, job->hdr.item_present);
648                /*
649                 * Handle 64 bit integer fields
650                 */
651                } else if (job_items[i].handler == store_time   ||
652                           job_items[i].handler == store_size   ||
653                           job_items[i].handler == store_int64) {
654                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
655                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
656                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
657                   lvalue = (int64_t *)((char *)job + offset);
658                   *lvalue = *def_lvalue;
659                   set_bit(i, job->hdr.item_present);
660                /*
661                 * Handle bool fields
662                 */
663                } else if (job_items[i].handler == store_bool) {
664                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
665                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
666                        job->hdr.name, job_items[i].name, *def_bvalue, i, offset);
667                   bvalue = (bool *)((char *)job + offset);
668                   *bvalue = *def_bvalue;
669                   set_bit(i, job->hdr.item_present);
670                }
671             }
672          }
673       }
674       /*
675        * Ensure that all required items are present
676        */
677       for (i=0; job_items[i].name; i++) {
678          if (job_items[i].flags & ITEM_REQUIRED) {
679                if (!bit_is_set(i, job->hdr.item_present)) {
680                   Jmsg(NULL, M_FATAL, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
681                     job_items[i].name, job->hdr.name);
682                   OK = false;
683                 }
684          }
685          /* If this triggers, take a look at lib/parse_conf.h */
686          if (i >= MAX_RES_ITEMS) {
687             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
688          }
689       }
690    } /* End loop over Job res */
691
692    /* Loop over databases */
693    CAT *catalog;
694    foreach_res(catalog, R_CATALOG) {
695       B_DB *db;
696       /*
697        * Make sure we can open catalog, otherwise print a warning
698        * message because the server is probably not running.
699        */
700       db = db_init_database(NULL, catalog->db_name, catalog->db_user,
701                          catalog->db_password, catalog->db_address,
702                          catalog->db_port, catalog->db_socket,
703                          catalog->mult_db_connections);
704       if (!db || !db_open_database(NULL, db)) {
705          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
706               catalog->hdr.name, catalog->db_name);
707          if (db) {
708             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
709          }
710          OK = false;
711          continue;
712       }
713
714       /* Loop over all pools, defining/updating them in each database */
715       POOL *pool;
716       foreach_res(pool, R_POOL) {
717          create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
718       }
719
720       STORE *store;
721       foreach_res(store, R_STORAGE) {
722          STORAGE_DBR sr;
723          MEDIATYPE_DBR mr;
724          if (store->media_type) {
725             bstrncpy(mr.MediaType, store->media_type, sizeof(mr.MediaType));
726             mr.ReadOnly = 0;
727             db_create_mediatype_record(NULL, db, &mr);
728          } else {
729             mr.MediaTypeId = 0;
730          }
731          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
732          sr.AutoChanger = store->autochanger;
733          db_create_storage_record(NULL, db, &sr);
734          store->StorageId = sr.StorageId;   /* set storage Id */
735          if (!sr.created) {                 /* if not created, update it */
736             db_update_storage_record(NULL, db, &sr);
737          }
738
739          /* tls_require implies tls_enable */
740          if (store->tls_require) {
741             if (have_tls) {
742                store->tls_enable = true;
743             } else {
744                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
745                OK = false;
746             }
747          } 
748
749          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && store->tls_enable) {
750             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
751                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
752                  store->hdr.name, configfile);
753             OK = false;
754          }
755
756          /* If everything is well, attempt to initialize our per-resource TLS context */
757          if (OK && (store->tls_enable || store->tls_require)) {
758            /* Initialize TLS context:
759             * Args: CA certfile, CA certdir, Certfile, Keyfile,
760             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
761             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
762                store->tls_ca_certdir, store->tls_certfile,
763                store->tls_keyfile, NULL, NULL, NULL, true);
764          
765             if (!store->tls_ctx) {
766                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
767                     store->hdr.name, configfile);
768                OK = false;
769             }
770          }
771       }
772
773       /* Loop over all counters, defining them in each database */
774       /* Set default value in all counters */
775       COUNTER *counter;
776       foreach_res(counter, R_COUNTER) {
777          /* Write to catalog? */
778          if (!counter->created && counter->Catalog == catalog) {
779             COUNTER_DBR cr;
780             bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
781             cr.MinValue = counter->MinValue;
782             cr.MaxValue = counter->MaxValue;
783             cr.CurrentValue = counter->MinValue;
784             if (counter->WrapCounter) {
785                bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
786             } else {
787                cr.WrapCounter[0] = 0;  /* empty string */
788             }
789             if (db_create_counter_record(NULL, db, &cr)) {
790                counter->CurrentValue = cr.CurrentValue;
791                counter->created = true;
792                Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
793             }
794          }
795          if (!counter->created) {
796             counter->CurrentValue = counter->MinValue;  /* default value */
797          }
798       }
799       db_close_database(NULL, db);
800    }
801
802    /* Loop over Consoles */
803    CONRES *cons;
804    foreach_res(cons, R_CONSOLE) {
805       /* tls_require implies tls_enable */
806       if (cons->tls_require) {
807          if (have_tls) {
808             cons->tls_enable = true;
809          } else {
810             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
811             OK = false;
812             continue;
813          }
814       }
815
816       if (!cons->tls_certfile && cons->tls_enable) {
817          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
818             cons->hdr.name, configfile);
819          OK = false;
820       }
821
822       if (!cons->tls_keyfile && cons->tls_enable) {
823          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
824             cons->hdr.name, configfile);
825          OK = false;
826       }
827
828       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir) && cons->tls_enable && cons->tls_verify_peer) {
829          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
830             " Certificate Dir\" are defined for Console \"%s\" in %s."
831             " At least one CA certificate store is required"
832             " when using \"TLS Verify Peer\".\n"),
833             cons->hdr.name, configfile);
834          OK = false;
835       }
836       /* If everything is well, attempt to initialize our per-resource TLS context */
837       if (OK && (cons->tls_enable || cons->tls_require)) {
838          /* Initialize TLS context:
839           * Args: CA certfile, CA certdir, Certfile, Keyfile,
840           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
841          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
842             cons->tls_ca_certdir, cons->tls_certfile,
843             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
844          
845          if (!cons->tls_ctx) {
846             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
847                cons->hdr.name, configfile);
848             OK = false;
849          }
850       }
851
852    }
853
854    /* Loop over Clients */
855    CLIENT *client;
856    foreach_res(client, R_CLIENT) {
857       /* tls_require implies tls_enable */
858       if (client->tls_require) {
859          if (have_tls) {
860             client->tls_enable = true;
861          } else {
862             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
863             OK = false;
864             continue;
865          }
866       }
867
868       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && client->tls_enable) {
869          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
870             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
871             client->hdr.name, configfile);
872          OK = false;
873       }
874
875       /* If everything is well, attempt to initialize our per-resource TLS context */
876       if (OK && (client->tls_enable || client->tls_require)) {
877          /* Initialize TLS context:
878           * Args: CA certfile, CA certdir, Certfile, Keyfile,
879           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
880          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
881             client->tls_ca_certdir, client->tls_certfile,
882             client->tls_keyfile, NULL, NULL, NULL,
883             true);
884          
885          if (!client->tls_ctx) {
886             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
887                client->hdr.name, configfile);
888             OK = false;
889          }
890       }
891    }
892
893    UnlockRes();
894    if (OK) {
895       close_msg(NULL);                /* close temp message handler */
896       init_msg(NULL, director->messages); /* open daemon message handler */
897    }
898    return OK;
899 }