]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
f68da92bd2fd68e1f0c352f89aeddcbc6fed0d6a
[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-2003 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    drop(uid, gid);                    /* reduce priveleges if requested */
210
211    /* Create pid must come after we are a daemon -- so we have our final pid */
212    create_pid_file(director->pid_directory, "bacula-dir", director->DIRport);
213
214 /* signal(SIGHUP, reload_config); */
215
216    init_console_msg(working_directory);
217
218    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
219       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
220
221    Dmsg0(200, "Start UA server\n");
222    start_UA_server(director->DIRaddr, director->DIRport);
223
224    start_watchdog();                  /* start network watchdog thread */
225
226    init_jcr_subsystem();              /* start JCR watchdogs etc. */
227
228    init_job_server(director->MaxConcurrentJobs);
229   
230    Dmsg0(200, "wait for next job\n");
231    /* Main loop -- call scheduler to get next job to run */
232    while ((jcr = wait_for_next_job(runjob))) {
233       run_job(jcr);                   /* run job */
234       free_jcr(jcr);                  /* release jcr */
235       if (runjob) {                   /* command line, run a single job? */
236          break;                       /* yes, terminate */
237       }
238    }
239
240    terminate_dird(0);
241 }
242
243 /* Cleanup and then exit */
244 static void terminate_dird(int sig)
245 {
246    static int already_here = FALSE;
247
248    if (already_here) {                /* avoid recursive temination problems */
249       exit(1);
250    }
251    already_here = TRUE;
252    delete_pid_file(director->pid_directory, "bacula-dir",  
253                    director->DIRport);
254 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
255    term_scheduler();
256    if (runjob) {
257       free(runjob);
258    }
259    if (configfile != NULL) {
260       free(configfile);
261    }
262    if (debug_level > 5) {
263       print_memory_pool_stats(); 
264    }
265    free_config_resources();
266    term_ua_server();
267    term_msg();                        /* terminate message handler */
268    stop_watchdog();
269    close_memory_pool();               /* release free memory in pool */
270    sm_dump(False);
271    exit(sig != 0);
272 }
273
274 /*
275  * If we get here, we have received a SIGHUP, which means to
276  * reread our configuration file. 
277  *
278  *  ***FIXME***  Check that there are no jobs running before
279  *               doing this. 
280  */
281 static void reload_config(int sig)
282 {
283    static int already_here = FALSE;
284    sigset_t set;        
285
286    if (already_here) {
287       abort();                        /* Oops, recursion -> die */
288    }
289    already_here = TRUE;
290    sigfillset(&set);
291    sigprocmask(SIG_BLOCK, &set, NULL);
292
293    free_config_resources();
294
295    parse_config(configfile);
296
297    Dmsg0(200, "check_resources()\n");
298    if (!check_resources()) {
299       Jmsg(NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
300    }
301
302    /* Reset globals */
303    set_working_directory(director->working_directory);
304    FDConnectTimeout = director->FDConnectTimeout;
305    SDConnectTimeout = director->SDConnectTimeout;
306  
307    sigprocmask(SIG_UNBLOCK, &set, NULL);
308    signal(SIGHUP, reload_config);
309    already_here = FALSE;
310    Dmsg0(0, "Director's configuration file reread.\n");
311 }
312
313 /*
314  * Make a quick check to see that we have all the
315  * resources needed.
316  *
317  *  **** FIXME **** this routine could be a lot more
318  *   intelligent and comprehensive.
319  */
320 static int check_resources()
321 {
322    bool OK = true;
323    JOB *job;
324
325    LockRes();
326
327    job = (JOB *)GetNextRes(R_JOB, NULL);
328    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
329    if (!director) {
330       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n\
331 Without that I don't know who I am :-(\n"), configfile);
332       OK = false;
333    } else {
334       set_working_directory(director->working_directory);
335       if (!director->messages) {       /* If message resource not specified */
336          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
337          if (!director->messages) {
338             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
339             OK = false;
340          }
341       }
342       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
343          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
344             configfile);
345          OK = false;
346       } 
347    }
348
349    if (!job) {
350       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
351       OK = false;
352    }
353    foreach_res(job, R_JOB) {
354       int i;
355
356       if (job->jobdefs) {
357          /* Transfer default items from JobDefs Resource */
358          for (i=0; job_items[i].name; i++) {
359             char **def_svalue, **svalue;  /* string value */
360             int *def_ivalue, *ivalue;     /* integer value */
361             int64_t *def_lvalue, *lvalue; /* 64 bit values */
362             uint32_t offset;
363
364             Dmsg4(400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
365                 job->hdr.name, job_items[i].name, 
366                 bit_is_set(i, job->hdr.item_present),  
367                 bit_is_set(i, job->jobdefs->hdr.item_present));
368
369             if (!bit_is_set(i, job->hdr.item_present) &&
370                  bit_is_set(i, job->jobdefs->hdr.item_present)) { 
371                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
372                  job->hdr.name, job_items[i].name);
373                offset = (char *)(job_items[i].value) - (char *)&res_all;   
374                /*
375                 * Handle strings and directory strings
376                 */
377                if (job_items[i].handler == store_str ||
378                    job_items[i].handler == store_dir) {
379                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
380                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n", 
381                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
382                   svalue = (char **)((char *)job + offset);
383                   if (*svalue) {
384                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
385                   }
386                   *svalue = bstrdup(*def_svalue);
387                   set_bit(i, job->hdr.item_present);
388                } else if (job_items[i].handler == store_res) {
389                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
390                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n", 
391                        job->hdr.name, job_items[i].name, i, offset);
392                   svalue = (char **)((char *)job + offset);
393                   if (*svalue) {
394                      Dmsg1(000, "Hey something is wrong. p=0x%u\n", (unsigned)*svalue);
395                   }
396                   *svalue = *def_svalue;
397                   set_bit(i, job->hdr.item_present);
398                /*
399                 * Handle integer fields 
400                 *    Note, our store_yesno does not handle bitmaped fields
401                 */
402                } else if (job_items[i].handler == store_yesno   ||
403                           job_items[i].handler == store_pint    ||
404                           job_items[i].handler == store_jobtype ||
405                           job_items[i].handler == store_level   ||
406                           job_items[i].handler == store_pint    ||
407                           job_items[i].handler == store_replace) {
408                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
409                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n", 
410                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
411                   ivalue = (int *)((char *)job + offset);
412                   *ivalue = *def_ivalue;
413                   set_bit(i, job->hdr.item_present);
414                /*
415                 * Handle 64 bit integer fields 
416                 */
417                } else if (job_items[i].handler == store_time   ||
418                           job_items[i].handler == store_size   ||
419                           job_items[i].handler == store_int64) {
420                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
421                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n", 
422                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
423                   lvalue = (int64_t *)((char *)job + offset);
424                   *lvalue = *def_lvalue;
425                   set_bit(i, job->hdr.item_present);
426                }
427             }
428          }
429       }
430       /* 
431        * Ensure that all required items are present
432        */
433       for (i=0; job_items[i].name; i++) {
434          if (job_items[i].flags & ITEM_REQUIRED) {
435                if (!bit_is_set(i, job->hdr.item_present)) {  
436                   Jmsg(NULL, M_FATAL, 0, "Field \"%s\" in Job \"%s\" resource is required, but not found.\n",
437                     job_items[i].name, job->hdr.name);
438                   OK = false;
439                 }
440          }
441          /* If this triggers, take a look at lib/parse_conf.h */
442          if (i >= MAX_RES_ITEMS) {
443             Emsg0(M_ERROR_TERM, 0, "Too many items in Job resource\n");
444          }
445       }
446       if (job->client && job->client->catalog) {
447          CAT *catalog = job->client->catalog;
448          B_DB *db;
449
450          /*
451           * Make sure we can open catalog, otherwise print a warning
452           * message because the server is probably not running.
453           */
454          db = db_init_database(NULL, catalog->db_name, catalog->db_user,
455                             catalog->db_password, catalog->db_address,
456                             catalog->db_port, catalog->db_socket);
457          if (!db || !db_open_database(NULL, db)) {
458             Jmsg(NULL, M_FATAL, 0, _("Could not open database \"%s\".\n"),
459                  catalog->db_name);
460             if (db) {
461                Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
462             }
463             OK = false;
464          } else {
465             /* If a pool is defined for this job, create the pool DB       
466              *  record if it is not already created. 
467              */
468             if (job->pool) {
469                create_pool(NULL, db, job->pool, POOL_OP_UPDATE);  /* update request */
470             }
471             /* Set default value in all counters */
472             COUNTER *counter;
473             foreach_res(counter, R_COUNTER) {
474                /* Write to catalog? */
475                if (!counter->created && counter->Catalog == catalog) {
476                   COUNTER_DBR cr;
477                   bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
478                   cr.MinValue = counter->MinValue;
479                   cr.MaxValue = counter->MaxValue;
480                   cr.CurrentValue = counter->MinValue;
481                   if (counter->WrapCounter) {
482                      bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
483                   } else {
484                      cr.WrapCounter[0] = 0;  /* empty string */
485                   }
486                   if (db_create_counter_record(NULL, db, &cr)) {
487                      counter->CurrentValue = cr.CurrentValue;
488                      counter->created = true;
489                      Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
490                   }
491                } 
492                if (!counter->created) {
493                   counter->CurrentValue = counter->MinValue;  /* default value */
494                }
495             }
496             db_close_database(NULL, db);
497          }
498       }
499    }
500
501    UnlockRes();
502    if (OK) {
503       close_msg(NULL);                /* close temp message handler */
504       init_msg(NULL, director->messages); /* open daemon message handler */
505    }
506    return OK;
507 }