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