]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
Update copyrights + Do not release source pointers when restarting a failed job.
[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    Bacula® - The Network Backup Solution
11
12    Copyright (C) 2000-2007 Free Software Foundation Europe e.V.
13
14    The main author of Bacula is Kern Sibbald, with contributions from
15    many others, a complete list can be found in the file AUTHORS.
16    This program is Free Software; you can redistribute it and/or
17    modify it under the terms of version two of the GNU General Public
18    License as published by the Free Software Foundation plus additions
19    that are listed in the file LICENSE.
20
21    This program is distributed in the hope that it will be useful, but
22    WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24    General Public License for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with this program; if not, write to the Free Software
28    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
29    02110-1301, USA.
30
31    Bacula® is a registered trademark of John Walker.
32    The licensor of Bacula is the Free Software Foundation Europe
33    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
34    Switzerland, email:ftf@fsfeurope.org.
35 */
36
37 #include "bacula.h"
38 #include "dird.h"
39
40 /* Forward referenced subroutines */
41 static void *job_thread(void *arg);
42 static void job_monitor_watchdog(watchdog_t *self);
43 static void job_monitor_destructor(watchdog_t *self);
44 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr);
45 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr);
46
47 /* Imported subroutines */
48 extern void term_scheduler();
49 extern void term_ua_server();
50
51 /* Imported variables */
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    wd = new_watchdog();
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 void term_job_server()
74 {
75    jobq_destroy(&job_queue);          /* ignore any errors */
76 }
77
78 /*
79  * Run a job -- typically called by the scheduler, but may also
80  *              be called by the UA (Console program).
81  *
82  *  Returns: 0 on failure
83  *           JobId on success
84  *
85  */
86 JobId_t run_job(JCR *jcr)
87 {
88    int stat;
89    if (setup_job(jcr)) {
90       Dmsg0(200, "Add jrc to work queue\n");
91       /* Queue the job to be run */
92       if ((stat = jobq_add(&job_queue, jcr)) != 0) {
93          berrno be;
94          Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror(stat));
95          return 0;
96       }
97       return jcr->JobId;
98    }
99    return 0;
100 }            
101
102 bool setup_job(JCR *jcr) 
103 {
104    int errstat;
105
106    jcr->lock();
107    sm_check(__FILE__, __LINE__, true);
108    init_msg(jcr, jcr->messages);
109
110    /* Initialize termination condition variable */
111    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
112       berrno be;
113       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(errstat));
114       goto bail_out;
115    }
116    jcr->term_wait_inited = true;
117
118    create_unique_job_name(jcr, jcr->job->name());
119    set_jcr_job_status(jcr, JS_Created);
120    jcr->unlock();
121
122    /*
123     * Open database
124     */
125    Dmsg0(50, "Open database\n");
126    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
127                             jcr->catalog->db_password, jcr->catalog->db_address,
128                             jcr->catalog->db_port, jcr->catalog->db_socket,
129                             jcr->catalog->mult_db_connections);
130    if (!jcr->db || !db_open_database(jcr, jcr->db)) {
131       Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
132                  jcr->catalog->db_name);
133       if (jcr->db) {
134          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
135       }
136       goto bail_out;
137    }
138    Dmsg0(50, "DB opened\n");
139
140    if (!jcr->fname) {
141       jcr->fname = get_pool_memory(PM_FNAME);
142    }
143    if (!jcr->pool_source) {
144       jcr->pool_source = get_pool_memory(PM_MESSAGE);
145       pm_strcpy(jcr->pool_source, _("unknown source"));
146    }
147    Dmsg2(500, "pool=%s (From %s)\n", jcr->pool->name(), jcr->pool_source);
148    if (jcr->JobType == JT_MIGRATE) {
149       if (!jcr->rpool_source) {
150          jcr->rpool_source = get_pool_memory(PM_MESSAGE);
151          pm_strcpy(jcr->rpool_source, _("unknown source"));
152       }
153    }
154
155    /*
156     * Create Job record
157     */
158    init_jcr_job_record(jcr);
159    if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
160       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
161       goto bail_out;
162    }
163    jcr->JobId = jcr->jr.JobId;
164    Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
165        jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
166
167    if (!get_or_create_client_record(jcr)) {
168       goto bail_out;
169    }
170
171    generate_daemon_event(jcr, "JobStart");
172
173    if (job_canceled(jcr)) {
174       goto bail_out;
175    }
176
177    /*
178     * Now, do pre-run stuff, like setting job level (Inc/diff, ...)
179     *  this allows us to setup a proper job start record for restarting
180     *  in case of later errors.
181     */
182    switch (jcr->JobType) {
183    case JT_BACKUP:
184       if (!do_backup_init(jcr)) {
185          backup_cleanup(jcr, JS_ErrorTerminated);
186       }
187       break;
188    case JT_VERIFY:
189       if (!do_verify_init(jcr)) {
190          verify_cleanup(jcr, JS_ErrorTerminated);
191       }
192       break;
193    case JT_RESTORE:
194       if (!do_restore_init(jcr)) {
195          restore_cleanup(jcr, JS_ErrorTerminated);
196       }
197       break;
198    case JT_ADMIN:
199       if (!do_admin_init(jcr)) {
200          admin_cleanup(jcr, JS_ErrorTerminated);
201       }
202       break;
203    case JT_MIGRATE:
204       if (!do_migration_init(jcr)) { 
205          migration_cleanup(jcr, JS_ErrorTerminated);
206       }
207       break;
208    default:
209       Pmsg1(0, _("Unimplemented job type: %d\n"), jcr->JobType);
210       set_jcr_job_status(jcr, JS_ErrorTerminated);
211       break;
212    }
213
214    generate_job_event(jcr, "JobInit");
215    return true;
216
217 bail_out:
218    return false;
219 }
220
221 void update_job_end(JCR *jcr, int TermCode)
222 {
223    dequeue_messages(jcr);             /* display any queued messages */
224    set_jcr_job_status(jcr, TermCode);
225    run_scripts(jcr, jcr->job->RunScripts, "AfterJob");
226    update_job_end_record(jcr);
227 }
228
229 /*
230  * This is the engine called by jobq.c:jobq_add() when we were pulled
231  *  from the work queue.
232  *  At this point, we are running in our own thread and all
233  *    necessary resources are allocated -- see jobq.c
234  */
235 static void *job_thread(void *arg)
236 {
237    JCR *jcr = (JCR *)arg;
238
239    jcr->my_thread_id = pthread_self();
240    pthread_detach(jcr->my_thread_id);
241    sm_check(__FILE__, __LINE__, true);
242
243    Dmsg0(200, "=====Start Job=========\n");
244    set_jcr_job_status(jcr, JS_Running);   /* this will be set only if no error */
245    jcr->start_time = time(NULL);      /* set the real start time */
246    jcr->jr.StartTime = jcr->start_time;
247
248    if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
249        (utime_t)(jcr->start_time - jcr->sched_time)) {
250       set_jcr_job_status(jcr, JS_Canceled);
251       Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
252    }
253
254    /* TODO : check if it is used somewhere */
255    if (jcr->job->RunScripts == NULL) {
256       Dmsg0(200, "Warning, job->RunScripts is empty\n");
257       jcr->job->RunScripts = New(alist(10, not_owned_by_alist));
258    }
259
260    if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
261       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
262    }
263
264    /* Run any script BeforeJob on dird */
265    run_scripts(jcr, jcr->job->RunScripts, "BeforeJob");
266
267    if (job_canceled(jcr)) {
268       update_job_end(jcr, jcr->JobStatus);
269
270    } else {
271       /*
272        * We re-update the job start record so that the start
273        *  time is set after the run before job.  This avoids
274        *  that any files created by the run before job will
275        *  be saved twice.  They will be backed up in the current
276        *  job, but not in the next one unless they are changed.
277        *  Without this, they will be backed up in this job and
278        *  in the next job run because in that case, their date
279        *   is after the start of this run.
280        */
281       jcr->start_time = time(NULL);
282       jcr->jr.StartTime = jcr->start_time;
283       if (!db_update_job_start_record(jcr, jcr->db, &jcr->jr)) {
284          Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
285       }
286       generate_job_event(jcr, "JobRun");
287
288       switch (jcr->JobType) {
289       case JT_BACKUP:
290          if (do_backup(jcr)) {
291             do_autoprune(jcr);
292          } else {
293             backup_cleanup(jcr, JS_ErrorTerminated);
294          }
295          break;
296       case JT_VERIFY:
297          if (do_verify(jcr)) {
298             do_autoprune(jcr);
299          } else {
300             verify_cleanup(jcr, JS_ErrorTerminated);
301          }
302          break;
303       case JT_RESTORE:
304          if (do_restore(jcr)) {
305             do_autoprune(jcr);
306          } else {
307             restore_cleanup(jcr, JS_ErrorTerminated);
308          }
309          break;
310       case JT_ADMIN:
311          if (do_admin(jcr)) {
312             do_autoprune(jcr);
313          } else {
314             admin_cleanup(jcr, JS_ErrorTerminated);
315          }
316          break;
317       case JT_MIGRATE:
318       case JT_COPY:
319       case JT_ARCHIVE:
320          if (do_migration(jcr)) {
321             do_autoprune(jcr);
322          } else {
323             migration_cleanup(jcr, JS_ErrorTerminated);
324          }
325          break;
326       default:
327          Pmsg1(0, _("Unimplemented job type: %d\n"), jcr->JobType);
328          break;
329       }
330
331       /* Send off any queued messages */
332       if (jcr->msg_queue && jcr->msg_queue->size() > 0) {
333          dequeue_messages(jcr);
334       }
335    }
336
337    generate_daemon_event(jcr, "JobEnd");
338    Dmsg1(50, "======== End Job stat=%c ==========\n", jcr->JobStatus);
339    sm_check(__FILE__, __LINE__, true);
340    return NULL;
341 }
342
343
344 /*
345  * Cancel a job -- typically called by the UA (Console program), but may also
346  *              be called by the job watchdog.
347  *
348  *  Returns: true  if cancel appears to be successful
349  *           false on failure. Message sent to ua->jcr.
350  */
351 bool cancel_job(UAContext *ua, JCR *jcr)
352 {
353    BSOCK *sd, *fd;
354    char ed1[50];
355
356    set_jcr_job_status(jcr, JS_Canceled);
357
358    switch (jcr->JobStatus) {
359    case JS_Created:
360    case JS_WaitJobRes:
361    case JS_WaitClientRes:
362    case JS_WaitStoreRes:
363    case JS_WaitPriority:
364    case JS_WaitMaxJobs:
365    case JS_WaitStartTime:
366       bsendmsg(ua, _("JobId %s, Job %s marked to be canceled.\n"),
367               edit_uint64(jcr->JobId, ed1), jcr->Job);
368       jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
369       return true;
370
371    default:
372       /* Cancel File daemon */
373       if (jcr->file_bsock) {
374          ua->jcr->client = jcr->client;
375          if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
376             bsendmsg(ua, _("Failed to connect to File daemon.\n"));
377             return 0;
378          }
379          Dmsg0(200, "Connected to file daemon\n");
380          fd = ua->jcr->file_bsock;
381          bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
382          while (bnet_recv(fd) >= 0) {
383             bsendmsg(ua, "%s", fd->msg);
384          }
385          bnet_sig(fd, BNET_TERMINATE);
386          bnet_close(fd);
387          ua->jcr->file_bsock = NULL;
388       }
389
390       /* Cancel Storage daemon */
391       if (jcr->store_bsock) {
392          if (!ua->jcr->wstorage) {
393             if (jcr->rstorage) {
394                copy_wstorage(ua->jcr, jcr->rstorage, _("Job resource")); 
395             } else {
396                copy_wstorage(ua->jcr, jcr->wstorage, _("Job resource")); 
397             }
398          } else {
399             USTORE store;
400             if (jcr->rstorage) {
401                store.store = jcr->rstore;
402             } else {
403                store.store = jcr->wstore;
404             }
405             set_wstorage(ua->jcr, &store);
406          }
407
408          if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
409             bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
410             return false;
411          }
412          Dmsg0(200, "Connected to storage daemon\n");
413          sd = ua->jcr->store_bsock;
414          bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
415          while (bnet_recv(sd) >= 0) {
416             bsendmsg(ua, "%s", sd->msg);
417          }
418          bnet_sig(sd, BNET_TERMINATE);
419          bnet_close(sd);
420          ua->jcr->store_bsock = NULL;
421       }
422    }
423
424    return true;
425 }
426
427
428 static void job_monitor_destructor(watchdog_t *self)
429 {
430    JCR *control_jcr = (JCR *)self->data;
431
432    free_jcr(control_jcr);
433 }
434
435 static void job_monitor_watchdog(watchdog_t *self)
436 {
437    JCR *control_jcr, *jcr;
438
439    control_jcr = (JCR *)self->data;
440
441    Dmsg1(800, "job_monitor_watchdog %p called\n", self);
442
443    foreach_jcr(jcr) {
444       bool cancel = false;
445
446       if (jcr->JobId == 0 || job_canceled(jcr)) {
447          Dmsg2(800, "Skipping JCR=%p Job=%s\n", jcr, jcr->Job);
448          continue;
449       }
450
451       /* check MaxWaitTime */
452       if (job_check_maxwaittime(control_jcr, jcr)) {
453          set_jcr_job_status(jcr, JS_Canceled);
454          Jmsg(jcr, M_FATAL, 0, _("Max wait time exceeded. Job canceled.\n"));
455          cancel = true;
456       /* check MaxRunTime */
457       } else if (job_check_maxruntime(control_jcr, jcr)) {
458          set_jcr_job_status(jcr, JS_Canceled);
459          Jmsg(jcr, M_FATAL, 0, _("Max run time exceeded. Job canceled.\n"));
460          cancel = true;
461       }
462
463       if (cancel) {
464          Dmsg3(800, "Cancelling JCR %p jobid %d (%s)\n", jcr, jcr->JobId, jcr->Job);
465          UAContext *ua = new_ua_context(jcr);
466          ua->jcr = control_jcr;
467          cancel_job(ua, jcr);
468          free_ua_context(ua);
469          Dmsg2(800, "Have cancelled JCR %p Job=%d\n", jcr, jcr->JobId);
470       }
471
472    }
473    /* Keep reference counts correct */
474    endeach_jcr(jcr);
475 }
476
477 /*
478  * Check if the maxwaittime has expired and it is possible
479  *  to cancel the job.
480  */
481 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
482 {
483    bool cancel = false;
484    bool ok_to_cancel = false;
485    JOB *job = jcr->job;
486
487    if (job_canceled(jcr)) {
488       return false;                /* already canceled */
489    }
490    if (job->MaxWaitTime == 0 && job->FullMaxWaitTime == 0 &&
491        job->IncMaxWaitTime == 0 && job->DiffMaxWaitTime == 0) {
492       return false;
493    } 
494    if (jcr->JobLevel == L_FULL && job->FullMaxWaitTime != 0 &&
495          (watchdog_time - jcr->start_time) >= job->FullMaxWaitTime) {
496       ok_to_cancel = true;
497    } else if (jcr->JobLevel == L_DIFFERENTIAL && job->DiffMaxWaitTime != 0 &&
498          (watchdog_time - jcr->start_time) >= job->DiffMaxWaitTime) {
499       ok_to_cancel = true;
500    } else if (jcr->JobLevel == L_INCREMENTAL && job->IncMaxWaitTime != 0 &&
501          (watchdog_time - jcr->start_time) >= job->IncMaxWaitTime) {
502       ok_to_cancel = true;
503    } else if (job->MaxWaitTime != 0 &&
504          (watchdog_time - jcr->start_time) >= job->MaxWaitTime) {
505       ok_to_cancel = true;
506    }
507    if (!ok_to_cancel) {
508       return false;
509    }
510
511 /*
512  * I don't see the need for all this -- kes 17Dec06
513  */
514 #ifdef xxx
515    Dmsg3(800, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
516          "checking status\n",
517          jcr->JobId, jcr->Job, job->MaxWaitTime);
518    switch (jcr->JobStatus) {
519    case JS_Created:
520    case JS_Blocked:
521    case JS_WaitFD:
522    case JS_WaitSD:
523    case JS_WaitStoreRes:
524    case JS_WaitClientRes:
525    case JS_WaitJobRes:
526    case JS_WaitPriority:
527    case JS_WaitMaxJobs:
528    case JS_WaitStartTime:
529       cancel = true;
530       Dmsg0(200, "JCR blocked in #1\n");
531       break;
532    case JS_Running:
533       Dmsg0(800, "JCR running, checking SD status\n");
534       switch (jcr->SDJobStatus) {
535       case JS_WaitMount:
536       case JS_WaitMedia:
537       case JS_WaitFD:
538          cancel = true;
539          Dmsg0(800, "JCR blocked in #2\n");
540          break;
541       default:
542          Dmsg0(800, "JCR not blocked in #2\n");
543          break;
544       }
545       break;
546    case JS_Terminated:
547    case JS_ErrorTerminated:
548    case JS_Canceled:
549    case JS_FatalError:
550       Dmsg0(800, "JCR already dead in #3\n");
551       break;
552    default:
553       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
554             jcr->JobStatus);
555    }
556    Dmsg3(800, "MaxWaitTime result: %scancel JCR %p (%s)\n",
557          cancel ? "" : "do not ", jcr, jcr->job);
558 #endif
559    return cancel;
560 }
561
562 /*
563  * Check if maxruntime has expired and if the job can be
564  *   canceled.
565  */
566 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
567 {
568    bool cancel = false;
569
570    if (jcr->job->MaxRunTime == 0 || job_canceled(jcr)) {
571       return false;
572    }
573    if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
574       Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
575             jcr, jcr->Job, jcr->job->MaxRunTime);
576       return false;
577    }
578
579 #ifdef xxx
580    switch (jcr->JobStatus) {
581    case JS_Created:
582    case JS_Running:
583    case JS_Blocked:
584    case JS_WaitFD:
585    case JS_WaitSD:
586    case JS_WaitStoreRes:
587    case JS_WaitClientRes:
588    case JS_WaitJobRes:
589    case JS_WaitPriority:
590    case JS_WaitMaxJobs:
591    case JS_WaitStartTime:
592    case JS_Differences:
593       cancel = true;
594       break;
595    case JS_Terminated:
596    case JS_ErrorTerminated:
597    case JS_Canceled:
598    case JS_FatalError:
599       cancel = false;
600       break;
601    default:
602       Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
603             jcr->JobStatus);
604    }
605
606    Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
607          cancel ? "" : "do not ", jcr, jcr->job);
608 #endif
609    return cancel;
610 }
611
612 /*
613  * Get or create a Pool record with the given name.
614  * Returns: 0 on error
615  *          poolid if OK
616  */
617 DBId_t get_or_create_pool_record(JCR *jcr, char *pool_name)
618 {
619    POOL_DBR pr;
620
621    memset(&pr, 0, sizeof(pr));
622    bstrncpy(pr.Name, pool_name, sizeof(pr.Name));
623    Dmsg1(010, "get_or_create_pool=%s\n", pool_name);
624
625    while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
626       /* Try to create the pool */
627       if (create_pool(jcr, jcr->db, jcr->pool, POOL_OP_CREATE) < 0) {
628          Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name,
629             db_strerror(jcr->db));
630          return 0;
631       } else {
632          Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
633       }
634    }
635    return pr.PoolId;
636 }
637
638 void apply_pool_overrides(JCR *jcr)
639 {
640    if (jcr->run_pool_override) {
641       pm_strcpy(jcr->pool_source, _("Run pool override"));
642    }
643    /*
644     * Apply any level related Pool selections
645     */
646    switch (jcr->JobLevel) {
647    case L_FULL:
648       if (jcr->full_pool) {
649          jcr->pool = jcr->full_pool;
650          if (jcr->run_full_pool_override) {
651             pm_strcpy(jcr->pool_source, _("Run FullPool override"));
652          } else {
653             pm_strcpy(jcr->pool_source, _("Job FullPool override"));
654          }
655       }
656       break;
657    case L_INCREMENTAL:
658       if (jcr->inc_pool) {
659          jcr->pool = jcr->inc_pool;
660          if (jcr->run_inc_pool_override) {
661             pm_strcpy(jcr->pool_source, _("Run IncPool override"));
662          } else {
663             pm_strcpy(jcr->pool_source, _("Job IncPool override"));
664          }
665       }
666       break;
667    case L_DIFFERENTIAL:
668       if (jcr->diff_pool) {
669          jcr->pool = jcr->diff_pool;
670          if (jcr->run_diff_pool_override) {
671             pm_strcpy(jcr->pool_source, _("Run DiffPool override"));
672          } else {
673             pm_strcpy(jcr->pool_source, _("Job DiffPool override"));
674          }
675       }
676       break;
677    }
678 }
679
680
681 /*
682  * Get or create a Client record for this Job
683  */
684 bool get_or_create_client_record(JCR *jcr)
685 {
686    CLIENT_DBR cr;
687
688    memset(&cr, 0, sizeof(cr));
689    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
690    cr.AutoPrune = jcr->client->AutoPrune;
691    cr.FileRetention = jcr->client->FileRetention;
692    cr.JobRetention = jcr->client->JobRetention;
693    if (!jcr->client_name) {
694       jcr->client_name = get_pool_memory(PM_NAME);
695    }
696    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
697    if (!db_create_client_record(jcr, jcr->db, &cr)) {
698       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
699          db_strerror(jcr->db));
700       return false;
701    }
702    jcr->jr.ClientId = cr.ClientId;
703    if (cr.Uname[0]) {
704       if (!jcr->client_uname) {
705          jcr->client_uname = get_pool_memory(PM_NAME);
706       }
707       pm_strcpy(jcr->client_uname, cr.Uname);
708    }
709    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
710       jcr->jr.ClientId);
711    return true;
712 }
713
714 bool get_or_create_fileset_record(JCR *jcr)
715 {
716    FILESET_DBR fsr;
717    /*
718     * Get or Create FileSet record
719     */
720    memset(&fsr, 0, sizeof(FILESET_DBR));
721    bstrncpy(fsr.FileSet, jcr->fileset->hdr.name, sizeof(fsr.FileSet));
722    if (jcr->fileset->have_MD5) {
723       struct MD5Context md5c;
724       unsigned char digest[MD5HashSize];
725       memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
726       MD5Final(digest, &md5c);
727       /*
728        * Keep the flag (last arg) set to false otherwise old FileSets will
729        * get new MD5 sums and the user will get Full backups on everything
730        */
731       bin_to_base64(fsr.MD5, sizeof(fsr.MD5), (char *)digest, MD5HashSize, false);
732       bstrncpy(jcr->fileset->MD5, fsr.MD5, sizeof(jcr->fileset->MD5));
733    } else {
734       Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 digest not found.\n"));
735    }
736    if (!jcr->fileset->ignore_fs_changes ||
737        !db_get_fileset_record(jcr, jcr->db, &fsr)) {
738       if (!db_create_fileset_record(jcr, jcr->db, &fsr)) {
739          Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
740             fsr.FileSet, db_strerror(jcr->db));
741          return false;
742       }
743    }
744    jcr->jr.FileSetId = fsr.FileSetId;
745    bstrncpy(jcr->FSCreateTime, fsr.cCreateTime, sizeof(jcr->FSCreateTime));
746    Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
747       jcr->jr.FileSetId);
748    return true;
749 }
750
751 void init_jcr_job_record(JCR *jcr)
752 {
753    jcr->jr.SchedTime = jcr->sched_time;
754    jcr->jr.StartTime = jcr->start_time;
755    jcr->jr.EndTime = 0;               /* perhaps rescheduled, clear it */
756    jcr->jr.JobType = jcr->JobType;
757    jcr->jr.JobLevel = jcr->JobLevel;
758    jcr->jr.JobStatus = jcr->JobStatus;
759    jcr->jr.JobId = jcr->JobId;
760    bstrncpy(jcr->jr.Name, jcr->job->name(), sizeof(jcr->jr.Name));
761    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
762 }
763
764 /*
765  * Write status and such in DB
766  */
767 void update_job_end_record(JCR *jcr)
768 {
769    jcr->jr.EndTime = time(NULL);
770    jcr->end_time = jcr->jr.EndTime;
771    jcr->jr.JobId = jcr->JobId;
772    jcr->jr.JobStatus = jcr->JobStatus;
773    jcr->jr.JobFiles = jcr->JobFiles;
774    jcr->jr.JobBytes = jcr->JobBytes;
775    jcr->jr.VolSessionId = jcr->VolSessionId;
776    jcr->jr.VolSessionTime = jcr->VolSessionTime;
777    jcr->jr.JobErrors = jcr->Errors;
778    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
779       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
780          db_strerror(jcr->db));
781    }
782 }
783
784 /*
785  * Takes base_name and appends (unique) current
786  *   date and time to form unique job name.
787  *
788  *  Returns: unique job name in jcr->Job
789  *    date/time in jcr->start_time
790  */
791 void create_unique_job_name(JCR *jcr, const char *base_name)
792 {
793    /* Job start mutex */
794    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
795    static time_t last_start_time = 0;
796    time_t now;
797    struct tm tm;
798    char dt[MAX_TIME_LENGTH];
799    char name[MAX_NAME_LENGTH];
800    char *p;
801
802    /* Guarantee unique start time -- maximum one per second, and
803     * thus unique Job Name
804     */
805    P(mutex);                          /* lock creation of jobs */
806    now = time(NULL);
807    while (now == last_start_time) {
808       bmicrosleep(0, 500000);
809       now = time(NULL);
810    }
811    last_start_time = now;
812    V(mutex);                          /* allow creation of jobs */
813    jcr->start_time = now;
814    /* Form Unique JobName */
815    (void)localtime_r(&now, &tm);
816    /* Use only characters that are permitted in Windows filenames */
817    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
818    bstrncpy(name, base_name, sizeof(name));
819    name[sizeof(name)-22] = 0;          /* truncate if too long */
820    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
821    /* Convert spaces into underscores */
822    for (p=jcr->Job; *p; p++) {
823       if (*p == ' ') {
824          *p = '_';
825       }
826    }
827 }
828
829 /* Called directly from job rescheduling */
830 void dird_free_jcr_pointers(JCR *jcr)
831 {
832    if (jcr->sd_auth_key) {
833       free(jcr->sd_auth_key);
834       jcr->sd_auth_key = NULL;
835    }
836    if (jcr->where) {
837       free(jcr->where);
838       jcr->where = NULL;
839    }
840    if (jcr->file_bsock) {
841       Dmsg0(200, "Close File bsock\n");
842       bnet_close(jcr->file_bsock);
843       jcr->file_bsock = NULL;
844    }
845    if (jcr->store_bsock) {
846       Dmsg0(200, "Close Store bsock\n");
847       bnet_close(jcr->store_bsock);
848       jcr->store_bsock = NULL;
849    }
850    if (jcr->fname) {
851       Dmsg0(200, "Free JCR fname\n");
852       free_pool_memory(jcr->fname);
853       jcr->fname = NULL;
854    }
855    if (jcr->stime) {
856       Dmsg0(200, "Free JCR stime\n");
857       free_pool_memory(jcr->stime);
858       jcr->stime = NULL;
859    }
860    if (jcr->RestoreBootstrap) {
861       free(jcr->RestoreBootstrap);
862       jcr->RestoreBootstrap = NULL;
863    }
864    if (jcr->client_uname) {
865       free_pool_memory(jcr->client_uname);
866       jcr->client_uname = NULL;
867    }
868    if (jcr->attr) {
869       free_pool_memory(jcr->attr);
870       jcr->attr = NULL;
871    }
872    if (jcr->ar) {
873       free(jcr->ar);
874       jcr->ar = NULL;
875    }
876 }
877
878 /*
879  * Free the Job Control Record if no one is still using it.
880  *  Called from main free_jcr() routine in src/lib/jcr.c so
881  *  that we can do our Director specific cleanup of the jcr.
882  */
883 void dird_free_jcr(JCR *jcr)
884 {
885    Dmsg0(200, "Start dird free_jcr\n");
886
887    dird_free_jcr_pointers(jcr);
888    if (jcr->term_wait_inited) {
889       pthread_cond_destroy(&jcr->term_wait);
890       jcr->term_wait_inited = false;
891    }
892    if (jcr->fname) {
893       Dmsg0(200, "Free JCR fname\n");
894       free_pool_memory(jcr->fname);
895       jcr->fname = NULL;
896    }
897    if (jcr->pool_source) {
898       free_pool_memory(jcr->pool_source);
899       jcr->pool_source = NULL;
900    }
901    if (jcr->rpool_source) {
902       free_pool_memory(jcr->rpool_source);
903       jcr->rpool_source = NULL;
904    }
905    if (jcr->wstore_source) {
906       free_pool_memory(jcr->wstore_source);
907       jcr->wstore_source = NULL;
908    }
909    if (jcr->rstore_source) {
910       free_pool_memory(jcr->rstore_source);
911       jcr->rstore_source = NULL;
912    }
913
914    /* Delete lists setup to hold storage pointers */
915    free_rwstorage(jcr);
916
917    jcr->job_end_push.destroy();
918    Dmsg0(200, "End dird free_jcr\n");
919 }
920
921 /* 
922  * The Job storage definition must be either in the Job record
923  *  or in the Pool record.  The Pool record overrides the Job 
924  *  record.
925  */
926 void get_job_storage(USTORE *store, JOB *job, RUN *run) 
927 {
928    if (run && run->pool && run->pool->storage) {
929       store->store = (STORE *)run->pool->storage->first();
930       pm_strcpy(store->store_source, _("Run pool override"));
931       return;
932    }
933    if (run && run->storage) {
934       store->store = run->storage;
935       pm_strcpy(store->store_source, _("Run storage override"));
936       return;
937    }
938    if (job->pool->storage) {
939       store->store = (STORE *)job->pool->storage->first();
940       pm_strcpy(store->store_source, _("Pool resource"));
941    } else {
942       store->store = (STORE *)job->storage->first();
943       pm_strcpy(store->store_source, _("Job resource"));
944    }
945 }
946
947 /*
948  * Set some defaults in the JCR necessary to
949  * run. These items are pulled from the job
950  * definition as defaults, but can be overridden
951  * later either by the Run record in the Schedule resource,
952  * or by the Console program.
953  */
954 void set_jcr_defaults(JCR *jcr, JOB *job)
955 {
956    jcr->job = job;
957    jcr->JobType = job->JobType;
958    switch (jcr->JobType) {
959    case JT_ADMIN:
960    case JT_RESTORE:
961       jcr->JobLevel = L_NONE;
962       break;
963    case JT_MIGRATE:
964       if (!jcr->rpool_source) {
965          jcr->rpool_source = get_pool_memory(PM_MESSAGE);
966          pm_strcpy(jcr->rpool_source, _("unknown source"));
967       }
968       /* Fall-through wanted */
969    default:
970       jcr->JobLevel = job->JobLevel;
971       break;
972    }
973    if (!jcr->fname) {
974       jcr->fname = get_pool_memory(PM_FNAME);
975    }
976    if (!jcr->pool_source) {
977       jcr->pool_source = get_pool_memory(PM_MESSAGE);
978       pm_strcpy(jcr->pool_source, _("unknown source"));
979    }
980
981    jcr->JobPriority = job->Priority;
982    /* Copy storage definitions -- deleted in dir_free_jcr above */
983    if (job->storage) {
984       copy_rwstorage(jcr, job->storage, _("Job resource"));
985    } else {
986       copy_rwstorage(jcr, job->pool->storage, _("Pool resource"));
987    }
988    jcr->client = job->client;
989    if (!jcr->client_name) {
990       jcr->client_name = get_pool_memory(PM_NAME);
991    }
992    pm_strcpy(jcr->client_name, jcr->client->hdr.name);
993    pm_strcpy(jcr->pool_source, _("Job resource"));
994    jcr->pool = job->pool;
995    jcr->full_pool = job->full_pool;
996    jcr->inc_pool = job->inc_pool;
997    jcr->diff_pool = job->diff_pool;
998    jcr->catalog = job->client->catalog;
999    jcr->fileset = job->fileset;
1000    jcr->messages = job->messages;
1001    jcr->spool_data = job->spool_data;
1002    jcr->write_part_after_job = job->write_part_after_job;
1003    if (jcr->RestoreBootstrap) {
1004       free(jcr->RestoreBootstrap);
1005       jcr->RestoreBootstrap = NULL;
1006    }
1007    /* This can be overridden by Console program */
1008    if (job->RestoreBootstrap) {
1009       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
1010    }
1011    /* This can be overridden by Console program */
1012    jcr->verify_job = job->verify_job;
1013    /* If no default level given, set one */
1014    if (jcr->JobLevel == 0) {
1015       switch (jcr->JobType) {
1016       case JT_VERIFY:
1017          jcr->JobLevel = L_VERIFY_CATALOG;
1018          break;
1019       case JT_BACKUP:
1020          jcr->JobLevel = L_INCREMENTAL;
1021          break;
1022       case JT_RESTORE:
1023       case JT_ADMIN:
1024          jcr->JobLevel = L_NONE;
1025          break;
1026       default:
1027          jcr->JobLevel = L_FULL;
1028          break;
1029       }
1030    }
1031 }
1032
1033 /* 
1034  * Copy the storage definitions from an alist to the JCR
1035  */
1036 void copy_rwstorage(JCR *jcr, alist *storage, const char *where)
1037 {
1038    switch(jcr->JobType) {
1039    case JT_RESTORE:
1040    case JT_VERIFY:
1041    case JT_MIGRATE:
1042       copy_rstorage(jcr, storage, where);
1043       break;
1044    default:
1045       copy_wstorage(jcr, storage, where);
1046       break;
1047    }
1048 }
1049
1050
1051 /* Set storage override */
1052 void set_rwstorage(JCR *jcr, USTORE *store)
1053 {
1054    if (!store) {
1055       Jmsg(jcr, M_FATAL, 0, _("No storage specified.\n"));
1056       return;
1057    }
1058    switch(jcr->JobType) {
1059    case JT_RESTORE:
1060    case JT_VERIFY:
1061    case JT_MIGRATE:
1062       set_rstorage(jcr, store);
1063       break;
1064    default:
1065       set_wstorage(jcr, store);
1066       break;
1067    }
1068 }
1069
1070 void free_rwstorage(JCR *jcr)
1071 {
1072    free_rstorage(jcr);
1073    free_wstorage(jcr);
1074 }
1075
1076 /* 
1077  * Copy the storage definitions from an alist to the JCR
1078  */
1079 void copy_rstorage(JCR *jcr, alist *storage, const char *where)
1080 {
1081    if (storage) {
1082       STORE *st;
1083       if (jcr->rstorage) {
1084          delete jcr->rstorage;
1085       }
1086       jcr->rstorage = New(alist(10, not_owned_by_alist));
1087       foreach_alist(st, storage) {
1088          jcr->rstorage->append(st);
1089       }
1090       if (!jcr->rstore_source) {
1091          jcr->rstore_source = get_pool_memory(PM_MESSAGE);
1092       }
1093       pm_strcpy(jcr->rstore_source, where);
1094       if (jcr->rstorage) {
1095          jcr->rstore = (STORE *)jcr->rstorage->first();
1096       }
1097    }
1098 }
1099
1100
1101 /* Set storage override */
1102 void set_rstorage(JCR *jcr, USTORE *store)
1103 {
1104    STORE *storage;
1105
1106    if (!store->store) {
1107       return;
1108    }
1109    if (!jcr->rstorage) {
1110       jcr->rstorage = New(alist(10, not_owned_by_alist));
1111    }
1112    jcr->rstore = store->store;
1113    if (!jcr->rstore_source) {
1114       jcr->rstore_source = get_pool_memory(PM_MESSAGE);
1115    }
1116    pm_strcpy(jcr->rstore_source, store->store_source);
1117    foreach_alist(storage, jcr->rstorage) {
1118       if (store->store == storage) {
1119          return;
1120       }
1121    }
1122    /* Store not in list, so add it */
1123    jcr->rstorage->prepend(store->store);
1124 }
1125
1126 void free_rstorage(JCR *jcr)
1127 {
1128    if (jcr->rstorage) {
1129       delete jcr->rstorage;
1130       jcr->rstorage = NULL;
1131    }
1132    jcr->rstore = NULL;
1133 }
1134
1135 /* 
1136  * Copy the storage definitions from an alist to the JCR
1137  */
1138 void copy_wstorage(JCR *jcr, alist *storage, const char *where)
1139 {
1140    if (storage) {
1141       STORE *st;
1142       if (jcr->wstorage) {
1143          delete jcr->wstorage;
1144       }
1145       jcr->wstorage = New(alist(10, not_owned_by_alist));
1146       foreach_alist(st, storage) {
1147          Dmsg1(50, "storage=%s\n", st->name());
1148          jcr->wstorage->append(st);
1149       }
1150       if (!jcr->wstore_source) {
1151          jcr->wstore_source = get_pool_memory(PM_MESSAGE);
1152       }
1153       pm_strcpy(jcr->wstore_source, where);
1154       if (jcr->wstorage) {
1155          jcr->wstore = (STORE *)jcr->wstorage->first();
1156          Dmsg2(100, "wstore=%s where=%s\n", jcr->wstore->name(), jcr->wstore_source);
1157       }
1158    }
1159 }
1160
1161
1162 /* Set storage override */
1163 void set_wstorage(JCR *jcr, USTORE *store)
1164 {
1165    STORE *storage;
1166
1167    if (!store->store) {
1168       return;
1169    }
1170    if (!jcr->wstorage) {
1171       jcr->wstorage = New(alist(10, not_owned_by_alist));
1172    }
1173    jcr->wstore = store->store;
1174    if (!jcr->wstore_source) {
1175       jcr->wstore_source = get_pool_memory(PM_MESSAGE);
1176    }
1177    pm_strcpy(jcr->wstore_source, store->store_source);
1178    Dmsg2(50, "wstore=%s where=%s\n", jcr->wstore->name(), jcr->wstore_source);
1179    foreach_alist(storage, jcr->wstorage) {
1180       if (store->store == storage) {
1181          return;
1182       }
1183    }
1184    /* Store not in list, so add it */
1185    jcr->wstorage->prepend(store->store);
1186 }
1187
1188 void free_wstorage(JCR *jcr)
1189 {
1190    if (jcr->wstorage) {
1191       delete jcr->wstorage;
1192       jcr->wstorage = NULL;
1193    }
1194    jcr->wstore = NULL;
1195 }
1196
1197 void create_clones(JCR *jcr)
1198 {
1199    /*
1200     * Fire off any clone jobs (run directives)
1201     */
1202    Dmsg2(900, "cloned=%d run_cmds=%p\n", jcr->cloned, jcr->job->run_cmds);
1203    if (!jcr->cloned && jcr->job->run_cmds) {
1204       char *runcmd;
1205       JOB *job = jcr->job;
1206       POOLMEM *cmd = get_pool_memory(PM_FNAME);
1207       UAContext *ua = new_ua_context(jcr);
1208       ua->batch = true;
1209       foreach_alist(runcmd, job->run_cmds) {
1210          cmd = edit_job_codes(jcr, cmd, runcmd, "");              
1211          Mmsg(ua->cmd, "run %s cloned=yes", cmd);
1212          Dmsg1(900, "=============== Clone cmd=%s\n", ua->cmd);
1213          parse_ua_args(ua);                 /* parse command */
1214          int stat = run_cmd(ua, ua->cmd);
1215          if (stat == 0) {
1216             Jmsg(jcr, M_ERROR, 0, _("Could not start clone job.\n"));
1217          } else {
1218             Jmsg(jcr, M_INFO, 0, _("Clone JobId %d started.\n"), stat);
1219          }
1220       }
1221       free_ua_context(ua);
1222       free_pool_memory(cmd);
1223    }
1224 }
1225
1226 bool create_restore_bootstrap_file(JCR *jcr)
1227 {
1228    RESTORE_CTX rx;
1229    UAContext *ua;
1230    memset(&rx, 0, sizeof(rx));
1231    rx.bsr = new_bsr();
1232    rx.JobIds = "";                       
1233    rx.bsr->JobId = jcr->previous_jr.JobId;
1234    ua = new_ua_context(jcr);
1235    complete_bsr(ua, rx.bsr);
1236    rx.bsr->fi = new_findex();
1237    rx.bsr->fi->findex = 1;
1238    rx.bsr->fi->findex2 = jcr->previous_jr.JobFiles;
1239    jcr->ExpectedFiles = write_bsr_file(ua, rx);
1240    if (jcr->ExpectedFiles == 0) {
1241       free_ua_context(ua);
1242       free_bsr(rx.bsr);
1243       return false;
1244    }
1245    free_ua_context(ua);
1246    free_bsr(rx.bsr);
1247    jcr->needs_sd = true;
1248    return true;
1249 }