]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/stored.c
93735c76b4e0e84fe28fd5cb483d6ad2878f2634
[bacula/bacula] / bacula / src / stored / stored.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2009 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 two of the GNU 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 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 #ifdef HAVE_PYTHON
50
51 #undef _POSIX_C_SOURCE
52 #include <Python.h>
53
54 #include "lib/pythonlib.h"
55
56 /* Imported Functions */
57 extern PyObject *job_getattr(PyObject *self, char *attrname);
58 extern int job_setattr(PyObject *self, char *attrname, PyObject *value);
59
60 #endif /* HAVE_PYTHON */
61
62 /* Imported functions */
63 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
64
65 /* Forward referenced functions */
66 void terminate_stored(int sig);
67 static int check_resources();
68 static void cleanup_old_files();
69
70 extern "C" void *device_initialization(void *arg);
71
72 #define CONFIG_FILE "bacula-sd.conf"  /* Default config file */
73
74 /* Global variables exported */
75 char OK_msg[]   = "3000 OK\n";
76 char TERM_msg[] = "3999 Terminate\n";
77 STORES *me = NULL;                    /* our Global resource */
78 bool forge_on = false;                /* proceed inspite of I/O errors */
79 pthread_mutex_t device_release_mutex = PTHREAD_MUTEX_INITIALIZER;
80 pthread_cond_t wait_device_release = PTHREAD_COND_INITIALIZER;
81 void *start_heap;
82
83
84 static uint32_t VolSessionId = 0;
85 uint32_t VolSessionTime;
86 char *configfile = NULL;
87 bool init_done = false;
88
89 /* Global static variables */
90 static bool foreground = 0;
91 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
92 static workq_t dird_workq;            /* queue for processing connections */
93 static CONFIG *config;
94
95
96 static void usage()
97 {
98    fprintf(stderr, _(
99 PROG_COPYRIGHT
100 "\nVersion: %s (%s)\n\n"
101 "Usage: stored [options] [-c config_file] [config_file]\n"
102 "        -c <file>   use <file> as configuration file\n"
103 "        -d <nn>     set debug level to <nn>\n"
104 "        -dt         print timestamp in debug output\n"
105 "        -f          run in foreground (for debugging)\n"
106 "        -g <group>  set groupid to group\n"
107 "        -m          print kaboom output (for debugging)\n"
108 "        -p          proceed despite I/O errors\n"
109 "        -s          no signals (for debugging)\n"
110 "        -t          test - read config and exit\n"
111 "        -u <user>   userid to <user>\n"
112 "        -v          verbose user messages\n"
113 "        -?          print this message.\n"
114 "\n"), 2000, VERSION, BDATE);
115    exit(1);
116 }
117
118 /*********************************************************************
119  *
120  *  Main Bacula Unix Storage Daemon
121  *
122  */
123 #if defined(HAVE_WIN32)
124 #define main BaculaMain
125 #endif
126
127 int main (int argc, char *argv[])
128 {
129    int ch;
130    bool no_signals = false;
131    bool test_config = false;
132    pthread_t thid;
133    char *uid = NULL;
134    char *gid = NULL;
135 #ifdef HAVE_PYTHON
136    init_python_interpreter_args python_args;
137 #endif /* HAVE_PYTHON */
138
139    start_heap = sbrk(0);
140    setlocale(LC_ALL, "");
141    bindtextdomain("bacula", LOCALEDIR);
142    textdomain("bacula");
143
144    init_stack_dump();
145    my_name_is(argc, argv, "bacula-sd");
146    init_msg(NULL, NULL);
147    daemon_start_time = time(NULL);
148
149    /* Sanity checks */
150    if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
151       Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
152          TAPE_BSIZE, B_DEV_BSIZE);
153    }
154    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
155       Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
156    }
157
158    while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?")) != -1) {
159       switch (ch) {
160       case 'c':                    /* configuration file */
161          if (configfile != NULL) {
162             free(configfile);
163          }
164          configfile = bstrdup(optarg);
165          break;
166
167       case 'd':                    /* debug level */
168          if (*optarg == 't') {
169             dbg_timestamp = true;
170          } else {
171             debug_level = atoi(optarg);
172             if (debug_level <= 0) {
173                debug_level = 1;
174             }
175          }
176          break;
177
178       case 'f':                    /* run in foreground */
179          foreground = true;
180          break;
181
182       case 'g':                    /* set group id */
183          gid = optarg;
184          break;
185
186       case 'm':                    /* print kaboom output */
187          prt_kaboom = true;
188          break;
189
190       case 'p':                    /* proceed in spite of I/O errors */
191          forge_on = true;
192          break;
193
194       case 's':                    /* no signals */
195          no_signals = true;
196          break;
197
198       case 't':
199          test_config = true;
200          break;
201
202       case 'u':                    /* set uid */
203          uid = optarg;
204          break;
205
206       case 'v':                    /* verbose */
207          verbose++;
208          break;
209
210       case '?':
211       default:
212          usage();
213          break;
214       }
215    }
216    argc -= optind;
217    argv += optind;
218
219    if (argc) {
220       if (configfile != NULL) {
221          free(configfile);
222       }
223       configfile = bstrdup(*argv);
224       argc--;
225       argv++;
226    }
227    if (argc)
228       usage();
229
230    if (!no_signals) {
231       init_signals(terminate_stored);
232    }
233
234    if (configfile == NULL) {
235       configfile = bstrdup(CONFIG_FILE);
236    }
237
238    config = new_config_parser();
239    parse_sd_config(config, configfile, M_ERROR_TERM);
240
241    if (init_crypto() != 0) {
242       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
243    }
244
245    if (!check_resources()) {
246       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
247    }
248
249    init_reservations_lock();
250
251    if (test_config) {
252       terminate_stored(0);
253    }
254
255    my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */
256
257    if (!foreground) {
258       daemon_start();                 /* become daemon */
259       init_stack_dump();              /* pick up new pid */
260    }
261
262    create_pid_file(me->pid_directory, "bacula-sd",
263                    get_first_port_host_order(me->sdaddrs));
264    read_state_file(me->working_directory, "bacula-sd", 
265                    get_first_port_host_order(me->sdaddrs));
266
267    /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
268    set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
269    lmgr_init_thread(); /* initialize the lockmanager stack */
270
271    load_sd_plugins(me->plugin_directory);
272
273    drop(uid, gid, false);
274
275    cleanup_old_files();
276
277
278    /* Ensure that Volume Session Time and Id are both
279     * set and are both non-zero.
280     */
281    VolSessionTime = (uint32_t)daemon_start_time;
282    if (VolSessionTime == 0) { /* paranoid */
283       Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
284    }
285
286 #ifdef HAVE_PYTHON
287    python_args.progname = me->hdr.name;
288    python_args.scriptdir = me->scripts_directory;
289    python_args.modulename = "SDStartUp";
290    python_args.configfile = configfile;
291    python_args.workingdir = me->working_directory;
292    python_args.job_getattr = job_getattr;
293    python_args.job_setattr = job_setattr;
294
295    init_python_interpreter(&python_args);
296 #endif /* HAVE_PYTHON */
297
298     /*
299      * Start the device allocation thread
300      */
301    create_volume_lists();             /* do before device_init */
302    if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
303       berrno be;
304       Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
305    }
306
307    start_watchdog();                  /* start watchdog thread */
308    init_jcr_subsystem();              /* start JCR watchdogs etc. */
309
310    /* Single server used for Director and File daemon */
311    bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
312                       &dird_workq, handle_connection_request);
313    exit(1);                           /* to keep compiler quiet */
314 }
315
316 /* Return a new Session Id */
317 uint32_t newVolSessionId()
318 {
319    uint32_t Id;
320
321    P(mutex);
322    VolSessionId++;
323    Id = VolSessionId;
324    V(mutex);
325    return Id;
326 }
327
328 /* Check Configuration file for necessary info */
329 static int check_resources()
330 {
331    bool OK = true;
332    bool tls_needed;
333
334
335    me = (STORES *)GetNextRes(R_STORAGE, NULL);
336    if (!me) {
337       Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
338          configfile);
339       OK = false;
340    }
341
342    if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
343       Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
344          configfile);
345       OK = false;
346    }
347    if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
348       Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
349          configfile);
350       OK = false;
351    }
352    if (GetNextRes(R_DEVICE, NULL) == NULL){
353       Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
354            configfile);
355       OK = false;
356    }
357
358    if (!me->messages) {
359       me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
360       if (!me->messages) {
361          Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
362             configfile);
363          OK = false;
364       }
365    }
366
367    if (!me->working_directory) {
368       Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
369          configfile);
370       OK = false;
371    }
372
373    DIRRES *director;
374    STORES *store;
375    foreach_res(store, R_STORAGE) { 
376       /* tls_require implies tls_enable */
377       if (store->tls_require) {
378          if (have_tls) {
379             store->tls_enable = true;
380          } else {
381             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
382             OK = false;
383             continue;
384          }
385       }
386
387       tls_needed = store->tls_enable || store->tls_authenticate;
388
389       if (!store->tls_certfile && tls_needed) {
390          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
391               store->hdr.name, configfile);
392          OK = false;
393       }
394
395       if (!store->tls_keyfile && tls_needed) {
396          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
397               store->hdr.name, configfile);
398          OK = false;
399       }
400
401       if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && tls_needed && store->tls_verify_peer) {
402          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
403               " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
404               " At least one CA certificate store is required"
405               " when using \"TLS Verify Peer\".\n"),
406               store->hdr.name, configfile);
407          OK = false;
408       }
409
410       /* If everything is well, attempt to initialize our per-resource TLS context */
411       if (OK && (tls_needed || store->tls_require)) {
412          /* Initialize TLS context:
413           * Args: CA certfile, CA certdir, Certfile, Keyfile,
414           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
415          store->tls_ctx = new_tls_context(store->tls_ca_certfile,
416             store->tls_ca_certdir, store->tls_certfile,
417             store->tls_keyfile, NULL, NULL, store->tls_dhfile,
418             store->tls_verify_peer);
419
420          if (!store->tls_ctx) { 
421             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
422                  store->hdr.name, configfile);
423             OK = false;
424          }
425       }
426    }
427
428    foreach_res(director, R_DIRECTOR) { 
429       /* tls_require implies tls_enable */
430       if (director->tls_require) {
431          director->tls_enable = true;
432       }
433
434       tls_needed = director->tls_enable || director->tls_authenticate;
435
436       if (!director->tls_certfile && tls_needed) {
437          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
438               director->hdr.name, configfile);
439          OK = false;
440       }
441
442       if (!director->tls_keyfile && tls_needed) {
443          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
444               director->hdr.name, configfile);
445          OK = false;
446       }
447
448       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed && director->tls_verify_peer) {
449          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
450               " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
451               " At least one CA certificate store is required"
452               " when using \"TLS Verify Peer\".\n"),
453               director->hdr.name, configfile);
454          OK = false;
455       }
456
457       /* If everything is well, attempt to initialize our per-resource TLS context */
458       if (OK && (tls_needed || director->tls_require)) {
459          /* Initialize TLS context:
460           * Args: CA certfile, CA certdir, Certfile, Keyfile,
461           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
462          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
463             director->tls_ca_certdir, director->tls_certfile,
464             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
465             director->tls_verify_peer);
466
467          if (!director->tls_ctx) { 
468             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
469                  director->hdr.name, configfile);
470             OK = false;
471          }
472       }
473    }
474
475    OK = init_autochangers();
476
477    
478    if (OK) {
479       close_msg(NULL);                   /* close temp message handler */
480       init_msg(NULL, me->messages);      /* open daemon message handler */
481       set_working_directory(me->working_directory);
482    }
483
484    return OK;
485 }
486
487 static void cleanup_old_files()
488 {
489    POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
490    POOLMEM *results = get_pool_memory(PM_MESSAGE);
491    int len = strlen(me->working_directory);
492 #if defined(HAVE_WIN32)
493    pm_strcpy(cleanup, "del /q ");
494 #else
495    pm_strcpy(cleanup, "/bin/rm -f ");
496 #endif
497    pm_strcat(cleanup, me->working_directory);
498    if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
499       pm_strcat(cleanup, "/");
500    }
501    pm_strcat(cleanup, my_name);
502    pm_strcat(cleanup, "*.spool");
503    run_program(cleanup, 0, results);
504    free_pool_memory(cleanup);
505    free_pool_memory(results);
506 }
507
508
509 /*
510  * Here we attempt to init and open each device. This is done
511  *  once at startup in a separate thread.
512  */
513 extern "C"
514 void *device_initialization(void *arg)
515 {
516    DEVRES *device;
517    DCR *dcr;
518    JCR *jcr;
519    DEVICE *dev;
520
521    LockRes();
522
523    pthread_detach(pthread_self());
524    jcr = new_jcr(sizeof(JCR), stored_free_jcr);
525    jcr->set_JobType(JT_SYSTEM);
526    /* Initialize FD start condition variable */
527    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
528    if (errstat != 0) {
529       berrno be;
530       Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
531    }
532
533    foreach_res(device, R_DEVICE) {
534       Dmsg1(90, "calling init_dev %s\n", device->device_name);
535       dev = init_dev(NULL, device);
536       Dmsg1(10, "SD init done %s\n", device->device_name);
537       if (!dev) {
538          Jmsg1(NULL, M_ERROR, 0, _("Could not initialize %s\n"), device->device_name);
539          continue;
540       }
541
542       jcr->dcr = dcr = new_dcr(jcr, NULL, dev);
543       if (dev->is_autochanger()) {
544          /* If autochanger set slot in dev sturcture */
545          get_autochanger_loaded_slot(dcr);
546       }
547
548       if (device->cap_bits & CAP_ALWAYSOPEN) {
549          Dmsg1(20, "calling first_open_device %s\n", dev->print_name());
550          if (!first_open_device(dcr)) {
551             Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), dev->print_name());
552             Dmsg1(20, "Could not open device %s\n", dev->print_name());
553             free_dcr(dcr);
554             jcr->dcr = NULL;
555             continue;
556          }
557       }
558       if (device->cap_bits & CAP_AUTOMOUNT && dev->is_open()) {
559          switch (read_dev_volume_label(dcr)) {
560          case VOL_OK:
561             memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
562             volume_unused(dcr);             /* mark volume "released" */
563             break;
564          default:
565             Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), dev->print_name());
566             break;
567          }
568       }
569       free_dcr(dcr);
570       jcr->dcr = NULL;
571    }
572 #ifdef xxx
573    if (jcr->dcr) {
574       Dmsg1(000, "free_dcr=%p\n", jcr->dcr);
575       free_dcr(jcr->dcr);
576       jcr->dcr = NULL;
577    }
578 #endif
579    free_jcr(jcr); 
580    init_done = true;
581    UnlockRes();
582    return NULL;
583 }
584
585
586 /* Clean up and then exit */
587 void terminate_stored(int sig)
588 {
589    static bool in_here = false;
590    DEVRES *device;
591    JCR *jcr;
592
593    if (in_here) {                     /* prevent loops */
594       bmicrosleep(2, 0);              /* yield */
595       exit(1);
596    }
597    in_here = true;
598    debug_level = 0;                   /* turn off any debug */
599    stop_watchdog();
600
601    if (sig == SIGTERM) {              /* normal shutdown request? */
602       /*
603        * This is a normal shutdown request. We wiffle through
604        *   all open jobs canceling them and trying to wake
605        *   them up so that they will report back the correct
606        *   volume status.
607        */
608       foreach_jcr(jcr) {
609          BSOCK *fd;
610          if (jcr->JobId == 0) {
611             free_jcr(jcr);
612             continue;                 /* ignore console */
613          }
614          set_jcr_job_status(jcr, JS_Canceled);
615          fd = jcr->file_bsock;
616          if (fd) {
617             fd->set_timed_out();
618             Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
619             pthread_kill(jcr->my_thread_id, TIMEOUT_SIGNAL);
620             /* ***FIXME*** wiffle through all dcrs */
621             if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->blocked()) {
622                pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
623                Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
624                pthread_cond_broadcast(&wait_device_release);
625             }
626             if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->blocked()) {
627                pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
628                pthread_cond_broadcast(&wait_device_release);
629             }
630             bmicrosleep(0, 50000);
631          }
632          free_jcr(jcr);
633       }
634       bmicrosleep(0, 500000);         /* give them 1/2 sec to clean up */
635    }
636
637    write_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
638    delete_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
639
640    Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
641
642    unload_plugins();
643    free_volume_lists();
644
645    foreach_res(device, R_DEVICE) {
646       Dmsg1(10, "Term device %s\n", device->device_name);
647       if (device->dev) {
648          device->dev->clear_volhdr();
649          device->dev->term();
650          device->dev = NULL;
651       } else {
652          Dmsg1(10, "No dev structure %s\n", device->device_name);
653       }
654    }
655
656    if (configfile) {
657       free(configfile);
658       configfile = NULL;
659    }
660    if (config) {
661       config->free_resources();
662       free(config);
663       config = NULL;
664   }
665
666    if (debug_level > 10) {
667       print_memory_pool_stats();
668    }
669    term_msg();
670    cleanup_crypto();
671    term_reservations_lock();
672    close_memory_pool();
673    lmgr_cleanup_main();
674
675    sm_dump(false);                    /* dump orphaned buffers */
676    exit(sig);
677 }