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