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