]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/stored.c
Vacation work -- see tech log
[bacula/bacula] / bacula / src / stored / stored.c
1 /*
2  * Second generation Storage daemon.
3  *
4  * It accepts a number of simple commands from the File daemon
5  * and acts on them. When a request to append data is made,
6  * it opens a data channel and accepts data from the
7  * File daemon.
8  *
9  *   Version $Id$
10  *
11  */
12 /*
13    Copyright (C) 2000-2005 Kern Sibbald
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 #include "bacula.h"
33 #include "stored.h"
34
35 /* Imported functions */
36
37
38 /* Forward referenced functions */
39 void terminate_stored(int sig);
40 static void check_config();
41
42 extern "C" void *device_allocation(void *arg);
43
44
45
46 #define CONFIG_FILE "bacula-sd.conf"  /* Default config file */
47
48
49 /* Global variables exported */
50 char OK_msg[]   = "3000 OK\n";
51 char TERM_msg[] = "3999 Terminate\n";
52 STORES *me = NULL;                    /* our Global resource */
53 bool forge_on = false;                /* proceed inspite of I/O errors */
54
55 static uint32_t VolSessionId = 0;
56 uint32_t VolSessionTime;
57 char *configfile;
58
59 /* Global static variables */
60 static int foreground = 0;
61 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
62 static workq_t dird_workq;            /* queue for processing connections */
63
64
65 static void usage()
66 {
67    fprintf(stderr, _(
68 "Copyright (C) 2000-2005 Kern Sibbald.\n"
69 "\nVersion: " VERSION " (" BDATE ")\n\n"
70 "Usage: stored [options] [-c config_file] [config_file]\n"
71 "        -c <file>   use <file> as configuration file\n"
72 "        -dnn        set debug level to nn\n"
73 "        -f          run in foreground (for debugging)\n"
74 "        -g <group>  set groupid to group\n"
75 "        -p          proceed despite I/O errors\n"
76 "        -s          no signals (for debugging)\n"
77 "        -t          test - read config and exit\n"
78 "        -u <user>   userid to <user>\n"
79 "        -v          verbose user messages\n"
80 "        -?          print this message.\n"
81 "\n"));
82    exit(1);
83 }
84
85 /*********************************************************************
86  *
87  *  Main Bacula Unix Storage Daemon
88  *
89  */
90 int main (int argc, char *argv[])
91 {
92    int ch;
93    int no_signals = FALSE;
94    int test_config = FALSE;
95    pthread_t thid;
96    char *uid = NULL;
97    char *gid = NULL;
98
99    init_stack_dump();
100    my_name_is(argc, argv, "bacula-sd");
101    textdomain("bacula");
102    init_msg(NULL, NULL);
103    daemon_start_time = time(NULL);
104
105    /* Sanity checks */
106    if (TAPE_BSIZE % DEV_BSIZE != 0 || TAPE_BSIZE / DEV_BSIZE == 0) {
107       Emsg2(M_ABORT, 0, "Tape block size (%d) not multiple of system size (%d)\n",
108          TAPE_BSIZE, DEV_BSIZE);
109    }
110    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
111       Emsg1(M_ABORT, 0, "Tape block size (%d) is not a power of 2\n", TAPE_BSIZE);
112    }
113
114    while ((ch = getopt(argc, argv, "c:d:fg:pstu:v?")) != -1) {
115       switch (ch) {
116       case 'c':                    /* configuration file */
117          if (configfile != NULL) {
118             free(configfile);
119          }
120          configfile = bstrdup(optarg);
121          break;
122
123       case 'd':                    /* debug level */
124          debug_level = atoi(optarg);
125          if (debug_level <= 0) {
126             debug_level = 1;
127          }
128          break;
129
130       case 'f':                    /* run in foreground */
131          foreground = TRUE;
132          break;
133
134       case 'g':                    /* set group id */
135          gid = optarg;
136          break;
137
138       case 'p':                    /* proceed in spite of I/O errors */
139          forge_on = true;
140          break;
141
142       case 's':                    /* no signals */
143          no_signals = TRUE;
144          break;
145
146       case 't':
147          test_config = TRUE;
148          break;
149
150       case 'u':                    /* set uid */
151          uid = optarg;
152          break;
153
154       case 'v':                    /* verbose */
155          verbose++;
156          break;
157
158       case '?':
159       default:
160          usage();
161          break;
162       }
163    }
164    argc -= optind;
165    argv += optind;
166
167    if (argc) {
168       if (configfile != NULL) {
169          free(configfile);
170       }
171       configfile = bstrdup(*argv);
172       argc--;
173       argv++;
174    }
175    if (argc)
176       usage();
177
178    if (!no_signals) {
179       init_signals(terminate_stored);
180    }
181
182    if (configfile == NULL) {
183       configfile = bstrdup(CONFIG_FILE);
184    }
185
186    parse_config(configfile);
187    check_config();
188
189    if (test_config) {
190       terminate_stored(0);
191    }
192
193    if (!foreground) {
194       daemon_start();                 /* become daemon */
195       init_stack_dump();              /* pick up new pid */
196    }
197
198    create_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
199    read_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
200
201    drop(uid, gid);
202
203    /* Ensure that Volume Session Time and Id are both
204     * set and are both non-zero.
205     */
206    VolSessionTime = (long)daemon_start_time;
207    if (VolSessionTime == 0) { /* paranoid */
208       Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
209    }
210
211    /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
212    set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
213
214     /*
215      * Start the device allocation thread
216      */
217    if (pthread_create(&thid, NULL, device_allocation, NULL) != 0) {
218       Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), strerror(errno));
219    }
220
221    start_watchdog();                  /* start watchdog thread */
222
223    init_jcr_subsystem();              /* start JCR watchdogs etc. */
224
225    /*
226     * Sleep a bit to give device thread a chance to lock the resource
227     * chain before we start the server.
228     */
229    bmicrosleep(1, 0);
230
231    /* Single server used for Director and File daemon */
232    bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
233                       &dird_workq, handle_connection_request);
234    exit(1);                           /* to keep compiler quiet */
235 }
236
237 /* Return a new Session Id */
238 uint32_t newVolSessionId()
239 {
240    uint32_t Id;
241
242    P(mutex);
243    VolSessionId++;
244    Id = VolSessionId;
245    V(mutex);
246    return Id;
247 }
248
249 /* Check Configuration file for necessary info */
250 static void check_config()
251 {
252    LockRes();
253    me = (STORES *)GetNextRes(R_STORAGE, NULL);
254    if (!me) {
255       UnlockRes();
256       Jmsg1(NULL, M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
257          configfile);
258    }
259
260    my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */
261
262    if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
263       UnlockRes();
264       Jmsg1(NULL, M_ERROR_TERM, 0, _("Only one Storage resource permitted in %s\n"),
265          configfile);
266    }
267    if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
268       UnlockRes();
269       Jmsg1(NULL, M_ERROR_TERM, 0, _("No Director resource defined in %s. Cannot continue.\n"),
270          configfile);
271    }
272    if (GetNextRes(R_DEVICE, NULL) == NULL){
273       UnlockRes();
274       Jmsg1(NULL, M_ERROR_TERM, 0, _("No Device resource defined in %s. Cannot continue.\n"),
275            configfile);
276    }
277    if (!me->messages) {
278       me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
279       if (!me->messages) {
280          Jmsg1(NULL, M_ERROR_TERM, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
281             configfile);
282       }
283    }
284    close_msg(NULL);                   /* close temp message handler */
285    init_msg(NULL, me->messages);      /* open daemon message handler */
286
287    UnlockRes();
288
289    if (!me->working_directory) {
290       Jmsg1(NULL, M_ERROR_TERM, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
291          configfile);
292    }
293
294    set_working_directory(me->working_directory);
295 }
296
297 /*
298  * Here we attempt to init and open each device. This is done
299  *  once at startup in a separate thread.
300  */
301 extern "C"
302 void *device_allocation(void *arg)
303 {
304    DEVRES *device;
305
306    LockRes();
307    pthread_detach(pthread_self());
308
309    foreach_res(device, R_DEVICE) {
310       Dmsg1(90, "calling init_dev %s\n", device->device_name);
311       device->dev = init_dev(NULL, device);
312       Dmsg1(10, "SD init done %s\n", device->device_name);
313       if (!device->dev) {
314          Jmsg1(NULL, M_ERROR, 0, _("Could not initialize %s\n"), device->device_name);
315          continue;
316       }
317
318       if (device->cap_bits & CAP_ALWAYSOPEN) {
319          Dmsg1(20, "calling first_open_device %s\n", device->device_name);
320          if (!first_open_device(device->dev)) {
321             Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), device->device_name);
322          }
323       }
324       if (device->cap_bits & CAP_AUTOMOUNT && device->dev &&
325           device->dev->state & ST_OPENED) {
326          JCR *jcr;
327          DCR *dcr;
328          jcr = new_jcr(sizeof(JCR), stored_free_jcr);
329          jcr->JobType = JT_SYSTEM;
330          /* Initialize FD start condition variable */
331          int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
332          if (errstat != 0) {
333             Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
334          }
335          dcr = new_dcr(jcr, device->dev);
336          switch (read_dev_volume_label(dcr)) {
337          case VOL_OK:
338             memcpy(&dcr->dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dcr->dev->VolCatInfo));
339             break;
340          default:
341             Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), device->device_name);
342             break;
343          }
344          free_jcr(jcr);
345       }
346    }
347    UnlockRes();
348    return NULL;
349 }
350
351
352 /* Clean up and then exit */
353 void terminate_stored(int sig)
354 {
355    static bool in_here = false;
356    DEVRES *device;
357    JCR *jcr;
358
359    if (in_here) {                     /* prevent loops */
360       exit(1);
361    }
362    in_here = true;
363
364    if (sig == SIGTERM) {              /* normal shutdown request? */
365       /*
366        * This is a normal shutdown request. We wiffle through
367        *   all open jobs canceling them and trying to wake
368        *   them up so that they will report back the correct
369        *   volume status.
370        */
371       lock_jcr_chain();
372       foreach_jcr(jcr) {
373          BSOCK *fd;
374          free_locked_jcr(jcr);
375          if (jcr->JobId == 0) {
376             continue;                 /* ignore console */
377          }
378          set_jcr_job_status(jcr, JS_Canceled);
379          fd = jcr->file_bsock;
380          if (fd) {
381             fd->timed_out = true;
382             Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
383             pthread_kill(jcr->my_thread_id, TIMEOUT_SIGNAL);
384             /* ***FIXME*** wiffle through all dcrs */
385             if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->dev_blocked) {
386                pthread_cond_signal(&jcr->dcr->dev->wait_next_vol);
387             }
388             bmicrosleep(0, 50000);
389           }
390       }
391       unlock_jcr_chain();
392       bmicrosleep(0, 500000);         /* give them 1/2 sec to clean up */
393    }
394
395    write_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
396    delete_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
397
398    Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
399
400    LockRes();
401    foreach_res(device, R_DEVICE) {
402       if (device->dev) {
403          term_dev(device->dev);
404       }
405    }
406    UnlockRes();
407
408    if (configfile)
409    free(configfile);
410    free_config_resources();
411
412    if (debug_level > 10) {
413       print_memory_pool_stats();
414    }
415    term_msg();
416    stop_watchdog();
417    close_memory_pool();
418
419    sm_dump(false);                    /* dump orphaned buffers */
420    exit(sig);
421 }