2 Bacula(R) - The Network Backup Solution
4 Copyright (C) 2000-2015 Kern Sibbald
5 Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
7 The original author of Bacula is Kern Sibbald, with contributions
8 from many others, a complete list can be found in the file AUTHORS.
10 You may use this file and others of this release according to the
11 license defined in the LICENSE file, which includes the Affero General
12 Public License, v3.0 ("AGPLv3") and some additional permissions and
13 terms pursuant to its AGPLv3 Section 7.
15 This notice must be preserved when any source code is
16 conveyed and/or propagated.
18 Bacula(R) is a registered trademark of Kern Sibbald.
22 * Bacula Director daemon -- this is the main program
24 * Kern Sibbald, March MM
31 #include "lib/bregex.h"
37 #define NAMELEN(dirent) (strlen((dirent)->d_name))
39 #ifndef HAVE_READDIR_R
40 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
43 /* Forward referenced subroutines */
44 void terminate_dird(int sig);
45 static bool check_resources();
46 static void cleanup_old_files();
48 /* Exported subroutines */
49 extern "C" void reload_config(int sig);
50 extern void invalidate_schedules();
51 extern bool parse_dir_config(CONFIG *config, const char *configfile, int exit_code);
53 /* Imported subroutines */
54 JCR *wait_for_next_job(char *runjob);
55 void term_scheduler();
56 void term_ua_server();
57 void start_UA_server(dlist *addrs);
58 void init_job_server(int max_workers);
59 void term_job_server();
60 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
61 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
62 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
63 void store_migtype(LEX *lc, RES_ITEM *item, int index, int pass);
64 void init_device_resources();
67 static char *runjob = NULL;
68 static bool background = true;
69 static void init_reload(void);
70 static CONFIG *config;
72 /* Globals Exported */
73 DIRRES *director; /* Director resource */
76 char *configfile = NULL;
78 utime_t last_reload_time = 0;
80 /* Globals Imported */
81 extern RES_ITEM job_items[];
83 extern "C" { // work around visual compiler mangling variables
91 CHECK_CONNECTION, /* Check catalog connection */
92 UPDATE_CATALOG, /* Ensure that catalog is ok with conf */
93 UPDATE_AND_FIX /* Ensure that catalog is ok, and fix old jobs */
95 static bool check_catalog(cat_op mode);
97 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
99 static bool dir_sql_query(JCR *jcr, const char *cmd)
101 if (jcr && jcr->db && jcr->db->is_connected()) {
102 return db_sql_query(jcr->db, cmd, NULL, NULL);
107 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len)
109 if (jcr && jcr->db && jcr->db->is_connected()) {
110 db_escape_string(jcr, mdb, snew, sold, len);
120 "\nVersion: %s (%s)\n\n"
121 "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
122 " -c <file> set configuration file to file\n"
123 " -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
124 " -dt print timestamp in debug output\n"
126 " -f run in foreground (for debugging)\n"
128 " -m print kaboom output (for debugging)\n"
129 " -r <job> run <job> now\n"
131 " -t test - read configuration and exit\n"
133 " -v verbose user messages\n"
134 " -? print this message.\n"
135 "\n"), 2000, VERSION, BDATE);
141 * !!! WARNING !!! Use this function only when bacula is stopped.
142 * ie, after a fatal signal and before exiting the program
143 * Print information about a JCR
145 static void dir_debug_print(JCR *jcr, FILE *fp)
147 fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
148 jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
151 /*********************************************************************
153 * Main Bacula Director Server program
156 #if defined(HAVE_WIN32)
157 /* For Win32 main() is in src/win32 code ... */
158 #define main BaculaMain
161 int main (int argc, char *argv[])
165 bool no_signals = false;
166 bool test_config = false;
170 start_heap = sbrk(0);
171 setlocale(LC_ALL, "");
172 bindtextdomain("bacula", LOCALEDIR);
173 textdomain("bacula");
176 my_name_is(argc, argv, "bacula-dir");
177 init_msg(NULL, NULL); /* initialize message handler */
179 daemon_start_time = time(NULL);
181 console_command = run_console_command;
183 while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?T")) != -1) {
185 case 'c': /* specify config file */
186 if (configfile != NULL) {
189 configfile = bstrdup(optarg);
192 case 'd': /* set debug level */
193 if (*optarg == 't') {
194 dbg_timestamp = true;
197 /* We probably find a tag list -d 10,sql,bvfs */
198 if ((p = strchr(optarg, ',')) != NULL) {
201 debug_level = atoi(optarg);
202 if (debug_level <= 0) {
206 debug_parse_tags(p+1, &debug_level_tags);
209 Dmsg1(10, "Debug level = %lld\n", debug_level);
216 case 'f': /* run in foreground */
220 case 'g': /* set group id */
224 case 'm': /* print kaboom output */
228 case 'r': /* run job */
229 if (runjob != NULL) {
233 runjob = bstrdup(optarg);
237 case 's': /* turn off signals */
241 case 't': /* test config */
245 case 'u': /* set uid */
249 case 'v': /* verbose */
263 init_signals(terminate_dird);
267 if (configfile != NULL) {
270 configfile = bstrdup(*argv);
278 if (!test_config) { /* we don't need to do this block in test mode */
281 init_stack_dump(); /* grab new pid */
285 if (configfile == NULL) {
286 configfile = bstrdup(CONFIG_FILE);
289 config = new_config_parser();
291 parse_dir_config(config, configfile, M_ERROR_TERM);
293 if (init_crypto() != 0) {
294 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
297 if (!check_resources()) {
298 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
302 /* Create pid must come after we are a daemon -- so we have our final pid */
303 create_pid_file(director->pid_directory, "bacula-dir",
304 get_first_port_host_order(director->DIRaddrs));
305 read_state_file(director->working_directory, "bacula-dir",
306 get_first_port_host_order(director->DIRaddrs));
309 set_jcr_in_tsd(INVALID_JCR);
310 set_thread_concurrency(director->MaxConcurrentJobs * 2 +
311 4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
312 lmgr_init_thread(); /* initialize the lockmanager stack */
314 load_dir_plugins(director->plugin_directory);
316 drop(uid, gid, false); /* reduce privileges if requested */
318 /* If we are in testing mode, we don't try to fix the catalog */
319 cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
321 if (!check_catalog(mode)) {
322 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
329 my_name_is(0, NULL, director->name()); /* set user defined name */
333 /* Plug database interface for library routines */
334 p_sql_query = (sql_query_call)dir_sql_query;
335 p_sql_escape = (sql_escape_call)dir_sql_escape;
337 FDConnectTimeout = (int)director->FDConnectTimeout;
338 SDConnectTimeout = (int)director->SDConnectTimeout;
340 #if !defined(HAVE_WIN32)
341 signal(SIGHUP, reload_config);
344 init_console_msg(working_directory);
346 Dmsg0(200, "Start UA server\n");
347 start_UA_server(director->DIRaddrs);
349 start_watchdog(); /* start network watchdog thread */
351 init_jcr_subsystem(); /* start JCR watchdogs etc. */
353 init_job_server(director->MaxConcurrentJobs);
355 dbg_jcr_add_hook(dir_debug_print); /* used to director variables */
356 dbg_jcr_add_hook(bdb_debug_print); /* used to debug B_DB connexion after fatal signal */
358 // init_device_resources();
360 Dmsg0(200, "wait for next job\n");
361 /* Main loop -- call scheduler to get next job to run */
362 while ( (jcr = wait_for_next_job(runjob)) ) {
363 run_job(jcr); /* run job */
364 free_jcr(jcr); /* release jcr */
365 set_jcr_in_tsd(INVALID_JCR);
366 if (runjob) { /* command line, run a single job? */
367 break; /* yes, terminate */
376 struct RELOAD_TABLE {
381 static const int max_reloads = 50;
382 static RELOAD_TABLE reload_table[max_reloads];
384 static void init_reload(void)
386 for (int i=0; i < max_reloads; i++) {
387 reload_table[i].job_count = 0;
388 reload_table[i].res_table = NULL;
393 * This subroutine frees a saved resource table.
394 * It was saved when a new table was created with "reload"
396 static void free_saved_resources(int table)
398 int num = r_last - r_first + 1;
399 RES **res_tab = reload_table[table].res_table;
401 Dmsg1(100, "res_tab for table %d already released.\n", table);
404 Dmsg1(100, "Freeing resources for table %d\n", table);
405 for (int j=0; j<num; j++) {
406 free_resource(res_tab[j], r_first + j);
409 reload_table[table].job_count = 0;
410 reload_table[table].res_table = NULL;
414 * Called here at the end of every job that was
415 * hooked decrementing the active job_count. When
416 * it goes to zero, no one is using the associated
417 * resource table, so free it.
419 static void reload_job_end_cb(JCR *jcr, void *ctx)
421 int reload_id = (int)((intptr_t)ctx);
422 Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
423 reload_id, reload_table[reload_id].job_count);
426 if (--reload_table[reload_id].job_count <= 0) {
427 free_saved_resources(reload_id);
433 static int find_free_reload_table_entry()
436 for (int i=0; i < max_reloads; i++) {
437 if (reload_table[i].res_table == NULL) {
446 * If we get here, we have received a SIGHUP, which means to
447 * reread our configuration file.
449 * The algorithm used is as follows: we count how many jobs are
450 * running and mark the running jobs to make a callback on
451 * exiting. The old config is saved with the reload table
452 * id in a reload table. The new config file is read. Now, as
453 * each job exits, it calls back to the reload_job_end_cb(), which
454 * decrements the count of open jobs for the given reload table.
455 * When the count goes to zero, we release those resources.
456 * This allows us to have pointers into the resource table (from
457 * jobs), and once they exit and all the pointers are released, we
458 * release the old table. Note, if no new jobs are running since the
459 * last reload, then the old resources will be immediately release.
460 * A console is considered a job because it may have pointers to
461 * resources, but a SYSTEM job is not since it *should* not have any
462 * permanent pointers to jobs.
465 void reload_config(int sig)
467 static bool already_here = false;
468 #if !defined(HAVE_WIN32)
472 int njobs = 0; /* number of running jobs */
477 abort(); /* Oops, recursion -> die */
481 #if !defined(HAVE_WIN32)
483 sigaddset(&set, SIGHUP);
484 sigprocmask(SIG_BLOCK, &set, NULL);
490 table = find_free_reload_table_entry();
492 Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
496 Dmsg1(100, "Reload_config njobs=%d\n", njobs);
497 reload_table[table].res_table = config->save_resources();
498 Dmsg1(100, "Saved old config in table %d\n", table);
500 ok = parse_dir_config(config, configfile, M_ERROR);
502 Dmsg0(100, "Reloaded config file\n");
503 if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
504 rtable = find_free_reload_table_entry(); /* save new, bad table */
506 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
507 Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
509 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
510 Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
512 reload_table[rtable].res_table = config->save_resources();
513 /* Now restore old resource values */
514 int num = r_last - r_first + 1;
515 RES **res_tab = reload_table[table].res_table;
516 for (int i=0; i<num; i++) {
517 res_head[i] = res_tab[i];
519 table = rtable; /* release new, bad, saved table below */
521 invalidate_schedules();
523 * Hook all active jobs so that they release this table
526 if (jcr->getJobType() != JT_SYSTEM) {
527 reload_table[table].job_count++;
528 job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
536 set_working_directory(director->working_directory);
537 FDConnectTimeout = director->FDConnectTimeout;
538 SDConnectTimeout = director->SDConnectTimeout;
539 Dmsg0(10, "Director's configuration file reread.\n");
541 /* Now release saved resources, if no jobs using the resources */
543 free_saved_resources(table);
549 #if !defined(HAVE_WIN32)
550 sigprocmask(SIG_UNBLOCK, &set, NULL);
551 signal(SIGHUP, reload_config);
553 already_here = false;
556 /* Cleanup and then exit */
557 void terminate_dird(int sig)
559 static bool already_here = false;
561 if (already_here) { /* avoid recursive temination problems */
562 bmicrosleep(2, 0); /* yield */
566 debug_level = 0; /* turn off debug */
568 generate_daemon_event(NULL, "Exit");
570 write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
571 delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
577 if (configfile != NULL) {
581 print_memory_pool_stats();
584 config->free_resources();
589 term_msg(); /* terminate message handler */
591 close_memory_pool(); /* release free memory in pool */
598 * Make a quick check to see that we have all the
601 * **** FIXME **** this routine could be a lot more
602 * intelligent and comprehensive.
604 static bool check_resources()
612 job = (JOB *)GetNextRes(R_JOB, NULL);
613 director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
615 Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
616 "Without that I don't know who I am :-(\n"), configfile);
619 set_working_directory(director->working_directory);
620 if (!director->messages) { /* If message resource not specified */
621 director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
622 if (!director->messages) {
623 Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
627 if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
628 Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
632 /* tls_require implies tls_enable */
633 if (director->tls_require) {
635 director->tls_enable = true;
637 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
642 need_tls = director->tls_enable || director->tls_authenticate;
644 if (!director->tls_certfile && need_tls) {
645 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
646 director->name(), configfile);
650 if (!director->tls_keyfile && need_tls) {
651 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
652 director->name(), configfile);
656 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
657 need_tls && director->tls_verify_peer) {
658 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
659 " Certificate Dir\" are defined for Director \"%s\" in %s."
660 " At least one CA certificate store is required"
661 " when using \"TLS Verify Peer\".\n"),
662 director->name(), configfile);
666 /* If everything is well, attempt to initialize our per-resource TLS context */
667 if (OK && (need_tls || director->tls_require)) {
668 /* Initialize TLS context:
669 * Args: CA certfile, CA certdir, Certfile, Keyfile,
670 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
671 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
672 director->tls_ca_certdir, director->tls_certfile,
673 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
674 director->tls_verify_peer);
676 if (!director->tls_ctx) {
677 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
678 director->name(), configfile);
685 Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
688 foreach_res(job, R_JOB) {
692 /* Handle Storage alists specifically */
693 JOB *jobdefs = job->jobdefs;
694 if (jobdefs->storage && !job->storage) {
696 job->storage = New(alist(10, not_owned_by_alist));
697 foreach_alist(st, jobdefs->storage) {
698 job->storage->append(st);
701 /* Handle RunScripts alists specifically */
702 if (jobdefs->RunScripts) {
705 if (!job->RunScripts) {
706 job->RunScripts = New(alist(10, not_owned_by_alist));
709 foreach_alist(rs, jobdefs->RunScripts) {
710 elt = copy_runscript(rs);
711 job->RunScripts->append(elt); /* we have to free it */
715 /* Transfer default items from JobDefs Resource */
716 for (i=0; job_items[i].name; i++) {
717 char **def_svalue, **svalue; /* string value */
718 uint32_t *def_ivalue, *ivalue; /* integer value */
719 bool *def_bvalue, *bvalue; /* bool value */
720 int64_t *def_lvalue, *lvalue; /* 64 bit values */
723 Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
724 job->name(), job_items[i].name,
725 bit_is_set(i, job->hdr.item_present),
726 bit_is_set(i, job->jobdefs->hdr.item_present));
728 if (!bit_is_set(i, job->hdr.item_present) &&
729 bit_is_set(i, job->jobdefs->hdr.item_present)) {
730 Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
731 job->name(), job_items[i].name);
732 offset = (char *)(job_items[i].value) - (char *)&res_all;
734 * Handle strings and directory strings
736 if (job_items[i].handler == store_str ||
737 job_items[i].handler == store_dir) {
738 def_svalue = (char **)((char *)(job->jobdefs) + offset);
739 Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
740 job->name(), job_items[i].name, *def_svalue, i, offset);
741 svalue = (char **)((char *)job + offset);
743 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
745 *svalue = bstrdup(*def_svalue);
746 set_bit(i, job->hdr.item_present);
750 } else if (job_items[i].handler == store_res) {
751 def_svalue = (char **)((char *)(job->jobdefs) + offset);
752 Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
753 job->name(), job_items[i].name, i, offset);
754 svalue = (char **)((char *)job + offset);
756 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
758 *svalue = *def_svalue;
759 set_bit(i, job->hdr.item_present);
761 * Handle alist resources
763 } else if (job_items[i].handler == store_alist_res) {
764 if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
765 set_bit(i, job->hdr.item_present);
768 * Handle integer fields
769 * Note, our store_bit does not handle bitmaped fields
771 } else if (job_items[i].handler == store_bit ||
772 job_items[i].handler == store_pint32 ||
773 job_items[i].handler == store_jobtype ||
774 job_items[i].handler == store_level ||
775 job_items[i].handler == store_int32 ||
776 job_items[i].handler == store_size32 ||
777 job_items[i].handler == store_migtype ||
778 job_items[i].handler == store_replace) {
779 def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
780 Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
781 job->name(), job_items[i].name, *def_ivalue, i, offset);
782 ivalue = (uint32_t *)((char *)job + offset);
783 *ivalue = *def_ivalue;
784 set_bit(i, job->hdr.item_present);
786 * Handle 64 bit integer fields
788 } else if (job_items[i].handler == store_time ||
789 job_items[i].handler == store_size64 ||
790 job_items[i].handler == store_speed ||
791 job_items[i].handler == store_int64) {
792 def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
793 Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
794 job->name(), job_items[i].name, *def_lvalue, i, offset);
795 lvalue = (int64_t *)((char *)job + offset);
796 *lvalue = *def_lvalue;
797 set_bit(i, job->hdr.item_present);
801 } else if (job_items[i].handler == store_bool) {
802 def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
803 Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
804 job->name(), job_items[i].name, *def_bvalue, i, offset);
805 bvalue = (bool *)((char *)job + offset);
806 *bvalue = *def_bvalue;
807 set_bit(i, job->hdr.item_present);
813 * Ensure that all required items are present
815 for (i=0; job_items[i].name; i++) {
816 if (job_items[i].flags & ITEM_REQUIRED) {
817 if (!bit_is_set(i, job->hdr.item_present)) {
818 Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
819 job_items[i].name, job->name());
823 /* If this triggers, take a look at lib/parse_conf.h */
824 if (i >= MAX_RES_ITEMS) {
825 Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
828 if (!job->storage && !job->pool->storage) {
829 Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
833 } /* End loop over Job res */
836 /* Loop over Consoles */
838 foreach_res(cons, R_CONSOLE) {
839 /* tls_require implies tls_enable */
840 if (cons->tls_require) {
842 cons->tls_enable = true;
844 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
850 need_tls = cons->tls_enable || cons->tls_authenticate;
852 if (!cons->tls_certfile && need_tls) {
853 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
854 cons->name(), configfile);
858 if (!cons->tls_keyfile && need_tls) {
859 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
860 cons->name(), configfile);
864 if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
865 && need_tls && cons->tls_verify_peer) {
866 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
867 " Certificate Dir\" are defined for Console \"%s\" in %s."
868 " At least one CA certificate store is required"
869 " when using \"TLS Verify Peer\".\n"),
870 cons->name(), configfile);
873 /* If everything is well, attempt to initialize our per-resource TLS context */
874 if (OK && (need_tls || cons->tls_require)) {
875 /* Initialize TLS context:
876 * Args: CA certfile, CA certdir, Certfile, Keyfile,
877 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
878 cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
879 cons->tls_ca_certdir, cons->tls_certfile,
880 cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
882 if (!cons->tls_ctx) {
883 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
884 cons->name(), configfile);
891 /* Loop over Clients */
893 foreach_res(client, R_CLIENT) {
894 /* tls_require implies tls_enable */
895 if (client->tls_require) {
897 client->tls_enable = true;
899 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
904 need_tls = client->tls_enable || client->tls_authenticate;
905 if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
906 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
907 " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
908 client->name(), configfile);
912 /* If everything is well, attempt to initialize our per-resource TLS context */
913 if (OK && (need_tls || client->tls_require)) {
914 /* Initialize TLS context:
915 * Args: CA certfile, CA certdir, Certfile, Keyfile,
916 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
917 client->tls_ctx = new_tls_context(client->tls_ca_certfile,
918 client->tls_ca_certdir, client->tls_certfile,
919 client->tls_keyfile, NULL, NULL, NULL,
922 if (!client->tls_ctx) {
923 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
924 client->name(), configfile);
932 close_msg(NULL); /* close temp message handler */
933 init_msg(NULL, director->messages); /* open daemon message handler */
934 last_reload_time = time(NULL);
941 * - we can check the connection (mode=CHECK_CONNECTION)
942 * - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
943 * - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
945 static bool check_catalog(cat_op mode)
950 /* Loop over databases */
952 foreach_res(catalog, R_CATALOG) {
955 * Make sure we can open catalog, otherwise print a warning
956 * message because the server is probably not running.
958 db = db_init_database(NULL, catalog->db_driver, catalog->db_name,
960 catalog->db_password, catalog->db_address,
961 catalog->db_port, catalog->db_socket,
962 catalog->mult_db_connections,
963 catalog->disable_batch_insert);
964 if (!db || !db_open_database(NULL, db)) {
965 Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
966 catalog->name(), catalog->db_name);
967 Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
968 catalog->name(), catalog->db_name);
970 Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
971 Pmsg1(000, "%s", db_strerror(db));
972 db_close_database(NULL, db);
978 /* Display a message if the db max_connections is too low */
979 if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
980 Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
981 Pmsg1(000, "%s", db_strerror(db));
984 /* we are in testing mode, so don't touch anything in the catalog */
985 if (mode == CHECK_CONNECTION) {
986 if (db) db_close_database(NULL, db);
990 /* Loop over all pools, defining/updating them in each database */
992 foreach_res(pool, R_POOL) {
994 * If the Pool has a catalog resource create the pool only
997 if (!pool->catalog || pool->catalog == catalog) {
998 create_pool(NULL, db, pool, POOL_OP_UPDATE); /* update request */
1002 /* Once they are created, we can loop over them again, updating
1003 * references (RecyclePool)
1005 foreach_res(pool, R_POOL) {
1007 * If the Pool has a catalog resource update the pool only
1010 if (!pool->catalog || pool->catalog == catalog) {
1011 update_pool_references(NULL, db, pool);
1015 /* Ensure basic client record is in DB */
1017 foreach_res(client, R_CLIENT) {
1019 /* Create clients only if they use the current catalog */
1020 if (client->catalog != catalog) {
1021 Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1022 client->name(), client->catalog->name(), catalog->name());
1025 Dmsg2(500, "create cat=%s for client=%s\n",
1026 client->catalog->name(), client->name());
1027 memset(&cr, 0, sizeof(cr));
1028 bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1030 db_create_client_record(NULL, db, &cr);
1033 /* Ensure basic storage record is in DB */
1035 foreach_res(store, R_STORAGE) {
1038 memset(&sr, 0, sizeof(sr));
1039 memset(&mtr, 0, sizeof(mtr));
1040 if (store->media_type) {
1041 bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1043 db_create_mediatype_record(NULL, db, &mtr);
1045 mtr.MediaTypeId = 0;
1047 bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1048 sr.AutoChanger = store->autochanger;
1049 if (!db_create_storage_record(NULL, db, &sr)) {
1050 Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1054 store->StorageId = sr.StorageId; /* set storage Id */
1055 if (!sr.created) { /* if not created, update it */
1056 sr.AutoChanger = store->autochanger;
1057 if (!db_update_storage_record(NULL, db, &sr)) {
1058 Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1064 /* tls_require implies tls_enable */
1065 if (store->tls_require) {
1067 store->tls_enable = true;
1069 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1074 need_tls = store->tls_enable || store->tls_authenticate;
1076 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1077 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1078 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1079 store->name(), configfile);
1083 /* If everything is well, attempt to initialize our per-resource TLS context */
1084 if (OK && (need_tls || store->tls_require)) {
1085 /* Initialize TLS context:
1086 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1087 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1088 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1089 store->tls_ca_certdir, store->tls_certfile,
1090 store->tls_keyfile, NULL, NULL, NULL, true);
1092 if (!store->tls_ctx) {
1093 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1094 store->name(), configfile);
1100 /* Loop over all counters, defining them in each database */
1101 /* Set default value in all counters */
1103 foreach_res(counter, R_COUNTER) {
1104 /* Write to catalog? */
1105 if (!counter->created && counter->Catalog == catalog) {
1107 bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1108 cr.MinValue = counter->MinValue;
1109 cr.MaxValue = counter->MaxValue;
1110 cr.CurrentValue = counter->MinValue;
1111 if (counter->WrapCounter) {
1112 bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1114 cr.WrapCounter[0] = 0; /* empty string */
1116 if (db_create_counter_record(NULL, db, &cr)) {
1117 counter->CurrentValue = cr.CurrentValue;
1118 counter->created = true;
1119 Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1122 if (!counter->created) {
1123 counter->CurrentValue = counter->MinValue; /* default value */
1126 /* cleanup old job records */
1127 if (mode == UPDATE_AND_FIX) {
1128 db_sql_query(db, cleanup_created_job, NULL, NULL);
1129 db_sql_query(db, cleanup_running_job, NULL, NULL);
1132 /* Set SQL engine name in global for debugging */
1133 set_db_engine_name(db_get_engine_name(db));
1134 if (db) db_close_database(NULL, db);
1139 static void cleanup_old_files()
1142 struct dirent *entry, *result;
1144 int my_name_len = strlen(my_name);
1145 int len = strlen(director->working_directory);
1146 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1147 POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1150 const int nmatch = 30;
1151 regmatch_t pmatch[nmatch];
1154 /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1155 const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1157 /* Setup working directory prefix */
1158 pm_strcpy(basename, director->working_directory);
1159 if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1160 pm_strcat(basename, "/");
1163 /* Compile regex expressions */
1164 rc = regcomp(&preg1, pat1, REG_EXTENDED);
1166 regerror(rc, &preg1, prbuf, sizeof(prbuf));
1167 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1172 name_max = pathconf(".", _PC_NAME_MAX);
1173 if (name_max < 1024) {
1177 if (!(dp = opendir(director->working_directory))) {
1179 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1180 director->working_directory, be.bstrerror());
1185 entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1187 if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1190 /* Exclude any name with ., .., not my_name or containing a space */
1191 if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1192 strncmp(result->d_name, my_name, my_name_len) != 0) {
1193 Dmsg1(500, "Skipped: %s\n", result->d_name);
1197 /* Unlink files that match regexes */
1198 if (regexec(&preg1, result->d_name, nmatch, pmatch, 0) == 0) {
1199 pm_strcpy(cleanup, basename);
1200 pm_strcat(cleanup, result->d_name);
1201 Dmsg1(100, "Unlink: %s\n", cleanup);
1208 /* Be careful to free up the correct resources */
1212 free_pool_memory(cleanup);
1213 free_pool_memory(basename);