2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
6 The main author of Bacula is Kern Sibbald, with contributions from
7 many others, a complete list can be found in the file AUTHORS.
8 This program is Free Software; you can redistribute it and/or
9 modify it under the terms of version three of the GNU Affero General Public
10 License as published by the Free Software Foundation and included
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU Affero General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 Bacula® is a registered trademark of Kern Sibbald.
24 The licensor of Bacula is the Free Software Foundation Europe
25 (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26 Switzerland, email:ftf@fsfeurope.org.
29 * Second generation Storage daemon.
33 * It accepts a number of simple commands from the File daemon
34 * and acts on them. When a request to append data is made,
35 * it opens a data channel and accepts data from the
43 /* TODO: fix problem with bls, bextract
44 * that use findlib and already declare
47 #include "sd_plugins.h"
49 /* Imported functions */
50 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
52 /* Forward referenced functions */
53 void terminate_stored(int sig);
54 static int check_resources();
55 static void cleanup_old_files();
57 extern "C" void *device_initialization(void *arg);
59 #define CONFIG_FILE "bacula-sd.conf" /* Default config file */
61 /* Global variables exported */
62 char OK_msg[] = "3000 OK\n";
63 char TERM_msg[] = "3999 Terminate\n";
64 STORES *me = NULL; /* our Global resource */
65 bool forge_on = false; /* proceed inspite of I/O errors */
66 pthread_mutex_t device_release_mutex = PTHREAD_MUTEX_INITIALIZER;
67 pthread_cond_t wait_device_release = PTHREAD_COND_INITIALIZER;
71 static uint32_t VolSessionId = 0;
72 uint32_t VolSessionTime;
73 char *configfile = NULL;
74 bool init_done = false;
76 /* Global static variables */
77 static bool foreground = 0;
78 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
79 static workq_t dird_workq; /* queue for processing connections */
80 static CONFIG *config;
87 "\nVersion: %s (%s)\n\n"
88 "Usage: stored [options] [-c config_file] [config_file]\n"
89 " -c <file> use <file> as configuration file\n"
90 " -d <nn> set debug level to <nn>\n"
91 " -dt print timestamp in debug output\n"
92 " -f run in foreground (for debugging)\n"
93 " -g <group> set groupid to group\n"
94 " -m print kaboom output (for debugging)\n"
95 " -p proceed despite I/O errors\n"
96 " -s no signals (for debugging)\n"
97 " -t test - read config and exit\n"
98 " -u <user> userid to <user>\n"
99 " -v verbose user messages\n"
100 " -? print this message.\n"
101 "\n"), 2000, VERSION, BDATE);
106 /*********************************************************************
108 * Main Bacula Unix Storage Daemon
111 #if defined(HAVE_WIN32)
112 #define main BaculaMain
115 int main (int argc, char *argv[])
118 bool no_signals = false;
119 bool test_config = false;
124 start_heap = sbrk(0);
125 setlocale(LC_ALL, "");
126 bindtextdomain("bacula", LOCALEDIR);
127 textdomain("bacula");
130 my_name_is(argc, argv, "bacula-sd");
131 init_msg(NULL, NULL);
132 daemon_start_time = time(NULL);
135 if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
136 Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
137 TAPE_BSIZE, B_DEV_BSIZE);
139 if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
140 Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
143 while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?")) != -1) {
145 case 'c': /* configuration file */
146 if (configfile != NULL) {
149 configfile = bstrdup(optarg);
152 case 'd': /* debug level */
153 if (*optarg == 't') {
154 dbg_timestamp = true;
156 debug_level = atoi(optarg);
157 if (debug_level <= 0) {
163 case 'f': /* run in foreground */
167 case 'g': /* set group id */
171 case 'm': /* print kaboom output */
175 case 'p': /* proceed in spite of I/O errors */
179 case 's': /* no signals */
187 case 'u': /* set uid */
191 case 'v': /* verbose */
205 if (configfile != NULL) {
208 configfile = bstrdup(*argv);
216 init_signals(terminate_stored);
219 if (configfile == NULL) {
220 configfile = bstrdup(CONFIG_FILE);
223 config = new_config_parser();
224 parse_sd_config(config, configfile, M_ERROR_TERM);
226 if (init_crypto() != 0) {
227 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
230 if (!check_resources()) {
231 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
234 init_reservations_lock();
240 my_name_is(0, (char **)NULL, me->hdr.name); /* Set our real name */
243 daemon_start(); /* become daemon */
244 init_stack_dump(); /* pick up new pid */
247 create_pid_file(me->pid_directory, "bacula-sd",
248 get_first_port_host_order(me->sdaddrs));
249 read_state_file(me->working_directory, "bacula-sd",
250 get_first_port_host_order(me->sdaddrs));
252 /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
253 set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
254 lmgr_init_thread(); /* initialize the lockmanager stack */
256 load_sd_plugins(me->plugin_directory);
258 drop(uid, gid, false);
263 /* Ensure that Volume Session Time and Id are both
264 * set and are both non-zero.
266 VolSessionTime = (uint32_t)daemon_start_time;
267 if (VolSessionTime == 0) { /* paranoid */
268 Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
272 * Start the device allocation thread
274 create_volume_lists(); /* do before device_init */
275 if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
277 Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
280 start_watchdog(); /* start watchdog thread */
281 init_jcr_subsystem(); /* start JCR watchdogs etc. */
283 /* Single server used for Director and File daemon */
284 bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
285 &dird_workq, handle_connection_request);
286 exit(1); /* to keep compiler quiet */
289 /* Return a new Session Id */
290 uint32_t newVolSessionId()
301 /* Check Configuration file for necessary info */
302 static int check_resources()
308 me = (STORES *)GetNextRes(R_STORAGE, NULL);
310 Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
315 if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
316 Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
320 if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
321 Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
325 if (GetNextRes(R_DEVICE, NULL) == NULL){
326 Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
332 me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
334 Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
340 if (!me->working_directory) {
341 Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
348 foreach_res(store, R_STORAGE) {
349 /* tls_require implies tls_enable */
350 if (store->tls_require) {
352 store->tls_enable = true;
354 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
360 tls_needed = store->tls_enable || store->tls_authenticate;
362 if (!store->tls_certfile && tls_needed) {
363 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
364 store->hdr.name, configfile);
368 if (!store->tls_keyfile && tls_needed) {
369 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
370 store->hdr.name, configfile);
374 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && tls_needed && store->tls_verify_peer) {
375 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
376 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
377 " At least one CA certificate store is required"
378 " when using \"TLS Verify Peer\".\n"),
379 store->hdr.name, configfile);
383 /* If everything is well, attempt to initialize our per-resource TLS context */
384 if (OK && (tls_needed || store->tls_require)) {
385 /* Initialize TLS context:
386 * Args: CA certfile, CA certdir, Certfile, Keyfile,
387 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
388 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
389 store->tls_ca_certdir, store->tls_certfile,
390 store->tls_keyfile, NULL, NULL, store->tls_dhfile,
391 store->tls_verify_peer);
393 if (!store->tls_ctx) {
394 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
395 store->hdr.name, configfile);
401 foreach_res(director, R_DIRECTOR) {
402 /* tls_require implies tls_enable */
403 if (director->tls_require) {
404 director->tls_enable = true;
407 tls_needed = director->tls_enable || director->tls_authenticate;
409 if (!director->tls_certfile && tls_needed) {
410 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
411 director->hdr.name, configfile);
415 if (!director->tls_keyfile && tls_needed) {
416 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
417 director->hdr.name, configfile);
421 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed && director->tls_verify_peer) {
422 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
423 " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
424 " At least one CA certificate store is required"
425 " when using \"TLS Verify Peer\".\n"),
426 director->hdr.name, configfile);
430 /* If everything is well, attempt to initialize our per-resource TLS context */
431 if (OK && (tls_needed || director->tls_require)) {
432 /* Initialize TLS context:
433 * Args: CA certfile, CA certdir, Certfile, Keyfile,
434 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
435 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
436 director->tls_ca_certdir, director->tls_certfile,
437 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
438 director->tls_verify_peer);
440 if (!director->tls_ctx) {
441 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
442 director->hdr.name, configfile);
448 OK = init_autochangers();
452 close_msg(NULL); /* close temp message handler */
453 init_msg(NULL, me->messages); /* open daemon message handler */
454 set_working_directory(me->working_directory);
460 static void cleanup_old_files()
462 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
463 POOLMEM *results = get_pool_memory(PM_MESSAGE);
464 int len = strlen(me->working_directory);
465 #if defined(HAVE_WIN32)
466 pm_strcpy(cleanup, "del /q ");
468 pm_strcpy(cleanup, "/bin/rm -f ");
470 pm_strcat(cleanup, me->working_directory);
471 if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
472 pm_strcat(cleanup, "/");
474 pm_strcat(cleanup, my_name);
475 pm_strcat(cleanup, "*.spool");
476 run_program(cleanup, 0, results);
477 free_pool_memory(cleanup);
478 free_pool_memory(results);
483 * Here we attempt to init and open each device. This is done
484 * once at startup in a separate thread.
487 void *device_initialization(void *arg)
496 pthread_detach(pthread_self());
497 jcr = new_jcr(sizeof(JCR), stored_free_jcr);
498 jcr->setJobType(JT_SYSTEM);
499 /* Initialize FD start condition variable */
500 int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
503 Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
506 foreach_res(device, R_DEVICE) {
507 Dmsg1(90, "calling init_dev %s\n", device->device_name);
508 dev = init_dev(NULL, device);
509 Dmsg1(10, "SD init done %s\n", device->device_name);
511 Jmsg1(NULL, M_ERROR, 0, _("Could not initialize %s\n"), device->device_name);
515 jcr->dcr = dcr = new_dcr(jcr, NULL, dev);
516 generate_plugin_event(jcr, bsdEventDeviceInit, dcr);
517 if (dev->is_autochanger()) {
518 /* If autochanger set slot in dev sturcture */
519 get_autochanger_loaded_slot(dcr);
522 if (device->cap_bits & CAP_ALWAYSOPEN) {
523 Dmsg1(20, "calling first_open_device %s\n", dev->print_name());
524 if (!first_open_device(dcr)) {
525 Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), dev->print_name());
526 Dmsg1(20, "Could not open device %s\n", dev->print_name());
532 if (device->cap_bits & CAP_AUTOMOUNT && dev->is_open()) {
533 switch (read_dev_volume_label(dcr)) {
535 memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
536 volume_unused(dcr); /* mark volume "released" */
539 Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), dev->print_name());
548 Dmsg1(000, "free_dcr=%p\n", jcr->dcr);
560 /* Clean up and then exit */
561 void terminate_stored(int sig)
563 static bool in_here = false;
567 if (in_here) { /* prevent loops */
568 bmicrosleep(2, 0); /* yield */
572 debug_level = 0; /* turn off any debug */
575 if (sig == SIGTERM) { /* normal shutdown request? */
577 * This is a normal shutdown request. We wiffle through
578 * all open jobs canceling them and trying to wake
579 * them up so that they will report back the correct
584 if (jcr->JobId == 0) {
586 continue; /* ignore console */
588 jcr->setJobStatus(JS_Canceled);
589 fd = jcr->file_bsock;
592 jcr->my_thread_send_signal(TIMEOUT_SIGNAL);
593 Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
594 /* ***FIXME*** wiffle through all dcrs */
595 if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->blocked()) {
596 pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
597 Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
598 pthread_cond_broadcast(&wait_device_release);
600 if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->blocked()) {
601 pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
602 pthread_cond_broadcast(&wait_device_release);
604 bmicrosleep(0, 50000);
608 bmicrosleep(0, 500000); /* give them 1/2 sec to clean up */
611 write_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
612 delete_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
614 Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
619 foreach_res(device, R_DEVICE) {
620 Dmsg1(10, "Term device %s\n", device->device_name);
622 device->dev->clear_volhdr();
626 Dmsg1(10, "No dev structure %s\n", device->device_name);
635 config->free_resources();
640 if (debug_level > 10) {
641 print_memory_pool_stats();
645 term_reservations_lock();
649 sm_dump(false); /* dump orphaned buffers */