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