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