2 Bacula(R) - The Network Backup Solution
4 Copyright (C) 2000-2017 Kern Sibbald
6 The original author of Bacula is Kern Sibbald, with contributions
7 from many others, a complete list can be found in the file AUTHORS.
9 You may use this file and others of this release according to the
10 license defined in the LICENSE file, which includes the Affero General
11 Public License, v3.0 ("AGPLv3") and some additional permissions and
12 terms pursuant to its AGPLv3 Section 7.
14 This notice must be preserved when any source code is
15 conveyed and/or propagated.
17 Bacula(R) is a registered trademark of Kern Sibbald.
20 * Bacula Director daemon -- this is the main program
22 * Kern Sibbald, March MM
28 #include "lib/bregex.h"
34 #define NAMELEN(dirent) (strlen((dirent)->d_name))
36 #ifndef HAVE_READDIR_R
37 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
40 /* Forward referenced subroutines */
41 void terminate_dird(int sig);
42 static bool check_resources();
43 static void cleanup_old_files();
44 static void resize_reload(int nb);
46 /* Exported subroutines */
47 extern "C" void reload_config(int sig);
48 extern void invalidate_schedules();
49 extern bool parse_dir_config(CONFIG *config, const char *configfile, int exit_code);
51 /* Imported subroutines */
52 JCR *wait_for_next_job(char *runjob);
53 void term_scheduler();
54 void term_ua_server();
55 void start_UA_server(dlist *addrs);
56 void init_job_server(int max_workers);
57 void term_job_server();
58 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
59 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
60 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
61 void store_migtype(LEX *lc, RES_ITEM *item, int index, int pass);
62 void init_device_resources();
65 static char *runjob = NULL;
66 static bool foreground = false;
67 static void init_reload(void);
68 static CONFIG *config;
69 static bool test_config = false;
71 /* Globals Exported */
72 DIRRES *director; /* Director resource */
75 char *configfile = NULL;
77 utime_t last_reload_time = 0;
80 /* Globals Imported */
81 extern dlist client_globals;
82 extern dlist store_globals;
83 extern dlist job_globals;
84 extern dlist sched_globals;
85 extern RES_ITEM job_items[];
87 extern "C" { // work around visual compiler mangling variables
95 CHECK_CONNECTION, /* Check catalog connection */
96 UPDATE_CATALOG, /* Ensure that catalog is ok with conf */
97 UPDATE_AND_FIX /* Ensure that catalog is ok, and fix old jobs */
99 static bool check_catalog(cat_op mode);
101 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
103 static bool dir_sql_query(JCR *jcr, const char *cmd)
105 if (jcr && jcr->db && jcr->db->is_connected()) {
106 return db_sql_query(jcr->db, cmd, NULL, NULL);
111 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len)
113 if (jcr && jcr->db && jcr->db->is_connected()) {
114 db_escape_string(jcr, mdb, snew, sold, len);
124 "\n%sVersion: %s (%s)\n\n"
125 "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
126 " -c <file> set configuration file to file\n"
127 " -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
128 " -dt print timestamp in debug output\n"
130 " -f run in foreground (for debugging)\n"
132 " -m print kaboom output (for debugging)\n"
133 " -r <job> run <job> now\n"
135 " -t test - read configuration and exit\n"
137 " -v verbose user messages\n"
138 " -? print this message.\n"
139 "\n"), 2000, "", VERSION, BDATE);
145 * !!! WARNING !!! Use this function only when bacula is stopped.
146 * ie, after a fatal signal and before exiting the program
147 * Print information about a JCR
149 static void dir_debug_print(JCR *jcr, FILE *fp)
151 fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
152 jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
155 /*********************************************************************
157 * Main Bacula Director Server program
160 #if defined(HAVE_WIN32)
161 /* For Win32 main() is in src/win32 code ... */
162 #define main BaculaMain
165 /* DELETE ME when bugs in MA1512, MA1632 MA1639 are fixed */
166 extern void (*MA1512_reload_job_end_cb)(JCR *,void *);
167 static void reload_job_end_cb(JCR *jcr, void *ctx);
169 int main (int argc, char *argv[])
173 bool no_signals = false;
177 /* DELETE ME when bugs in MA1512, MA1632 MA1639 are fixed */
178 MA1512_reload_job_end_cb = reload_job_end_cb;
180 start_heap = sbrk(0);
181 setlocale(LC_ALL, "");
182 bindtextdomain("bacula", LOCALEDIR);
183 textdomain("bacula");
186 my_name_is(argc, argv, "bacula-dir");
187 init_msg(NULL, NULL); /* initialize message handler */
189 daemon_start_time = time(NULL);
190 setup_daemon_message_queue();
191 console_command = run_console_command;
193 while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?T")) != -1) {
195 case 'c': /* specify config file */
196 if (configfile != NULL) {
199 configfile = bstrdup(optarg);
202 case 'd': /* set debug level */
203 if (*optarg == 't') {
204 dbg_timestamp = true;
207 /* We probably find a tag list -d 10,sql,bvfs */
208 if ((p = strchr(optarg, ',')) != NULL) {
211 debug_level = atoi(optarg);
212 if (debug_level <= 0) {
216 debug_parse_tags(p+1, &debug_level_tags);
219 Dmsg1(10, "Debug level = %lld\n", debug_level);
226 case 'f': /* run in foreground */
230 case 'g': /* set group id */
234 case 'm': /* print kaboom output */
238 case 'r': /* run job */
239 if (runjob != NULL) {
243 runjob = bstrdup(optarg);
247 case 's': /* turn off signals */
251 case 't': /* test config */
255 case 'u': /* set uid */
259 case 'v': /* verbose */
273 if (configfile != NULL) {
276 configfile = bstrdup(*argv);
284 if (!foreground && !test_config) {
286 init_stack_dump(); /* grab new pid */
290 init_signals(terminate_dird);
293 if (configfile == NULL) {
294 configfile = bstrdup(CONFIG_FILE);
297 config = New(CONFIG());
298 parse_dir_config(config, configfile, M_ERROR_TERM);
300 if (init_crypto() != 0) {
301 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
304 if (!check_resources()) {
305 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
309 /* Create pid must come after we are a daemon -- so we have our final pid */
310 create_pid_file(director->pid_directory, "bacula-dir",
311 get_first_port_host_order(director->DIRaddrs));
312 read_state_file(director->working_directory, "bacula-dir",
313 get_first_port_host_order(director->DIRaddrs));
316 set_jcr_in_tsd(INVALID_JCR);
317 set_thread_concurrency(director->MaxConcurrentJobs * 2 +
318 4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
319 lmgr_init_thread(); /* initialize the lockmanager stack */
321 load_dir_plugins(director->plugin_directory);
323 drop(uid, gid, false); /* reduce privileges if requested */
325 /* If we are in testing mode, we don't try to fix the catalog */
326 cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
328 if (!check_catalog(mode)) {
329 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
336 my_name_is(0, NULL, director->name()); /* set user defined name */
340 /* Plug database interface for library routines */
341 p_sql_query = (sql_query_call)dir_sql_query;
342 p_sql_escape = (sql_escape_call)dir_sql_escape;
344 FDConnectTimeout = (int)director->FDConnectTimeout;
345 SDConnectTimeout = (int)director->SDConnectTimeout;
347 resize_reload(director->MaxReload);
349 #if !defined(HAVE_WIN32)
350 signal(SIGHUP, reload_config);
353 init_console_msg(working_directory);
355 Dmsg0(200, "Start UA server\n");
356 start_UA_server(director->DIRaddrs);
358 start_watchdog(); /* start network watchdog thread */
360 init_jcr_subsystem(); /* start JCR watchdogs etc. */
362 init_job_server(director->MaxConcurrentJobs);
364 dbg_jcr_add_hook(dir_debug_print); /* used to director variables */
365 dbg_jcr_add_hook(bdb_debug_print); /* used to debug B_DB connexion after fatal signal */
367 // init_device_resources();
369 Dmsg0(200, "wait for next job\n");
370 /* Main loop -- call scheduler to get next job to run */
371 while ( (jcr = wait_for_next_job(runjob)) ) {
372 run_job(jcr); /* run job */
373 free_jcr(jcr); /* release jcr */
374 set_jcr_in_tsd(INVALID_JCR);
375 if (runjob) { /* command line, run a single job? */
376 break; /* yes, terminate */
385 struct RELOAD_TABLE {
390 static int max_reloads = 32;
391 static RELOAD_TABLE *reload_table=NULL;
393 static void resize_reload(int nb)
395 if (nb <= max_reloads) {
399 reload_table = (RELOAD_TABLE*)realloc(reload_table, nb * sizeof(RELOAD_TABLE));
400 for (int i=max_reloads; i < nb ; i++) {
401 reload_table[i].job_count = 0;
402 reload_table[i].res_head = NULL;
407 static void init_reload(void)
409 reload_table = (RELOAD_TABLE*)malloc(max_reloads * sizeof(RELOAD_TABLE));
410 for (int i=0; i < max_reloads; i++) {
411 reload_table[i].job_count = 0;
412 reload_table[i].res_head = NULL;
417 * This subroutine frees a saved resource table.
418 * It was saved when a new table was created with "reload"
420 static void free_saved_resources(int table)
423 int num = r_last - r_first + 1;
424 RES_HEAD **res_tab = reload_table[table].res_head;
426 if (res_tab == NULL) {
427 Dmsg1(100, "res_tab for table %d already released.\n", table);
430 Dmsg1(100, "Freeing resources for table %d\n", table);
431 for (int j=0; j<num; j++) {
433 next = res_tab[j]->first;
436 next = res->res_next;
437 free_resource(res, r_first + j);
439 free(res_tab[j]->res_list);
445 reload_table[table].job_count = 0;
446 reload_table[table].res_head = NULL;
450 * Called here at the end of every job that was
451 * hooked decrementing the active job_count. When
452 * it goes to zero, no one is using the associated
453 * resource table, so free it.
455 static void reload_job_end_cb(JCR *jcr, void *ctx)
457 int reload_id = (int)((intptr_t)ctx);
458 Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
459 reload_id, reload_table[reload_id].job_count);
462 if (--reload_table[reload_id].job_count <= 0) {
463 free_saved_resources(reload_id);
469 static int find_free_reload_table_entry()
472 for (int i=0; i < max_reloads; i++) {
473 if (reload_table[i].res_head == NULL) {
481 static pthread_mutex_t reload_mutex = PTHREAD_MUTEX_INITIALIZER;
484 * If we get here, we have received a SIGHUP, which means to
485 * reread our configuration file.
487 * The algorithm used is as follows: we count how many jobs are
488 * running and mark the running jobs to make a callback on
489 * exiting. The old config is saved with the reload table
490 * id in a reload table. The new config file is read. Now, as
491 * each job exits, it calls back to the reload_job_end_cb(), which
492 * decrements the count of open jobs for the given reload table.
493 * When the count goes to zero, we release those resources.
494 * This allows us to have pointers into the resource table (from
495 * jobs), and once they exit and all the pointers are released, we
496 * release the old table. Note, if no new jobs are running since the
497 * last reload, then the old resources will be immediately release.
498 * A console is considered a job because it may have pointers to
499 * resources, but a SYSTEM job is not since it *should* not have any
500 * permanent pointers to jobs.
503 void reload_config(int sig)
505 static bool already_here = false;
506 #if !defined(HAVE_WIN32)
510 int njobs = 0; /* number of running jobs */
515 /* Wait to do the reload */
521 Jmsg(NULL, M_INFO, 0, _("Already doing a reload request, "
522 "request ignored.\n"));
525 Dmsg0(10, "Already doing a reload request, waiting a bit\n");
534 #if !defined(HAVE_WIN32)
536 sigaddset(&set, SIGHUP);
537 sigprocmask(SIG_BLOCK, &set, NULL);
543 table = find_free_reload_table_entry();
545 Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. "
546 "Request ignored.\n"));
550 Dmsg1(100, "Reload_config njobs=%d\n", njobs);
551 /* Save current res_head */
552 reload_table[table].res_head = res_head;
553 Dmsg1(100, "Saved old config in table %d\n", table);
555 /* Create a new res_head and parse into it */
556 ok = parse_dir_config(config, configfile, M_ERROR);
558 Dmsg0(100, "Reloaded config file\n");
559 if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
561 * We got an error, save broken point, restore old one,
562 * then release everything from broken pointer.
564 rtable = find_free_reload_table_entry(); /* save new, bad table */
566 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
567 Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
569 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
570 Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
572 /* Save broken res_head pointer */
573 reload_table[rtable].res_head = res_head;
575 /* Now restore old resource pointer */
576 res_head = reload_table[table].res_head;
577 table = rtable; /* release new, bad, saved table below */
579 invalidate_schedules();
581 * Hook all active jobs so that they release this table
584 if (jcr->getJobType() != JT_SYSTEM) {
585 reload_table[table].job_count++;
586 job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
592 * Now walk through globals tables and plug them into the
596 foreach_dlist(cg, &client_globals) {
598 client = GetClientResWithName(cg->name);
600 Jmsg(NULL, M_INFO, 0, _("Client=%s not found. Assuming it was removed!!!\n"), cg->name);
602 client->globals = cg; /* Set globals pointer */
606 foreach_dlist(sg, &store_globals) {
608 store = GetStoreResWithName(sg->name);
610 Jmsg(NULL, M_INFO, 0, _("Storage=%s not found. Assuming it was removed!!!\n"), sg->name);
612 store->globals = sg; /* set globals pointer */
613 Dmsg2(200, "Reload found numConcurrent=%ld for Store %s\n",
614 sg->NumConcurrentJobs, sg->name);
618 foreach_dlist(jg, &job_globals) {
620 job = GetJobResWithName(jg->name);
622 Jmsg(NULL, M_INFO, 0, _("Job=%s not found. Assuming it was removed!!!\n"), jg->name);
624 job->globals = jg; /* Set globals pointer */
628 foreach_dlist(schg, &sched_globals) {
630 sched = GetSchedResWithName(schg->name);
632 Jmsg(NULL, M_INFO, 0, _("Schedule=%s not found. Assuming it was removed!!!\n"), schg->name);
634 sched->globals = schg; /* Set globals pointer */
639 /* Reset other globals */
640 set_working_directory(director->working_directory);
641 FDConnectTimeout = director->FDConnectTimeout;
642 SDConnectTimeout = director->SDConnectTimeout;
643 Dmsg0(10, "Director's configuration file reread.\n");
645 /* Now release saved resources, if no jobs using the resources */
647 free_saved_resources(table);
653 #if !defined(HAVE_WIN32)
654 sigprocmask(SIG_UNBLOCK, &set, NULL);
655 signal(SIGHUP, reload_config);
657 already_here = false;
660 /* Cleanup and then exit */
661 void terminate_dird(int sig)
663 static bool already_here = false;
665 if (already_here) { /* avoid recursive temination problems */
666 bmicrosleep(2, 0); /* yield */
670 debug_level = 0; /* turn off debug */
672 generate_daemon_event(NULL, "Exit");
675 write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
676 delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
683 if (configfile != NULL) {
687 print_memory_pool_stats();
694 term_msg(); /* terminate message handler */
697 free_daemon_message_queue();
705 * Now walk through resource globals tables and release them
708 foreach_dlist(cg, &client_globals) {
710 if (cg->SetIPaddress) {
711 free(cg->SetIPaddress);
716 foreach_dlist(sg, &store_globals) {
721 foreach_dlist(jg, &job_globals) {
725 close_memory_pool(); /* release free memory in pool */
732 * Make a quick check to see that we have all the
735 * **** FIXME **** this routine could be a lot more
736 * intelligent and comprehensive.
738 static bool check_resources()
746 job = (JOB *)GetNextRes(R_JOB, NULL);
747 director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
749 Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
750 "Without that I don't know who I am :-(\n"), configfile);
753 set_working_directory(director->working_directory);
754 if (!director->messages) { /* If message resource not specified */
755 director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
756 if (!director->messages) {
757 Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
761 if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
762 Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
766 /* tls_require implies tls_enable */
767 if (director->tls_require) {
769 director->tls_enable = true;
771 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
776 need_tls = director->tls_enable || director->tls_authenticate;
778 if (!director->tls_certfile && need_tls) {
779 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
780 director->name(), configfile);
784 if (!director->tls_keyfile && need_tls) {
785 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
786 director->name(), configfile);
790 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
791 need_tls && director->tls_verify_peer) {
792 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
793 " Certificate Dir\" are defined for Director \"%s\" in %s."
794 " At least one CA certificate store is required"
795 " when using \"TLS Verify Peer\".\n"),
796 director->name(), configfile);
800 /* If everything is well, attempt to initialize our per-resource TLS context */
801 if (OK && (need_tls || director->tls_require)) {
802 /* Initialize TLS context:
803 * Args: CA certfile, CA certdir, Certfile, Keyfile,
804 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
805 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
806 director->tls_ca_certdir, director->tls_certfile,
807 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
808 director->tls_verify_peer);
810 if (!director->tls_ctx) {
811 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
812 director->name(), configfile);
819 Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
822 foreach_res(job, R_JOB) {
826 JOB *jobdefs = job->jobdefs;
827 /* Handle RunScripts alists specifically */
828 if (jobdefs->RunScripts) {
831 if (!job->RunScripts) {
832 job->RunScripts = New(alist(10, not_owned_by_alist));
835 foreach_alist(rs, jobdefs->RunScripts) {
836 elt = copy_runscript(rs);
837 job->RunScripts->append(elt); /* we have to free it */
841 /* Transfer default items from JobDefs Resource */
842 for (i=0; job_items[i].name; i++) {
843 char **def_svalue, **svalue; /* string value */
844 uint32_t *def_ivalue, *ivalue; /* integer value */
845 bool *def_bvalue, *bvalue; /* bool value */
846 int64_t *def_lvalue, *lvalue; /* 64 bit values */
847 alist **def_avalue, **avalue; /* alist values */
850 Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
851 job->name(), job_items[i].name,
852 bit_is_set(i, job->hdr.item_present),
853 bit_is_set(i, job->jobdefs->hdr.item_present));
855 if (!bit_is_set(i, job->hdr.item_present) &&
856 bit_is_set(i, job->jobdefs->hdr.item_present)) {
857 Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
858 job->name(), job_items[i].name);
859 offset = (char *)(job_items[i].value) - (char *)&res_all;
861 * Handle strings and directory strings
863 if (job_items[i].handler == store_str ||
864 job_items[i].handler == store_dir) {
865 def_svalue = (char **)((char *)(job->jobdefs) + offset);
866 Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
867 job->name(), job_items[i].name, *def_svalue, i, offset);
868 svalue = (char **)((char *)job + offset);
870 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
872 *svalue = bstrdup(*def_svalue);
873 set_bit(i, job->hdr.item_present);
877 } else if (job_items[i].handler == store_res) {
878 def_svalue = (char **)((char *)(job->jobdefs) + offset);
879 Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
880 job->name(), job_items[i].name, i, offset);
881 svalue = (char **)((char *)job + offset);
883 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
885 *svalue = *def_svalue;
886 set_bit(i, job->hdr.item_present);
888 * Handle alist resources
890 } else if (job_items[i].handler == store_alist_res) {
893 def_avalue = (alist **)((char *)(job->jobdefs) + offset);
894 avalue = (alist **)((char *)job + offset);
896 *avalue = New(alist(10, not_owned_by_alist));
898 foreach_alist(elt, (*def_avalue)) {
899 (*avalue)->append(elt);
901 set_bit(i, job->hdr.item_present);
903 * Handle integer fields
904 * Note, our store_bit does not handle bitmaped fields
906 } else if (job_items[i].handler == store_bit ||
907 job_items[i].handler == store_pint32 ||
908 job_items[i].handler == store_jobtype ||
909 job_items[i].handler == store_level ||
910 job_items[i].handler == store_int32 ||
911 job_items[i].handler == store_size32 ||
912 job_items[i].handler == store_migtype ||
913 job_items[i].handler == store_replace) {
914 def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
915 Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
916 job->name(), job_items[i].name, *def_ivalue, i, offset);
917 ivalue = (uint32_t *)((char *)job + offset);
918 *ivalue = *def_ivalue;
919 set_bit(i, job->hdr.item_present);
921 * Handle 64 bit integer fields
923 } else if (job_items[i].handler == store_time ||
924 job_items[i].handler == store_size64 ||
925 job_items[i].handler == store_speed ||
926 job_items[i].handler == store_int64) {
927 def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
928 Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
929 job->name(), job_items[i].name, *def_lvalue, i, offset);
930 lvalue = (int64_t *)((char *)job + offset);
931 *lvalue = *def_lvalue;
932 set_bit(i, job->hdr.item_present);
936 } else if (job_items[i].handler == store_bool) {
937 def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
938 Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
939 job->name(), job_items[i].name, *def_bvalue, i, offset);
940 bvalue = (bool *)((char *)job + offset);
941 *bvalue = *def_bvalue;
942 set_bit(i, job->hdr.item_present);
948 * Ensure that all required items are present
950 for (i=0; job_items[i].name; i++) {
951 if (job_items[i].flags & ITEM_REQUIRED) {
952 if (!bit_is_set(i, job->hdr.item_present)) {
953 Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
954 job_items[i].name, job->name());
958 /* If this triggers, take a look at lib/parse_conf.h */
959 if (i >= MAX_RES_ITEMS) {
960 Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
963 if (!job->storage && !job->pool->storage) {
964 Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
969 /* Make sure the job doesn't use the Scratch Pool to start with */
971 if (!check_pool(job->JobType, job->JobLevel,
972 job->pool, job->next_pool, &name)) {
973 Jmsg(NULL, M_FATAL, 0,
974 _("%s \"Scratch\" not valid in Job \"%s\".\n"),
978 } /* End loop over Job res */
981 /* Loop over Consoles */
983 foreach_res(cons, R_CONSOLE) {
984 /* tls_require implies tls_enable */
985 if (cons->tls_require) {
987 cons->tls_enable = true;
989 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
995 need_tls = cons->tls_enable || cons->tls_authenticate;
997 if (!cons->tls_certfile && need_tls) {
998 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
999 cons->name(), configfile);
1003 if (!cons->tls_keyfile && need_tls) {
1004 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
1005 cons->name(), configfile);
1009 if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
1010 && need_tls && cons->tls_verify_peer) {
1011 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
1012 " Certificate Dir\" are defined for Console \"%s\" in %s."
1013 " At least one CA certificate store is required"
1014 " when using \"TLS Verify Peer\".\n"),
1015 cons->name(), configfile);
1018 /* If everything is well, attempt to initialize our per-resource TLS context */
1019 if (OK && (need_tls || cons->tls_require)) {
1020 /* Initialize TLS context:
1021 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1022 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1023 cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
1024 cons->tls_ca_certdir, cons->tls_certfile,
1025 cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
1027 if (!cons->tls_ctx) {
1028 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
1029 cons->name(), configfile);
1036 /* Loop over Clients */
1038 foreach_res(client, R_CLIENT) {
1039 /* tls_require implies tls_enable */
1040 if (client->tls_require) {
1042 client->tls_enable = true;
1044 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1049 need_tls = client->tls_enable || client->tls_authenticate;
1050 if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
1051 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1052 " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
1053 client->name(), configfile);
1057 /* If everything is well, attempt to initialize our per-resource TLS context */
1058 if (OK && (need_tls || client->tls_require)) {
1059 /* Initialize TLS context:
1060 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1061 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1062 client->tls_ctx = new_tls_context(client->tls_ca_certfile,
1063 client->tls_ca_certdir, client->tls_certfile,
1064 client->tls_keyfile, NULL, NULL, NULL,
1067 if (!client->tls_ctx) {
1068 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
1069 client->name(), configfile);
1075 /* Loop over all pools, check PoolType */
1077 foreach_res(pool, R_POOL) {
1078 if (!pool->pool_type) {
1079 /* This case is checked by the parse engine, we should not */
1080 Jmsg(NULL, M_FATAL, 0, _("PoolType required in Pool resource \"%s\".\n"), pool->hdr.name);
1084 if ((strcasecmp(pool->pool_type, NT_("backup")) != 0) &&
1085 (strcasecmp(pool->pool_type, NT_("copy")) != 0) &&
1086 (strcasecmp(pool->pool_type, NT_("cloned")) != 0) &&
1087 (strcasecmp(pool->pool_type, NT_("archive")) != 0) &&
1088 (strcasecmp(pool->pool_type, NT_("migration")) != 0) &&
1089 (strcasecmp(pool->pool_type, NT_("scratch")) != 0))
1091 Jmsg(NULL, M_FATAL, 0, _("Invalid PoolType \"%s\" in Pool resource \"%s\".\n"), pool->pool_type, pool->hdr.name);
1095 if (pool->NextPool && strcmp(pool->NextPool->name(), "Scratch") == 0) {
1096 Jmsg(NULL, M_FATAL, 0,
1097 _("NextPool \"Scratch\" not valid in Pool \"%s\".\n"),
1105 close_msg(NULL); /* close temp message handler */
1106 init_msg(NULL, director->messages); /* open daemon message handler */
1107 last_reload_time = time(NULL);
1114 * - we can check the connection (mode=CHECK_CONNECTION)
1115 * - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
1116 * - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
1117 * - we hook up the Autochange children with the parent, and
1118 * we hook the shared autochangers together.
1120 static bool check_catalog(cat_op mode)
1124 STORE *store, *ac_child;
1126 /* Loop over databases */
1128 foreach_res(catalog, R_CATALOG) {
1131 * Make sure we can open catalog, otherwise print a warning
1132 * message because the server is probably not running.
1134 db = db_init_database(NULL, catalog->db_driver, catalog->db_name,
1136 catalog->db_password, catalog->db_address,
1137 catalog->db_port, catalog->db_socket,
1138 catalog->db_ssl_mode, catalog->db_ssl_key,
1139 catalog->db_ssl_cert, catalog->db_ssl_ca,
1140 catalog->db_ssl_capath, catalog->db_ssl_cipher,
1141 catalog->mult_db_connections,
1142 catalog->disable_batch_insert);
1143 if (!db || !db_open_database(NULL, db)) {
1144 Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
1145 catalog->name(), catalog->db_name);
1146 Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
1147 catalog->name(), catalog->db_name);
1149 Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
1150 Pmsg1(000, "%s", db_strerror(db));
1151 db_close_database(NULL, db);
1157 /* Display a message if the db max_connections is too low */
1158 if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
1159 Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
1160 Pmsg1(000, "%s", db_strerror(db));
1163 /* we are in testing mode, so don't touch anything in the catalog */
1164 if (mode == CHECK_CONNECTION) {
1165 if (db) db_close_database(NULL, db);
1169 /* Loop over all pools, defining/updating them in each database */
1171 foreach_res(pool, R_POOL) {
1173 * If the Pool has a catalog resource create the pool only
1176 if (!pool->catalog || pool->catalog == catalog) {
1177 create_pool(NULL, db, pool, POOL_OP_UPDATE); /* update request */
1181 /* Once they are created, we can loop over them again, updating
1182 * references (RecyclePool)
1184 foreach_res(pool, R_POOL) {
1186 * If the Pool has a catalog resource update the pool only
1189 if (!pool->catalog || pool->catalog == catalog) {
1190 update_pool_references(NULL, db, pool);
1194 /* Ensure basic client record is in DB */
1196 foreach_res(client, R_CLIENT) {
1198 /* Create clients only if they use the current catalog */
1199 if (client->catalog != catalog) {
1200 Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1201 client->name(), client->catalog->name(), catalog->name());
1204 Dmsg2(500, "create cat=%s for client=%s\n",
1205 client->catalog->name(), client->name());
1206 memset(&cr, 0, sizeof(cr));
1207 bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1209 db_create_client_record(NULL, db, &cr);
1212 /* Ensure basic storage record is in DB */
1213 foreach_res(store, R_STORAGE) {
1216 memset(&sr, 0, sizeof(sr));
1217 memset(&mtr, 0, sizeof(mtr));
1218 if (store->media_type) {
1219 bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1221 db_create_mediatype_record(NULL, db, &mtr);
1223 mtr.MediaTypeId = 0;
1225 bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1226 sr.AutoChanger = store->autochanger;
1227 if (!db_create_storage_record(NULL, db, &sr)) {
1228 Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1232 store->StorageId = sr.StorageId; /* set storage Id */
1233 if (!sr.created) { /* if not created, update it */
1234 sr.AutoChanger = store->autochanger;
1235 if (!db_update_storage_record(NULL, db, &sr)) {
1236 Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1242 /* tls_require implies tls_enable */
1243 if (store->tls_require) {
1245 store->tls_enable = true;
1247 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1252 need_tls = store->tls_enable || store->tls_authenticate;
1254 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1255 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1256 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1257 store->name(), configfile);
1261 /* If everything is well, attempt to initialize our per-resource TLS context */
1262 if (OK && (need_tls || store->tls_require)) {
1263 /* Initialize TLS context:
1264 * Args: CA certfile, CA certdir, Certfile, Keyfile,
1265 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1266 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1267 store->tls_ca_certdir, store->tls_certfile,
1268 store->tls_keyfile, NULL, NULL, NULL, true);
1270 if (!store->tls_ctx) {
1271 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1272 store->name(), configfile);
1278 /* Link up all the children for each changer */
1279 foreach_res(store, R_STORAGE) {
1281 if (store->changer == store) { /* we are a real Autochanger */
1282 store->ac_group = get_pool_memory(PM_FNAME);
1283 store->ac_group[0] = 0;
1284 pm_strcat(store->ac_group, edit_int64(store->StorageId, sid));
1285 /* Now look for children who point to this storage */
1286 foreach_res(ac_child, R_STORAGE) {
1287 if (ac_child != store && ac_child->changer == store) {
1288 /* Found a child -- add StorageId */
1289 pm_strcat(store->ac_group, ",");
1290 pm_strcat(store->ac_group, edit_int64(ac_child->StorageId, sid));
1296 /* Link up all the shared storage devices */
1297 foreach_res(store, R_STORAGE) {
1298 if (store->ac_group) { /* we are a real Autochanger */
1299 /* Now look for Shared Storage who point to this storage */
1300 foreach_res(ac_child, R_STORAGE) {
1301 if (ac_child->shared_storage == store && ac_child->ac_group &&
1302 ac_child->shared_storage != ac_child) {
1303 pm_strcat(store->ac_group, ",");
1304 pm_strcat(store->ac_group, ac_child->ac_group);
1310 /* Loop over all counters, defining them in each database */
1311 /* Set default value in all counters */
1313 foreach_res(counter, R_COUNTER) {
1314 /* Write to catalog? */
1315 if (!counter->created && counter->Catalog == catalog) {
1317 bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1318 cr.MinValue = counter->MinValue;
1319 cr.MaxValue = counter->MaxValue;
1320 cr.CurrentValue = counter->MinValue;
1321 if (counter->WrapCounter) {
1322 bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1324 cr.WrapCounter[0] = 0; /* empty string */
1326 if (db_create_counter_record(NULL, db, &cr)) {
1327 counter->CurrentValue = cr.CurrentValue;
1328 counter->created = true;
1329 Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1332 if (!counter->created) {
1333 counter->CurrentValue = counter->MinValue; /* default value */
1336 /* cleanup old job records */
1337 if (mode == UPDATE_AND_FIX) {
1338 db_sql_query(db, cleanup_created_job, NULL, NULL);
1339 db_sql_query(db, cleanup_running_job, NULL, NULL);
1342 /* Set SQL engine name in global for debugging */
1343 set_db_engine_name(db_get_engine_name(db));
1344 if (db) db_close_database(NULL, db);
1349 static void cleanup_old_files()
1352 struct dirent *entry, *result;
1354 int my_name_len = strlen(my_name);
1355 int len = strlen(director->working_directory);
1356 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1357 POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1360 const int nmatch = 30;
1361 regmatch_t pmatch[nmatch];
1364 /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1365 const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1367 /* Setup working directory prefix */
1368 pm_strcpy(basename, director->working_directory);
1369 if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1370 pm_strcat(basename, "/");
1373 /* Compile regex expressions */
1374 rc = regcomp(&preg1, pat1, REG_EXTENDED);
1376 regerror(rc, &preg1, prbuf, sizeof(prbuf));
1377 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1382 name_max = pathconf(".", _PC_NAME_MAX);
1383 if (name_max < 1024) {
1387 if (!(dp = opendir(director->working_directory))) {
1389 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1390 director->working_directory, be.bstrerror());
1395 entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1397 if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1400 /* Exclude any name with ., .., not my_name or containing a space */
1401 if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1402 strncmp(result->d_name, my_name, my_name_len) != 0) {
1403 Dmsg1(500, "Skipped: %s\n", result->d_name);
1407 /* Unlink files that match regexes */
1408 if (regexec(&preg1, result->d_name, nmatch, pmatch, 0) == 0) {
1409 pm_strcpy(cleanup, basename);
1410 pm_strcat(cleanup, result->d_name);
1411 Dmsg1(100, "Unlink: %s\n", cleanup);
1418 /* Be careful to free up the correct resources */
1422 free_pool_memory(cleanup);
1423 free_pool_memory(basename);