]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/stored.c
05c108a9cc258e6ac70decc14c6198c95c068ee1
[bacula/bacula] / bacula / src / stored / stored.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
5
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
11    in the file LICENSE.
12
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.
17
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
21    02110-1301, USA.
22
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.
27 */
28 /*
29  * Second generation Storage daemon.
30  *
31  *  Kern Sibbald, MM
32  *
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
36  * File daemon.
37  *
38  */
39
40 #include "bacula.h"
41 #include "stored.h"
42
43 /* TODO: fix problem with bls, bextract
44  * that use findlib and already declare
45  * filed plugins 
46  */
47 #include "sd_plugins.h"         
48
49 /* Imported functions */
50 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
51
52 /* Forward referenced functions */
53 void terminate_stored(int sig);
54 static int check_resources();
55 static void cleanup_old_files();
56
57 extern "C" void *device_initialization(void *arg);
58
59 #define CONFIG_FILE "bacula-sd.conf"  /* Default config file */
60
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;
68 void *start_heap;
69
70
71 static uint32_t VolSessionId = 0;
72 uint32_t VolSessionTime;
73 char *configfile = NULL;
74 bool init_done = false;
75
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;
81
82
83 static void usage()
84 {
85    fprintf(stderr, _(
86 PROG_COPYRIGHT
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);
102
103    exit(1);
104 }
105
106 /*********************************************************************
107  *
108  *  Main Bacula Unix Storage Daemon
109  *
110  */
111 #if defined(HAVE_WIN32)
112 #define main BaculaMain
113 #endif
114
115 int main (int argc, char *argv[])
116 {
117    int ch;
118    bool no_signals = false;
119    bool test_config = false;
120    pthread_t thid;
121    char *uid = NULL;
122    char *gid = NULL;
123
124    start_heap = sbrk(0);
125    setlocale(LC_ALL, "");
126    bindtextdomain("bacula", LOCALEDIR);
127    textdomain("bacula");
128
129    init_stack_dump();
130    my_name_is(argc, argv, "bacula-sd");
131    init_msg(NULL, NULL);
132    daemon_start_time = time(NULL);
133
134    /* Sanity checks */
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);
138    }
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);
141    }
142
143    while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?")) != -1) {
144       switch (ch) {
145       case 'c':                    /* configuration file */
146          if (configfile != NULL) {
147             free(configfile);
148          }
149          configfile = bstrdup(optarg);
150          break;
151
152       case 'd':                    /* debug level */
153          if (*optarg == 't') {
154             dbg_timestamp = true;
155          } else {
156             debug_level = atoi(optarg);
157             if (debug_level <= 0) {
158                debug_level = 1;
159             }
160          }
161          break;
162
163       case 'f':                    /* run in foreground */
164          foreground = true;
165          break;
166
167       case 'g':                    /* set group id */
168          gid = optarg;
169          break;
170
171       case 'm':                    /* print kaboom output */
172          prt_kaboom = true;
173          break;
174
175       case 'p':                    /* proceed in spite of I/O errors */
176          forge_on = true;
177          break;
178
179       case 's':                    /* no signals */
180          no_signals = true;
181          break;
182
183       case 't':
184          test_config = true;
185          break;
186
187       case 'u':                    /* set uid */
188          uid = optarg;
189          break;
190
191       case 'v':                    /* verbose */
192          verbose++;
193          break;
194
195       case '?':
196       default:
197          usage();
198          break;
199       }
200    }
201    argc -= optind;
202    argv += optind;
203
204    if (argc) {
205       if (configfile != NULL) {
206          free(configfile);
207       }
208       configfile = bstrdup(*argv);
209       argc--;
210       argv++;
211    }
212    if (argc)
213       usage();
214
215    if (!no_signals) {
216       init_signals(terminate_stored);
217    }
218
219    if (configfile == NULL) {
220       configfile = bstrdup(CONFIG_FILE);
221    }
222
223    config = new_config_parser();
224    parse_sd_config(config, configfile, M_ERROR_TERM);
225
226    if (init_crypto() != 0) {
227       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
228    }
229
230    if (!check_resources()) {
231       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
232    }
233
234    init_reservations_lock();
235
236    if (test_config) {
237       terminate_stored(0);
238    }
239
240    my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */
241
242    if (!foreground) {
243       daemon_start();                 /* become daemon */
244       init_stack_dump();              /* pick up new pid */
245    }
246
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));
251
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 */
255
256    load_sd_plugins(me->plugin_directory);
257
258    drop(uid, gid, false);
259
260    cleanup_old_files();
261
262
263    /* Ensure that Volume Session Time and Id are both
264     * set and are both non-zero.
265     */
266    VolSessionTime = (uint32_t)daemon_start_time;
267    if (VolSessionTime == 0) { /* paranoid */
268       Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
269    }
270
271    /*
272     * Start the device allocation thread
273     */
274    create_volume_lists();             /* do before device_init */
275    if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
276       berrno be;
277       Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
278    }
279
280    start_watchdog();                  /* start watchdog thread */
281    init_jcr_subsystem();              /* start JCR watchdogs etc. */
282
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 */
287 }
288
289 /* Return a new Session Id */
290 uint32_t newVolSessionId()
291 {
292    uint32_t Id;
293
294    P(mutex);
295    VolSessionId++;
296    Id = VolSessionId;
297    V(mutex);
298    return Id;
299 }
300
301 /* Check Configuration file for necessary info */
302 static int check_resources()
303 {
304    bool OK = true;
305    bool tls_needed;
306
307
308    me = (STORES *)GetNextRes(R_STORAGE, NULL);
309    if (!me) {
310       Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
311          configfile);
312       OK = false;
313    }
314
315    if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
316       Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
317          configfile);
318       OK = false;
319    }
320    if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
321       Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
322          configfile);
323       OK = false;
324    }
325    if (GetNextRes(R_DEVICE, NULL) == NULL){
326       Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
327            configfile);
328       OK = false;
329    }
330
331    if (!me->messages) {
332       me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
333       if (!me->messages) {
334          Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
335             configfile);
336          OK = false;
337       }
338    }
339
340    if (!me->working_directory) {
341       Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
342          configfile);
343       OK = false;
344    }
345
346    DIRRES *director;
347    STORES *store;
348    foreach_res(store, R_STORAGE) { 
349       /* tls_require implies tls_enable */
350       if (store->tls_require) {
351          if (have_tls) {
352             store->tls_enable = true;
353          } else {
354             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
355             OK = false;
356             continue;
357          }
358       }
359
360       tls_needed = store->tls_enable || store->tls_authenticate;
361
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);
365          OK = false;
366       }
367
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);
371          OK = false;
372       }
373
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);
380          OK = false;
381       }
382
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);
392
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);
396             OK = false;
397          }
398       }
399    }
400
401    foreach_res(director, R_DIRECTOR) { 
402       /* tls_require implies tls_enable */
403       if (director->tls_require) {
404          director->tls_enable = true;
405       }
406
407       tls_needed = director->tls_enable || director->tls_authenticate;
408
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);
412          OK = false;
413       }
414
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);
418          OK = false;
419       }
420
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);
427          OK = false;
428       }
429
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);
439
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);
443             OK = false;
444          }
445       }
446    }
447
448    OK = init_autochangers();
449
450    
451    if (OK) {
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);
455    }
456
457    return OK;
458 }
459
460 static void cleanup_old_files()
461 {
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 ");
467 #else
468    pm_strcpy(cleanup, "/bin/rm -f ");
469 #endif
470    pm_strcat(cleanup, me->working_directory);
471    if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
472       pm_strcat(cleanup, "/");
473    }
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);
479 }
480
481
482 /*
483  * Here we attempt to init and open each device. This is done
484  *  once at startup in a separate thread.
485  */
486 extern "C"
487 void *device_initialization(void *arg)
488 {
489    DEVRES *device;
490    DCR *dcr;
491    JCR *jcr;
492    DEVICE *dev;
493
494    LockRes();
495
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);
501    if (errstat != 0) {
502       berrno be;
503       Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
504    }
505
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);
510       if (!dev) {
511          Jmsg1(NULL, M_ERROR, 0, _("Could not initialize %s\n"), device->device_name);
512          continue;
513       }
514
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);
520       }
521
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());
527             free_dcr(dcr);
528             jcr->dcr = NULL;
529             continue;
530          }
531       }
532       if (device->cap_bits & CAP_AUTOMOUNT && dev->is_open()) {
533          switch (read_dev_volume_label(dcr)) {
534          case VOL_OK:
535             memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
536             volume_unused(dcr);             /* mark volume "released" */
537             break;
538          default:
539             Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), dev->print_name());
540             break;
541          }
542       }
543       free_dcr(dcr);
544       jcr->dcr = NULL;
545    }
546 #ifdef xxx
547    if (jcr->dcr) {
548       Dmsg1(000, "free_dcr=%p\n", jcr->dcr);
549       free_dcr(jcr->dcr);
550       jcr->dcr = NULL;
551    }
552 #endif
553    free_jcr(jcr); 
554    init_done = true;
555    UnlockRes();
556    return NULL;
557 }
558
559
560 /* Clean up and then exit */
561 void terminate_stored(int sig)
562 {
563    static bool in_here = false;
564    DEVRES *device;
565    JCR *jcr;
566
567    if (in_here) {                     /* prevent loops */
568       bmicrosleep(2, 0);              /* yield */
569       exit(1);
570    }
571    in_here = true;
572    debug_level = 0;                   /* turn off any debug */
573    stop_watchdog();
574
575    if (sig == SIGTERM) {              /* normal shutdown request? */
576       /*
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
580        *   volume status.
581        */
582       foreach_jcr(jcr) {
583          BSOCK *fd;
584          if (jcr->JobId == 0) {
585             free_jcr(jcr);
586             continue;                 /* ignore console */
587          }
588          jcr->setJobStatus(JS_Canceled);
589          fd = jcr->file_bsock;
590          if (fd) {
591             fd->set_timed_out();
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);
599             }
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);
603             }
604             bmicrosleep(0, 50000);
605          }
606          free_jcr(jcr);
607       }
608       bmicrosleep(0, 500000);         /* give them 1/2 sec to clean up */
609    }
610
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));
613
614    Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
615
616    unload_plugins();
617    free_volume_lists();
618
619    foreach_res(device, R_DEVICE) {
620       Dmsg1(10, "Term device %s\n", device->device_name);
621       if (device->dev) {
622          device->dev->clear_volhdr();
623          device->dev->term();
624          device->dev = NULL;
625       } else {
626          Dmsg1(10, "No dev structure %s\n", device->device_name);
627       }
628    }
629
630    if (configfile) {
631       free(configfile);
632       configfile = NULL;
633    }
634    if (config) {
635       config->free_resources();
636       free(config);
637       config = NULL;
638    }
639
640    if (debug_level > 10) {
641       print_memory_pool_stats();
642    }
643    term_msg();
644    cleanup_crypto();
645    term_reservations_lock();
646    close_memory_pool();
647    lmgr_cleanup_main();
648
649    sm_dump(false);                    /* dump orphaned buffers */
650    exit(sig);
651 }