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