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