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;
71 static bool test_config = false;
73 /* Globals Exported */
74 DIRRES *director; /* Director resource */
77 char *configfile = NULL;
79 utime_t last_reload_time = 0;
81 /* Globals Imported */
82 extern RES_ITEM job_items[];
84 extern "C" { // work around visual compiler mangling variables
92 CHECK_CONNECTION, /* Check catalog connection */
93 UPDATE_CATALOG, /* Ensure that catalog is ok with conf */
94 UPDATE_AND_FIX /* Ensure that catalog is ok, and fix old jobs */
96 static bool check_catalog(cat_op mode);
98 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
100 static bool dir_sql_query(JCR *jcr, const char *cmd)
102 if (jcr && jcr->db && jcr->db->is_connected()) {
103 return db_sql_query(jcr->db, cmd, NULL, NULL);
108 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len)
110 if (jcr && jcr->db && jcr->db->is_connected()) {
111 db_escape_string(jcr, mdb, snew, sold, len);
121 "\nVersion: %s (%s)\n\n"
122 "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
123 " -c <file> set configuration file to file\n"
124 " -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
125 " -dt print timestamp in debug output\n"
127 " -f run in foreground (for debugging)\n"
129 " -m print kaboom output (for debugging)\n"
130 " -r <job> run <job> now\n"
132 " -t test - read configuration and exit\n"
134 " -v verbose user messages\n"
135 " -? print this message.\n"
136 "\n"), 2000, VERSION, BDATE);
142 * !!! WARNING !!! Use this function only when bacula is stopped.
143 * ie, after a fatal signal and before exiting the program
144 * Print information about a JCR
146 static void dir_debug_print(JCR *jcr, FILE *fp)
148 fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
149 jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
152 /*********************************************************************
154 * Main Bacula Director Server program
157 #if defined(HAVE_WIN32)
158 /* For Win32 main() is in src/win32 code ... */
159 #define main BaculaMain
162 int main (int argc, char *argv[])
166 bool no_signals = 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");
571 write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
572 delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
579 if (configfile != NULL) {
583 print_memory_pool_stats();
586 config->free_resources();
591 term_msg(); /* terminate message handler */
593 close_memory_pool(); /* release free memory in pool */
600 * Make a quick check to see that we have all the
603 * **** FIXME **** this routine could be a lot more
604 * intelligent and comprehensive.
606 static bool check_resources()
614 job = (JOB *)GetNextRes(R_JOB, NULL);
615 director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
617 Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
618 "Without that I don't know who I am :-(\n"), configfile);
621 set_working_directory(director->working_directory);
622 if (!director->messages) { /* If message resource not specified */
623 director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
624 if (!director->messages) {
625 Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
629 if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
630 Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
634 /* tls_require implies tls_enable */
635 if (director->tls_require) {
637 director->tls_enable = true;
639 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
644 need_tls = director->tls_enable || director->tls_authenticate;
646 if (!director->tls_certfile && need_tls) {
647 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
648 director->name(), configfile);
652 if (!director->tls_keyfile && need_tls) {
653 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
654 director->name(), configfile);
658 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
659 need_tls && director->tls_verify_peer) {
660 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
661 " Certificate Dir\" are defined for Director \"%s\" in %s."
662 " At least one CA certificate store is required"
663 " when using \"TLS Verify Peer\".\n"),
664 director->name(), configfile);
668 /* If everything is well, attempt to initialize our per-resource TLS context */
669 if (OK && (need_tls || director->tls_require)) {
670 /* Initialize TLS context:
671 * Args: CA certfile, CA certdir, Certfile, Keyfile,
672 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
673 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
674 director->tls_ca_certdir, director->tls_certfile,
675 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
676 director->tls_verify_peer);
678 if (!director->tls_ctx) {
679 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
680 director->name(), configfile);
687 Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
690 foreach_res(job, R_JOB) {
694 /* Handle Storage alists specifically */
695 JOB *jobdefs = job->jobdefs;
696 if (jobdefs->storage && !job->storage) {
698 job->storage = New(alist(10, not_owned_by_alist));
699 foreach_alist(st, jobdefs->storage) {
700 job->storage->append(st);
703 /* Handle RunScripts alists specifically */
704 if (jobdefs->RunScripts) {
707 if (!job->RunScripts) {
708 job->RunScripts = New(alist(10, not_owned_by_alist));
711 foreach_alist(rs, jobdefs->RunScripts) {
712 elt = copy_runscript(rs);
713 job->RunScripts->append(elt); /* we have to free it */
717 /* Transfer default items from JobDefs Resource */
718 for (i=0; job_items[i].name; i++) {
719 char **def_svalue, **svalue; /* string value */
720 uint32_t *def_ivalue, *ivalue; /* integer value */
721 bool *def_bvalue, *bvalue; /* bool value */
722 int64_t *def_lvalue, *lvalue; /* 64 bit values */
725 Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
726 job->name(), job_items[i].name,
727 bit_is_set(i, job->hdr.item_present),
728 bit_is_set(i, job->jobdefs->hdr.item_present));
730 if (!bit_is_set(i, job->hdr.item_present) &&
731 bit_is_set(i, job->jobdefs->hdr.item_present)) {
732 Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
733 job->name(), job_items[i].name);
734 offset = (char *)(job_items[i].value) - (char *)&res_all;
736 * Handle strings and directory strings
738 if (job_items[i].handler == store_str ||
739 job_items[i].handler == store_dir) {
740 def_svalue = (char **)((char *)(job->jobdefs) + offset);
741 Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
742 job->name(), job_items[i].name, *def_svalue, i, offset);
743 svalue = (char **)((char *)job + offset);
745 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
747 *svalue = bstrdup(*def_svalue);
748 set_bit(i, job->hdr.item_present);
752 } else if (job_items[i].handler == store_res) {
753 def_svalue = (char **)((char *)(job->jobdefs) + offset);
754 Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
755 job->name(), job_items[i].name, i, offset);
756 svalue = (char **)((char *)job + offset);
758 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
760 *svalue = *def_svalue;
761 set_bit(i, job->hdr.item_present);
763 * Handle alist resources
765 } else if (job_items[i].handler == store_alist_res) {
766 if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
767 set_bit(i, job->hdr.item_present);
770 * Handle integer fields
771 * Note, our store_bit does not handle bitmaped fields
773 } else if (job_items[i].handler == store_bit ||
774 job_items[i].handler == store_pint32 ||
775 job_items[i].handler == store_jobtype ||
776 job_items[i].handler == store_level ||
777 job_items[i].handler == store_int32 ||
778 job_items[i].handler == store_size32 ||
779 job_items[i].handler == store_migtype ||
780 job_items[i].handler == store_replace) {
781 def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
782 Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
783 job->name(), job_items[i].name, *def_ivalue, i, offset);
784 ivalue = (uint32_t *)((char *)job + offset);
785 *ivalue = *def_ivalue;
786 set_bit(i, job->hdr.item_present);
788 * Handle 64 bit integer fields
790 } else if (job_items[i].handler == store_time ||
791 job_items[i].handler == store_size64 ||
792 job_items[i].handler == store_speed ||
793 job_items[i].handler == store_int64) {
794 def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
795 Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
796 job->name(), job_items[i].name, *def_lvalue, i, offset);
797 lvalue = (int64_t *)((char *)job + offset);
798 *lvalue = *def_lvalue;
799 set_bit(i, job->hdr.item_present);
803 } else if (job_items[i].handler == store_bool) {
804 def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
805 Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
806 job->name(), job_items[i].name, *def_bvalue, i, offset);
807 bvalue = (bool *)((char *)job + offset);
808 *bvalue = *def_bvalue;
809 set_bit(i, job->hdr.item_present);
815 * Ensure that all required items are present
817 for (i=0; job_items[i].name; i++) {
818 if (job_items[i].flags & ITEM_REQUIRED) {
819 if (!bit_is_set(i, job->hdr.item_present)) {
820 Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
821 job_items[i].name, job->name());
825 /* If this triggers, take a look at lib/parse_conf.h */
826 if (i >= MAX_RES_ITEMS) {
827 Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
830 if (!job->storage && !job->pool->storage) {
831 Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
835 } /* End loop over Job res */
838 /* Loop over Consoles */
840 foreach_res(cons, R_CONSOLE) {
841 /* tls_require implies tls_enable */
842 if (cons->tls_require) {
844 cons->tls_enable = true;
846 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
852 need_tls = cons->tls_enable || cons->tls_authenticate;
854 if (!cons->tls_certfile && need_tls) {
855 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
856 cons->name(), configfile);
860 if (!cons->tls_keyfile && need_tls) {
861 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
862 cons->name(), configfile);
866 if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
867 && need_tls && cons->tls_verify_peer) {
868 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
869 " Certificate Dir\" are defined for Console \"%s\" in %s."
870 " At least one CA certificate store is required"
871 " when using \"TLS Verify Peer\".\n"),
872 cons->name(), configfile);
875 /* If everything is well, attempt to initialize our per-resource TLS context */
876 if (OK && (need_tls || cons->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 cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
881 cons->tls_ca_certdir, cons->tls_certfile,
882 cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
884 if (!cons->tls_ctx) {
885 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
886 cons->name(), configfile);
893 /* Loop over Clients */
895 foreach_res(client, R_CLIENT) {
896 /* tls_require implies tls_enable */
897 if (client->tls_require) {
899 client->tls_enable = true;
901 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
906 need_tls = client->tls_enable || client->tls_authenticate;
907 if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
908 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
909 " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
910 client->name(), configfile);
914 /* If everything is well, attempt to initialize our per-resource TLS context */
915 if (OK && (need_tls || client->tls_require)) {
916 /* Initialize TLS context:
917 * Args: CA certfile, CA certdir, Certfile, Keyfile,
918 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
919 client->tls_ctx = new_tls_context(client->tls_ca_certfile,
920 client->tls_ca_certdir, client->tls_certfile,
921 client->tls_keyfile, NULL, NULL, NULL,
924 if (!client->tls_ctx) {
925 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
926 client->name(), configfile);
934 close_msg(NULL); /* close temp message handler */
935 init_msg(NULL, director->messages); /* open daemon message handler */
936 last_reload_time = time(NULL);
943 * - we can check the connection (mode=CHECK_CONNECTION)
944 * - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
945 * - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
947 static bool check_catalog(cat_op mode)
952 /* Loop over databases */
954 foreach_res(catalog, R_CATALOG) {
957 * Make sure we can open catalog, otherwise print a warning
958 * message because the server is probably not running.
960 db = db_init_database(NULL, catalog->db_driver, catalog->db_name,
962 catalog->db_password, catalog->db_address,
963 catalog->db_port, catalog->db_socket,
964 catalog->mult_db_connections,
965 catalog->disable_batch_insert);
966 if (!db || !db_open_database(NULL, db)) {
967 Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
968 catalog->name(), catalog->db_name);
969 Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
970 catalog->name(), catalog->db_name);
972 Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
973 Pmsg1(000, "%s", db_strerror(db));
974 db_close_database(NULL, db);
980 /* Display a message if the db max_connections is too low */
981 if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
982 Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
983 Pmsg1(000, "%s", db_strerror(db));
986 /* we are in testing mode, so don't touch anything in the catalog */
987 if (mode == CHECK_CONNECTION) {
988 if (db) db_close_database(NULL, db);
992 /* Loop over all pools, defining/updating them in each database */
994 foreach_res(pool, R_POOL) {
996 * If the Pool has a catalog resource create the pool only
999 if (!pool->catalog || pool->catalog == catalog) {
1000 create_pool(NULL, db, pool, POOL_OP_UPDATE); /* update request */
1004 /* Once they are created, we can loop over them again, updating
1005 * references (RecyclePool)
1007 foreach_res(pool, R_POOL) {
1009 * If the Pool has a catalog resource update the pool only
1012 if (!pool->catalog || pool->catalog == catalog) {
1013 update_pool_references(NULL, db, pool);
1017 /* Ensure basic client record is in DB */
1019 foreach_res(client, R_CLIENT) {
1021 /* Create clients only if they use the current catalog */
1022 if (client->catalog != catalog) {
1023 Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1024 client->name(), client->catalog->name(), catalog->name());
1027 Dmsg2(500, "create cat=%s for client=%s\n",
1028 client->catalog->name(), client->name());
1029 memset(&cr, 0, sizeof(cr));
1030 bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1032 db_create_client_record(NULL, db, &cr);
1035 /* Ensure basic storage record is in DB */
1037 foreach_res(store, R_STORAGE) {
1040 memset(&sr, 0, sizeof(sr));
1041 memset(&mtr, 0, sizeof(mtr));
1042 if (store->media_type) {
1043 bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1045 db_create_mediatype_record(NULL, db, &mtr);
1047 mtr.MediaTypeId = 0;
1049 bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1050 sr.AutoChanger = store->autochanger;
1051 if (!db_create_storage_record(NULL, db, &sr)) {
1052 Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1056 store->StorageId = sr.StorageId; /* set storage Id */
1057 if (!sr.created) { /* if not created, update it */
1058 sr.AutoChanger = store->autochanger;
1059 if (!db_update_storage_record(NULL, db, &sr)) {
1060 Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1066 /* tls_require implies tls_enable */
1067 if (store->tls_require) {
1069 store->tls_enable = true;
1071 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1076 need_tls = store->tls_enable || store->tls_authenticate;
1078 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1079 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1080 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1081 store->name(), configfile);
1085 /* If everything is well, attempt to initialize our per-resource TLS context */
1086 if (OK && (need_tls || store->tls_require)) {
1087 /* Initialize TLS context:
1088 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1089 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1090 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1091 store->tls_ca_certdir, store->tls_certfile,
1092 store->tls_keyfile, NULL, NULL, NULL, true);
1094 if (!store->tls_ctx) {
1095 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1096 store->name(), configfile);
1102 /* Loop over all counters, defining them in each database */
1103 /* Set default value in all counters */
1105 foreach_res(counter, R_COUNTER) {
1106 /* Write to catalog? */
1107 if (!counter->created && counter->Catalog == catalog) {
1109 bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1110 cr.MinValue = counter->MinValue;
1111 cr.MaxValue = counter->MaxValue;
1112 cr.CurrentValue = counter->MinValue;
1113 if (counter->WrapCounter) {
1114 bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1116 cr.WrapCounter[0] = 0; /* empty string */
1118 if (db_create_counter_record(NULL, db, &cr)) {
1119 counter->CurrentValue = cr.CurrentValue;
1120 counter->created = true;
1121 Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1124 if (!counter->created) {
1125 counter->CurrentValue = counter->MinValue; /* default value */
1128 /* cleanup old job records */
1129 if (mode == UPDATE_AND_FIX) {
1130 db_sql_query(db, cleanup_created_job, NULL, NULL);
1131 db_sql_query(db, cleanup_running_job, NULL, NULL);
1134 /* Set SQL engine name in global for debugging */
1135 set_db_engine_name(db_get_engine_name(db));
1136 if (db) db_close_database(NULL, db);
1141 static void cleanup_old_files()
1144 struct dirent *entry, *result;
1146 int my_name_len = strlen(my_name);
1147 int len = strlen(director->working_directory);
1148 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1149 POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1152 const int nmatch = 30;
1153 regmatch_t pmatch[nmatch];
1156 /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1157 const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1159 /* Setup working directory prefix */
1160 pm_strcpy(basename, director->working_directory);
1161 if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1162 pm_strcat(basename, "/");
1165 /* Compile regex expressions */
1166 rc = regcomp(&preg1, pat1, REG_EXTENDED);
1168 regerror(rc, &preg1, prbuf, sizeof(prbuf));
1169 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1174 name_max = pathconf(".", _PC_NAME_MAX);
1175 if (name_max < 1024) {
1179 if (!(dp = opendir(director->working_directory))) {
1181 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1182 director->working_directory, be.bstrerror());
1187 entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1189 if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1192 /* Exclude any name with ., .., not my_name or containing a space */
1193 if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1194 strncmp(result->d_name, my_name, my_name_len) != 0) {
1195 Dmsg1(500, "Skipped: %s\n", result->d_name);
1199 /* Unlink files that match regexes */
1200 if (regexec(&preg1, result->d_name, nmatch, pmatch, 0) == 0) {
1201 pm_strcpy(cleanup, basename);
1202 pm_strcat(cleanup, result->d_name);
1203 Dmsg1(100, "Unlink: %s\n", cleanup);
1210 /* Be careful to free up the correct resources */
1214 free_pool_memory(cleanup);
1215 free_pool_memory(basename);