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