]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
Apply reschedule patch to 1.37 code.
[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 /* Exported subroutines */
40
41 /* Imported subroutines */
42 extern void term_scheduler();
43 extern void term_ua_server();
44
45 /* Imported variables */
46 extern time_t watchdog_time;
47
48 jobq_t job_queue;
49
50 void init_job_server(int max_workers)
51 {
52    int stat;
53    watchdog_t *wd;
54
55    if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
56       berrno be;
57       Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.strerror(stat));
58    }
59    wd = new_watchdog();
60    wd->callback = job_monitor_watchdog;
61    wd->destructor = job_monitor_destructor;
62    wd->one_shot = false;
63    wd->interval = 60;
64    wd->data = new_control_jcr("*JobMonitor*", JT_SYSTEM);
65    register_watchdog(wd);
66 }
67
68 void term_job_server()
69 {
70    jobq_destroy(&job_queue);          /* ignore any errors */
71 }
72
73 /*
74  * Run a job -- typically called by the scheduler, but may also
75  *              be called by the UA (Console program).
76  *
77  *  Returns: 0 on failure
78  *           JobId on success
79  *
80  */
81 JobId_t run_job(JCR *jcr)
82 {
83    int stat, errstat;
84    JobId_t JobId = 0;
85
86    P(jcr->mutex);
87    sm_check(__FILE__, __LINE__, true);
88    init_msg(jcr, jcr->messages);
89
90    /* Initialize termination condition variable */
91    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
92       berrno be;
93       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(errstat));
94       goto bail_out;
95    }
96    jcr->term_wait_inited = true;
97
98    /*
99     * Open database
100     */
101    Dmsg0(50, "Open database\n");
102    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
103                             jcr->catalog->db_password, jcr->catalog->db_address,
104                             jcr->catalog->db_port, jcr->catalog->db_socket,
105                             jcr->catalog->mult_db_connections);
106    if (!jcr->db || !db_open_database(jcr, jcr->db)) {
107       Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
108                  jcr->catalog->db_name);
109       if (jcr->db) {
110          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
111       }
112       goto bail_out;
113    }
114    Dmsg0(50, "DB opened\n");
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
128    Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
129        jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
130
131    if (!get_or_create_client_record(jcr)) {
132       goto bail_out;
133    }
134
135    if (!jcr->fname) {
136       jcr->fname = get_pool_memory(PM_FNAME);
137    }
138
139    /* Now, do pre-run stuff, like setting job level (Inc/diff, ...) */
140    switch (jcr->JobType) {
141    case JT_BACKUP:
142       if (!do_backup_init(jcr)) {
143          backup_cleanup(jcr, JS_ErrorTerminated);
144       }
145       break;
146    case JT_VERIFY:
147       if (!do_verify_init(jcr)) {
148          verify_cleanup(jcr, JS_ErrorTerminated);
149       }
150       break;
151    case JT_RESTORE:
152       if (!do_restore_init(jcr)) {
153          restore_cleanup(jcr, JS_ErrorTerminated);
154       }
155       break;
156    case JT_ADMIN:
157       if (!do_admin_init(jcr)) {
158          admin_cleanup(jcr, JS_ErrorTerminated);
159       }
160       break;
161    case JT_MIGRATION:
162    case JT_COPY:
163    case JT_ARCHIVE:
164       if (!do_mac_init(jcr)) {             /* migration, archive, copy */
165          mac_cleanup(jcr, JS_ErrorTerminated);
166       }
167       break;
168    default:
169       Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
170       set_jcr_job_status(jcr, JS_ErrorTerminated);
171       break;
172    }
173    if (job_canceled(jcr)) {
174       goto bail_out;
175    }
176
177    Dmsg0(200, "Add jrc to work queue\n");
178
179    /* Queue the job to be run */
180    if ((stat = jobq_add(&job_queue, jcr)) != 0) {
181       berrno be;
182       Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror(stat));
183       JobId = 0;
184       goto bail_out;
185    }
186    Dmsg0(100, "Done run_job()\n");
187
188    V(jcr->mutex);
189    return JobId;
190
191 bail_out:
192    if (jcr->fname) {
193       free_memory(jcr->fname);
194       jcr->fname = NULL;
195    }
196    V(jcr->mutex);
197    return JobId;
198
199 }
200
201
202 /*
203  * This is the engine called by jobq.c:jobq_add() when we were pulled
204  *  from the work queue.
205  *  At this point, we are running in our own thread and all
206  *    necessary resources are allocated -- see jobq.c
207  */
208 static void *job_thread(void *arg)
209 {
210    JCR *jcr = (JCR *)arg;
211
212    jcr->my_thread_id = pthread_self();
213    pthread_detach(jcr->my_thread_id);
214    sm_check(__FILE__, __LINE__, true);
215
216    for ( ;; ) {
217       Dmsg0(200, "=====Start Job=========\n");
218       jcr->start_time = time(NULL);      /* set the real start time */
219       jcr->jr.StartTime = jcr->start_time;
220       set_jcr_job_status(jcr, JS_Running);
221       if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
222          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
223       }
224
225       if (job_canceled(jcr)) {
226          update_job_end_record(jcr);
227       } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
228           (utime_t)(jcr->start_time - jcr->sched_time)) {
229          Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
230          set_jcr_job_status(jcr, JS_Canceled);
231          update_job_end_record(jcr);
232       } else {
233
234          /* Run Job */
235          generate_event(jcr, "StartJob");
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          generate_event(jcr, "EndJob");
331          /* Send off any queued messages */
332          if (jcr->msg_queue->size() > 0) {
333             dequeue_messages(jcr);
334          }
335       }
336 bail_out:
337       break;
338    }
339
340    Dmsg1(50, "======== End Job stat=%c ==========\n", jcr->JobStatus);
341    sm_check(__FILE__, __LINE__, true);
342    return NULL;
343 }
344
345
346 /*
347  * Cancel a job -- typically called by the UA (Console program), but may also
348  *              be called by the job watchdog.
349  *
350  *  Returns: 1 if cancel appears to be successful
351  *           0 on failure. Message sent to ua->jcr.
352  */
353 int cancel_job(UAContext *ua, JCR *jcr)
354 {
355    BSOCK *sd, *fd;
356
357    switch (jcr->JobStatus) {
358    case JS_Created:
359    case JS_WaitJobRes:
360    case JS_WaitClientRes:
361    case JS_WaitStoreRes:
362    case JS_WaitPriority:
363    case JS_WaitMaxJobs:
364    case JS_WaitStartTime:
365       set_jcr_job_status(jcr, JS_Canceled);
366       bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
367               jcr->JobId, jcr->Job);
368       jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
369       return 1;
370
371    default:
372       set_jcr_job_status(jcr, JS_Canceled);
373
374       /* Cancel File daemon */
375       if (jcr->file_bsock) {
376          ua->jcr->client = jcr->client;
377          if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
378             bsendmsg(ua, _("Failed to connect to File daemon.\n"));
379             return 0;
380          }
381          Dmsg0(200, "Connected to file daemon\n");
382          fd = ua->jcr->file_bsock;
383          bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
384          while (bnet_recv(fd) >= 0) {
385             bsendmsg(ua, "%s", fd->msg);
386          }
387          bnet_sig(fd, BNET_TERMINATE);
388          bnet_close(fd);
389          ua->jcr->file_bsock = NULL;
390       }
391
392       /* Cancel Storage daemon */
393       if (jcr->store_bsock) {
394          if (!ua->jcr->storage) {
395             copy_storage(ua->jcr, jcr);
396          } else {
397             set_storage(ua->jcr, jcr->store);
398          }
399          if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
400             bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
401             return 0;
402          }
403          Dmsg0(200, "Connected to storage daemon\n");
404          sd = ua->jcr->store_bsock;
405          bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
406          while (bnet_recv(sd) >= 0) {
407             bsendmsg(ua, "%s", sd->msg);
408          }
409          bnet_sig(sd, BNET_TERMINATE);
410          bnet_close(sd);
411          ua->jcr->store_bsock = NULL;
412       }
413    }
414
415    return 1;
416 }
417
418
419 static void job_monitor_destructor(watchdog_t *self)
420 {
421    JCR *control_jcr = (JCR *) self->data;
422
423    free_jcr(control_jcr);
424 }
425
426 static void job_monitor_watchdog(watchdog_t *self)
427 {
428    JCR *control_jcr, *jcr;
429
430    control_jcr = (JCR *)self->data;
431
432    Dmsg1(800, "job_monitor_watchdog %p called\n", self);
433
434    lock_jcr_chain();
435
436    foreach_jcr(jcr) {
437       bool cancel;
438
439       if (jcr->JobId == 0) {
440          Dmsg2(800, "Skipping JCR %p (%s) with JobId 0\n",
441                jcr, jcr->Job);
442          /* Keep reference counts correct */
443          free_locked_jcr(jcr);
444          continue;
445       }
446
447       /* check MaxWaitTime */
448       cancel = job_check_maxwaittime(control_jcr, jcr);
449
450       /* check MaxRunTime */
451       cancel |= job_check_maxruntime(control_jcr, jcr);
452
453       if (cancel) {
454          Dmsg3(800, "Cancelling JCR %p jobid %d (%s)\n",
455                jcr, jcr->JobId, jcr->Job);
456
457          UAContext *ua = new_ua_context(jcr);
458          ua->jcr = control_jcr;
459          cancel_job(ua, jcr);
460          free_ua_context(ua);
461
462          Dmsg1(800, "Have cancelled JCR %p\n", jcr);
463       }
464
465       /* Keep reference counts correct */
466       free_locked_jcr(jcr);
467    }
468    unlock_jcr_chain();
469 }
470
471 /*
472  * Check if the maxwaittime has expired and it is possible
473  *  to cancel the job.
474  */
475 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
476 {
477    bool cancel = false;
478    bool ok_to_cancel = false;
479    JOB *job = jcr->job;
480
481    if (job->MaxWaitTime == 0 && job->FullMaxWaitTime == 0 &&
482        job->IncMaxWaitTime == 0 && job->DiffMaxWaitTime == 0) {
483       return false;
484    } 
485    if (jcr->JobLevel == L_FULL && job->FullMaxWaitTime != 0 &&
486          (watchdog_time - jcr->start_time) >= job->FullMaxWaitTime) {
487       ok_to_cancel = true;
488    } else if (jcr->JobLevel == L_DIFFERENTIAL && job->DiffMaxWaitTime != 0 &&
489          (watchdog_time - jcr->start_time) >= job->DiffMaxWaitTime) {
490       ok_to_cancel = true;
491    } else if (jcr->JobLevel == L_INCREMENTAL && job->IncMaxWaitTime != 0 &&
492          (watchdog_time - jcr->start_time) >= job->IncMaxWaitTime) {
493       ok_to_cancel = true;
494    } else if (job->MaxWaitTime != 0 &&
495          (watchdog_time - jcr->start_time) >= job->MaxWaitTime) {
496       ok_to_cancel = true;
497    }
498    if (!ok_to_cancel) {
499       return false;
500    }
501    Dmsg3(800, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
502          "checking status\n",
503          jcr->JobId, jcr->Job, job->MaxWaitTime);
504    switch (jcr->JobStatus) {
505    case JS_Created:
506    case JS_Blocked:
507    case JS_WaitFD:
508    case JS_WaitSD:
509    case JS_WaitStoreRes:
510    case JS_WaitClientRes:
511    case JS_WaitJobRes:
512    case JS_WaitPriority:
513    case JS_WaitMaxJobs:
514    case JS_WaitStartTime:
515       cancel = true;
516       Dmsg0(200, "JCR blocked in #1\n");
517       break;
518    case JS_Running:
519       Dmsg0(800, "JCR running, checking SD status\n");
520       switch (jcr->SDJobStatus) {
521       case JS_WaitMount:
522       case JS_WaitMedia:
523       case JS_WaitFD:
524          cancel = true;
525          Dmsg0(800, "JCR blocked in #2\n");
526          break;
527       default:
528          Dmsg0(800, "JCR not blocked in #2\n");
529          break;
530       }
531       break;
532    case JS_Terminated:
533    case JS_ErrorTerminated:
534    case JS_Canceled:
535    case JS_FatalError:
536       Dmsg0(800, "JCR already dead in #3\n");
537       break;
538    default:
539       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
540             jcr->JobStatus);
541    }
542    Dmsg3(800, "MaxWaitTime result: %scancel JCR %p (%s)\n",
543          cancel ? "" : "do not ", jcr, jcr->job);
544
545    return cancel;
546 }
547
548 /*
549  * Check if maxruntime has expired and if the job can be
550  *   canceled.
551  */
552 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
553 {
554    bool cancel = false;
555
556    if (jcr->job->MaxRunTime == 0) {
557       return false;
558    }
559    if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
560       Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
561             jcr, jcr->Job, jcr->job->MaxRunTime);
562       return false;
563    }
564
565    switch (jcr->JobStatus) {
566    case JS_Created:
567    case JS_Running:
568    case JS_Blocked:
569    case JS_WaitFD:
570    case JS_WaitSD:
571    case JS_WaitStoreRes:
572    case JS_WaitClientRes:
573    case JS_WaitJobRes:
574    case JS_WaitPriority:
575    case JS_WaitMaxJobs:
576    case JS_WaitStartTime:
577    case JS_Differences:
578       cancel = true;
579       break;
580    case JS_Terminated:
581    case JS_ErrorTerminated:
582    case JS_Canceled:
583    case JS_FatalError:
584       cancel = false;
585       break;
586    default:
587       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
588             jcr->JobStatus);
589    }
590
591    Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
592          cancel ? "" : "do not ", jcr, jcr->job);
593
594    return cancel;
595 }
596
597
598 /*
599  * Get or create a Client record for this Job
600  */
601 bool get_or_create_client_record(JCR *jcr)
602 {
603    CLIENT_DBR cr;
604
605    memset(&cr, 0, sizeof(cr));
606    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
607    cr.AutoPrune = jcr->client->AutoPrune;
608    cr.FileRetention = jcr->client->FileRetention;
609    cr.JobRetention = jcr->client->JobRetention;
610    if (!jcr->client_name) {
611       jcr->client_name = get_pool_memory(PM_NAME);
612    }
613    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
614    if (!db_create_client_record(jcr, jcr->db, &cr)) {
615       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
616          db_strerror(jcr->db));
617       return false;
618    }
619    jcr->jr.ClientId = cr.ClientId;
620    if (cr.Uname[0]) {
621       if (!jcr->client_uname) {
622          jcr->client_uname = get_pool_memory(PM_NAME);
623       }
624       pm_strcpy(jcr->client_uname, cr.Uname);
625    }
626    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
627       jcr->jr.ClientId);
628    return true;
629 }
630
631 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
632 {
633    /*
634     * Get or Create FileSet record
635     */
636    memset(fsr, 0, sizeof(FILESET_DBR));
637    bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
638    if (jcr->fileset->have_MD5) {
639       struct MD5Context md5c;
640       unsigned char signature[16];
641       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
642       MD5Final(signature, &md5c);
643       bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
644       bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
645    } else {
646       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
647    }
648    if (!jcr->fileset->ignore_fs_changes ||
649        !db_get_fileset_record(jcr, jcr->db, fsr)) {
650       if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
651          Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
652             fsr->FileSet, db_strerror(jcr->db));
653          return false;
654       }
655    }
656    jcr->jr.FileSetId = fsr->FileSetId;
657    if (fsr->created) {
658       Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
659          fsr->FileSet, fsr->cCreateTime);
660    }
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 }