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