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