]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
b8ff96b8ace7cfeeee24913eb61fad7c74cfe9f7
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2  *
3  *   Bacula Director daemon -- this is the main program
4  *
5  *     Kern Sibbald, March MM
6  *
7  *   Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2004 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "dird.h"
31
32 /* Forward referenced subroutines */
33 static void terminate_dird(int sig);
34 static int check_resources();
35
36 /* Exported subroutines */
37 void reload_config(int sig);
38
39
40 /* Imported subroutines */
41 JCR *wait_for_next_job(char *runjob);
42 void term_scheduler();
43 void term_ua_server();
44 int do_backup(JCR *jcr);
45 void backup_cleanup(void);
46 void start_UA_server(char *addr, int port);
47 void init_job_server(int max_workers);
48 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
49 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
50 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
51
52 static char *configfile = NULL;
53 static char *runjob = NULL;
54 static int background = 1;
55 static void init_reload(void);
56
57 /* Globals Exported */
58 DIRRES *director;                     /* Director resource */
59 int FDConnectTimeout;
60 int SDConnectTimeout;
61
62 /* Globals Imported */
63 extern int r_first, r_last;           /* first and last resources */
64 extern RES_TABLE resources[];
65 extern RES_ITEM job_items[];
66 extern URES res_all;
67
68
69 #define CONFIG_FILE "./bacula-dir.conf" /* default configuration file */
70
71 static void usage()
72 {
73    fprintf(stderr, _(
74 "\nVersion: " VERSION " (" BDATE ")\n\n"
75 "Usage: dird [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
76 "       -c <file>   set configuration file to file\n"
77 "       -dnn        set debug level to nn\n"
78 "       -f          run in foreground (for debugging)\n"
79 "       -g          groupid\n"
80 "       -r <job>    run <job> now\n"
81 "       -s          no signals\n"
82 "       -t          test - read configuration and exit\n"
83 "       -u          userid\n"
84 "       -v          verbose user messages\n"
85 "       -?          print this message.\n"  
86 "\n"));
87
88    exit(1);
89 }
90
91
92 /*********************************************************************
93  *
94  *         Main Bacula Server program
95  *
96  */
97 int main (int argc, char *argv[])
98 {
99    int ch;
100    JCR *jcr;
101    int no_signals = FALSE;
102    int test_config = FALSE;
103    char *uid = NULL;
104    char *gid = NULL;
105
106    init_stack_dump();
107    my_name_is(argc, argv, "bacula-dir");
108    textdomain("bacula");
109    init_msg(NULL, NULL);              /* initialize message handler */
110    init_reload();
111    daemon_start_time = time(NULL);
112
113    while ((ch = getopt(argc, argv, "c:d:fg:r:stu:v?")) != -1) {
114       switch (ch) {
115       case 'c':                    /* specify config file */
116          if (configfile != NULL) {
117             free(configfile);
118          }
119          configfile = bstrdup(optarg);
120          break;
121
122       case 'd':                    /* set debug level */
123          debug_level = atoi(optarg);
124          if (debug_level <= 0) {
125             debug_level = 1; 
126          }
127          Dmsg1(0, "Debug level = %d\n", debug_level);
128          break;
129
130       case 'f':                    /* run in foreground */
131          background = FALSE;
132          break;
133
134       case 'g':                    /* set group id */
135          gid = optarg;
136          break;
137
138       case 'r':                    /* run job */
139          if (runjob != NULL) {
140             free(runjob);
141          }
142          if (optarg) {
143             runjob = bstrdup(optarg);
144          }
145          break;
146
147       case 's':                    /* turn off signals */
148          no_signals = TRUE;
149          break;
150
151       case 't':                    /* test config */
152          test_config = TRUE;
153          break;
154
155       case 'u':                    /* set uid */
156          uid = optarg;
157          break;
158
159       case 'v':                    /* verbose */
160          verbose++;
161          break;
162
163       case '?':
164       default:
165          usage();
166
167       }  
168    }
169    argc -= optind;
170    argv += optind;
171
172    if (!no_signals) {
173       init_signals(terminate_dird);
174    }
175
176    if (argc) {
177       if (configfile != NULL) {
178          free(configfile);
179       }
180       configfile = bstrdup(*argv);
181       argc--; 
182       argv++;
183    }
184    if (argc) {
185       usage();
186    }
187
188    if (configfile == NULL) {
189       configfile = bstrdup(CONFIG_FILE);
190    }
191
192    parse_config(configfile);
193
194    if (!check_resources()) {
195       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
196    }
197
198    if (test_config) {
199       terminate_dird(0);
200    }
201
202    my_name_is(0, NULL, director->hdr.name);    /* set user defined name */
203
204    FDConnectTimeout = (int)director->FDConnectTimeout;
205    SDConnectTimeout = (int)director->SDConnectTimeout;
206
207    if (background) {
208       daemon_start();
209       init_stack_dump();              /* grab new pid */
210    }
211
212    /* Create pid must come after we are a daemon -- so we have our final pid */
213    create_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
214    read_state_file(director->working_directory, "bacula-dir", director->DIRport);
215
216    drop(uid, gid);                    /* reduce priveleges if requested */
217
218    /* signal(SIGHUP, reload_config); */
219
220    init_console_msg(working_directory);
221
222    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
223       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
224
225    Dmsg0(200, "Start UA server\n");
226    start_UA_server(director->DIRaddr, director->DIRport);
227
228    start_watchdog();                  /* start network watchdog thread */
229
230    init_jcr_subsystem();              /* start JCR watchdogs etc. */
231
232    init_job_server(director->MaxConcurrentJobs);
233   
234    Dmsg0(200, "wait for next job\n");
235    /* Main loop -- call scheduler to get next job to run */
236    while ((jcr = wait_for_next_job(runjob))) {
237       run_job(jcr);                   /* run job */
238       free_jcr(jcr);                  /* release jcr */
239       if (runjob) {                   /* command line, run a single job? */
240          break;                       /* yes, terminate */
241       }
242    }
243
244    terminate_dird(0);
245 }
246
247 /* Cleanup and then exit */
248 static void terminate_dird(int sig)
249 {
250    static int already_here = FALSE;
251
252    if (already_here) {                /* avoid recursive temination problems */
253       exit(1);
254    }
255    already_here = TRUE;
256    write_state_file(director->working_directory, "bacula-dir", director->DIRport);
257    delete_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
258 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
259    term_scheduler();
260    if (runjob) {
261       free(runjob);
262    }
263    if (configfile != NULL) {
264       free(configfile);
265    }
266    if (debug_level > 5) {
267       print_memory_pool_stats(); 
268    }
269    free_config_resources();
270    term_ua_server();
271    term_msg();                        /* terminate message handler */
272    stop_watchdog();
273    close_memory_pool();               /* release free memory in pool */
274    sm_dump(false);
275    exit(sig);
276 }
277
278 struct RELOAD_TABLE {
279    int job_count;
280    RES **res_table;
281 };
282
283 static const int max_reloads = 10;
284 static RELOAD_TABLE reload_table[max_reloads];
285
286 static void init_reload(void) 
287 {
288    for (int i=0; i < max_reloads; i++) {
289       reload_table[i].job_count = 0;
290       reload_table[i].res_table = NULL;
291    }
292 }
293
294 static void free_saved_resources(int table)
295 {
296    int num = r_last - r_first + 1;
297    RES **res_tab = reload_table[table].res_table;
298    Dmsg1(000, "Freeing resources for table %d\n", table);
299    for (int j=0; j<num; j++) {
300       free_resource(res_tab[j], r_first + j);
301    }
302    free(res_tab);
303    reload_table[table].job_count = 0;
304    reload_table[table].res_table = NULL;
305 }
306
307 /*
308  * Called here at the end of every job that was
309  * hooked decrementing the active job_count. When
310  * it goes to zero, no one is using the associated
311  * resource table, so free it.
312  */
313 static void reload_job_end_cb(JCR *jcr)
314 {
315 #ifdef working
316    int i = jcr->reload_id - 1;
317    Dmsg1(000, "reload job_end JobId=%d\n", jcr->JobId);
318    lock_jcr_chain();
319    LockRes();
320    if (--reload_table[i].job_count <= 0) {
321       free_saved_resources(i);
322    }
323    UnlockRes();
324    unlock_jcr_chain();
325 #endif
326 }
327
328 static int find_free_table()
329 {
330    int table = -1;
331    for (int i=0; i < max_reloads; i++) {
332       if (reload_table[i].res_table == NULL) {
333          table = i;
334          break;
335       }
336    }
337    return table;
338 }
339
340 /*
341  * If we get here, we have received a SIGHUP, which means to
342  *    reread our configuration file. 
343  */
344 void reload_config(int sig)
345 {
346    static bool already_here = false;
347    sigset_t set;        
348    JCR *jcr;
349    int njobs = 0;
350    int table, rtable;
351
352    if (already_here) {
353       abort();                        /* Oops, recursion -> die */
354    }
355    already_here = true;
356    sigfillset(&set);
357    sigprocmask(SIG_BLOCK, &set, NULL);
358
359    lock_jcr_chain();
360    LockRes();
361
362    table = find_free_table();
363    if (table < 0) {
364       Jmsg(NULL, M_ERROR, 0, _("Too many reload requests.\n"));
365       goto bail_out;
366    }
367
368    /*
369     * Hook all active jobs that are not already hooked (i.e.
370     *  reload_id == 0
371     */
372    foreach_jcr(jcr) {
373       if (jcr->reload_id == 0) {
374          reload_table[table].job_count++;
375          jcr->reload_id = table + 1;
376          job_end_push(jcr, reload_job_end_cb);
377          njobs++;
378       }
379       free_locked_jcr(jcr);
380    }
381    Dmsg1(000, "Reload_config njobs=%d\n", njobs);
382    reload_table[table].res_table = save_config_resources();
383    Dmsg1(000, "Saved old config in table %d\n", table);
384
385    Dmsg0(000, "Calling parse config\n");
386    parse_config(configfile);
387
388    Dmsg0(000, "Reloaded config file\n");
389    if (!check_resources()) {
390       rtable = find_free_table();     /* save new, bad table */
391       if (rtable < 0) {
392          Jmsg(NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
393       } else {
394          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
395       }
396       reload_table[rtable].res_table = save_config_resources();
397       /* Now restore old resoure values */
398       int num = r_last - r_first + 1;
399       RES **res_tab = reload_table[table].res_table;
400       for (int i=0; i<num; i++) {
401          resources[i].res_head = res_tab[i];
402       }
403       table = rtable;                 /* release new, bad, saved table below */
404    }
405
406    /* Reset globals */
407    set_working_directory(director->working_directory);
408    FDConnectTimeout = director->FDConnectTimeout;
409    SDConnectTimeout = director->SDConnectTimeout;
410    Dmsg0(0, "Director's configuration file reread.\n");
411         
412    /* Now release saved resources */
413    free_saved_resources(table);
414
415 bail_out:
416    UnlockRes();
417    unlock_jcr_chain();
418    sigprocmask(SIG_UNBLOCK, &set, NULL);
419    signal(SIGHUP, reload_config);
420    already_here = false;
421 }
422
423 /*
424  * Make a quick check to see that we have all the
425  * resources needed.
426  *
427  *  **** FIXME **** this routine could be a lot more
428  *   intelligent and comprehensive.
429  */
430 static int check_resources()
431 {
432    bool OK = true;
433    JOB *job;
434
435    LockRes();
436
437    job = (JOB *)GetNextRes(R_JOB, NULL);
438    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
439    if (!director) {
440       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n\
441 Without that I don't know who I am :-(\n"), configfile);
442       OK = false;
443    } else {
444       set_working_directory(director->working_directory);
445       if (!director->messages) {       /* If message resource not specified */
446          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
447          if (!director->messages) {
448             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
449             OK = false;
450          }
451       }
452       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
453          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
454             configfile);
455          OK = false;
456       } 
457    }
458
459    if (!job) {
460       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
461       OK = false;
462    }
463    foreach_res(job, R_JOB) {
464       int i;
465
466       if (job->jobdefs) {
467          /* Transfer default items from JobDefs Resource */
468          for (i=0; job_items[i].name; i++) {
469             char **def_svalue, **svalue;  /* string value */
470             int *def_ivalue, *ivalue;     /* integer value */
471             int64_t *def_lvalue, *lvalue; /* 64 bit values */
472             uint32_t offset;
473
474             Dmsg4(400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
475                 job->hdr.name, job_items[i].name, 
476                 bit_is_set(i, job->hdr.item_present),  
477                 bit_is_set(i, job->jobdefs->hdr.item_present));
478
479             if (!bit_is_set(i, job->hdr.item_present) &&
480                  bit_is_set(i, job->jobdefs->hdr.item_present)) { 
481                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
482                  job->hdr.name, job_items[i].name);
483                offset = (char *)(job_items[i].value) - (char *)&res_all;   
484                /*
485                 * Handle strings and directory strings
486                 */
487                if (job_items[i].handler == store_str ||
488                    job_items[i].handler == store_dir) {
489                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
490                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n", 
491                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
492                   svalue = (char **)((char *)job + offset);
493                   if (*svalue) {
494                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
495                   }
496                   *svalue = bstrdup(*def_svalue);
497                   set_bit(i, job->hdr.item_present);
498                } else if (job_items[i].handler == store_res) {
499                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
500                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n", 
501                        job->hdr.name, job_items[i].name, i, offset);
502                   svalue = (char **)((char *)job + offset);
503                   if (*svalue) {
504                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
505                   }
506                   *svalue = *def_svalue;
507                   set_bit(i, job->hdr.item_present);
508                /*
509                 * Handle integer fields 
510                 *    Note, our store_yesno does not handle bitmaped fields
511                 */
512                } else if (job_items[i].handler == store_yesno   ||
513                           job_items[i].handler == store_pint    ||
514                           job_items[i].handler == store_jobtype ||
515                           job_items[i].handler == store_level   ||
516                           job_items[i].handler == store_pint    ||
517                           job_items[i].handler == store_replace) {
518                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
519                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n", 
520                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
521                   ivalue = (int *)((char *)job + offset);
522                   *ivalue = *def_ivalue;
523                   set_bit(i, job->hdr.item_present);
524                /*
525                 * Handle 64 bit integer fields 
526                 */
527                } else if (job_items[i].handler == store_time   ||
528                           job_items[i].handler == store_size   ||
529                           job_items[i].handler == store_int64) {
530                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
531                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n", 
532                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
533                   lvalue = (int64_t *)((char *)job + offset);
534                   *lvalue = *def_lvalue;
535                   set_bit(i, job->hdr.item_present);
536                }
537             }
538          }
539       }
540       /* 
541        * Ensure that all required items are present
542        */
543       for (i=0; job_items[i].name; i++) {
544          if (job_items[i].flags & ITEM_REQUIRED) {
545                if (!bit_is_set(i, job->hdr.item_present)) {  
546                   Jmsg(NULL, M_FATAL, 0, "Field \"%s\" in Job \"%s\" resource is required, but not found.\n",
547                     job_items[i].name, job->hdr.name);
548                   OK = false;
549                 }
550          }
551          /* If this triggers, take a look at lib/parse_conf.h */
552          if (i >= MAX_RES_ITEMS) {
553             Emsg0(M_ERROR_TERM, 0, "Too many items in Job resource\n");
554          }
555       }
556       if (job->client && job->client->catalog) {
557          CAT *catalog = job->client->catalog;
558          B_DB *db;
559
560          /*
561           * Make sure we can open catalog, otherwise print a warning
562           * message because the server is probably not running.
563           */
564          db = db_init_database(NULL, catalog->db_name, catalog->db_user,
565                             catalog->db_password, catalog->db_address,
566                             catalog->db_port, catalog->db_socket);
567          if (!db || !db_open_database(NULL, db)) {
568             Jmsg(NULL, M_FATAL, 0, _("Could not open database \"%s\".\n"),
569                  catalog->db_name);
570             if (db) {
571                Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
572             }
573             OK = false;
574          } else {
575             /* If a pool is defined for this job, create the pool DB       
576              *  record if it is not already created. 
577              */
578             if (job->pool) {
579                create_pool(NULL, db, job->pool, POOL_OP_UPDATE);  /* update request */
580             }
581             /* Set default value in all counters */
582             COUNTER *counter;
583             foreach_res(counter, R_COUNTER) {
584                /* Write to catalog? */
585                if (!counter->created && counter->Catalog == catalog) {
586                   COUNTER_DBR cr;
587                   bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
588                   cr.MinValue = counter->MinValue;
589                   cr.MaxValue = counter->MaxValue;
590                   cr.CurrentValue = counter->MinValue;
591                   if (counter->WrapCounter) {
592                      bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
593                   } else {
594                      cr.WrapCounter[0] = 0;  /* empty string */
595                   }
596                   if (db_create_counter_record(NULL, db, &cr)) {
597                      counter->CurrentValue = cr.CurrentValue;
598                      counter->created = true;
599                      Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
600                   }
601                } 
602                if (!counter->created) {
603                   counter->CurrentValue = counter->MinValue;  /* default value */
604                }
605             }
606          }
607          db_close_database(NULL, db);
608       }
609    }
610
611    UnlockRes();
612    if (OK) {
613       close_msg(NULL);                /* close temp message handler */
614       init_msg(NULL, director->messages); /* open daemon message handler */
615    }
616    return OK;
617 }