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