]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Fix reporting jobs from state file + misc
[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 static void reload_config(int sig);
36
37 /* Exported subroutines */
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, struct res_items *item, int index, int pass);
49 void store_level(LEX *lc, struct res_items *item, int index, int pass);
50 void store_replace(LEX *lc, struct res_items *item, int index, int pass);
51
52 static char *configfile = NULL;
53 static char *runjob = NULL;
54 static int background = 1;
55
56 /* Globals Exported */
57 DIRRES *director;                     /* Director resource */
58 int FDConnectTimeout;
59 int SDConnectTimeout;
60
61 /* Globals Imported */
62 extern int r_first, r_last;           /* first and last resources */
63 extern struct res_items job_items[];
64 extern URES res_all;
65
66
67 #define CONFIG_FILE "./bacula-dir.conf" /* default configuration file */
68
69 static void usage()
70 {
71    fprintf(stderr, _(
72 "\nVersion: " VERSION " (" BDATE ")\n\n"
73 "Usage: dird [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
74 "       -c <file>   set configuration file to file\n"
75 "       -dnn        set debug level to nn\n"
76 "       -f          run in foreground (for debugging)\n"
77 "       -g          groupid\n"
78 "       -r <job>    run <job> now\n"
79 "       -s          no signals\n"
80 "       -t          test - read configuration and exit\n"
81 "       -u          userid\n"
82 "       -v          verbose user messages\n"
83 "       -?          print this message.\n"  
84 "\n"));
85
86    exit(1);
87 }
88
89
90 /*********************************************************************
91  *
92  *         Main Bacula Server program
93  *
94  */
95 int main (int argc, char *argv[])
96 {
97    int ch;
98    JCR *jcr;
99    int no_signals = FALSE;
100    int test_config = FALSE;
101    char *uid = NULL;
102    char *gid = NULL;
103
104    init_stack_dump();
105    my_name_is(argc, argv, "bacula-dir");
106    textdomain("bacula-dir");
107    init_msg(NULL, NULL);              /* initialize message handler */
108    daemon_start_time = time(NULL);
109
110    while ((ch = getopt(argc, argv, "c:d:fg:r:stu:v?")) != -1) {
111       switch (ch) {
112       case 'c':                    /* specify config file */
113          if (configfile != NULL) {
114             free(configfile);
115          }
116          configfile = bstrdup(optarg);
117          break;
118
119       case 'd':                    /* set debug level */
120          debug_level = atoi(optarg);
121          if (debug_level <= 0) {
122             debug_level = 1; 
123          }
124          Dmsg1(0, "Debug level = %d\n", debug_level);
125          break;
126
127       case 'f':                    /* run in foreground */
128          background = FALSE;
129          break;
130
131       case 'g':                    /* set group id */
132          gid = optarg;
133          break;
134
135       case 'r':                    /* run job */
136          if (runjob != NULL) {
137             free(runjob);
138          }
139          if (optarg) {
140             runjob = bstrdup(optarg);
141          }
142          break;
143
144       case 's':                    /* turn off signals */
145          no_signals = TRUE;
146          break;
147
148       case 't':                    /* test config */
149          test_config = TRUE;
150          break;
151
152       case 'u':                    /* set uid */
153          uid = optarg;
154          break;
155
156       case 'v':                    /* verbose */
157          verbose++;
158          break;
159
160       case '?':
161       default:
162          usage();
163
164       }  
165    }
166    argc -= optind;
167    argv += optind;
168
169    if (!no_signals) {
170       init_signals(terminate_dird);
171    }
172
173    if (argc) {
174       if (configfile != NULL) {
175          free(configfile);
176       }
177       configfile = bstrdup(*argv);
178       argc--; 
179       argv++;
180    }
181    if (argc) {
182       usage();
183    }
184
185    if (configfile == NULL) {
186       configfile = bstrdup(CONFIG_FILE);
187    }
188
189    parse_config(configfile);
190
191    if (!check_resources()) {
192       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
193    }
194
195    if (test_config) {
196       terminate_dird(0);
197    }
198
199    my_name_is(0, NULL, director->hdr.name);    /* set user defined name */
200
201    FDConnectTimeout = (int)director->FDConnectTimeout;
202    SDConnectTimeout = (int)director->SDConnectTimeout;
203
204    if (background) {
205       daemon_start();
206       init_stack_dump();              /* grab new pid */
207    }
208
209    /* Create pid must come after we are a daemon -- so we have our final pid */
210    create_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
211    read_state_file(director->working_directory, "bacula-dir", director->DIRport);
212
213    drop(uid, gid);                    /* reduce priveleges if requested */
214
215    signal(SIGHUP, reload_config);
216
217    init_console_msg(working_directory);
218
219    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
220       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
221
222    Dmsg0(200, "Start UA server\n");
223    start_UA_server(director->DIRaddr, director->DIRport);
224
225    start_watchdog();                  /* start network watchdog thread */
226
227    init_jcr_subsystem();              /* start JCR watchdogs etc. */
228
229    init_job_server(director->MaxConcurrentJobs);
230   
231    Dmsg0(200, "wait for next job\n");
232    /* Main loop -- call scheduler to get next job to run */
233    while ((jcr = wait_for_next_job(runjob))) {
234       run_job(jcr);                   /* run job */
235       free_jcr(jcr);                  /* release jcr */
236       if (runjob) {                   /* command line, run a single job? */
237          break;                       /* yes, terminate */
238       }
239    }
240
241    terminate_dird(0);
242 }
243
244 /* Cleanup and then exit */
245 static void terminate_dird(int sig)
246 {
247    static int already_here = FALSE;
248
249    if (already_here) {                /* avoid recursive temination problems */
250       exit(1);
251    }
252    already_here = TRUE;
253    write_state_file(director->working_directory, "bacula-dir", director->DIRport);
254    delete_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
255 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
256    term_scheduler();
257    if (runjob) {
258       free(runjob);
259    }
260    if (configfile != NULL) {
261       free(configfile);
262    }
263    if (debug_level > 5) {
264       print_memory_pool_stats(); 
265    }
266    free_config_resources();
267    term_ua_server();
268    term_msg();                        /* terminate message handler */
269    stop_watchdog();
270    close_memory_pool();               /* release free memory in pool */
271    sm_dump(False);
272    exit(sig != 0);
273 }
274
275 /*
276  * If we get here, we have received a SIGHUP, which means to
277  * reread our configuration file. 
278  *
279  *  ***FIXME***  Check that there are no jobs running before
280  *               doing this. 
281  */
282 static void reload_config(int sig)
283 {
284    static bool already_here = false;
285    sigset_t set;        
286    JCR *jcr;
287    int njobs = 0;
288
289    if (already_here) {
290       abort();                        /* Oops, recursion -> die */
291    }
292    already_here = TRUE;
293    sigfillset(&set);
294    sigprocmask(SIG_BLOCK, &set, NULL);
295
296    lock_jcr_chain();
297    LockRes();
298
299    foreach_jcr(jcr) {
300       if (jcr->JobId != 0) {      /* this is a console */
301          njobs++;
302       }
303       free_locked_jcr(jcr);
304    }
305    if (njobs > 0) {
306       goto bail_out;
307    }
308
309    free_config_resources();
310
311    parse_config(configfile);
312
313    if (!check_resources()) {
314       Jmsg(NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
315    }
316
317    /* Reset globals */
318    set_working_directory(director->working_directory);
319    FDConnectTimeout = director->FDConnectTimeout;
320    SDConnectTimeout = director->SDConnectTimeout;
321    Dmsg0(0, "Director's configuration file reread.\n");
322
323 bail_out:
324    UnlockRes();
325    unlock_jcr_chain();
326    sigprocmask(SIG_UNBLOCK, &set, NULL);
327    signal(SIGHUP, reload_config);
328    already_here = false;
329 }
330
331 /*
332  * Make a quick check to see that we have all the
333  * resources needed.
334  *
335  *  **** FIXME **** this routine could be a lot more
336  *   intelligent and comprehensive.
337  */
338 static int check_resources()
339 {
340    bool OK = true;
341    JOB *job;
342
343    LockRes();
344
345    job = (JOB *)GetNextRes(R_JOB, NULL);
346    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
347    if (!director) {
348       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n\
349 Without that I don't know who I am :-(\n"), configfile);
350       OK = false;
351    } else {
352       set_working_directory(director->working_directory);
353       if (!director->messages) {       /* If message resource not specified */
354          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
355          if (!director->messages) {
356             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
357             OK = false;
358          }
359       }
360       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
361          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
362             configfile);
363          OK = false;
364       } 
365    }
366
367    if (!job) {
368       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
369       OK = false;
370    }
371    foreach_res(job, R_JOB) {
372       int i;
373
374       if (job->jobdefs) {
375          /* Transfer default items from JobDefs Resource */
376          for (i=0; job_items[i].name; i++) {
377             char **def_svalue, **svalue;  /* string value */
378             int *def_ivalue, *ivalue;     /* integer value */
379             int64_t *def_lvalue, *lvalue; /* 64 bit values */
380             uint32_t offset;
381
382             Dmsg4(400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
383                 job->hdr.name, job_items[i].name, 
384                 bit_is_set(i, job->hdr.item_present),  
385                 bit_is_set(i, job->jobdefs->hdr.item_present));
386
387             if (!bit_is_set(i, job->hdr.item_present) &&
388                  bit_is_set(i, job->jobdefs->hdr.item_present)) { 
389                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
390                  job->hdr.name, job_items[i].name);
391                offset = (char *)(job_items[i].value) - (char *)&res_all;   
392                /*
393                 * Handle strings and directory strings
394                 */
395                if (job_items[i].handler == store_str ||
396                    job_items[i].handler == store_dir) {
397                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
398                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n", 
399                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
400                   svalue = (char **)((char *)job + offset);
401                   if (*svalue) {
402                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
403                   }
404                   *svalue = bstrdup(*def_svalue);
405                   set_bit(i, job->hdr.item_present);
406                } else if (job_items[i].handler == store_res) {
407                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
408                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n", 
409                        job->hdr.name, job_items[i].name, i, offset);
410                   svalue = (char **)((char *)job + offset);
411                   if (*svalue) {
412                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
413                   }
414                   *svalue = *def_svalue;
415                   set_bit(i, job->hdr.item_present);
416                /*
417                 * Handle integer fields 
418                 *    Note, our store_yesno does not handle bitmaped fields
419                 */
420                } else if (job_items[i].handler == store_yesno   ||
421                           job_items[i].handler == store_pint    ||
422                           job_items[i].handler == store_jobtype ||
423                           job_items[i].handler == store_level   ||
424                           job_items[i].handler == store_pint    ||
425                           job_items[i].handler == store_replace) {
426                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
427                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n", 
428                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
429                   ivalue = (int *)((char *)job + offset);
430                   *ivalue = *def_ivalue;
431                   set_bit(i, job->hdr.item_present);
432                /*
433                 * Handle 64 bit integer fields 
434                 */
435                } else if (job_items[i].handler == store_time   ||
436                           job_items[i].handler == store_size   ||
437                           job_items[i].handler == store_int64) {
438                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
439                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n", 
440                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
441                   lvalue = (int64_t *)((char *)job + offset);
442                   *lvalue = *def_lvalue;
443                   set_bit(i, job->hdr.item_present);
444                }
445             }
446          }
447       }
448       /* 
449        * Ensure that all required items are present
450        */
451       for (i=0; job_items[i].name; i++) {
452          if (job_items[i].flags & ITEM_REQUIRED) {
453                if (!bit_is_set(i, job->hdr.item_present)) {  
454                   Jmsg(NULL, M_FATAL, 0, "Field \"%s\" in Job \"%s\" resource is required, but not found.\n",
455                     job_items[i].name, job->hdr.name);
456                   OK = false;
457                 }
458          }
459          /* If this triggers, take a look at lib/parse_conf.h */
460          if (i >= MAX_RES_ITEMS) {
461             Emsg0(M_ERROR_TERM, 0, "Too many items in Job resource\n");
462          }
463       }
464       if (job->client && job->client->catalog) {
465          CAT *catalog = job->client->catalog;
466          B_DB *db;
467
468          /*
469           * Make sure we can open catalog, otherwise print a warning
470           * message because the server is probably not running.
471           */
472          db = db_init_database(NULL, catalog->db_name, catalog->db_user,
473                             catalog->db_password, catalog->db_address,
474                             catalog->db_port, catalog->db_socket);
475          if (!db || !db_open_database(NULL, db)) {
476             Jmsg(NULL, M_FATAL, 0, _("Could not open database \"%s\".\n"),
477                  catalog->db_name);
478             if (db) {
479                Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
480             }
481             OK = false;
482          } else {
483             /* If a pool is defined for this job, create the pool DB       
484              *  record if it is not already created. 
485              */
486             if (job->pool) {
487                create_pool(NULL, db, job->pool, POOL_OP_UPDATE);  /* update request */
488             }
489             /* Set default value in all counters */
490             COUNTER *counter;
491             foreach_res(counter, R_COUNTER) {
492                /* Write to catalog? */
493                if (!counter->created && counter->Catalog == catalog) {
494                   COUNTER_DBR cr;
495                   bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
496                   cr.MinValue = counter->MinValue;
497                   cr.MaxValue = counter->MaxValue;
498                   cr.CurrentValue = counter->MinValue;
499                   if (counter->WrapCounter) {
500                      bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
501                   } else {
502                      cr.WrapCounter[0] = 0;  /* empty string */
503                   }
504                   if (db_create_counter_record(NULL, db, &cr)) {
505                      counter->CurrentValue = cr.CurrentValue;
506                      counter->created = true;
507                      Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
508                   }
509                } 
510                if (!counter->created) {
511                   counter->CurrentValue = counter->MinValue;  /* default value */
512                }
513             }
514          }
515          db_close_database(NULL, db);
516       }
517    }
518
519    UnlockRes();
520    if (OK) {
521       close_msg(NULL);                /* close temp message handler */
522       init_msg(NULL, director->messages); /* open daemon message handler */
523    }
524    return OK;
525 }