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