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