3 * Bacula Director Job processing routines
5 * Kern Sibbald, October MM
10 Copyright (C) 2000-2004 Kern Sibbald and John Walker
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.
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.
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,
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);
39 /* Exported subroutines */
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 int do_verify(JCR *jcr);
50 /* Imported variables */
51 extern time_t watchdog_time;
55 void init_job_server(int max_workers)
60 if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
62 Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.strerror(stat));
64 if ((wd = new_watchdog()) == NULL) {
65 Emsg0(M_ABORT, 0, _("Could not init job monitor watchdogs\n"));
67 wd->callback = job_monitor_watchdog;
68 wd->destructor = job_monitor_destructor;
71 wd->data = new_control_jcr("*JobMonitor*", JT_SYSTEM);
72 register_watchdog(wd);
75 void term_job_server()
77 jobq_destroy(&job_queue); /* ignore any errors */
81 * Run a job -- typically called by the scheduler, but may also
82 * be called by the UA (Console program).
84 * Returns: 0 on failure
88 JobId_t run_job(JCR *jcr)
94 sm_check(__FILE__, __LINE__, true);
95 init_msg(jcr, jcr->messages);
97 /* Initialize termination condition variable */
98 if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
100 Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(errstat));
103 jcr->term_wait_inited = true;
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);
117 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
121 Dmsg0(50, "DB opened\n");
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));
133 JobId = jcr->JobId = jcr->jr.JobId;
135 Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
136 jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
137 Dmsg0(200, "Add jrc to work queue\n");
139 /* Queue the job to be run */
140 if ((stat = jobq_add(&job_queue, jcr)) != 0) {
142 Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror(stat));
146 Dmsg0(100, "Done run_job()\n");
152 set_jcr_job_status(jcr, JS_ErrorTerminated);
160 * This is the engine called by jobq.c:jobq_add() when we were pulled
161 * from the work queue.
162 * At this point, we are running in our own thread and all
163 * necessary resources are allocated -- see jobq.c
165 static void *job_thread(void *arg)
167 JCR *jcr = (JCR *)arg;
169 jcr->my_thread_id = pthread_self();
170 pthread_detach(jcr->my_thread_id);
171 sm_check(__FILE__, __LINE__, true);
174 Dmsg0(200, "=====Start Job=========\n");
175 jcr->start_time = time(NULL); /* set the real start time */
176 set_jcr_job_status(jcr, JS_Running);
178 if (job_canceled(jcr)) {
179 update_job_end_record(jcr);
180 } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
181 (utime_t)(jcr->start_time - jcr->sched_time)) {
182 Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
183 set_jcr_job_status(jcr, JS_Canceled);
184 update_job_end_record(jcr);
188 if (jcr->job->RunBeforeJob) {
189 POOLMEM *before = get_pool_memory(PM_FNAME);
192 char line[MAXSTRING];
194 before = edit_job_codes(jcr, before, jcr->job->RunBeforeJob, "");
195 bpipe = open_bpipe(before, 0, "r");
196 free_pool_memory(before);
197 while (fgets(line, sizeof(line), bpipe->rfd)) {
198 Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
200 status = close_bpipe(bpipe);
203 Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob error: ERR=%s\n"), be.strerror(status));
204 set_jcr_job_status(jcr, JS_FatalError);
205 update_job_end_record(jcr);
209 switch (jcr->JobType) {
212 if (jcr->JobStatus == JS_Terminated) {
218 if (jcr->JobStatus == JS_Terminated) {
224 if (jcr->JobStatus == JS_Terminated) {
230 if (jcr->JobStatus == JS_Terminated) {
237 do_mac(jcr); /* migration, archive, copy */
238 if (jcr->JobStatus == JS_Terminated) {
243 Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
246 if ((jcr->job->RunAfterJob && jcr->JobStatus == JS_Terminated) ||
247 (jcr->job->RunAfterFailedJob && jcr->JobStatus != JS_Terminated)) {
248 POOLMEM *after = get_pool_memory(PM_FNAME);
251 char line[MAXSTRING];
253 if (jcr->JobStatus == JS_Terminated) {
254 after = edit_job_codes(jcr, after, jcr->job->RunAfterJob, "");
256 after = edit_job_codes(jcr, after, jcr->job->RunAfterFailedJob, "");
258 bpipe = open_bpipe(after, 0, "r");
259 free_pool_memory(after);
260 while (fgets(line, sizeof(line), bpipe->rfd)) {
261 Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
263 status = close_bpipe(bpipe);
265 * Note, if we get an error here, do not mark the
266 * job in error, simply report the error condition.
270 if (jcr->JobStatus == JS_Terminated) {
271 Jmsg(jcr, M_WARNING, 0, _("RunAfterJob error: ERR=%s\n"), be.strerror(status));
273 Jmsg(jcr, M_FATAL, 0, _("RunAfterFailedJob error: ERR=%s\n"), be.strerror(status));
277 /* Send off any queued messages */
278 if (jcr->msg_queue->size() > 0) {
279 dequeue_messages(jcr);
286 Dmsg0(50, "======== End Job ==========\n");
287 sm_check(__FILE__, __LINE__, true);
293 * Cancel a job -- typically called by the UA (Console program), but may also
294 * be called by the job watchdog.
296 * Returns: 1 if cancel appears to be successful
297 * 0 on failure. Message sent to ua->jcr.
299 int cancel_job(UAContext *ua, JCR *jcr)
303 switch (jcr->JobStatus) {
306 case JS_WaitClientRes:
307 case JS_WaitStoreRes:
308 case JS_WaitPriority:
310 case JS_WaitStartTime:
311 set_jcr_job_status(jcr, JS_Canceled);
312 bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
313 jcr->JobId, jcr->Job);
314 jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
318 set_jcr_job_status(jcr, JS_Canceled);
320 /* Cancel File daemon */
321 if (jcr->file_bsock) {
322 ua->jcr->client = jcr->client;
323 if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
324 bsendmsg(ua, _("Failed to connect to File daemon.\n"));
327 Dmsg0(200, "Connected to file daemon\n");
328 fd = ua->jcr->file_bsock;
329 bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
330 while (bnet_recv(fd) >= 0) {
331 bsendmsg(ua, "%s", fd->msg);
333 bnet_sig(fd, BNET_TERMINATE);
335 ua->jcr->file_bsock = NULL;
338 /* Cancel Storage daemon */
339 if (jcr->store_bsock) {
340 ua->jcr->store = jcr->store;
341 for (int i=0; i<MAX_STORE; i++) {
342 ua->jcr->storage[i] = jcr->storage[i];
344 if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
345 bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
348 Dmsg0(200, "Connected to storage daemon\n");
349 sd = ua->jcr->store_bsock;
350 bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
351 while (bnet_recv(sd) >= 0) {
352 bsendmsg(ua, "%s", sd->msg);
354 bnet_sig(sd, BNET_TERMINATE);
356 ua->jcr->store_bsock = NULL;
364 static void job_monitor_destructor(watchdog_t *self)
366 JCR *control_jcr = (JCR *) self->data;
368 free_jcr(control_jcr);
371 static void job_monitor_watchdog(watchdog_t *self)
373 JCR *control_jcr, *jcr;
375 control_jcr = (JCR *)self->data;
377 Dmsg1(400, "job_monitor_watchdog %p called\n", self);
384 if (jcr->JobId == 0) {
385 Dmsg2(400, "Skipping JCR %p (%s) with JobId 0\n",
387 /* Keep reference counts correct */
388 free_locked_jcr(jcr);
392 /* check MaxWaitTime */
393 cancel = job_check_maxwaittime(control_jcr, jcr);
395 /* check MaxRunTime */
396 cancel |= job_check_maxruntime(control_jcr, jcr);
399 Dmsg3(200, "Cancelling JCR %p jobid %d (%s)\n",
400 jcr, jcr->JobId, jcr->Job);
402 UAContext *ua = new_ua_context(jcr);
403 ua->jcr = control_jcr;
407 Dmsg1(200, "Have cancelled JCR %p\n", jcr);
410 /* Keep reference counts correct */
411 free_locked_jcr(jcr);
417 * Check if the maxwaittime has expired and it is possible
420 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
424 if (jcr->job->MaxWaitTime == 0) {
427 if ((watchdog_time - jcr->start_time) < jcr->job->MaxWaitTime) {
428 Dmsg3(200, "Job %p (%s) with MaxWaitTime %d not expired\n",
429 jcr, jcr->Job, jcr->job->MaxWaitTime);
432 Dmsg3(200, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
434 jcr->JobId, jcr->Job, jcr->job->MaxWaitTime);
435 switch (jcr->JobStatus) {
440 case JS_WaitStoreRes:
441 case JS_WaitClientRes:
443 case JS_WaitPriority:
445 case JS_WaitStartTime:
447 Dmsg0(200, "JCR blocked in #1\n");
450 Dmsg0(200, "JCR running, checking SD status\n");
451 switch (jcr->SDJobStatus) {
456 Dmsg0(200, "JCR blocked in #2\n");
459 Dmsg0(200, "JCR not blocked in #2\n");
464 case JS_ErrorTerminated:
467 Dmsg0(200, "JCR already dead in #3\n");
470 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
473 Dmsg3(200, "MaxWaitTime result: %scancel JCR %p (%s)\n",
474 cancel ? "" : "do not ", jcr, jcr->job);
480 * Check if maxruntime has expired and if the job can be
483 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
487 if (jcr->job->MaxRunTime == 0) {
490 if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
491 Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
492 jcr, jcr->Job, jcr->job->MaxRunTime);
496 switch (jcr->JobStatus) {
502 case JS_WaitStoreRes:
503 case JS_WaitClientRes:
505 case JS_WaitPriority:
507 case JS_WaitStartTime:
512 case JS_ErrorTerminated:
518 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
522 Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
523 cancel ? "" : "do not ", jcr, jcr->job);
530 * Get or create a Client record for this Job
532 bool get_or_create_client_record(JCR *jcr)
536 memset(&cr, 0, sizeof(cr));
537 bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
538 cr.AutoPrune = jcr->client->AutoPrune;
539 cr.FileRetention = jcr->client->FileRetention;
540 cr.JobRetention = jcr->client->JobRetention;
541 if (!jcr->client_name) {
542 jcr->client_name = get_pool_memory(PM_NAME);
544 pm_strcpy(jcr->client_name, jcr->client->hdr.name);
545 if (!db_create_client_record(jcr, jcr->db, &cr)) {
546 Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
547 db_strerror(jcr->db));
550 jcr->jr.ClientId = cr.ClientId;
552 if (!jcr->client_uname) {
553 jcr->client_uname = get_pool_memory(PM_NAME);
555 pm_strcpy(jcr->client_uname, cr.Uname);
557 Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
562 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
565 * Get or Create FileSet record
567 memset(fsr, 0, sizeof(FILESET_DBR));
568 bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
569 if (jcr->fileset->have_MD5) {
570 struct MD5Context md5c;
571 unsigned char signature[16];
572 memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
573 MD5Final(signature, &md5c);
574 bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
575 bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
577 Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
579 if (!jcr->fileset->ignore_fs_changes ||
580 !db_get_fileset_record(jcr, jcr->db, fsr)) {
581 if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
582 Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
583 fsr->FileSet, db_strerror(jcr->db));
587 jcr->jr.FileSetId = fsr->FileSetId;
589 Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
590 fsr->FileSet, fsr->cCreateTime);
592 Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
597 void init_jcr_job_record(JCR *jcr)
599 jcr->jr.SchedTime = jcr->sched_time;
600 jcr->jr.StartTime = jcr->start_time;
601 jcr->jr.EndTime = 0; /* perhaps rescheduled, clear it */
602 jcr->jr.JobType = jcr->JobType;
603 jcr->jr.JobLevel = jcr->JobLevel;
604 jcr->jr.JobStatus = jcr->JobStatus;
605 jcr->jr.JobId = jcr->JobId;
606 bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
607 bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
611 * Write status and such in DB
613 void update_job_end_record(JCR *jcr)
615 jcr->jr.EndTime = time(NULL);
616 jcr->end_time = jcr->jr.EndTime;
617 jcr->jr.JobId = jcr->JobId;
618 jcr->jr.JobStatus = jcr->JobStatus;
619 jcr->jr.JobFiles = jcr->JobFiles;
620 jcr->jr.JobBytes = jcr->JobBytes;
621 jcr->jr.VolSessionId = jcr->VolSessionId;
622 jcr->jr.VolSessionTime = jcr->VolSessionTime;
623 if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
624 Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
625 db_strerror(jcr->db));
630 * Takes base_name and appends (unique) current
631 * date and time to form unique job name.
633 * Returns: unique job name in jcr->Job
634 * date/time in jcr->start_time
636 void create_unique_job_name(JCR *jcr, const char *base_name)
638 /* Job start mutex */
639 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
640 static time_t last_start_time = 0;
643 char dt[MAX_TIME_LENGTH];
644 char name[MAX_NAME_LENGTH];
647 /* Guarantee unique start time -- maximum one per second, and
648 * thus unique Job Name
650 P(mutex); /* lock creation of jobs */
652 while (now == last_start_time) {
653 bmicrosleep(0, 500000);
656 last_start_time = now;
657 V(mutex); /* allow creation of jobs */
658 jcr->start_time = now;
659 /* Form Unique JobName */
660 localtime_r(&now, &tm);
661 /* Use only characters that are permitted in Windows filenames */
662 strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
663 bstrncpy(name, base_name, sizeof(name));
664 name[sizeof(name)-22] = 0; /* truncate if too long */
665 bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
666 /* Convert spaces into underscores */
667 for (p=jcr->Job; *p; p++) {
675 * Free the Job Control Record if no one is still using it.
676 * Called from main free_jcr() routine in src/lib/jcr.c so
677 * that we can do our Director specific cleanup of the jcr.
679 void dird_free_jcr(JCR *jcr)
681 Dmsg0(200, "Start dird free_jcr\n");
683 if (jcr->sd_auth_key) {
684 free(jcr->sd_auth_key);
685 jcr->sd_auth_key = NULL;
691 if (jcr->file_bsock) {
692 Dmsg0(200, "Close File bsock\n");
693 bnet_close(jcr->file_bsock);
694 jcr->file_bsock = NULL;
696 if (jcr->store_bsock) {
697 Dmsg0(200, "Close Store bsock\n");
698 bnet_close(jcr->store_bsock);
699 jcr->store_bsock = NULL;
702 Dmsg0(200, "Free JCR fname\n");
703 free_pool_memory(jcr->fname);
707 Dmsg0(200, "Free JCR stime\n");
708 free_pool_memory(jcr->stime);
711 if (jcr->RestoreBootstrap) {
712 free(jcr->RestoreBootstrap);
713 jcr->RestoreBootstrap = NULL;
715 if (jcr->client_uname) {
716 free_pool_memory(jcr->client_uname);
717 jcr->client_uname = NULL;
719 if (jcr->term_wait_inited) {
720 pthread_cond_destroy(&jcr->term_wait);
722 jcr->job_end_push.destroy();
723 Dmsg0(200, "End dird free_jcr\n");
727 * Set some defaults in the JCR necessary to
728 * run. These items are pulled from the job
729 * definition as defaults, but can be overridden
730 * later either by the Run record in the Schedule resource,
731 * or by the Console program.
733 void set_jcr_defaults(JCR *jcr, JOB *job)
736 jcr->JobType = job->JobType;
737 switch (jcr->JobType) {
740 jcr->JobLevel = L_NONE;
743 jcr->JobLevel = job->JobLevel;
746 jcr->JobPriority = job->Priority;
747 for (int i=0; i<MAX_STORE; i++) {
748 jcr->storage[i] = job->storage[i];
750 jcr->client = job->client;
751 if (!jcr->client_name) {
752 jcr->client_name = get_pool_memory(PM_NAME);
754 pm_strcpy(jcr->client_name, jcr->client->hdr.name);
755 jcr->pool = job->pool;
756 jcr->full_pool = job->full_pool;
757 jcr->inc_pool = job->inc_pool;
758 jcr->dif_pool = job->dif_pool;
759 jcr->catalog = job->client->catalog;
760 jcr->fileset = job->fileset;
761 jcr->messages = job->messages;
762 jcr->spool_data = job->spool_data;
763 if (jcr->RestoreBootstrap) {
764 free(jcr->RestoreBootstrap);
765 jcr->RestoreBootstrap = NULL;
767 /* This can be overridden by Console program */
768 if (job->RestoreBootstrap) {
769 jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
771 /* If no default level given, set one */
772 if (jcr->JobLevel == 0) {
773 switch (jcr->JobType) {
775 jcr->JobLevel = L_VERIFY_CATALOG;
778 jcr->JobLevel = L_INCREMENTAL;
782 jcr->JobLevel = L_NONE;