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