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