1 /*
2 Bacula(R) - The Network Backup Solution
3
4 Copyright (C) 2000-2020 Kern Sibbald
5
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.
8
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.
13
14 This notice must be preserved when any source code is
15 conveyed and/or propagated.
16
17 Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20 * Third generation Storage daemon.
21 *
22 * Written by Kern Sibbald, MM
23 *
24 * It accepts a number of simple commands from the File daemon
25 * and acts on them. When a request to append data is made,
26 * it opens a data channel and accepts data from the
27 * File daemon.
28 *
29 */
30
31 #include "bacula.h"
32 #include "stored.h"
33
34 /* TODO: fix problem with bls, bextract
35 * that use findlib and already declare
36 * filed plugins
37 */
38 #include "sd_plugins.h"
39
40 /* Imported functions and variables */
41 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
42
43 /* Forward referenced functions */
44 void terminate_stored(int sig);
45 static int check_resources();
46 static void cleanup_old_files();
47
48 extern "C" void *device_initialization(void *arg);
49
50 #define CONFIG_FILE "bacula-sd.conf" /* Default config file */
51
52 /* Global variables exported */
53 char OK_msg[] = "3000 OK\n";
54 char TERM_msg[] = "3999 Terminate\n";
55 static bool test_config = false;
56 bstatcollect *statcollector = NULL;
57 sdstatmetrics_t sdstatmetrics;
58
59 static uint32_t VolSessionId = 0;
60 uint32_t VolSessionTime;
61 char *configfile = NULL;
62 bool init_done = false;
63 static pthread_t server_tid;
64 static bool server_tid_valid = false;
65
66 /* Global static variables */
67 static bool foreground = false;
68 static bool make_pid_file = true; /* create pid file */
69 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
70 static workq_t dird_workq; /* queue for processing connections */
71 static CONFIG *config;
72
usage()73 static void usage()
74 {
75 fprintf(stderr, _(
76 PROG_COPYRIGHT
77 "\n%sVersion: %s (%s)\n\n"
78 "Usage: bacula-sd [options] [-c config_file] [config_file]\n"
79 " -c <file> use <file> as configuration file\n"
80 " -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
81 " -dt print timestamp in debug output\n"
82 " -T set trace on\n"
83 " -f run in foreground (for debugging)\n"
84 " -g <group> set groupid to group\n"
85 " -m print kaboom output (for debugging)\n"
86 " -p proceed despite I/O errors\n"
87 " -P do not create pid file\n"
88 " -s no signals (for debugging)\n"
89 " -t test - read config and exit\n"
90 " -u <user> userid to <user>\n"
91 " -v verbose user messages\n"
92 " -? print this message.\n"
93 "\n"), 2000, BDEMO, VERSION, BDATE);
94 exit(1);
95 }
96
97 /*
98 * !!! WARNING !!! Use this function only when bacula is stopped.
99 * ie, after a fatal signal and before exiting the program
100 * Print information about a JCR
101 */
sd_debug_print(JCR * jcr,FILE * fp)102 static void sd_debug_print(JCR *jcr, FILE *fp)
103 {
104 if (jcr->dcr) {
105 DCR *dcr = jcr->dcr;
106 fprintf(fp, "\tdcr=%p volumename=%s dev=%p newvol=%d reserved=%d locked=%d\n",
107 dcr, dcr->VolumeName, dcr->dev, dcr->NewVol,
108 dcr->is_reserved(),
109 dcr->is_dev_locked());
110 } else {
111 fprintf(fp, "dcr=*None*\n");
112 }
113 }
114
115 /*********************************************************************
116 *
117 * Main Bacula Unix Storage Daemon
118 *
119 */
120 #if defined(HAVE_WIN32)
121 #define main BaculaMain
122 #endif
123
main(int argc,char * argv[])124 int main (int argc, char *argv[])
125 {
126 int ch;
127 bool no_signals = false;
128 pthread_t thid;
129 char *uid = NULL;
130 char *gid = NULL;
131
132 device_default_open_mode = omd_write;
133
134 mark_heap();
135 setlocale(LC_ALL, "");
136 bindtextdomain("bacula", LOCALEDIR);
137 textdomain("bacula");
138
139 init_stack_dump();
140 my_name_is(argc, argv, "bacula-sd");
141 init_msg(NULL, NULL);
142 daemon_start_time = time(NULL);
143 setup_daemon_message_queue();
144
145 /* Sanity checks */
146 if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
147 Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
148 TAPE_BSIZE, B_DEV_BSIZE);
149 }
150 if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
151 Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
152 }
153
154 while ((ch = getopt(argc, argv, "c:d:fg:mpPstu:v?Ti")) != -1) {
155 switch (ch) {
156 case 'c': /* configuration file */
157 if (configfile != NULL) {
158 free(configfile);
159 }
160 configfile = bstrdup(optarg);
161 break;
162
163 case 'd': /* debug level */
164 if (*optarg == 't') {
165 dbg_timestamp = true;
166 } else {
167 char *p;
168 /* We probably find a tag list -d 10,sql,bvfs */
169 if ((p = strchr(optarg, ',')) != NULL) {
170 *p = 0;
171 }
172 debug_level = atoi(optarg);
173 if (debug_level <= 0) {
174 debug_level = 1;
175 }
176 if (p) {
177 debug_parse_tags(p+1, &debug_level_tags);
178 }
179 }
180 break;
181
182 case 'T':
183 set_trace(true);
184 break;
185
186 case 'f': /* run in foreground */
187 foreground = true;
188 break;
189
190 case 'g': /* set group id */
191 gid = optarg;
192 break;
193
194 /* Temp code to enable new match_bsr() code, not documented */
195 case 'i':
196 use_new_match_all = 1;
197
198 break;
199 case 'm': /* print kaboom output */
200 prt_kaboom = true;
201 break;
202
203 case 'p': /* proceed in spite of I/O errors */
204 forge_on = true;
205 break;
206
207 case 'P': /* no pid file */
208 make_pid_file = false;
209 break;
210
211 case 's': /* no signals */
212 no_signals = true;
213 break;
214
215 case 't':
216 test_config = true;
217 break;
218
219 case 'u': /* set uid */
220 uid = optarg;
221 break;
222
223 case 'v': /* verbose */
224 verbose++;
225 break;
226
227 case '?':
228 default:
229 usage();
230 break;
231 }
232 }
233 argc -= optind;
234 argv += optind;
235
236 if (argc) {
237 if (configfile != NULL) {
238 free(configfile);
239 }
240 configfile = bstrdup(*argv);
241 argc--;
242 argv++;
243 }
244 if (argc) {
245 usage();
246 }
247
248 if (!foreground && !test_config) {
249 daemon_start(); /* become daemon */
250 init_stack_dump(); /* pick up new pid */
251 }
252
253 if (!no_signals) {
254 init_signals(terminate_stored);
255 }
256
257 if (configfile == NULL) {
258 configfile = bstrdup(CONFIG_FILE);
259 }
260
261 config = New(CONFIG());
262 parse_sd_config(config, configfile, M_ERROR_TERM);
263
264 if (init_crypto() != 0) {
265 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
266 }
267
268 if (!check_resources()) {
269 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
270 }
271
272 if (crypto_check_fips(me->require_fips) < 0) {
273 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Unable to set FIPS mode\n"));
274 }
275
276 init_reservations_lock();
277
278 if (test_config) {
279 terminate_stored(0);
280 }
281
282 my_name_is(0, (char **)NULL, me->hdr.name); /* Set our real name */
283 /* relocate trace file if needed, must be run after set_working_directory()
284 * and my_name_is() */
285 update_trace_file_location(false);
286
287 if (make_pid_file) {
288 create_pid_file(me->pid_directory, "bacula-sd",
289 get_first_port_host_order(me->sdaddrs));
290 }
291 read_state_file(me->working_directory, "bacula-sd",
292 get_first_port_host_order(me->sdaddrs));
293
294 set_jcr_in_tsd(INVALID_JCR);
295 /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
296 set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
297 lmgr_init_thread(); /* initialize the lockmanager stack */
298
299 load_sd_plugins(me->plugin_directory);
300
301 drop(uid, gid, false);
302
303 /* initialize a statistics collector */
304 initialize_statcollector();
305
306 cleanup_old_files();
307
308 /* Ensure that Volume Session Time and Id are both
309 * set and are both non-zero.
310 */
311 VolSessionTime = (uint32_t)daemon_start_time;
312 if (VolSessionTime == 0) { /* paranoid */
313 Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
314 }
315
316 /*
317 * Start the device allocation thread
318 */
319 create_volume_lists(); /* do before device_init */
320 if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
321 berrno be;
322 Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
323 }
324
325 start_watchdog(); /* start watchdog thread */
326 init_jcr_subsystem(); /* start JCR watchdogs etc. */
327 dbg_jcr_add_hook(sd_debug_print); /* used to director variables */
328
329 start_collector_threads(); /* start collector thread for every Collector resource */
330
331 /* Keep track of important events */
332 events_send_msg(NULL, "SD0001", EVENTS_TYPE_DAEMON, "*Daemon*",
333 (intptr_t)get_first_port_host_order(me->sdaddrs),
334 "Storage startup");
335
336 /* Single server used for Director and File daemon */
337 server_tid = pthread_self();
338 server_tid_valid = true;
339 bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
340 &dird_workq, handle_connection_request);
341 exit(1); /* to keep compiler quiet */
342 }
343
344 /* Return a new Session Id */
newVolSessionId()345 uint32_t newVolSessionId()
346 {
347 uint32_t Id;
348
349 P(mutex);
350 VolSessionId++;
351 Id = VolSessionId;
352 V(mutex);
353 return Id;
354 }
355
356 /* Check Configuration file for necessary info */
check_resources()357 static int check_resources()
358 {
359 bool OK = true;
360 bool tls_needed;
361 AUTOCHANGER *changer;
362 DEVRES *device;
363
364 me = (STORES *)GetNextRes(R_STORAGE, NULL);
365 if (!me) {
366 Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
367 configfile);
368 OK = false;
369 }
370
371 if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
372 Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
373 configfile);
374 OK = false;
375 }
376 if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
377 Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
378 configfile);
379 OK = false;
380 }
381 if (GetNextRes(R_DEVICE, NULL) == NULL){
382 Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
383 configfile);
384 OK = false;
385 }
386
387 if (!me->messages) {
388 me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
389 if (!me->messages) {
390 Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
391 configfile);
392 OK = false;
393 }
394 }
395
396 if (!me->working_directory) {
397 Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
398 configfile);
399 OK = false;
400 }
401
402 DIRRES *director;
403 STORES *store;
404 foreach_res(store, R_STORAGE) {
405 /* tls_require implies tls_enable */
406 if (store->tls_require) {
407 if (have_tls) {
408 if (store->tls_certfile || store->tls_keyfile) {
409 store->tls_enable = true;
410 }
411 } else {
412 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
413 OK = false;
414 continue;
415 }
416 }
417
418 tls_needed = store->tls_enable || store->tls_authenticate;
419
420 if (!store->tls_certfile && tls_needed) {
421 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
422 store->hdr.name, configfile);
423 OK = false;
424 }
425
426 if (!store->tls_keyfile && tls_needed) {
427 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
428 store->hdr.name, configfile);
429 OK = false;
430 }
431
432 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && tls_needed && store->tls_verify_peer) {
433 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
434 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
435 " At least one CA certificate store is required"
436 " when using \"TLS Verify Peer\".\n"),
437 store->hdr.name, configfile);
438 OK = false;
439 }
440
441 /* If everything is well, attempt to initialize our per-resource TLS context */
442 if (OK && tls_needed) {
443 /* Initialize TLS context:
444 * Args: CA certfile, CA certdir, Certfile, Keyfile,
445 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
446 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
447 store->tls_ca_certdir, store->tls_certfile,
448 store->tls_keyfile, NULL, NULL, store->tls_dhfile,
449 store->tls_verify_peer);
450
451 if (!store->tls_ctx) {
452 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
453 store->hdr.name, configfile);
454 OK = false;
455 }
456 }
457 store->psk_ctx = new_psk_context(NULL); /* shared key generated by DIR */
458 /* In this case, we have TLS Require=Yes and TLS not setup and no PSK */
459 if (OK && tls_needed == false && store->tls_require) {
460 if (!store->psk_ctx) {
461 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS PSK context for Storage \"%s\" in %s.\n"),
462 store->hdr.name, configfile);
463 OK = false;
464 }
465 }
466 }
467
468 foreach_res(director, R_DIRECTOR) {
469 /* tls_require implies tls_enable */
470 if (director->tls_require) {
471 if (director->tls_certfile || director->tls_keyfile) {
472 director->tls_enable = true;
473 }
474 }
475
476 tls_needed = director->tls_enable || director->tls_authenticate;
477
478 if (!director->tls_certfile && tls_needed) {
479 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
480 director->hdr.name, configfile);
481 OK = false;
482 }
483
484 if (!director->tls_keyfile && tls_needed) {
485 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
486 director->hdr.name, configfile);
487 OK = false;
488 }
489
490 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed && director->tls_verify_peer) {
491 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
492 " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
493 " At least one CA certificate store is required"
494 " when using \"TLS Verify Peer\".\n"),
495 director->hdr.name, configfile);
496 OK = false;
497 }
498
499 /* If everything is well, attempt to initialize our per-resource TLS context */
500 if (OK && tls_needed) {
501 /* Initialize TLS context:
502 * Args: CA certfile, CA certdir, Certfile, Keyfile,
503 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
504 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
505 director->tls_ca_certdir, director->tls_certfile,
506 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
507 director->tls_verify_peer);
508
509 if (!director->tls_ctx) {
510 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
511 director->hdr.name, configfile);
512 OK = false;
513 }
514 }
515 director->psk_ctx = new_psk_context(director->password);
516 /* In this case, we have TLS Require=Yes and TLS not setup and no PSK */
517 if (OK && (tls_needed == false && director->tls_require)) {
518 if (!director->psk_ctx) {
519 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS PSK context for Director \"%s\" in %s.\n"),
520 director->hdr.name, configfile);
521 OK = false;
522 }
523 }
524 }
525
526 foreach_res(changer, R_AUTOCHANGER) {
527 foreach_alist(device, changer->device) {
528 device->cap_bits |= CAP_AUTOCHANGER;
529 }
530 }
531
532 CLOUD *cloud;
533 /* TODO: Can use a table */
534 foreach_res(cloud, R_CLOUD) {
535 if (cloud->driver_type == C_S3_DRIVER ||
536 cloud->driver_type == C_FILE_DRIVER)
537 {
538 if (cloud->host_name == NULL) {
539 Jmsg(NULL, M_FATAL, 0,
540 _("Failed to initialize Cloud. Hostname not defined for Cloud \"%s\"\n"),
541 cloud->hdr.name);
542 OK = false;
543 }
544 }
545 if (cloud->driver_type == C_WAS_DRIVER ||
546 cloud->driver_type == C_S3_DRIVER)
547 {
548 if (cloud->access_key == NULL) {
549 Jmsg(NULL, M_FATAL, 0,
550 _("Failed to initialize Cloud. AccessKey not set for Cloud \"%s\"\n"),
551 cloud->hdr.name);
552 OK = false;
553 }
554 if (cloud->secret_key == NULL) {
555 Jmsg(NULL, M_FATAL, 0,
556 _("Failed to initialize Cloud. SecretKey not set for Cloud \"%s\"\n"),
557 cloud->hdr.name);
558 OK = false;
559 }
560 }
561 }
562
563 #ifdef SD_DEDUP_SUPPORT
564 DEDUPRES *dedup;
565 foreach_res(dedup, R_DEDUP) {
566 if (dedup->driver_type == D_LEGACY_DRIVER)
567 {
568 if (dedup->dedup_dir == NULL) {
569 Jmsg(NULL, M_FATAL, 0,
570 _("Failed to initialize Dedup. DedupDirectory not defined for Dedup \"%s\"\n"),
571 dedup->hdr.name);
572 OK = false;
573 }
574 }
575 }
576 #endif
577
578 if (OK) {
579 OK = init_autochangers();
580 }
581
582 if (OK) {
583 close_msg(NULL); /* close temp message handler */
584 init_msg(NULL, me->messages); /* open daemon message handler */
585 set_working_directory(me->working_directory);
586 }
587
588 return OK;
589 }
590
591 /*
592 * Remove old .spool files written by me from the working directory.
593 */
cleanup_old_files()594 static void cleanup_old_files()
595 {
596 DIR* dp;
597 int rc, name_max;
598 int my_name_len = strlen(my_name);
599 int len = strlen(me->working_directory);
600 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
601 POOLMEM *basename = get_pool_memory(PM_MESSAGE);
602 POOL_MEM dname(PM_FNAME);
603 regex_t preg1;
604 char prbuf[500];
605 const int nmatch = 30;
606 regmatch_t pmatch[nmatch];
607 berrno be;
608
609 /* Look for .spool files but don't allow spaces */
610 const char *pat1 = "^[^ ]+\\.spool$";
611
612 /* Setup working directory prefix */
613 pm_strcpy(basename, me->working_directory);
614 if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
615 pm_strcat(basename, "/");
616 }
617
618 /* Compile regex expressions */
619 rc = regcomp(&preg1, pat1, REG_EXTENDED);
620 if (rc != 0) {
621 regerror(rc, &preg1, prbuf, sizeof(prbuf));
622 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
623 pat1, prbuf);
624 goto get_out2;
625 }
626
627 name_max = pathconf(".", _PC_NAME_MAX);
628 if (name_max < 1024) {
629 name_max = 1024;
630 }
631
632 if (!(dp = opendir(me->working_directory))) {
633 berrno be;
634 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
635 me->working_directory, be.bstrerror());
636 goto get_out1;
637 }
638
639 while (1) {
640 if (breaddir(dp, dname.addr()) != 0) {
641 break;
642 }
643 /* Exclude any name with ., .., not my_name or containing a space */
644 if (strcmp(dname.c_str(), ".") == 0 || strcmp(dname.c_str(), "..") == 0 ||
645 strncmp(dname.c_str(), my_name, my_name_len) != 0) {
646 Dmsg1(500, "Skipped: %s\n", dname.c_str());
647 continue;
648 }
649
650 /* Unlink files that match regex */
651 if (regexec(&preg1, dname.c_str(), nmatch, pmatch, 0) == 0) {
652 pm_strcpy(cleanup, basename);
653 pm_strcat(cleanup, dname);
654 Dmsg1(500, "Unlink: %s\n", cleanup);
655 unlink(cleanup);
656 }
657 }
658 closedir(dp);
659
660 get_out1:
661 regfree(&preg1);
662 get_out2:
663 free_pool_memory(cleanup);
664 free_pool_memory(basename);
665 }
666
dbg_print_devices(FILE * fp)667 void dbg_print_devices(FILE *fp)
668 {
669 DEVRES *device;
670 foreach_res(device, R_DEVICE) {
671 if (device->dev) {
672 device->dev->dbg_print(fp);
673 }
674 }
675 }
676
677 /*
678 * Here we attempt to init and open each device. This is done
679 * once at startup in a separate thread.
680 */
681 extern "C"
device_initialization(void * arg)682 void *device_initialization(void *arg)
683 {
684 DEVRES *device;
685 DCR *dcr;
686 JCR *jcr;
687 DEVICE *dev;
688 struct stat statp;
689
690 pthread_detach(pthread_self());
691 jcr = new_jcr(sizeof(JCR), stored_free_jcr);
692 new_plugins(jcr); /* instantiate plugins */
693 jcr->setJobType(JT_SYSTEM);
694 /* Initialize SD start condition variable */
695 int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
696 if (errstat != 0) {
697 berrno be;
698 Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
699 }
700
701 LockRes();
702
703 foreach_res(device, R_DEVICE) {
704 Dmsg1(90, "calling init_dev %s\n", device->hdr.name);
705 dev = init_dev(NULL, device, false, statcollector);
706 Dmsg2(10, "SD init done %s (0x%p)\n", device->hdr.name, dev);
707 if (!dev) {
708 Jmsg1(NULL, M_ERROR, 0, _("Could not initialize SD device \"%s\"\n"), device->hdr.name);
709 continue;
710 }
711 jcr->dcr = dcr = new_dcr(jcr, NULL, dev);
712 generate_plugin_event(jcr, bsdEventDeviceInit, dcr);
713
714 /* Keep track of important events */
715 events_send_msg(jcr, "SD0002", EVENTS_TYPE_DAEMON, "*Daemon*",
716 (intptr_t)get_first_port_host_order(me->sdaddrs),
717 "Device initialization %s", device->hdr.name);
718
719 /* With USB devices, it might not be here when we start */
720 if (device->control_name && stat(device->control_name, &statp) < 0) {
721 berrno be;
722 Jmsg2(jcr, M_ERROR, 0, _("Unable to stat ControlDevice %s: ERR=%s\n"),
723 device->control_name, be.bstrerror());
724 }
725
726 if ((device->lock_command && device->control_name) &&
727 !me->plugin_directory) {
728 Jmsg0(jcr, M_ERROR_TERM, 0, _("No plugin directory configured for SAN shared storage\n"));
729 }
730
731 if (device->min_block_size > device->max_block_size) {
732 Jmsg1(jcr, M_ERROR_TERM, 0, _("MaximumBlockSize must be greater or equal than MinimumBlockSize for Device \"%s\"\n"),
733 dev->print_name());
734 }
735
736 #ifdef HAVE_WIN32
737 if (device->cap_bits & CAP_SYNCONCLOSE) {
738 device->cap_bits &= ~CAP_SYNCONCLOSE; /* Not available on windows */
739 }
740 #endif
741 /*
742 * Note: be careful setting the slot here. If the drive
743 * is shared storage, the contents can change before
744 * the drive is used.
745 */
746 if (device->cap_bits & CAP_ALWAYSOPEN) {
747 if (dev->is_autochanger()) {
748 /* If autochanger set slot in dev sturcture */
749 get_autochanger_loaded_slot(dcr);
750 }
751 Dmsg1(20, "calling first_open_device %s\n", dev->print_name());
752 if (generate_plugin_event(jcr, bsdEventDeviceOpen, dcr) != bRC_OK) {
753 Jmsg(jcr, M_FATAL, 0, _("generate_plugin_event(bsdEventDeviceOpen) Failed\n"));
754 continue;
755 }
756
757 if (!first_open_device(dcr)) {
758 Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), dev->print_name());
759 Dmsg1(20, "Could not open device %s\n", dev->print_name());
760 generate_plugin_event(jcr, bsdEventDeviceClose, dcr);
761 free_dcr(dcr);
762 jcr->dcr = NULL;
763 continue;
764 }
765 } else {
766 /* If not always open, we don't know what is in the drive */
767 dev->clear_slot();
768 }
769 if (device->cap_bits & CAP_AUTOMOUNT && dev->is_open()) {
770 switch (dev->read_dev_volume_label(dcr)) {
771 case VOL_OK:
772 memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
773 volume_unused(dcr); /* mark volume "released" */
774 break;
775 default:
776 Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), dev->print_name());
777 break;
778 }
779 }
780 free_dcr(dcr);
781 jcr->dcr = NULL;
782 }
783
784 UnlockRes();
785 #ifndef HAVE_WIN32
786 dbg_add_hook(dbg_print_devices);
787 #endif
788
789 #ifdef xxx
790 if (jcr->dcr) {
791 Pmsg1(000, "free_dcr=%p\n", jcr->dcr);
792 free_dcr(jcr->dcr);
793 jcr->dcr = NULL;
794 }
795 #endif
796 free_plugins(jcr);
797 free_jcr(jcr);
798 init_done = true;
799 return NULL;
800 }
801
802
803 /* Clean up and then exit */
terminate_stored(int sig)804 void terminate_stored(int sig)
805 {
806 static bool in_here = false;
807 DEVRES *device;
808 DEDUPRES *dedup;
809 JCR *jcr;
810
811 if (in_here) { /* prevent loops */
812 bmicrosleep(2, 0); /* yield */
813 exit(1);
814 }
815 in_here = true;
816 debug_level = 0; /* turn off any debug */
817 stop_watchdog();
818 terminate_collector_threads();
819
820 if (sig == SIGTERM || sig == SIGINT) { /* normal shutdown request? or ^C */
821 /*
822 * This is a normal shutdown request. We wiffle through
823 * all open jobs canceling them and trying to wake
824 * them up so that they will report back the correct
825 * volume status.
826 */
827 foreach_jcr(jcr) {
828 BSOCK *fd;
829 if (jcr->JobId == 0) {
830 free_jcr(jcr);
831 continue; /* ignore console */
832 }
833 if (jcr->dcr) {
834 /* Make sure no device remains locked */
835 generate_plugin_event(jcr, bsdEventDeviceClose, jcr->dcr);
836 }
837 jcr->setJobStatus(JS_Canceled);
838 fd = jcr->file_bsock;
839 if (fd) {
840 fd->set_timed_out();
841 jcr->my_thread_send_signal(TIMEOUT_SIGNAL);
842 Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
843 /* ***FIXME*** wiffle through all dcrs */
844 if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->blocked()) {
845 pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
846 Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
847 pthread_cond_broadcast(&wait_device_release);
848 }
849 if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->blocked()) {
850 pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
851 pthread_cond_broadcast(&wait_device_release);
852 }
853 bmicrosleep(0, 50000);
854 }
855 free_jcr(jcr);
856 }
857 bmicrosleep(0, 500000); /* give them 1/2 sec to clean up */
858 }
859
860 if (!test_config) {
861 write_state_file(me->working_directory,
862 "bacula-sd", get_first_port_host_order(me->sdaddrs));
863 if (make_pid_file) {
864 delete_pid_file(me->pid_directory,
865 "bacula-sd", get_first_port_host_order(me->sdaddrs));
866 }
867
868 /* Keep track of important events */
869 events_send_msg(NULL, "SD0003", EVENTS_TYPE_DAEMON, "*Daemon*",
870 get_first_port_host_order(me->sdaddrs),
871 "Storage shutdown");
872 }
873
874 Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
875
876 unload_plugins();
877 free_volume_lists();
878
879 free_daemon_message_queue();
880
881 foreach_res(device, R_DEVICE) {
882 Dmsg2(10, "Term device %s %s\n", device->hdr.name, device->device_name);
883 if (device->dev) {
884 device->dev->clear_volhdr();
885 device->dev->term(NULL);
886 device->dev = NULL;
887 } else {
888 Dmsg2(10, "No dev structure %s %s\n", device->hdr.name, device->device_name);
889 }
890 }
891
892 foreach_res(dedup, R_DEDUP) {
893 if (dedup->dedupengine) {
894 dedup->dedupengine = NULL; // Should have been closed by the last device
895 } else {
896 Dmsg1(10, "No dev Dedupengine structure %s\n", dedup->hdr.name);
897 }
898 }
899
900 if (server_tid_valid) {
901 server_tid_valid = false;
902 bnet_stop_thread_server(server_tid);
903 }
904
905 if (configfile) {
906 free(configfile);
907 configfile = NULL;
908 }
909 if (config) {
910 delete config;
911 config = NULL;
912 }
913
914 if (chk_dbglvl(10)) {
915 print_memory_pool_stats();
916 }
917 if (statcollector){
918 // statcollector->dump();
919 delete(statcollector);
920 }
921 term_msg();
922 cleanup_crypto();
923 term_reservations_lock();
924 free(res_head);
925 res_head = NULL;
926 close_memory_pool();
927 lmgr_cleanup_main();
928
929 sm_dump(false); /* dump orphaned buffers */
930 exit(sig);
931 }
932