]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
ea8a41bc8f595ab8c411a4c17a32fcddb7a1246a
[bacula/bacula] / bacula / src / dird / job.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2008 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of John Walker.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *
30  *   Bacula Director Job processing routines
31  *
32  *     Kern Sibbald, October MM
33  *
34  *    Version $Id$
35  */
36
37 #include "bacula.h"
38 #include "dird.h"
39
40 /* Forward referenced subroutines */
41 static void *job_thread(void *arg);
42 static void job_monitor_watchdog(watchdog_t *self);
43 static void job_monitor_destructor(watchdog_t *self);
44 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr);
45 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr);
46
47 /* Imported subroutines */
48 extern void term_scheduler();
49 extern void term_ua_server();
50
51 /* Imported variables */
52
53 jobq_t job_queue;
54
55 void init_job_server(int max_workers)
56 {
57    int stat;
58    watchdog_t *wd;
59
60    if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
61       berrno be;
62       Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.bstrerror(stat));
63    }
64    wd = new_watchdog();
65    wd->callback = job_monitor_watchdog;
66    wd->destructor = job_monitor_destructor;
67    wd->one_shot = false;
68    wd->interval = 60;
69    wd->data = new_control_jcr("*JobMonitor*", JT_SYSTEM);
70    register_watchdog(wd);
71 }
72
73 void term_job_server()
74 {
75    jobq_destroy(&job_queue);          /* ignore any errors */
76 }
77
78 /*
79  * Run a job -- typically called by the scheduler, but may also
80  *              be called by the UA (Console program).
81  *
82  *  Returns: 0 on failure
83  *           JobId on success
84  *
85  */
86 JobId_t run_job(JCR *jcr)
87 {
88    int stat;
89    if (setup_job(jcr)) {
90       Dmsg0(200, "Add jrc to work queue\n");
91       /* Queue the job to be run */
92       if ((stat = jobq_add(&job_queue, jcr)) != 0) {
93          berrno be;
94          Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.bstrerror(stat));
95          return 0;
96       }
97       return jcr->JobId;
98    }
99    return 0;
100 }            
101
102 bool setup_job(JCR *jcr) 
103 {
104    int errstat;
105
106    jcr->lock();
107    sm_check(__FILE__, __LINE__, true);
108    init_msg(jcr, jcr->messages);
109
110    /* Initialize termination condition variable */
111    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
112       berrno be;
113       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
114       goto bail_out;
115    }
116    jcr->term_wait_inited = true;
117
118    create_unique_job_name(jcr, jcr->job->name());
119    set_jcr_job_status(jcr, JS_Created);
120    jcr->unlock();
121
122    /*
123     * Open database
124     */
125    Dmsg0(100, "Open database\n");
126    jcr->db=db_init(jcr, jcr->catalog->db_driver, jcr->catalog->db_name, 
127                    jcr->catalog->db_user,
128                    jcr->catalog->db_password, jcr->catalog->db_address,
129                    jcr->catalog->db_port, jcr->catalog->db_socket,
130                    jcr->catalog->mult_db_connections);
131    if (!jcr->db || !db_open_database(jcr, jcr->db)) {
132       Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
133                  jcr->catalog->db_name);
134       if (jcr->db) {
135          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
136          db_close_database(jcr, jcr->db);
137       }
138       goto bail_out;
139    }
140    Dmsg0(150, "DB opened\n");
141
142    if (!jcr->fname) {
143       jcr->fname = get_pool_memory(PM_FNAME);
144    }
145    if (!jcr->pool_source) {
146       jcr->pool_source = get_pool_memory(PM_MESSAGE);
147       pm_strcpy(jcr->pool_source, _("unknown source"));
148    }
149    Dmsg2(500, "pool=%s (From %s)\n", jcr->pool->name(), jcr->pool_source);
150    if (jcr->JobType == JT_MIGRATE) {
151       if (!jcr->rpool_source) {
152          jcr->rpool_source = get_pool_memory(PM_MESSAGE);
153          pm_strcpy(jcr->rpool_source, _("unknown source"));
154       }
155    }
156
157    /*
158     * Create Job record
159     */
160    init_jcr_job_record(jcr);
161    if (!get_or_create_client_record(jcr)) {
162       goto bail_out;
163    }
164
165    if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
166       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
167       goto bail_out;
168    }
169    jcr->JobId = jcr->jr.JobId;
170    Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
171        jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
172
173    generate_daemon_event(jcr, "JobStart");
174
175    if (job_canceled(jcr)) {
176       goto bail_out;
177    }
178
179    /*
180     * Now, do pre-run stuff, like setting job level (Inc/diff, ...)
181     *  this allows us to setup a proper job start record for restarting
182     *  in case of later errors.
183     */
184    switch (jcr->JobType) {
185    case JT_BACKUP:
186       if (!do_backup_init(jcr)) {
187          backup_cleanup(jcr, JS_ErrorTerminated);
188       }
189       break;
190    case JT_VERIFY:
191       if (!do_verify_init(jcr)) {
192          verify_cleanup(jcr, JS_ErrorTerminated);
193       }
194       break;
195    case JT_RESTORE:
196       if (!do_restore_init(jcr)) {
197          restore_cleanup(jcr, JS_ErrorTerminated);
198       }
199       break;
200    case JT_ADMIN:
201       if (!do_admin_init(jcr)) {
202          admin_cleanup(jcr, JS_ErrorTerminated);
203       }
204       break;
205    case JT_MIGRATE:
206       if (!do_migration_init(jcr)) { 
207          migration_cleanup(jcr, JS_ErrorTerminated);
208       }
209       break;
210    default:
211       Pmsg1(0, _("Unimplemented job type: %d\n"), jcr->JobType);
212       set_jcr_job_status(jcr, JS_ErrorTerminated);
213       break;
214    }
215
216    generate_job_event(jcr, "JobInit");
217    Dsm_check(1);
218    return true;
219
220 bail_out:
221    return false;
222 }
223
224 void update_job_end(JCR *jcr, int TermCode)
225 {
226    dequeue_messages(jcr);             /* display any queued messages */
227    set_jcr_job_status(jcr, TermCode);
228    update_job_end_record(jcr);
229 }
230
231 /*
232  * This is the engine called by jobq.c:jobq_add() when we were pulled
233  *  from the work queue.
234  *  At this point, we are running in our own thread and all
235  *    necessary resources are allocated -- see jobq.c
236  */
237 static void *job_thread(void *arg)
238 {
239    JCR *jcr = (JCR *)arg;
240
241    pthread_detach(pthread_self());
242    Dsm_check(1);
243
244    Dmsg0(200, "=====Start Job=========\n");
245    set_jcr_job_status(jcr, JS_Running);   /* this will be set only if no error */
246    jcr->start_time = time(NULL);      /* set the real start time */
247    jcr->jr.StartTime = jcr->start_time;
248
249    if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
250        (utime_t)(jcr->start_time - jcr->sched_time)) {
251       set_jcr_job_status(jcr, JS_Canceled);
252       Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
253    }
254
255    /* TODO : check if it is used somewhere */
256    if (jcr->job->RunScripts == NULL) {
257       Dmsg0(200, "Warning, job->RunScripts is empty\n");
258       jcr->job->RunScripts = New(alist(10, not_owned_by_alist));
259    }
260
261    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
262       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
263    }
264
265    /* Run any script BeforeJob on dird */
266    run_scripts(jcr, jcr->job->RunScripts, "BeforeJob");
267
268    if (job_canceled(jcr)) {
269       update_job_end(jcr, jcr->JobStatus);
270
271    } else {
272       /*
273        * We re-update the job start record so that the start
274        *  time is set after the run before job.  This avoids
275        *  that any files created by the run before job will
276        *  be saved twice.  They will be backed up in the current
277        *  job, but not in the next one unless they are changed.
278        *  Without this, they will be backed up in this job and
279        *  in the next job run because in that case, their date
280        *   is after the start of this run.
281        */
282       jcr->start_time = time(NULL);
283       jcr->jr.StartTime = jcr->start_time;
284       if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
285          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
286       }
287       generate_job_event(jcr, "JobRun");
288
289       switch (jcr->JobType) {
290       case JT_BACKUP:
291          if (do_backup(jcr)) {
292             do_autoprune(jcr);
293          } else {
294             backup_cleanup(jcr, JS_ErrorTerminated);
295          }
296          break;
297       case JT_VERIFY:
298          if (do_verify(jcr)) {
299             do_autoprune(jcr);
300          } else {
301             verify_cleanup(jcr, JS_ErrorTerminated);
302          }
303          break;
304       case JT_RESTORE:
305          if (do_restore(jcr)) {
306             do_autoprune(jcr);
307          } else {
308             restore_cleanup(jcr, JS_ErrorTerminated);
309          }
310          break;
311       case JT_ADMIN:
312          if (do_admin(jcr)) {
313             do_autoprune(jcr);
314          } else {
315             admin_cleanup(jcr, JS_ErrorTerminated);
316          }
317          break;
318       case JT_MIGRATE:
319       case JT_COPY:
320       case JT_ARCHIVE:
321          if (do_migration(jcr)) {
322             do_autoprune(jcr);
323          } else {
324             migration_cleanup(jcr, JS_ErrorTerminated);
325          }
326          break;
327       default:
328          Pmsg1(0, _("Unimplemented job type: %d\n"), jcr->JobType);
329          break;
330       }
331    }
332
333    run_scripts(jcr, jcr->job->RunScripts, "AfterJob");
334
335    /* Send off any queued messages */
336    if (jcr->msg_queue && jcr->msg_queue->size() > 0) {
337       dequeue_messages(jcr);
338    }
339
340    generate_daemon_event(jcr, "JobEnd");
341    Dmsg1(50, "======== End Job stat=%c ==========\n", jcr->JobStatus);
342    sm_check(__FILE__, __LINE__, true);
343    return NULL;
344 }
345
346
347 /*
348  * Cancel a job -- typically called by the UA (Console program), but may also
349  *              be called by the job watchdog.
350  *
351  *  Returns: true  if cancel appears to be successful
352  *           false on failure. Message sent to ua->jcr.
353  */
354 bool cancel_job(UAContext *ua, JCR *jcr)
355 {
356    BSOCK *sd, *fd;
357    char ed1[50];
358
359    set_jcr_job_status(jcr, JS_Canceled);
360
361    switch (jcr->JobStatus) {
362    case JS_Created:
363    case JS_WaitJobRes:
364    case JS_WaitClientRes:
365    case JS_WaitStoreRes:
366    case JS_WaitPriority:
367    case JS_WaitMaxJobs:
368    case JS_WaitStartTime:
369       ua->info_msg(_("JobId %s, Job %s marked to be canceled.\n"),
370               edit_uint64(jcr->JobId, ed1), jcr->Job);
371       jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
372       return true;
373
374    default:
375       /* Cancel File daemon */
376       if (jcr->file_bsock) {
377          ua->jcr->client = jcr->client;
378          if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
379             ua->error_msg(_("Failed to connect to File daemon.\n"));
380             return 0;
381          }
382          Dmsg0(200, "Connected to file daemon\n");
383          fd = ua->jcr->file_bsock;
384          bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
385          while (bnet_recv(fd) >= 0) {
386             ua->send_msg("%s", fd->msg);
387          }
388          bnet_sig(fd, BNET_TERMINATE);
389          bnet_close(fd);
390          ua->jcr->file_bsock = NULL;
391       }
392
393       /* Cancel Storage daemon */
394       if (jcr->store_bsock) {
395          if (!ua->jcr->wstorage) {
396             if (jcr->rstorage) {
397                copy_wstorage(ua->jcr, jcr->rstorage, _("Job resource")); 
398             } else {
399                copy_wstorage(ua->jcr, jcr->wstorage, _("Job resource")); 
400             }
401          } else {
402             USTORE store;
403             if (jcr->rstorage) {
404                store.store = jcr->rstore;
405             } else {
406                store.store = jcr->wstore;
407             }
408             set_wstorage(ua->jcr, &store);
409          }
410
411          if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
412             ua->error_msg(_("Failed to connect to Storage daemon.\n"));
413             return false;
414          }
415          Dmsg0(200, "Connected to storage daemon\n");
416          sd = ua->jcr->store_bsock;
417          sd->fsend("cancel Job=%s\n", jcr->Job);
418          while (sd->recv() >= 0) {
419             ua->send_msg("%s", sd->msg);
420          }
421          sd->signal(BNET_TERMINATE);
422          sd->close();
423          ua->jcr->store_bsock = NULL;
424       }
425    }
426
427    return true;
428 }
429
430 void cancel_storage_daemon_job(JCR *jcr)
431 {
432    UAContext *ua = new_ua_context(jcr);
433    JCR *control_jcr = new_control_jcr("*JobCancel*", JT_SYSTEM);
434    BSOCK *sd;
435
436    ua->jcr = control_jcr;
437    if (jcr->store_bsock) {
438       if (!ua->jcr->wstorage) {
439          if (jcr->rstorage) {
440             copy_wstorage(ua->jcr, jcr->rstorage, _("Job resource")); 
441          } else {
442             copy_wstorage(ua->jcr, jcr->wstorage, _("Job resource")); 
443          }
444       } else {
445          USTORE store;
446          if (jcr->rstorage) {
447             store.store = jcr->rstore;
448          } else {
449             store.store = jcr->wstore;
450          }
451          set_wstorage(ua->jcr, &store);
452       }
453
454       if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
455          goto bail_out;
456       }
457       Dmsg0(200, "Connected to storage daemon\n");
458       sd = ua->jcr->store_bsock;
459       sd->fsend("cancel Job=%s\n", jcr->Job);
460       while (sd->recv() >= 0) {
461       }
462       sd->signal(BNET_TERMINATE);
463       sd->close();
464       ua->jcr->store_bsock = NULL;
465    }
466 bail_out:
467    free_jcr(control_jcr);
468    free_ua_context(ua);
469 }
470
471 static void job_monitor_destructor(watchdog_t *self)
472 {
473    JCR *control_jcr = (JCR *)self->data;
474
475    free_jcr(control_jcr);
476 }
477
478 static void job_monitor_watchdog(watchdog_t *self)
479 {
480    JCR *control_jcr, *jcr;
481
482    control_jcr = (JCR *)self->data;
483
484    Dsm_check(1);
485    Dmsg1(800, "job_monitor_watchdog %p called\n", self);
486
487    foreach_jcr(jcr) {
488       bool cancel = false;
489
490       if (jcr->JobId == 0 || job_canceled(jcr)) {
491          Dmsg2(800, "Skipping JCR=%p Job=%s\n", jcr, jcr->Job);
492          continue;
493       }
494
495       /* check MaxWaitTime */
496       if (job_check_maxwaittime(control_jcr, jcr)) {
497          set_jcr_job_status(jcr, JS_Canceled);
498          Jmsg(jcr, M_FATAL, 0, _("Max wait time exceeded. Job canceled.\n"));
499          cancel = true;
500       /* check MaxRunTime */
501       } else if (job_check_maxruntime(control_jcr, jcr)) {
502          set_jcr_job_status(jcr, JS_Canceled);
503          Jmsg(jcr, M_FATAL, 0, _("Max run time exceeded. Job canceled.\n"));
504          cancel = true;
505       }
506
507       if (cancel) {
508          Dmsg3(800, "Cancelling JCR %p jobid %d (%s)\n", jcr, jcr->JobId, jcr->Job);
509          UAContext *ua = new_ua_context(jcr);
510          ua->jcr = control_jcr;
511          cancel_job(ua, jcr);
512          free_ua_context(ua);
513          Dmsg2(800, "Have cancelled JCR %p Job=%d\n", jcr, jcr->JobId);
514       }
515
516    }
517    /* Keep reference counts correct */
518    endeach_jcr(jcr);
519 }
520
521 /*
522  * Check if the maxwaittime has expired and it is possible
523  *  to cancel the job.
524  */
525 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
526 {
527    bool cancel = false;
528    JOB *job = jcr->job;
529
530    if (job_canceled(jcr)) {
531       return false;                /* already canceled */
532    }
533    if (job->MaxWaitTime == 0 && job->FullMaxWaitTime == 0 &&
534        job->IncMaxWaitTime == 0 && job->DiffMaxWaitTime == 0) {
535       return false;
536    } 
537    if (jcr->JobLevel == L_FULL && job->FullMaxWaitTime != 0 &&
538          (watchdog_time - jcr->start_time) >= job->FullMaxWaitTime) {
539       cancel = true;
540    } else if (jcr->JobLevel == L_DIFFERENTIAL && job->DiffMaxWaitTime != 0 &&
541          (watchdog_time - jcr->start_time) >= job->DiffMaxWaitTime) {
542       cancel = true;
543    } else if (jcr->JobLevel == L_INCREMENTAL && job->IncMaxWaitTime != 0 &&
544          (watchdog_time - jcr->start_time) >= job->IncMaxWaitTime) {
545       cancel = true;
546    } else if (job->MaxWaitTime != 0 &&
547          (watchdog_time - jcr->start_time) >= job->MaxWaitTime) {
548       cancel = true;
549    }
550
551    return cancel;
552 }
553
554 /*
555  * Check if maxruntime has expired and if the job can be
556  *   canceled.
557  */
558 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
559 {
560    if (jcr->job->MaxRunTime == 0 || job_canceled(jcr) || jcr->JobStatus == JS_Created) {
561       return false;
562    }
563    if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
564       Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
565             jcr, jcr->Job, jcr->job->MaxRunTime);
566       return false;
567    }
568
569    return true;
570 }
571
572 /*
573  * Get or create a Pool record with the given name.
574  * Returns: 0 on error
575  *          poolid if OK
576  */
577 DBId_t get_or_create_pool_record(JCR *jcr, char *pool_name)
578 {
579    POOL_DBR pr;
580
581    memset(&pr, 0, sizeof(pr));
582    bstrncpy(pr.Name, pool_name, sizeof(pr.Name));
583    Dmsg1(110, "get_or_create_pool=%s\n", pool_name);
584
585    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
586       /* Try to create the pool */
587       if (create_pool(jcr, jcr->db, jcr->pool, POOL_OP_CREATE) < 0) {
588          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name,
589             db_strerror(jcr->db));
590          return 0;
591       } else {
592          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
593       }
594    }
595    return pr.PoolId;
596 }
597
598 void apply_pool_overrides(JCR *jcr)
599 {
600    bool pool_override = false;
601
602    if (jcr->run_pool_override) {
603       pm_strcpy(jcr->pool_source, _("Run pool override"));
604    }
605    /*
606     * Apply any level related Pool selections
607     */
608    switch (jcr->JobLevel) {
609    case L_FULL:
610       if (jcr->full_pool) {
611          jcr->pool = jcr->full_pool;
612          pool_override = true;
613          if (jcr->run_full_pool_override) {
614             pm_strcpy(jcr->pool_source, _("Run FullPool override"));
615          } else {
616             pm_strcpy(jcr->pool_source, _("Job FullPool override"));
617          }
618       }
619       break;
620    case L_INCREMENTAL:
621       if (jcr->inc_pool) {
622          jcr->pool = jcr->inc_pool;
623          pool_override = true;
624          if (jcr->run_inc_pool_override) {
625             pm_strcpy(jcr->pool_source, _("Run IncPool override"));
626          } else {
627             pm_strcpy(jcr->pool_source, _("Job IncPool override"));
628          }
629       }
630       break;
631    case L_DIFFERENTIAL:
632       if (jcr->diff_pool) {
633          jcr->pool = jcr->diff_pool;
634          pool_override = true;
635          if (jcr->run_diff_pool_override) {
636             pm_strcpy(jcr->pool_source, _("Run DiffPool override"));
637          } else {
638             pm_strcpy(jcr->pool_source, _("Job DiffPool override"));
639          }
640       }
641       break;
642    }
643    /* Update catalog if pool overridden */
644    if (pool_override && jcr->pool->catalog) {
645       jcr->catalog = jcr->pool->catalog;
646       pm_strcpy(jcr->catalog_source, _("Pool resource"));
647    }
648 }
649
650
651 /*
652  * Get or create a Client record for this Job
653  */
654 bool get_or_create_client_record(JCR *jcr)
655 {
656    CLIENT_DBR cr;
657
658    memset(&cr, 0, sizeof(cr));
659    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
660    cr.AutoPrune = jcr->client->AutoPrune;
661    cr.FileRetention = jcr->client->FileRetention;
662    cr.JobRetention = jcr->client->JobRetention;
663    if (!jcr->client_name) {
664       jcr->client_name = get_pool_memory(PM_NAME);
665    }
666    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
667    if (!db_create_client_record(jcr, jcr->db, &cr)) {
668       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
669          db_strerror(jcr->db));
670       return false;
671    }
672    jcr->jr.ClientId = cr.ClientId;
673    if (cr.Uname[0]) {
674       if (!jcr->client_uname) {
675          jcr->client_uname = get_pool_memory(PM_NAME);
676       }
677       pm_strcpy(jcr->client_uname, cr.Uname);
678    }
679    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
680       jcr->jr.ClientId);
681    return true;
682 }
683
684 bool get_or_create_fileset_record(JCR *jcr)
685 {
686    FILESET_DBR fsr;
687    /*
688     * Get or Create FileSet record
689     */
690    memset(&fsr, 0, sizeof(FILESET_DBR));
691    bstrncpy(fsr.FileSet, jcr->fileset->hdr.name, sizeof(fsr.FileSet));
692    if (jcr->fileset->have_MD5) {
693       struct MD5Context md5c;
694       unsigned char digest[MD5HashSize];
695       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
696       MD5Final(digest, &md5c);
697       /*
698        * Keep the flag (last arg) set to false otherwise old FileSets will
699        * get new MD5 sums and the user will get Full backups on everything
700        */
701       bin_to_base64(fsr.MD5, sizeof(fsr.MD5), (char *)digest, MD5HashSize, false);
702       bstrncpy(jcr->fileset->MD5, fsr.MD5, sizeof(jcr->fileset->MD5));
703    } else {
704       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 digest not found.\n"));
705    }
706    if (!jcr->fileset->ignore_fs_changes ||
707        !db_get_fileset_record(jcr, jcr->db, &fsr)) {
708       if (!db_create_fileset_record(jcr, jcr->db, &fsr)) {
709          Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
710             fsr.FileSet, db_strerror(jcr->db));
711          return false;
712       }
713    }
714    jcr->jr.FileSetId = fsr.FileSetId;
715    bstrncpy(jcr->FSCreateTime, fsr.cCreateTime, sizeof(jcr->FSCreateTime));
716    Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
717       jcr->jr.FileSetId);
718    return true;
719 }
720
721 void init_jcr_job_record(JCR *jcr)
722 {
723    jcr->jr.SchedTime = jcr->sched_time;
724    jcr->jr.StartTime = jcr->start_time;
725    jcr->jr.EndTime = 0;               /* perhaps rescheduled, clear it */
726    jcr->jr.JobType = jcr->JobType;
727    jcr->jr.JobLevel = jcr->JobLevel;
728    jcr->jr.JobStatus = jcr->JobStatus;
729    jcr->jr.JobId = jcr->JobId;
730    bstrncpy(jcr->jr.Name, jcr->job->name(), sizeof(jcr->jr.Name));
731    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
732 }
733
734 /*
735  * Write status and such in DB
736  */
737 void update_job_end_record(JCR *jcr)
738 {
739    jcr->jr.EndTime = time(NULL);
740    jcr->end_time = jcr->jr.EndTime;
741    jcr->jr.JobId = jcr->JobId;
742    jcr->jr.JobStatus = jcr->JobStatus;
743    jcr->jr.JobFiles = jcr->JobFiles;
744    jcr->jr.JobBytes = jcr->JobBytes;
745    jcr->jr.VolSessionId = jcr->VolSessionId;
746    jcr->jr.VolSessionTime = jcr->VolSessionTime;
747    jcr->jr.JobErrors = jcr->Errors;
748    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
749       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
750          db_strerror(jcr->db));
751    }
752 }
753
754 /*
755  * Takes base_name and appends (unique) current
756  *   date and time to form unique job name.
757  *
758  *  Note, the seconds are actually a sequence number. This
759  *   permits us to start a maximum fo 59 unique jobs a second, which
760  *   should be sufficient.
761  *
762  *  Returns: unique job name in jcr->Job
763  *    date/time in jcr->start_time
764  */
765 void create_unique_job_name(JCR *jcr, const char *base_name)
766 {
767    /* Job start mutex */
768    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
769    static time_t last_start_time = 0;
770    static int seq = 0;
771    time_t now;
772    struct tm tm;
773    char dt[MAX_TIME_LENGTH];
774    char name[MAX_NAME_LENGTH];
775    char *p;
776
777    /* Guarantee unique start time -- maximum one per second, and
778     * thus unique Job Name
779     */
780    P(mutex);                          /* lock creation of jobs */
781    now = time(NULL);
782    seq++;
783    if (seq > 59) {                    /* wrap as if it is seconds */
784       seq = 0;
785       while (now == last_start_time) {
786          bmicrosleep(0, 500000);
787          now = time(NULL);
788       }
789    }
790    last_start_time = now;
791    V(mutex);                          /* allow creation of jobs */
792    jcr->start_time = now;
793    /* Form Unique JobName */
794    (void)localtime_r(&now, &tm);
795    /* Use only characters that are permitted in Windows filenames */
796    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M", &tm);
797    bstrncpy(name, base_name, sizeof(name));
798    name[sizeof(name)-22] = 0;          /* truncate if too long */
799    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s.%02d", name, dt, seq); /* add date & time */
800    /* Convert spaces into underscores */
801    for (p=jcr->Job; *p; p++) {
802       if (*p == ' ') {
803          *p = '_';
804       }
805    }
806 }
807
808 /* Called directly from job rescheduling */
809 void dird_free_jcr_pointers(JCR *jcr)
810 {
811    if (jcr->sd_auth_key) {
812       free(jcr->sd_auth_key);
813       jcr->sd_auth_key = NULL;
814    }
815    if (jcr->where) {
816       free(jcr->where);
817       jcr->where = NULL;
818    }
819    if (jcr->file_bsock) {
820       Dmsg0(200, "Close File bsock\n");
821       bnet_close(jcr->file_bsock);
822       jcr->file_bsock = NULL;
823    }
824    if (jcr->store_bsock) {
825       Dmsg0(200, "Close Store bsock\n");
826       bnet_close(jcr->store_bsock);
827       jcr->store_bsock = NULL;
828    }
829    if (jcr->fname) {
830       Dmsg0(200, "Free JCR fname\n");
831       free_pool_memory(jcr->fname);
832       jcr->fname = NULL;
833    }
834    if (jcr->RestoreBootstrap) {
835       free(jcr->RestoreBootstrap);
836       jcr->RestoreBootstrap = NULL;
837    }
838    if (jcr->client_uname) {
839       free_pool_memory(jcr->client_uname);
840       jcr->client_uname = NULL;
841    }
842    if (jcr->attr) {
843       free_pool_memory(jcr->attr);
844       jcr->attr = NULL;
845    }
846    if (jcr->ar) {
847       free(jcr->ar);
848       jcr->ar = NULL;
849    }
850 }
851
852 /*
853  * Free the Job Control Record if no one is still using it.
854  *  Called from main free_jcr() routine in src/lib/jcr.c so
855  *  that we can do our Director specific cleanup of the jcr.
856  */
857 void dird_free_jcr(JCR *jcr)
858 {
859    Dmsg0(200, "Start dird free_jcr\n");
860
861    dird_free_jcr_pointers(jcr);
862    if (jcr->term_wait_inited) {
863       pthread_cond_destroy(&jcr->term_wait);
864       jcr->term_wait_inited = false;
865    }
866    if (jcr->db_batch && jcr->db_batch != jcr->db) {
867       db_close_database(jcr, jcr->db_batch);
868    }
869    jcr->db_batch = NULL;
870    if (jcr->db) {
871       db_close_database(jcr, jcr->db);
872       jcr->db = NULL;
873    }
874    if (jcr->stime) {
875       Dmsg0(200, "Free JCR stime\n");
876       free_pool_memory(jcr->stime);
877       jcr->stime = NULL;
878    }
879    if (jcr->fname) {
880       Dmsg0(200, "Free JCR fname\n");
881       free_pool_memory(jcr->fname);
882       jcr->fname = NULL;
883    }
884    if (jcr->pool_source) {
885       free_pool_memory(jcr->pool_source);
886       jcr->pool_source = NULL;
887    }
888    if (jcr->catalog_source) {
889       free_pool_memory(jcr->catalog_source);
890       jcr->catalog_source = NULL;
891    }
892    if (jcr->rpool_source) {
893       free_pool_memory(jcr->rpool_source);
894       jcr->rpool_source = NULL;
895    }
896    if (jcr->wstore_source) {
897       free_pool_memory(jcr->wstore_source);
898       jcr->wstore_source = NULL;
899    }
900    if (jcr->rstore_source) {
901       free_pool_memory(jcr->rstore_source);
902       jcr->rstore_source = NULL;
903    }
904
905    /* Delete lists setup to hold storage pointers */
906    free_rwstorage(jcr);
907
908    jcr->job_end_push.destroy();
909
910    if (jcr->JobId != 0)
911       write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
912
913    Dmsg0(200, "End dird free_jcr\n");
914 }
915
916 /* 
917  * The Job storage definition must be either in the Job record
918  *  or in the Pool record.  The Pool record overrides the Job 
919  *  record.
920  */
921 void get_job_storage(USTORE *store, JOB *job, RUN *run) 
922 {
923    if (run && run->pool && run->pool->storage) {
924       store->store = (STORE *)run->pool->storage->first();
925       pm_strcpy(store->store_source, _("Run pool override"));
926       return;
927    }
928    if (run && run->storage) {
929       store->store = run->storage;
930       pm_strcpy(store->store_source, _("Run storage override"));
931       return;
932    }
933    if (job->pool->storage) {
934       store->store = (STORE *)job->pool->storage->first();
935       pm_strcpy(store->store_source, _("Pool resource"));
936    } else {
937       store->store = (STORE *)job->storage->first();
938       pm_strcpy(store->store_source, _("Job resource"));
939    }
940 }
941
942 /*
943  * Set some defaults in the JCR necessary to
944  * run. These items are pulled from the job
945  * definition as defaults, but can be overridden
946  * later either by the Run record in the Schedule resource,
947  * or by the Console program.
948  */
949 void set_jcr_defaults(JCR *jcr, JOB *job)
950 {
951    jcr->job = job;
952    jcr->JobType = job->JobType;
953    jcr->JobStatus = JS_Created;
954    switch (jcr->JobType) {
955    case JT_ADMIN:
956    case JT_RESTORE:
957       jcr->JobLevel = L_NONE;
958       break;
959    case JT_MIGRATE:
960       if (!jcr->rpool_source) {
961          jcr->rpool_source = get_pool_memory(PM_MESSAGE);
962          pm_strcpy(jcr->rpool_source, _("unknown source"));
963       }
964       /* Fall-through wanted */
965    default:
966       jcr->JobLevel = job->JobLevel;
967       break;
968    }
969    if (!jcr->fname) {
970       jcr->fname = get_pool_memory(PM_FNAME);
971    }
972    if (!jcr->pool_source) {
973       jcr->pool_source = get_pool_memory(PM_MESSAGE);
974       pm_strcpy(jcr->pool_source, _("unknown source"));
975    }
976    if (!jcr->catalog_source) {
977       jcr->catalog_source = get_pool_memory(PM_MESSAGE);
978       pm_strcpy(jcr->catalog_source, _("unknown source"));
979    }
980
981    jcr->JobPriority = job->Priority;
982    /* Copy storage definitions -- deleted in dir_free_jcr above */
983    if (job->storage) {
984       copy_rwstorage(jcr, job->storage, _("Job resource"));
985    } else {
986       copy_rwstorage(jcr, job->pool->storage, _("Pool resource"));
987    }
988    jcr->client = job->client;
989    if (!jcr->client_name) {
990       jcr->client_name = get_pool_memory(PM_NAME);
991    }
992    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
993    pm_strcpy(jcr->pool_source, _("Job resource"));
994    jcr->pool = job->pool;
995    jcr->full_pool = job->full_pool;
996    jcr->inc_pool = job->inc_pool;
997    jcr->diff_pool = job->diff_pool;
998    if (job->pool->catalog) {
999       jcr->catalog = job->pool->catalog;
1000       pm_strcpy(jcr->catalog_source, _("Pool resource"));
1001    } else {
1002       jcr->catalog = job->client->catalog;
1003       pm_strcpy(jcr->catalog_source, _("Client resource"));
1004    }
1005    jcr->fileset = job->fileset;
1006    jcr->messages = job->messages;
1007    jcr->spool_data = job->spool_data;
1008    jcr->spool_size = job->spool_size;
1009    jcr->write_part_after_job = job->write_part_after_job;
1010    jcr->accurate = job->accurate;
1011    if (jcr->RestoreBootstrap) {
1012       free(jcr->RestoreBootstrap);
1013       jcr->RestoreBootstrap = NULL;
1014    }
1015    /* This can be overridden by Console program */
1016    if (job->RestoreBootstrap) {
1017       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
1018    }
1019    /* This can be overridden by Console program */
1020    jcr->verify_job = job->verify_job;
1021    /* If no default level given, set one */
1022    if (jcr->JobLevel == 0) {
1023       switch (jcr->JobType) {
1024       case JT_VERIFY:
1025          jcr->JobLevel = L_VERIFY_CATALOG;
1026          break;
1027       case JT_BACKUP:
1028          jcr->JobLevel = L_INCREMENTAL;
1029          break;
1030       case JT_RESTORE:
1031       case JT_ADMIN:
1032          jcr->JobLevel = L_NONE;
1033          break;
1034       default:
1035          jcr->JobLevel = L_FULL;
1036          break;
1037       }
1038    }
1039 }
1040
1041 /* 
1042  * Copy the storage definitions from an alist to the JCR
1043  */
1044 void copy_rwstorage(JCR *jcr, alist *storage, const char *where)
1045 {
1046    switch(jcr->JobType) {
1047    case JT_RESTORE:
1048    case JT_VERIFY:
1049    case JT_MIGRATE:
1050       copy_rstorage(jcr, storage, where);
1051       break;
1052    default:
1053       copy_wstorage(jcr, storage, where);
1054       break;
1055    }
1056 }
1057
1058
1059 /* Set storage override.  Releases any previous storage definition */
1060 void set_rwstorage(JCR *jcr, USTORE *store)
1061 {
1062    if (!store) {
1063       Jmsg(jcr, M_FATAL, 0, _("No storage specified.\n"));
1064       return;
1065    }
1066    switch(jcr->JobType) {
1067    case JT_RESTORE:
1068    case JT_VERIFY:
1069    case JT_MIGRATE:
1070       set_rstorage(jcr, store);
1071       break;
1072    default:
1073       set_wstorage(jcr, store);
1074       break;
1075    }
1076 }
1077
1078 void free_rwstorage(JCR *jcr)
1079 {
1080    free_rstorage(jcr);
1081    free_wstorage(jcr);
1082 }
1083
1084 /* 
1085  * Copy the storage definitions from an alist to the JCR
1086  */
1087 void copy_rstorage(JCR *jcr, alist *storage, const char *where)
1088 {
1089    if (storage) {
1090       STORE *st;
1091       if (jcr->rstorage) {
1092          delete jcr->rstorage;
1093       }
1094       jcr->rstorage = New(alist(10, not_owned_by_alist));
1095       foreach_alist(st, storage) {
1096          jcr->rstorage->append(st);
1097       }
1098       if (!jcr->rstore_source) {
1099          jcr->rstore_source = get_pool_memory(PM_MESSAGE);
1100       }
1101       pm_strcpy(jcr->rstore_source, where);
1102       if (jcr->rstorage) {
1103          jcr->rstore = (STORE *)jcr->rstorage->first();
1104       }
1105    }
1106 }
1107
1108
1109 /* Set storage override.  Remove all previous storage */
1110 void set_rstorage(JCR *jcr, USTORE *store)
1111 {
1112    STORE *storage;
1113
1114    if (!store->store) {
1115       return;
1116    }
1117    if (jcr->rstorage) {
1118       free_rstorage(jcr);
1119    }
1120    if (!jcr->rstorage) {
1121       jcr->rstorage = New(alist(10, not_owned_by_alist));
1122    }
1123    jcr->rstore = store->store;
1124    if (!jcr->rstore_source) {
1125       jcr->rstore_source = get_pool_memory(PM_MESSAGE);
1126    }
1127    pm_strcpy(jcr->rstore_source, store->store_source);
1128    foreach_alist(storage, jcr->rstorage) {
1129       if (store->store == storage) {
1130          return;
1131       }
1132    }
1133    /* Store not in list, so add it */
1134    jcr->rstorage->prepend(store->store);
1135 }
1136
1137 void free_rstorage(JCR *jcr)
1138 {
1139    if (jcr->rstorage) {
1140       delete jcr->rstorage;
1141       jcr->rstorage = NULL;
1142    }
1143    jcr->rstore = NULL;
1144 }
1145
1146 /* 
1147  * Copy the storage definitions from an alist to the JCR
1148  */
1149 void copy_wstorage(JCR *jcr, alist *storage, const char *where)
1150 {
1151    if (storage) {
1152       STORE *st;
1153       if (jcr->wstorage) {
1154          delete jcr->wstorage;
1155       }
1156       jcr->wstorage = New(alist(10, not_owned_by_alist));
1157       foreach_alist(st, storage) {
1158          Dmsg1(100, "wstorage=%s\n", st->name());
1159          jcr->wstorage->append(st);
1160       }
1161       if (!jcr->wstore_source) {
1162          jcr->wstore_source = get_pool_memory(PM_MESSAGE);
1163       }
1164       pm_strcpy(jcr->wstore_source, where);
1165       if (jcr->wstorage) {
1166          jcr->wstore = (STORE *)jcr->wstorage->first();
1167          Dmsg2(100, "wstore=%s where=%s\n", jcr->wstore->name(), jcr->wstore_source);
1168       }
1169    }
1170 }
1171
1172
1173 /* Set storage override. Remove all previous storage */
1174 void set_wstorage(JCR *jcr, USTORE *store)
1175 {
1176    STORE *storage;
1177
1178    if (!store->store) {
1179       return;
1180    }
1181    if (jcr->wstorage) {
1182       free_wstorage(jcr);
1183    }
1184    if (!jcr->wstorage) {
1185       jcr->wstorage = New(alist(10, not_owned_by_alist));
1186    }
1187    jcr->wstore = store->store;
1188    if (!jcr->wstore_source) {
1189       jcr->wstore_source = get_pool_memory(PM_MESSAGE);
1190    }
1191    pm_strcpy(jcr->wstore_source, store->store_source);
1192    Dmsg2(50, "wstore=%s where=%s\n", jcr->wstore->name(), jcr->wstore_source);
1193    foreach_alist(storage, jcr->wstorage) {
1194       if (store->store == storage) {
1195          return;
1196       }
1197    }
1198    /* Store not in list, so add it */
1199    jcr->wstorage->prepend(store->store);
1200 }
1201
1202 void free_wstorage(JCR *jcr)
1203 {
1204    if (jcr->wstorage) {
1205       delete jcr->wstorage;
1206       jcr->wstorage = NULL;
1207    }
1208    jcr->wstore = NULL;
1209 }
1210
1211 void create_clones(JCR *jcr)
1212 {
1213    /*
1214     * Fire off any clone jobs (run directives)
1215     */
1216    Dmsg2(900, "cloned=%d run_cmds=%p\n", jcr->cloned, jcr->job->run_cmds);
1217    if (!jcr->cloned && jcr->job->run_cmds) {
1218       char *runcmd;
1219       JOB *job = jcr->job;
1220       POOLMEM *cmd = get_pool_memory(PM_FNAME);
1221       UAContext *ua = new_ua_context(jcr);
1222       ua->batch = true;
1223       foreach_alist(runcmd, job->run_cmds) {
1224          cmd = edit_job_codes(jcr, cmd, runcmd, "");              
1225          Mmsg(ua->cmd, "run %s cloned=yes", cmd);
1226          Dmsg1(900, "=============== Clone cmd=%s\n", ua->cmd);
1227          parse_ua_args(ua);                 /* parse command */
1228          int stat = run_cmd(ua, ua->cmd);
1229          if (stat == 0) {
1230             Jmsg(jcr, M_ERROR, 0, _("Could not start clone job.\n"));
1231          } else {
1232             Jmsg(jcr, M_INFO, 0, _("Clone JobId %d started.\n"), stat);
1233          }
1234       }
1235       free_ua_context(ua);
1236       free_pool_memory(cmd);
1237    }
1238 }
1239
1240 bool create_restore_bootstrap_file(JCR *jcr)
1241 {
1242    RESTORE_CTX rx;
1243    UAContext *ua;
1244    memset(&rx, 0, sizeof(rx));
1245    rx.bsr = new_bsr();
1246    rx.JobIds = (char *)"";                       
1247    rx.bsr->JobId = jcr->previous_jr.JobId;
1248    ua = new_ua_context(jcr);
1249    complete_bsr(ua, rx.bsr);
1250    rx.bsr->fi = new_findex();
1251    rx.bsr->fi->findex = 1;
1252    rx.bsr->fi->findex2 = jcr->previous_jr.JobFiles;
1253    jcr->ExpectedFiles = write_bsr_file(ua, rx);
1254    if (jcr->ExpectedFiles == 0) {
1255       free_ua_context(ua);
1256       free_bsr(rx.bsr);
1257       return false;
1258    }
1259    free_ua_context(ua);
1260    free_bsr(rx.bsr);
1261    jcr->needs_sd = true;
1262    return true;
1263 }
1264
1265 bool run_console_command(JCR *jcr, const char *cmd){
1266    UAContext *ua;
1267    bool ok;
1268
1269    ua = new_ua_context(jcr);
1270    Mmsg(ua->cmd, "%s", cmd);
1271    Dmsg1(100, "Console command: %s\n", ua->cmd);
1272    parse_ua_args(ua);
1273    ok= do_a_command(ua);
1274    free_ua_context(ua);
1275    return ok;
1276 }