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