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