]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Misc bug fixes
[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    Jmsg(NULL, M_ERROR, 0, _("Command not implemented\n"));
353    return;
354
355    if (already_here) {
356       abort();                        /* Oops, recursion -> die */
357    }
358    already_here = true;
359    sigfillset(&set);
360    sigprocmask(SIG_BLOCK, &set, NULL);
361
362    lock_jcr_chain();
363    LockRes();
364
365    table = find_free_table();
366    if (table < 0) {
367       Jmsg(NULL, M_ERROR, 0, _("Too many reload requests.\n"));
368       goto bail_out;
369    }
370
371    /*
372     * Hook all active jobs that are not already hooked (i.e.
373     *  reload_id == 0
374     */
375    foreach_jcr(jcr) {
376       if (jcr->reload_id == 0) {
377          reload_table[table].job_count++;
378          jcr->reload_id = table + 1;
379          job_end_push(jcr, reload_job_end_cb);
380          njobs++;
381       }
382       free_locked_jcr(jcr);
383    }
384    Dmsg1(000, "Reload_config njobs=%d\n", njobs);
385    reload_table[table].res_table = save_config_resources();
386    Dmsg1(000, "Saved old config in table %d\n", table);
387
388    Dmsg0(000, "Calling parse config\n");
389    parse_config(configfile);
390
391    Dmsg0(000, "Reloaded config file\n");
392    if (!check_resources()) {
393       rtable = find_free_table();     /* save new, bad table */
394       if (rtable < 0) {
395          Jmsg(NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
396       } else {
397          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
398       }
399       reload_table[rtable].res_table = save_config_resources();
400       /* Now restore old resoure values */
401       int num = r_last - r_first + 1;
402       RES **res_tab = reload_table[table].res_table;
403       for (int i=0; i<num; i++) {
404          resources[i].res_head = res_tab[i];
405       }
406       table = rtable;                 /* release new, bad, saved table below */
407    }
408
409    /* Reset globals */
410    set_working_directory(director->working_directory);
411    FDConnectTimeout = director->FDConnectTimeout;
412    SDConnectTimeout = director->SDConnectTimeout;
413    Dmsg0(0, "Director's configuration file reread.\n");
414         
415    /* Now release saved resources */
416    free_saved_resources(table);
417
418 bail_out:
419    UnlockRes();
420    unlock_jcr_chain();
421    sigprocmask(SIG_UNBLOCK, &set, NULL);
422    signal(SIGHUP, reload_config);
423    already_here = false;
424 }
425
426 /*
427  * Make a quick check to see that we have all the
428  * resources needed.
429  *
430  *  **** FIXME **** this routine could be a lot more
431  *   intelligent and comprehensive.
432  */
433 static int check_resources()
434 {
435    bool OK = true;
436    JOB *job;
437
438    LockRes();
439
440    job = (JOB *)GetNextRes(R_JOB, NULL);
441    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
442    if (!director) {
443       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n\
444 Without that I don't know who I am :-(\n"), configfile);
445       OK = false;
446    } else {
447       set_working_directory(director->working_directory);
448       if (!director->messages) {       /* If message resource not specified */
449          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
450          if (!director->messages) {
451             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
452             OK = false;
453          }
454       }
455       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
456          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
457             configfile);
458          OK = false;
459       } 
460    }
461
462    if (!job) {
463       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
464       OK = false;
465    }
466    foreach_res(job, R_JOB) {
467       int i;
468
469       if (job->jobdefs) {
470          /* Transfer default items from JobDefs Resource */
471          for (i=0; job_items[i].name; i++) {
472             char **def_svalue, **svalue;  /* string value */
473             int *def_ivalue, *ivalue;     /* integer value */
474             int64_t *def_lvalue, *lvalue; /* 64 bit values */
475             uint32_t offset;
476
477             Dmsg4(400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
478                 job->hdr.name, job_items[i].name, 
479                 bit_is_set(i, job->hdr.item_present),  
480                 bit_is_set(i, job->jobdefs->hdr.item_present));
481
482             if (!bit_is_set(i, job->hdr.item_present) &&
483                  bit_is_set(i, job->jobdefs->hdr.item_present)) { 
484                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
485                  job->hdr.name, job_items[i].name);
486                offset = (char *)(job_items[i].value) - (char *)&res_all;   
487                /*
488                 * Handle strings and directory strings
489                 */
490                if (job_items[i].handler == store_str ||
491                    job_items[i].handler == store_dir) {
492                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
493                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n", 
494                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
495                   svalue = (char **)((char *)job + offset);
496                   if (*svalue) {
497                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
498                   }
499                   *svalue = bstrdup(*def_svalue);
500                   set_bit(i, job->hdr.item_present);
501                } else if (job_items[i].handler == store_res) {
502                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
503                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n", 
504                        job->hdr.name, job_items[i].name, i, offset);
505                   svalue = (char **)((char *)job + offset);
506                   if (*svalue) {
507                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
508                   }
509                   *svalue = *def_svalue;
510                   set_bit(i, job->hdr.item_present);
511                /*
512                 * Handle integer fields 
513                 *    Note, our store_yesno does not handle bitmaped fields
514                 */
515                } else if (job_items[i].handler == store_yesno   ||
516                           job_items[i].handler == store_pint    ||
517                           job_items[i].handler == store_jobtype ||
518                           job_items[i].handler == store_level   ||
519                           job_items[i].handler == store_pint    ||
520                           job_items[i].handler == store_replace) {
521                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
522                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n", 
523                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
524                   ivalue = (int *)((char *)job + offset);
525                   *ivalue = *def_ivalue;
526                   set_bit(i, job->hdr.item_present);
527                /*
528                 * Handle 64 bit integer fields 
529                 */
530                } else if (job_items[i].handler == store_time   ||
531                           job_items[i].handler == store_size   ||
532                           job_items[i].handler == store_int64) {
533                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
534                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n", 
535                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
536                   lvalue = (int64_t *)((char *)job + offset);
537                   *lvalue = *def_lvalue;
538                   set_bit(i, job->hdr.item_present);
539                }
540             }
541          }
542       }
543       /* 
544        * Ensure that all required items are present
545        */
546       for (i=0; job_items[i].name; i++) {
547          if (job_items[i].flags & ITEM_REQUIRED) {
548                if (!bit_is_set(i, job->hdr.item_present)) {  
549                   Jmsg(NULL, M_FATAL, 0, "Field \"%s\" in Job \"%s\" resource is required, but not found.\n",
550                     job_items[i].name, job->hdr.name);
551                   OK = false;
552                 }
553          }
554          /* If this triggers, take a look at lib/parse_conf.h */
555          if (i >= MAX_RES_ITEMS) {
556             Emsg0(M_ERROR_TERM, 0, "Too many items in Job resource\n");
557          }
558       }
559       if (job->client && job->client->catalog) {
560          CAT *catalog = job->client->catalog;
561          B_DB *db;
562
563          /*
564           * Make sure we can open catalog, otherwise print a warning
565           * message because the server is probably not running.
566           */
567          db = db_init_database(NULL, catalog->db_name, catalog->db_user,
568                             catalog->db_password, catalog->db_address,
569                             catalog->db_port, catalog->db_socket);
570          if (!db || !db_open_database(NULL, db)) {
571             Jmsg(NULL, M_FATAL, 0, _("Could not open database \"%s\".\n"),
572                  catalog->db_name);
573             if (db) {
574                Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
575             }
576             OK = false;
577          } else {
578             /* If a pool is defined for this job, create the pool DB       
579              *  record if it is not already created. 
580              */
581             if (job->pool) {
582                create_pool(NULL, db, job->pool, POOL_OP_UPDATE);  /* update request */
583             }
584             /* Set default value in all counters */
585             COUNTER *counter;
586             foreach_res(counter, R_COUNTER) {
587                /* Write to catalog? */
588                if (!counter->created && counter->Catalog == catalog) {
589                   COUNTER_DBR cr;
590                   bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
591                   cr.MinValue = counter->MinValue;
592                   cr.MaxValue = counter->MaxValue;
593                   cr.CurrentValue = counter->MinValue;
594                   if (counter->WrapCounter) {
595                      bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
596                   } else {
597                      cr.WrapCounter[0] = 0;  /* empty string */
598                   }
599                   if (db_create_counter_record(NULL, db, &cr)) {
600                      counter->CurrentValue = cr.CurrentValue;
601                      counter->created = true;
602                      Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
603                   }
604                } 
605                if (!counter->created) {
606                   counter->CurrentValue = counter->MinValue;  /* default value */
607                }
608             }
609          }
610          db_close_database(NULL, db);
611       }
612    }
613
614    UnlockRes();
615    if (OK) {
616       close_msg(NULL);                /* close temp message handler */
617       init_msg(NULL, director->messages); /* open daemon message handler */
618    }
619    return OK;
620 }