]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
0ff1adbae5cf81734229447580a3782158eeb273
[bacula/bacula] / bacula / src / dird / job.c
1 /*
2  *
3  *   Bacula Director Job processing routines
4  *
5  *     Kern Sibbald, October MM
6  *
7  *    Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2005 Kern Sibbald
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 *job_thread(void *arg);
34 static void job_monitor_watchdog(watchdog_t *self);
35 static void job_monitor_destructor(watchdog_t *self);
36 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr);
37 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr);
38
39 /* Imported subroutines */
40 extern void term_scheduler();
41 extern void term_ua_server();
42
43 /* Imported variables */
44 extern time_t watchdog_time;
45
46 jobq_t job_queue;
47
48 void init_job_server(int max_workers)
49 {
50    int stat;
51    watchdog_t *wd;
52
53    if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
54       berrno be;
55       Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.strerror(stat));
56    }
57    wd = new_watchdog();
58    wd->callback = job_monitor_watchdog;
59    wd->destructor = job_monitor_destructor;
60    wd->one_shot = false;
61    wd->interval = 60;
62    wd->data = new_control_jcr("*JobMonitor*", JT_SYSTEM);
63    register_watchdog(wd);
64 }
65
66 void term_job_server()
67 {
68    jobq_destroy(&job_queue);          /* ignore any errors */
69 }
70
71 /*
72  * Run a job -- typically called by the scheduler, but may also
73  *              be called by the UA (Console program).
74  *
75  *  Returns: 0 on failure
76  *           JobId on success
77  *
78  */
79 JobId_t run_job(JCR *jcr)
80 {
81    int stat, errstat;
82    JobId_t JobId = 0;
83
84    P(jcr->mutex);
85    sm_check(__FILE__, __LINE__, true);
86    init_msg(jcr, jcr->messages);
87
88    /* Initialize termination condition variable */
89    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
90       berrno be;
91       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(errstat));
92       goto bail_out;
93    }
94    jcr->term_wait_inited = true;
95
96    /*
97     * Open database
98     */
99    Dmsg0(50, "Open database\n");
100    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
101                             jcr->catalog->db_password, jcr->catalog->db_address,
102                             jcr->catalog->db_port, jcr->catalog->db_socket,
103                             jcr->catalog->mult_db_connections);
104    if (!jcr->db || !db_open_database(jcr, jcr->db)) {
105       Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
106                  jcr->catalog->db_name);
107       if (jcr->db) {
108          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
109       }
110       goto bail_out;
111    }
112    Dmsg0(50, "DB opened\n");
113
114    /*
115     * Create Job record
116     */
117    create_unique_job_name(jcr, jcr->job->hdr.name);
118    set_jcr_job_status(jcr, JS_Created);
119    init_jcr_job_record(jcr);
120    if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
121       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
122       goto bail_out;
123    }
124    JobId = jcr->JobId = jcr->jr.JobId;
125
126    Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
127        jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
128
129    if (!get_or_create_client_record(jcr)) {
130       goto bail_out;
131    }
132
133    if (!jcr->fname) {
134       jcr->fname = get_pool_memory(PM_FNAME);
135    }
136
137    /* Now, do pre-run stuff, like setting job level (Inc/diff, ...) */
138    switch (jcr->JobType) {
139    case JT_BACKUP:
140       if (!do_backup_init(jcr)) {
141          backup_cleanup(jcr, JS_ErrorTerminated);
142       }
143       break;
144    case JT_VERIFY:
145       if (!do_verify_init(jcr)) {
146          verify_cleanup(jcr, JS_ErrorTerminated);
147       }
148       break;
149    case JT_RESTORE:
150       if (!do_restore_init(jcr)) {
151          restore_cleanup(jcr, JS_ErrorTerminated);
152       }
153       break;
154    case JT_ADMIN:
155       if (!do_admin_init(jcr)) {
156          admin_cleanup(jcr, JS_ErrorTerminated);
157       }
158       break;
159    case JT_MIGRATION:
160    case JT_COPY:
161    case JT_ARCHIVE:
162       if (!do_mac_init(jcr)) {             /* migration, archive, copy */
163          mac_cleanup(jcr, JS_ErrorTerminated);
164       }
165       break;
166    default:
167       Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
168       set_jcr_job_status(jcr, JS_ErrorTerminated);
169       break;
170    }
171    if (job_canceled(jcr)) {
172       goto bail_out;
173    }
174
175    Dmsg0(200, "Add jrc to work queue\n");
176
177    /* Queue the job to be run */
178    if ((stat = jobq_add(&job_queue, jcr)) != 0) {
179       berrno be;
180       Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror(stat));
181       JobId = 0;
182       goto bail_out;
183    }
184    Dmsg0(100, "Done run_job()\n");
185
186    V(jcr->mutex);
187    return JobId;
188
189 bail_out:
190    if (jcr->fname) {
191       free_memory(jcr->fname);
192       jcr->fname = NULL;
193    }
194    V(jcr->mutex);
195    return JobId;
196
197 }
198
199
200 /*
201  * This is the engine called by jobq.c:jobq_add() when we were pulled
202  *  from the work queue.
203  *  At this point, we are running in our own thread and all
204  *    necessary resources are allocated -- see jobq.c
205  */
206 static void *job_thread(void *arg)
207 {
208    JCR *jcr = (JCR *)arg;
209
210    jcr->my_thread_id = pthread_self();
211    pthread_detach(jcr->my_thread_id);
212    sm_check(__FILE__, __LINE__, true);
213
214    for ( ;; ) {
215       Dmsg0(200, "=====Start Job=========\n");
216       jcr->start_time = time(NULL);      /* set the real start time */
217       jcr->jr.StartTime = jcr->start_time;
218       set_jcr_job_status(jcr, JS_Running);
219       if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
220          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
221       }
222
223       if (job_canceled(jcr)) {
224          update_job_end_record(jcr);
225       } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
226           (utime_t)(jcr->start_time - jcr->sched_time)) {
227          Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
228          set_jcr_job_status(jcr, JS_Canceled);
229          update_job_end_record(jcr);
230       } else {
231
232          /* Run Job */
233          generate_event(jcr, "StartJob");
234          if (jcr->job->RunBeforeJob) {
235             POOLMEM *before = get_pool_memory(PM_FNAME);
236             int status;
237             BPIPE *bpipe;
238             char line[MAXSTRING];
239
240             before = edit_job_codes(jcr, before, jcr->job->RunBeforeJob, "");
241             bpipe = open_bpipe(before, 0, "r");
242             free_pool_memory(before);
243             while (fgets(line, sizeof(line), bpipe->rfd)) {
244                Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
245             }
246             status = close_bpipe(bpipe);
247             if (status != 0) {
248                berrno be;
249                Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob error: ERR=%s\n"), be.strerror(status));
250                set_jcr_job_status(jcr, JS_FatalError);
251                update_job_end_record(jcr);
252                goto bail_out;
253             }
254          }
255          switch (jcr->JobType) {
256          case JT_BACKUP:
257             if (do_backup(jcr)) {
258                do_autoprune(jcr);
259             } else {
260                backup_cleanup(jcr, JS_ErrorTerminated);
261             }
262             break;
263          case JT_VERIFY:
264             if (do_verify(jcr)) {
265                do_autoprune(jcr);
266             } else {
267                verify_cleanup(jcr, JS_ErrorTerminated);
268             }
269             break;
270          case JT_RESTORE:
271             if (do_restore(jcr)) {
272                do_autoprune(jcr);
273             } else {
274                restore_cleanup(jcr, JS_ErrorTerminated);
275             }
276             break;
277          case JT_ADMIN:
278             if (do_admin(jcr)) {
279                do_autoprune(jcr);
280             } else {
281                admin_cleanup(jcr, JS_ErrorTerminated);
282             }
283             break;
284          case JT_MIGRATION:
285          case JT_COPY:
286          case JT_ARCHIVE:
287             if (do_mac(jcr)) {              /* migration, archive, copy */
288                do_autoprune(jcr);
289             } else {
290                mac_cleanup(jcr, JS_ErrorTerminated);
291             }
292             break;
293          default:
294             Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
295             break;
296          }
297          if ((jcr->job->RunAfterJob && jcr->JobStatus == JS_Terminated) ||
298              (jcr->job->RunAfterFailedJob && jcr->JobStatus != JS_Terminated)) {
299             POOLMEM *after = get_pool_memory(PM_FNAME);
300             int status;
301             BPIPE *bpipe;
302             char line[MAXSTRING];
303
304             if (jcr->JobStatus == JS_Terminated) {
305                after = edit_job_codes(jcr, after, jcr->job->RunAfterJob, "");
306             } else {
307                after = edit_job_codes(jcr, after, jcr->job->RunAfterFailedJob, "");
308             }
309             bpipe = open_bpipe(after, 0, "r");
310             free_pool_memory(after);
311             while (fgets(line, sizeof(line), bpipe->rfd)) {
312                Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
313             }
314             status = close_bpipe(bpipe);
315             /*
316              * Note, if we get an error here, do not mark the
317              *  job in error, simply report the error condition.
318              */
319             if (status != 0) {
320                berrno be;
321                if (jcr->JobStatus == JS_Terminated) {
322                   Jmsg(jcr, M_WARNING, 0, _("RunAfterJob error: ERR=%s\n"), be.strerror(status));
323                } else {
324                   Jmsg(jcr, M_FATAL, 0, _("RunAfterFailedJob error: ERR=%s\n"), be.strerror(status));
325                }
326             }
327          }
328          generate_event(jcr, "EndJob");
329          /* Send off any queued messages */
330          if (jcr->msg_queue->size() > 0) {
331             dequeue_messages(jcr);
332          }
333       }
334 bail_out:
335       break;
336    }
337
338    Dmsg1(50, "======== End Job stat=%c ==========\n", jcr->JobStatus);
339    sm_check(__FILE__, __LINE__, true);
340    return NULL;
341 }
342
343
344 /*
345  * Cancel a job -- typically called by the UA (Console program), but may also
346  *              be called by the job watchdog.
347  *
348  *  Returns: 1 if cancel appears to be successful
349  *           0 on failure. Message sent to ua->jcr.
350  */
351 int cancel_job(UAContext *ua, JCR *jcr)
352 {
353    BSOCK *sd, *fd;
354
355    switch (jcr->JobStatus) {
356    case JS_Created:
357    case JS_WaitJobRes:
358    case JS_WaitClientRes:
359    case JS_WaitStoreRes:
360    case JS_WaitPriority:
361    case JS_WaitMaxJobs:
362    case JS_WaitStartTime:
363       set_jcr_job_status(jcr, JS_Canceled);
364       bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
365               jcr->JobId, jcr->Job);
366       jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
367       return 1;
368
369    default:
370       set_jcr_job_status(jcr, JS_Canceled);
371
372       /* Cancel File daemon */
373       if (jcr->file_bsock) {
374          ua->jcr->client = jcr->client;
375          if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
376             bsendmsg(ua, _("Failed to connect to File daemon.\n"));
377             return 0;
378          }
379          Dmsg0(200, "Connected to file daemon\n");
380          fd = ua->jcr->file_bsock;
381          bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
382          while (bnet_recv(fd) >= 0) {
383             bsendmsg(ua, "%s", fd->msg);
384          }
385          bnet_sig(fd, BNET_TERMINATE);
386          bnet_close(fd);
387          ua->jcr->file_bsock = NULL;
388       }
389
390       /* Cancel Storage daemon */
391       if (jcr->store_bsock) {
392          if (!ua->jcr->storage) {
393             copy_storage(ua->jcr, jcr);
394          } else {
395             set_storage(ua->jcr, jcr->store);
396          }
397          if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
398             bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
399             return 0;
400          }
401          Dmsg0(200, "Connected to storage daemon\n");
402          sd = ua->jcr->store_bsock;
403          bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
404          while (bnet_recv(sd) >= 0) {
405             bsendmsg(ua, "%s", sd->msg);
406          }
407          bnet_sig(sd, BNET_TERMINATE);
408          bnet_close(sd);
409          ua->jcr->store_bsock = NULL;
410       }
411    }
412
413    return 1;
414 }
415
416
417 static void job_monitor_destructor(watchdog_t *self)
418 {
419    JCR *control_jcr = (JCR *) self->data;
420
421    free_jcr(control_jcr);
422 }
423
424 static void job_monitor_watchdog(watchdog_t *self)
425 {
426    JCR *control_jcr, *jcr;
427
428    control_jcr = (JCR *)self->data;
429
430    Dmsg1(800, "job_monitor_watchdog %p called\n", self);
431
432    lock_jcr_chain();
433
434    foreach_jcr(jcr) {
435       bool cancel;
436
437       if (jcr->JobId == 0) {
438          Dmsg2(800, "Skipping JCR %p (%s) with JobId 0\n",
439                jcr, jcr->Job);
440          /* Keep reference counts correct */
441          free_locked_jcr(jcr);
442          continue;
443       }
444
445       /* check MaxWaitTime */
446       cancel = job_check_maxwaittime(control_jcr, jcr);
447
448       /* check MaxRunTime */
449       cancel |= job_check_maxruntime(control_jcr, jcr);
450
451       if (cancel) {
452          Dmsg3(800, "Cancelling JCR %p jobid %d (%s)\n",
453                jcr, jcr->JobId, jcr->Job);
454
455          UAContext *ua = new_ua_context(jcr);
456          ua->jcr = control_jcr;
457          cancel_job(ua, jcr);
458          free_ua_context(ua);
459
460          Dmsg1(800, "Have cancelled JCR %p\n", jcr);
461       }
462
463       /* Keep reference counts correct */
464       free_locked_jcr(jcr);
465    }
466    unlock_jcr_chain();
467 }
468
469 /*
470  * Check if the maxwaittime has expired and it is possible
471  *  to cancel the job.
472  */
473 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
474 {
475    bool cancel = false;
476    bool ok_to_cancel = false;
477    JOB *job = jcr->job;
478
479    if (job->MaxWaitTime == 0 && job->FullMaxWaitTime == 0 &&
480        job->IncMaxWaitTime == 0 && job->DiffMaxWaitTime == 0) {
481       return false;
482    } 
483    if (jcr->JobLevel == L_FULL && job->FullMaxWaitTime != 0 &&
484          (watchdog_time - jcr->start_time) >= job->FullMaxWaitTime) {
485       ok_to_cancel = true;
486    } else if (jcr->JobLevel == L_DIFFERENTIAL && job->DiffMaxWaitTime != 0 &&
487          (watchdog_time - jcr->start_time) >= job->DiffMaxWaitTime) {
488       ok_to_cancel = true;
489    } else if (jcr->JobLevel == L_INCREMENTAL && job->IncMaxWaitTime != 0 &&
490          (watchdog_time - jcr->start_time) >= job->IncMaxWaitTime) {
491       ok_to_cancel = true;
492    } else if (job->MaxWaitTime != 0 &&
493          (watchdog_time - jcr->start_time) >= job->MaxWaitTime) {
494       ok_to_cancel = true;
495    }
496    if (!ok_to_cancel) {
497       return false;
498    }
499    Dmsg3(800, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
500          "checking status\n",
501          jcr->JobId, jcr->Job, job->MaxWaitTime);
502    switch (jcr->JobStatus) {
503    case JS_Created:
504    case JS_Blocked:
505    case JS_WaitFD:
506    case JS_WaitSD:
507    case JS_WaitStoreRes:
508    case JS_WaitClientRes:
509    case JS_WaitJobRes:
510    case JS_WaitPriority:
511    case JS_WaitMaxJobs:
512    case JS_WaitStartTime:
513       cancel = true;
514       Dmsg0(200, "JCR blocked in #1\n");
515       break;
516    case JS_Running:
517       Dmsg0(800, "JCR running, checking SD status\n");
518       switch (jcr->SDJobStatus) {
519       case JS_WaitMount:
520       case JS_WaitMedia:
521       case JS_WaitFD:
522          cancel = true;
523          Dmsg0(800, "JCR blocked in #2\n");
524          break;
525       default:
526          Dmsg0(800, "JCR not blocked in #2\n");
527          break;
528       }
529       break;
530    case JS_Terminated:
531    case JS_ErrorTerminated:
532    case JS_Canceled:
533    case JS_FatalError:
534       Dmsg0(800, "JCR already dead in #3\n");
535       break;
536    default:
537       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
538             jcr->JobStatus);
539    }
540    Dmsg3(800, "MaxWaitTime result: %scancel JCR %p (%s)\n",
541          cancel ? "" : "do not ", jcr, jcr->job);
542
543    return cancel;
544 }
545
546 /*
547  * Check if maxruntime has expired and if the job can be
548  *   canceled.
549  */
550 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
551 {
552    bool cancel = false;
553
554    if (jcr->job->MaxRunTime == 0) {
555       return false;
556    }
557    if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
558       Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
559             jcr, jcr->Job, jcr->job->MaxRunTime);
560       return false;
561    }
562
563    switch (jcr->JobStatus) {
564    case JS_Created:
565    case JS_Running:
566    case JS_Blocked:
567    case JS_WaitFD:
568    case JS_WaitSD:
569    case JS_WaitStoreRes:
570    case JS_WaitClientRes:
571    case JS_WaitJobRes:
572    case JS_WaitPriority:
573    case JS_WaitMaxJobs:
574    case JS_WaitStartTime:
575    case JS_Differences:
576       cancel = true;
577       break;
578    case JS_Terminated:
579    case JS_ErrorTerminated:
580    case JS_Canceled:
581    case JS_FatalError:
582       cancel = false;
583       break;
584    default:
585       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
586             jcr->JobStatus);
587    }
588
589    Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
590          cancel ? "" : "do not ", jcr, jcr->job);
591
592    return cancel;
593 }
594
595
596 /*
597  * Get or create a Client record for this Job
598  */
599 bool get_or_create_client_record(JCR *jcr)
600 {
601    CLIENT_DBR cr;
602
603    memset(&cr, 0, sizeof(cr));
604    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
605    cr.AutoPrune = jcr->client->AutoPrune;
606    cr.FileRetention = jcr->client->FileRetention;
607    cr.JobRetention = jcr->client->JobRetention;
608    if (!jcr->client_name) {
609       jcr->client_name = get_pool_memory(PM_NAME);
610    }
611    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
612    if (!db_create_client_record(jcr, jcr->db, &cr)) {
613       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
614          db_strerror(jcr->db));
615       return false;
616    }
617    jcr->jr.ClientId = cr.ClientId;
618    if (cr.Uname[0]) {
619       if (!jcr->client_uname) {
620          jcr->client_uname = get_pool_memory(PM_NAME);
621       }
622       pm_strcpy(jcr->client_uname, cr.Uname);
623    }
624    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
625       jcr->jr.ClientId);
626    return true;
627 }
628
629 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
630 {
631    /*
632     * Get or Create FileSet record
633     */
634    memset(fsr, 0, sizeof(FILESET_DBR));
635    bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
636    if (jcr->fileset->have_MD5) {
637       struct MD5Context md5c;
638       unsigned char signature[16];
639       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
640       MD5Final(signature, &md5c);
641       bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
642       bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
643    } else {
644       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
645    }
646    if (!jcr->fileset->ignore_fs_changes ||
647        !db_get_fileset_record(jcr, jcr->db, fsr)) {
648       if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
649          Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
650             fsr->FileSet, db_strerror(jcr->db));
651          return false;
652       }
653    }
654    jcr->jr.FileSetId = fsr->FileSetId;
655 #ifdef needed
656    if (fsr->created && jcr != NULL) {
657       Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
658          fsr->FileSet, fsr->cCreateTime);
659    }
660 #endif
661    Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
662       jcr->jr.FileSetId);
663    return true;
664 }
665
666 void init_jcr_job_record(JCR *jcr)
667 {
668    jcr->jr.SchedTime = jcr->sched_time;
669    jcr->jr.StartTime = jcr->start_time;
670    jcr->jr.EndTime = 0;               /* perhaps rescheduled, clear it */
671    jcr->jr.JobType = jcr->JobType;
672    jcr->jr.JobLevel = jcr->JobLevel;
673    jcr->jr.JobStatus = jcr->JobStatus;
674    jcr->jr.JobId = jcr->JobId;
675    bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
676    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
677 }
678
679 /*
680  * Write status and such in DB
681  */
682 void update_job_end_record(JCR *jcr)
683 {
684    jcr->jr.EndTime = time(NULL);
685    jcr->end_time = jcr->jr.EndTime;
686    jcr->jr.JobId = jcr->JobId;
687    jcr->jr.JobStatus = jcr->JobStatus;
688    jcr->jr.JobFiles = jcr->JobFiles;
689    jcr->jr.JobBytes = jcr->JobBytes;
690    jcr->jr.VolSessionId = jcr->VolSessionId;
691    jcr->jr.VolSessionTime = jcr->VolSessionTime;
692    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
693       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
694          db_strerror(jcr->db));
695    }
696 }
697
698 /*
699  * Takes base_name and appends (unique) current
700  *   date and time to form unique job name.
701  *
702  *  Returns: unique job name in jcr->Job
703  *    date/time in jcr->start_time
704  */
705 void create_unique_job_name(JCR *jcr, const char *base_name)
706 {
707    /* Job start mutex */
708    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
709    static time_t last_start_time = 0;
710    time_t now;
711    struct tm tm;
712    char dt[MAX_TIME_LENGTH];
713    char name[MAX_NAME_LENGTH];
714    char *p;
715
716    /* Guarantee unique start time -- maximum one per second, and
717     * thus unique Job Name
718     */
719    P(mutex);                          /* lock creation of jobs */
720    now = time(NULL);
721    while (now == last_start_time) {
722       bmicrosleep(0, 500000);
723       now = time(NULL);
724    }
725    last_start_time = now;
726    V(mutex);                          /* allow creation of jobs */
727    jcr->start_time = now;
728    /* Form Unique JobName */
729    localtime_r(&now, &tm);
730    /* Use only characters that are permitted in Windows filenames */
731    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
732    bstrncpy(name, base_name, sizeof(name));
733    name[sizeof(name)-22] = 0;          /* truncate if too long */
734    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
735    /* Convert spaces into underscores */
736    for (p=jcr->Job; *p; p++) {
737       if (*p == ' ') {
738          *p = '_';
739       }
740    }
741 }
742
743 /* Called directly from job rescheduling */
744 void dird_free_jcr_pointers(JCR *jcr)
745 {
746    if (jcr->sd_auth_key) {
747       free(jcr->sd_auth_key);
748       jcr->sd_auth_key = NULL;
749    }
750    if (jcr->where) {
751       free(jcr->where);
752       jcr->where = NULL;
753    }
754    if (jcr->file_bsock) {
755       Dmsg0(200, "Close File bsock\n");
756       bnet_close(jcr->file_bsock);
757       jcr->file_bsock = NULL;
758    }
759    if (jcr->store_bsock) {
760       Dmsg0(200, "Close Store bsock\n");
761       bnet_close(jcr->store_bsock);
762       jcr->store_bsock = NULL;
763    }
764    if (jcr->fname) {
765       Dmsg0(200, "Free JCR fname\n");
766       free_pool_memory(jcr->fname);
767       jcr->fname = NULL;
768    }
769    if (jcr->stime) {
770       Dmsg0(200, "Free JCR stime\n");
771       free_pool_memory(jcr->stime);
772       jcr->stime = NULL;
773    }
774    if (jcr->RestoreBootstrap) {
775       free(jcr->RestoreBootstrap);
776       jcr->RestoreBootstrap = NULL;
777    }
778    if (jcr->client_uname) {
779       free_pool_memory(jcr->client_uname);
780       jcr->client_uname = NULL;
781    }
782    if (jcr->term_wait_inited) {
783       pthread_cond_destroy(&jcr->term_wait);
784       jcr->term_wait_inited = false;
785    }
786 }
787
788 /*
789  * Free the Job Control Record if no one is still using it.
790  *  Called from main free_jcr() routine in src/lib/jcr.c so
791  *  that we can do our Director specific cleanup of the jcr.
792  */
793 void dird_free_jcr(JCR *jcr)
794 {
795    Dmsg0(200, "Start dird free_jcr\n");
796
797    dird_free_jcr_pointers(jcr);
798
799    /* Delete lists setup to hold storage pointers */
800    if (jcr->storage) {
801       delete jcr->storage;
802    }
803    jcr->job_end_push.destroy();
804    Dmsg0(200, "End dird free_jcr\n");
805 }
806
807 /*
808  * Set some defaults in the JCR necessary to
809  * run. These items are pulled from the job
810  * definition as defaults, but can be overridden
811  * later either by the Run record in the Schedule resource,
812  * or by the Console program.
813  */
814 void set_jcr_defaults(JCR *jcr, JOB *job)
815 {
816    STORE *st;
817    jcr->job = job;
818    jcr->JobType = job->JobType;
819    switch (jcr->JobType) {
820    case JT_ADMIN:
821    case JT_RESTORE:
822       jcr->JobLevel = L_NONE;
823       break;
824    default:
825       jcr->JobLevel = job->JobLevel;
826       break;
827    }
828    jcr->JobPriority = job->Priority;
829    /* Copy storage definitions -- deleted in dir_free_jcr above */
830    if (job->storage) {
831       if (jcr->storage) {
832          delete jcr->storage;
833       }
834       jcr->storage = New(alist(10, not_owned_by_alist));
835       foreach_alist(st, job->storage) {
836          jcr->storage->append(st);
837       }
838    }
839    if (jcr->storage) {
840       jcr->store = (STORE *)jcr->storage->first();
841    }
842    jcr->client = job->client;
843    if (!jcr->client_name) {
844       jcr->client_name = get_pool_memory(PM_NAME);
845    }
846    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
847    jcr->pool = job->pool;
848    jcr->full_pool = job->full_pool;
849    jcr->inc_pool = job->inc_pool;
850    jcr->dif_pool = job->dif_pool;
851    jcr->catalog = job->client->catalog;
852    jcr->fileset = job->fileset;
853    jcr->messages = job->messages;
854    jcr->spool_data = job->spool_data;
855    jcr->write_part_after_job = job->write_part_after_job;
856    if (jcr->RestoreBootstrap) {
857       free(jcr->RestoreBootstrap);
858       jcr->RestoreBootstrap = NULL;
859    }
860    /* This can be overridden by Console program */
861    if (job->RestoreBootstrap) {
862       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
863    }
864    /* This can be overridden by Console program */
865    jcr->verify_job = job->verify_job;
866    /* If no default level given, set one */
867    if (jcr->JobLevel == 0) {
868       switch (jcr->JobType) {
869       case JT_VERIFY:
870          jcr->JobLevel = L_VERIFY_CATALOG;
871          break;
872       case JT_BACKUP:
873          jcr->JobLevel = L_INCREMENTAL;
874          break;
875       case JT_RESTORE:
876       case JT_ADMIN:
877          jcr->JobLevel = L_NONE;
878          break;
879       default:
880          break;
881       }
882    }
883 }
884
885 /*
886  * copy the storage definitions from an old JCR to a new one
887  */
888 void copy_storage(JCR *new_jcr, JCR *old_jcr)
889 {
890    if (old_jcr->storage) {
891       STORE *st;
892       if (old_jcr->storage) {
893          delete old_jcr->storage;
894       }
895       new_jcr->storage = New(alist(10, not_owned_by_alist));
896       foreach_alist(st, old_jcr->storage) {
897          new_jcr->storage->append(st);
898       }
899    }
900    if (old_jcr->store) {
901       new_jcr->store = old_jcr->store;
902    } else if (new_jcr->storage) {
903       new_jcr->store = (STORE *)new_jcr->storage->first();
904    }
905 }
906
907 /* Set storage override */
908 void set_storage(JCR *jcr, STORE *store)
909 {
910    STORE *storage;
911
912    jcr->store = store;
913    foreach_alist(storage, jcr->storage) {
914       if (store == storage) {
915          return;
916       }
917    }
918    /* Store not in list, so add it */
919    jcr->storage->prepend(store);
920 }