]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
- Make clean remove old CVS files
[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    bool ok_to_cancel = false;
440    JOB *job = jcr->job;
441
442    if (job->MaxWaitTime == 0 && job->FullMaxWaitTime == 0 &&
443        job->IncMaxWaitTime == 0 && job->DiffMaxWaitTime == 0) {
444       return false;
445    } 
446    if (jcr->JobLevel == L_FULL && job->FullMaxWaitTime != 0 &&
447          (watchdog_time - jcr->start_time) >= job->FullMaxWaitTime) {
448       ok_to_cancel = true;
449    } else if (jcr->JobLevel == L_DIFFERENTIAL && job->DiffMaxWaitTime != 0 &&
450          (watchdog_time - jcr->start_time) >= job->DiffMaxWaitTime) {
451       ok_to_cancel = true;
452    } else if (jcr->JobLevel == L_INCREMENTAL && job->IncMaxWaitTime != 0 &&
453          (watchdog_time - jcr->start_time) >= job->IncMaxWaitTime) {
454       ok_to_cancel = true;
455    } else if (job->MaxWaitTime != 0 &&
456          (watchdog_time - jcr->start_time) >= job->MaxWaitTime) {
457       ok_to_cancel = true;
458    }
459    if (!ok_to_cancel) {
460       return false;
461    }
462    Dmsg3(800, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
463          "checking status\n",
464          jcr->JobId, jcr->Job, job->MaxWaitTime);
465    switch (jcr->JobStatus) {
466    case JS_Created:
467    case JS_Blocked:
468    case JS_WaitFD:
469    case JS_WaitSD:
470    case JS_WaitStoreRes:
471    case JS_WaitClientRes:
472    case JS_WaitJobRes:
473    case JS_WaitPriority:
474    case JS_WaitMaxJobs:
475    case JS_WaitStartTime:
476       cancel = true;
477       Dmsg0(200, "JCR blocked in #1\n");
478       break;
479    case JS_Running:
480       Dmsg0(800, "JCR running, checking SD status\n");
481       switch (jcr->SDJobStatus) {
482       case JS_WaitMount:
483       case JS_WaitMedia:
484       case JS_WaitFD:
485          cancel = true;
486          Dmsg0(800, "JCR blocked in #2\n");
487          break;
488       default:
489          Dmsg0(800, "JCR not blocked in #2\n");
490          break;
491       }
492       break;
493    case JS_Terminated:
494    case JS_ErrorTerminated:
495    case JS_Canceled:
496    case JS_FatalError:
497       Dmsg0(800, "JCR already dead in #3\n");
498       break;
499    default:
500       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
501             jcr->JobStatus);
502    }
503    Dmsg3(800, "MaxWaitTime result: %scancel JCR %p (%s)\n",
504          cancel ? "" : "do not ", jcr, jcr->job);
505
506    return cancel;
507 }
508
509 /*
510  * Check if maxruntime has expired and if the job can be
511  *   canceled.
512  */
513 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
514 {
515    bool cancel = false;
516
517    if (jcr->job->MaxRunTime == 0) {
518       return false;
519    }
520    if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
521       Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
522             jcr, jcr->Job, jcr->job->MaxRunTime);
523       return false;
524    }
525
526    switch (jcr->JobStatus) {
527    case JS_Created:
528    case JS_Running:
529    case JS_Blocked:
530    case JS_WaitFD:
531    case JS_WaitSD:
532    case JS_WaitStoreRes:
533    case JS_WaitClientRes:
534    case JS_WaitJobRes:
535    case JS_WaitPriority:
536    case JS_WaitMaxJobs:
537    case JS_WaitStartTime:
538    case JS_Differences:
539       cancel = true;
540       break;
541    case JS_Terminated:
542    case JS_ErrorTerminated:
543    case JS_Canceled:
544    case JS_FatalError:
545       cancel = false;
546       break;
547    default:
548       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
549             jcr->JobStatus);
550    }
551
552    Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
553          cancel ? "" : "do not ", jcr, jcr->job);
554
555    return cancel;
556 }
557
558
559 /*
560  * Get or create a Client record for this Job
561  */
562 bool get_or_create_client_record(JCR *jcr)
563 {
564    CLIENT_DBR cr;
565
566    memset(&cr, 0, sizeof(cr));
567    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
568    cr.AutoPrune = jcr->client->AutoPrune;
569    cr.FileRetention = jcr->client->FileRetention;
570    cr.JobRetention = jcr->client->JobRetention;
571    if (!jcr->client_name) {
572       jcr->client_name = get_pool_memory(PM_NAME);
573    }
574    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
575    if (!db_create_client_record(jcr, jcr->db, &cr)) {
576       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
577          db_strerror(jcr->db));
578       return false;
579    }
580    jcr->jr.ClientId = cr.ClientId;
581    if (cr.Uname[0]) {
582       if (!jcr->client_uname) {
583          jcr->client_uname = get_pool_memory(PM_NAME);
584       }
585       pm_strcpy(jcr->client_uname, cr.Uname);
586    }
587    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
588       jcr->jr.ClientId);
589    return true;
590 }
591
592 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
593 {
594    /*
595     * Get or Create FileSet record
596     */
597    memset(fsr, 0, sizeof(FILESET_DBR));
598    bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
599    if (jcr->fileset->have_MD5) {
600       struct MD5Context md5c;
601       unsigned char signature[16];
602       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
603       MD5Final(signature, &md5c);
604       bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
605       bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
606    } else {
607       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
608    }
609    if (!jcr->fileset->ignore_fs_changes ||
610        !db_get_fileset_record(jcr, jcr->db, fsr)) {
611       if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
612          Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
613             fsr->FileSet, db_strerror(jcr->db));
614          return false;
615       }
616    }
617    jcr->jr.FileSetId = fsr->FileSetId;
618    if (fsr->created) {
619       Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
620          fsr->FileSet, fsr->cCreateTime);
621    }
622    Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
623       jcr->jr.FileSetId);
624    return true;
625 }
626
627 void init_jcr_job_record(JCR *jcr)
628 {
629    jcr->jr.SchedTime = jcr->sched_time;
630    jcr->jr.StartTime = jcr->start_time;
631    jcr->jr.EndTime = 0;               /* perhaps rescheduled, clear it */
632    jcr->jr.JobType = jcr->JobType;
633    jcr->jr.JobLevel = jcr->JobLevel;
634    jcr->jr.JobStatus = jcr->JobStatus;
635    jcr->jr.JobId = jcr->JobId;
636    bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
637    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
638 }
639
640 /*
641  * Write status and such in DB
642  */
643 void update_job_end_record(JCR *jcr)
644 {
645    jcr->jr.EndTime = time(NULL);
646    jcr->end_time = jcr->jr.EndTime;
647    jcr->jr.JobId = jcr->JobId;
648    jcr->jr.JobStatus = jcr->JobStatus;
649    jcr->jr.JobFiles = jcr->JobFiles;
650    jcr->jr.JobBytes = jcr->JobBytes;
651    jcr->jr.VolSessionId = jcr->VolSessionId;
652    jcr->jr.VolSessionTime = jcr->VolSessionTime;
653    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
654       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
655          db_strerror(jcr->db));
656    }
657 }
658
659 /*
660  * Takes base_name and appends (unique) current
661  *   date and time to form unique job name.
662  *
663  *  Returns: unique job name in jcr->Job
664  *    date/time in jcr->start_time
665  */
666 void create_unique_job_name(JCR *jcr, const char *base_name)
667 {
668    /* Job start mutex */
669    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
670    static time_t last_start_time = 0;
671    time_t now;
672    struct tm tm;
673    char dt[MAX_TIME_LENGTH];
674    char name[MAX_NAME_LENGTH];
675    char *p;
676
677    /* Guarantee unique start time -- maximum one per second, and
678     * thus unique Job Name
679     */
680    P(mutex);                          /* lock creation of jobs */
681    now = time(NULL);
682    while (now == last_start_time) {
683       bmicrosleep(0, 500000);
684       now = time(NULL);
685    }
686    last_start_time = now;
687    V(mutex);                          /* allow creation of jobs */
688    jcr->start_time = now;
689    /* Form Unique JobName */
690    localtime_r(&now, &tm);
691    /* Use only characters that are permitted in Windows filenames */
692    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
693    bstrncpy(name, base_name, sizeof(name));
694    name[sizeof(name)-22] = 0;          /* truncate if too long */
695    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
696    /* Convert spaces into underscores */
697    for (p=jcr->Job; *p; p++) {
698       if (*p == ' ') {
699          *p = '_';
700       }
701    }
702 }
703
704 /*
705  * Free the Job Control Record if no one is still using it.
706  *  Called from main free_jcr() routine in src/lib/jcr.c so
707  *  that we can do our Director specific cleanup of the jcr.
708  */
709 void dird_free_jcr(JCR *jcr)
710 {
711    Dmsg0(200, "Start dird free_jcr\n");
712
713    if (jcr->sd_auth_key) {
714       free(jcr->sd_auth_key);
715       jcr->sd_auth_key = NULL;
716    }
717    if (jcr->where) {
718       free(jcr->where);
719       jcr->where = NULL;
720    }
721    if (jcr->file_bsock) {
722       Dmsg0(200, "Close File bsock\n");
723       bnet_close(jcr->file_bsock);
724       jcr->file_bsock = NULL;
725    }
726    if (jcr->store_bsock) {
727       Dmsg0(200, "Close Store bsock\n");
728       bnet_close(jcr->store_bsock);
729       jcr->store_bsock = NULL;
730    }
731    if (jcr->fname) {
732       Dmsg0(200, "Free JCR fname\n");
733       free_pool_memory(jcr->fname);
734       jcr->fname = NULL;
735    }
736    if (jcr->stime) {
737       Dmsg0(200, "Free JCR stime\n");
738       free_pool_memory(jcr->stime);
739       jcr->stime = NULL;
740    }
741    if (jcr->RestoreBootstrap) {
742       free(jcr->RestoreBootstrap);
743       jcr->RestoreBootstrap = NULL;
744    }
745    if (jcr->client_uname) {
746       free_pool_memory(jcr->client_uname);
747       jcr->client_uname = NULL;
748    }
749    if (jcr->term_wait_inited) {
750       pthread_cond_destroy(&jcr->term_wait);
751    }
752    /* Delete lists setup to hold storage pointers */
753    if (jcr->storage) {
754       delete jcr->storage;
755    }
756    jcr->job_end_push.destroy();
757    Dmsg0(200, "End dird free_jcr\n");
758 }
759
760 /*
761  * Set some defaults in the JCR necessary to
762  * run. These items are pulled from the job
763  * definition as defaults, but can be overridden
764  * later either by the Run record in the Schedule resource,
765  * or by the Console program.
766  */
767 void set_jcr_defaults(JCR *jcr, JOB *job)
768 {
769    STORE *st;
770    jcr->job = job;
771    jcr->JobType = job->JobType;
772    switch (jcr->JobType) {
773    case JT_ADMIN:
774    case JT_RESTORE:
775       jcr->JobLevel = L_NONE;
776       break;
777    default:
778       jcr->JobLevel = job->JobLevel;
779       break;
780    }
781    jcr->JobPriority = job->Priority;
782    /* Copy storage definitions -- deleted in dir_free_jcr above */
783    if (job->storage) {
784       if (jcr->storage) {
785          delete jcr->storage;
786       }
787       jcr->storage = New(alist(10, not_owned_by_alist));
788       foreach_alist(st, job->storage) {
789          jcr->storage->append(st);
790       }
791    }
792    if (jcr->storage) {
793       jcr->store = (STORE *)jcr->storage->first();
794    }
795    jcr->client = job->client;
796    if (!jcr->client_name) {
797       jcr->client_name = get_pool_memory(PM_NAME);
798    }
799    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
800    jcr->pool = job->pool;
801    jcr->full_pool = job->full_pool;
802    jcr->inc_pool = job->inc_pool;
803    jcr->dif_pool = job->dif_pool;
804    jcr->catalog = job->client->catalog;
805    jcr->fileset = job->fileset;
806    jcr->messages = job->messages;
807    jcr->spool_data = job->spool_data;
808    jcr->write_part_after_job = job->write_part_after_job;
809    if (jcr->RestoreBootstrap) {
810       free(jcr->RestoreBootstrap);
811       jcr->RestoreBootstrap = NULL;
812    }
813    /* This can be overridden by Console program */
814    if (job->RestoreBootstrap) {
815       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
816    }
817    /* This can be overridden by Console program */
818    jcr->verify_job = job->verify_job;
819    /* If no default level given, set one */
820    if (jcr->JobLevel == 0) {
821       switch (jcr->JobType) {
822       case JT_VERIFY:
823          jcr->JobLevel = L_VERIFY_CATALOG;
824          break;
825       case JT_BACKUP:
826          jcr->JobLevel = L_INCREMENTAL;
827          break;
828       case JT_RESTORE:
829       case JT_ADMIN:
830          jcr->JobLevel = L_NONE;
831          break;
832       default:
833          break;
834       }
835    }
836 }
837
838 /*
839  * copy the storage definitions from an old JCR to a new one
840  */
841 void copy_storage(JCR *new_jcr, JCR *old_jcr)
842 {
843    if (old_jcr->storage) {
844       STORE *st;
845       if (old_jcr->storage) {
846          delete old_jcr->storage;
847       }
848       new_jcr->storage = New(alist(10, not_owned_by_alist));
849       foreach_alist(st, old_jcr->storage) {
850          new_jcr->storage->append(st);
851       }
852    }
853    if (old_jcr->store) {
854       new_jcr->store = old_jcr->store;
855    } else if (new_jcr->storage) {
856       new_jcr->store = (STORE *)new_jcr->storage->first();
857    }
858 }
859
860 /* Set storage override */
861 void set_storage(JCR *jcr, STORE *store)
862 {
863    STORE *storage;
864
865    jcr->store = store;
866    foreach_alist(storage, jcr->storage) {
867       if (store == storage) {
868          return;
869       }
870    }
871    /* Store not in list, so add it */
872    jcr->storage->prepend(store);
873 }