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