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 int do_admin(JCR *jcr);
46 extern int do_restore(JCR *jcr);
47 extern int do_verify(JCR *jcr);
49 /* Imported variables */
50 extern time_t watchdog_time;
54 void init_job_server(int max_workers)
59 if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
61 Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.strerror(stat));
63 if ((wd = new_watchdog()) == NULL) {
64 Emsg0(M_ABORT, 0, _("Could not init job monitor watchdogs\n"));
66 wd->callback = job_monitor_watchdog;
67 wd->destructor = job_monitor_destructor;
70 wd->data = new_control_jcr("*JobMonitor*", JT_SYSTEM);
71 register_watchdog(wd);
74 void term_job_server()
77 if ((stat=jobq_destroy(&job_queue)) != 0) {
79 Emsg1(M_INFO, 0, _("Could not term job queue: ERR=%s\n"), be.strerror(stat));
84 * Run a job -- typically called by the scheduler, but may also
85 * be called by the UA (Console program).
87 * Returns: 0 on failure
91 JobId_t run_job(JCR *jcr)
97 sm_check(__FILE__, __LINE__, true);
98 init_msg(jcr, jcr->messages);
100 /* Initialize termination condition variable */
101 if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
103 Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(errstat));
106 jcr->term_wait_inited = true;
111 Dmsg0(50, "Open database\n");
112 jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
113 jcr->catalog->db_password, jcr->catalog->db_address,
114 jcr->catalog->db_port, jcr->catalog->db_socket);
115 if (!jcr->db || !db_open_database(jcr, jcr->db)) {
116 Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
117 jcr->catalog->db_name);
119 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
123 Dmsg0(50, "DB opened\n");
128 create_unique_job_name(jcr, jcr->job->hdr.name);
129 set_jcr_job_status(jcr, JS_Created);
130 init_jcr_job_record(jcr);
131 if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
132 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
135 JobId = jcr->JobId = jcr->jr.JobId;
137 Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
138 jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
139 Dmsg0(200, "Add jrc to work queue\n");
141 /* Queue the job to be run */
142 if ((stat = jobq_add(&job_queue, jcr)) != 0) {
144 Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror(stat));
148 Dmsg0(100, "Done run_job()\n");
154 set_jcr_job_status(jcr, JS_ErrorTerminated);
162 * This is the engine called by jobq.c:jobq_add() when we were pulled
163 * from the work queue.
164 * At this point, we are running in our own thread and all
165 * necessary resources are allocated -- see jobq.c
167 static void *job_thread(void *arg)
169 JCR *jcr = (JCR *)arg;
171 jcr->my_thread_id = pthread_self();
172 pthread_detach(jcr->my_thread_id);
173 sm_check(__FILE__, __LINE__, true);
176 Dmsg0(200, "=====Start Job=========\n");
177 jcr->start_time = time(NULL); /* set the real start time */
178 set_jcr_job_status(jcr, JS_Running);
180 if (job_canceled(jcr)) {
181 update_job_end_record(jcr);
182 } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
183 (utime_t)(jcr->start_time - jcr->sched_time)) {
184 Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
185 set_jcr_job_status(jcr, JS_Canceled);
186 update_job_end_record(jcr);
190 if (jcr->job->RunBeforeJob) {
191 POOLMEM *before = get_pool_memory(PM_FNAME);
194 char line[MAXSTRING];
196 before = edit_job_codes(jcr, before, jcr->job->RunBeforeJob, "");
197 bpipe = open_bpipe(before, 0, "r");
198 free_pool_memory(before);
199 while (fgets(line, sizeof(line), bpipe->rfd)) {
200 Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
202 status = close_bpipe(bpipe);
205 Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob error: ERR=%s\n"), be.strerror(status));
206 set_jcr_job_status(jcr, JS_FatalError);
207 update_job_end_record(jcr);
211 switch (jcr->JobType) {
214 if (jcr->JobStatus == JS_Terminated) {
220 if (jcr->JobStatus == JS_Terminated) {
226 if (jcr->JobStatus == JS_Terminated) {
232 if (jcr->JobStatus == JS_Terminated) {
237 Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
240 if ((jcr->job->RunAfterJob && jcr->JobStatus == JS_Terminated) ||
241 (jcr->job->RunAfterFailedJob && jcr->JobStatus != JS_Terminated)) {
242 POOLMEM *after = get_pool_memory(PM_FNAME);
245 char line[MAXSTRING];
247 if (jcr->JobStatus == JS_Terminated) {
248 after = edit_job_codes(jcr, after, jcr->job->RunAfterJob, "");
250 after = edit_job_codes(jcr, after, jcr->job->RunAfterFailedJob, "");
252 bpipe = open_bpipe(after, 0, "r");
253 free_pool_memory(after);
254 while (fgets(line, sizeof(line), bpipe->rfd)) {
255 Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
257 status = close_bpipe(bpipe);
259 * Note, if we get an error here, do not mark the
260 * job in error, simply report the error condition.
264 if (jcr->JobStatus == JS_Terminated) {
265 Jmsg(jcr, M_WARNING, 0, _("RunAfterJob error: ERR=%s\n"), be.strerror(status));
267 Jmsg(jcr, M_FATAL, 0, _("RunAfterFailedJob error: ERR=%s\n"), be.strerror(status));
271 /* Send off any queued messages */
272 if (jcr->msg_queue->size() > 0) {
273 dequeue_messages(jcr);
280 Dmsg0(50, "======== End Job ==========\n");
281 sm_check(__FILE__, __LINE__, true);
287 * Cancel a job -- typically called by the UA (Console program), but may also
288 * be called by the job watchdog.
290 * Returns: 1 if cancel appears to be successful
291 * 0 on failure. Message sent to ua->jcr.
293 int cancel_job(UAContext *ua, JCR *jcr)
297 switch (jcr->JobStatus) {
300 case JS_WaitClientRes:
301 case JS_WaitStoreRes:
302 case JS_WaitPriority:
304 case JS_WaitStartTime:
305 set_jcr_job_status(jcr, JS_Canceled);
306 bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
307 jcr->JobId, jcr->Job);
308 jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
312 set_jcr_job_status(jcr, JS_Canceled);
314 /* Cancel File daemon */
315 if (jcr->file_bsock) {
316 ua->jcr->client = jcr->client;
317 if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
318 bsendmsg(ua, _("Failed to connect to File daemon.\n"));
321 Dmsg0(200, "Connected to file daemon\n");
322 fd = ua->jcr->file_bsock;
323 bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
324 while (bnet_recv(fd) >= 0) {
325 bsendmsg(ua, "%s", fd->msg);
327 bnet_sig(fd, BNET_TERMINATE);
329 ua->jcr->file_bsock = NULL;
332 /* Cancel Storage daemon */
333 if (jcr->store_bsock) {
334 ua->jcr->store = jcr->store;
335 if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
336 bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
339 Dmsg0(200, "Connected to storage daemon\n");
340 sd = ua->jcr->store_bsock;
341 bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
342 while (bnet_recv(sd) >= 0) {
343 bsendmsg(ua, "%s", sd->msg);
345 bnet_sig(sd, BNET_TERMINATE);
347 ua->jcr->store_bsock = NULL;
355 static void job_monitor_destructor(watchdog_t *self)
357 JCR *control_jcr = (JCR *) self->data;
359 free_jcr(control_jcr);
362 static void job_monitor_watchdog(watchdog_t *self)
364 JCR *control_jcr, *jcr;
366 control_jcr = (JCR *)self->data;
368 Dmsg1(400, "job_monitor_watchdog %p called\n", self);
375 if (jcr->JobId == 0) {
376 Dmsg2(400, "Skipping JCR %p (%s) with JobId 0\n",
378 /* Keep reference counts correct */
379 free_locked_jcr(jcr);
383 /* check MaxWaitTime */
384 cancel = job_check_maxwaittime(control_jcr, jcr);
386 /* check MaxRunTime */
387 cancel |= job_check_maxruntime(control_jcr, jcr);
390 Dmsg3(200, "Cancelling JCR %p jobid %d (%s)\n",
391 jcr, jcr->JobId, jcr->Job);
393 UAContext *ua = new_ua_context(jcr);
394 ua->jcr = control_jcr;
398 Dmsg1(200, "Have cancelled JCR %p\n", jcr);
401 /* Keep reference counts correct */
402 free_locked_jcr(jcr);
408 * Check if the maxwaittime has expired and it is possible
411 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
415 if (jcr->job->MaxWaitTime == 0) {
418 if ((watchdog_time - jcr->start_time) < jcr->job->MaxWaitTime) {
419 Dmsg3(200, "Job %p (%s) with MaxWaitTime %d not expired\n",
420 jcr, jcr->Job, jcr->job->MaxWaitTime);
423 Dmsg3(200, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
425 jcr->JobId, jcr->Job, jcr->job->MaxWaitTime);
426 switch (jcr->JobStatus) {
431 case JS_WaitStoreRes:
432 case JS_WaitClientRes:
434 case JS_WaitPriority:
436 case JS_WaitStartTime:
438 Dmsg0(200, "JCR blocked in #1\n");
441 Dmsg0(200, "JCR running, checking SD status\n");
442 switch (jcr->SDJobStatus) {
447 Dmsg0(200, "JCR blocked in #2\n");
450 Dmsg0(200, "JCR not blocked in #2\n");
455 case JS_ErrorTerminated:
458 Dmsg0(200, "JCR already dead in #3\n");
461 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
464 Dmsg3(200, "MaxWaitTime result: %scancel JCR %p (%s)\n",
465 cancel ? "" : "do not ", jcr, jcr->job);
471 * Check if maxruntime has expired and if the job can be
474 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
478 if (jcr->job->MaxRunTime == 0) {
481 if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
482 Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
483 jcr, jcr->Job, jcr->job->MaxRunTime);
487 switch (jcr->JobStatus) {
493 case JS_WaitStoreRes:
494 case JS_WaitClientRes:
496 case JS_WaitPriority:
498 case JS_WaitStartTime:
503 case JS_ErrorTerminated:
509 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
513 Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
514 cancel ? "" : "do not ", jcr, jcr->job);
521 * Get or create a Client record for this Job
523 bool get_or_create_client_record(JCR *jcr)
527 memset(&cr, 0, sizeof(cr));
528 bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
529 cr.AutoPrune = jcr->client->AutoPrune;
530 cr.FileRetention = jcr->client->FileRetention;
531 cr.JobRetention = jcr->client->JobRetention;
532 if (!jcr->client_name) {
533 jcr->client_name = get_pool_memory(PM_NAME);
535 pm_strcpy(jcr->client_name, jcr->client->hdr.name);
536 if (!db_create_client_record(jcr, jcr->db, &cr)) {
537 Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
538 db_strerror(jcr->db));
541 jcr->jr.ClientId = cr.ClientId;
543 if (!jcr->client_uname) {
544 jcr->client_uname = get_pool_memory(PM_NAME);
546 pm_strcpy(jcr->client_uname, cr.Uname);
548 Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
553 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
556 * Get or Create FileSet record
558 memset(fsr, 0, sizeof(FILESET_DBR));
559 bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
560 if (jcr->fileset->have_MD5) {
561 struct MD5Context md5c;
562 unsigned char signature[16];
563 memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
564 MD5Final(signature, &md5c);
565 bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
566 bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
568 Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
570 if (!jcr->fileset->ignore_fs_changes ||
571 !db_get_fileset_record(jcr, jcr->db, fsr)) {
572 if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
573 Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
574 fsr->FileSet, db_strerror(jcr->db));
578 jcr->jr.FileSetId = fsr->FileSetId;
580 Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
581 fsr->FileSet, fsr->cCreateTime);
583 Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
588 void init_jcr_job_record(JCR *jcr)
590 jcr->jr.SchedTime = jcr->sched_time;
591 jcr->jr.StartTime = jcr->start_time;
592 jcr->jr.EndTime = 0; /* perhaps rescheduled, clear it */
593 jcr->jr.JobType = jcr->JobType;
594 jcr->jr.JobLevel = jcr->JobLevel;
595 jcr->jr.JobStatus = jcr->JobStatus;
596 jcr->jr.JobId = jcr->JobId;
597 bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
598 bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
602 * Write status and such in DB
604 void update_job_end_record(JCR *jcr)
606 jcr->jr.EndTime = time(NULL);
607 jcr->end_time = jcr->jr.EndTime;
608 jcr->jr.JobId = jcr->JobId;
609 jcr->jr.JobStatus = jcr->JobStatus;
610 jcr->jr.JobFiles = jcr->JobFiles;
611 jcr->jr.JobBytes = jcr->JobBytes;
612 jcr->jr.VolSessionId = jcr->VolSessionId;
613 jcr->jr.VolSessionTime = jcr->VolSessionTime;
614 if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
615 Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
616 db_strerror(jcr->db));
621 * Takes base_name and appends (unique) current
622 * date and time to form unique job name.
624 * Returns: unique job name in jcr->Job
625 * date/time in jcr->start_time
627 void create_unique_job_name(JCR *jcr, const char *base_name)
629 /* Job start mutex */
630 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
631 static time_t last_start_time = 0;
634 char dt[MAX_TIME_LENGTH];
635 char name[MAX_NAME_LENGTH];
638 /* Guarantee unique start time -- maximum one per second, and
639 * thus unique Job Name
641 P(mutex); /* lock creation of jobs */
643 while (now == last_start_time) {
644 bmicrosleep(0, 500000);
647 last_start_time = now;
648 V(mutex); /* allow creation of jobs */
649 jcr->start_time = now;
650 /* Form Unique JobName */
651 localtime_r(&now, &tm);
652 /* Use only characters that are permitted in Windows filenames */
653 strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
654 bstrncpy(name, base_name, sizeof(name));
655 name[sizeof(name)-22] = 0; /* truncate if too long */
656 bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
657 /* Convert spaces into underscores */
658 for (p=jcr->Job; *p; p++) {
666 * Free the Job Control Record if no one is still using it.
667 * Called from main free_jcr() routine in src/lib/jcr.c so
668 * that we can do our Director specific cleanup of the jcr.
670 void dird_free_jcr(JCR *jcr)
672 Dmsg0(200, "Start dird free_jcr\n");
674 if (jcr->sd_auth_key) {
675 free(jcr->sd_auth_key);
676 jcr->sd_auth_key = NULL;
682 if (jcr->file_bsock) {
683 Dmsg0(200, "Close File bsock\n");
684 bnet_close(jcr->file_bsock);
685 jcr->file_bsock = NULL;
687 if (jcr->store_bsock) {
688 Dmsg0(200, "Close Store bsock\n");
689 bnet_close(jcr->store_bsock);
690 jcr->store_bsock = NULL;
693 Dmsg0(200, "Free JCR fname\n");
694 free_pool_memory(jcr->fname);
698 Dmsg0(200, "Free JCR stime\n");
699 free_pool_memory(jcr->stime);
702 if (jcr->RestoreBootstrap) {
703 free(jcr->RestoreBootstrap);
704 jcr->RestoreBootstrap = NULL;
706 if (jcr->client_uname) {
707 free_pool_memory(jcr->client_uname);
708 jcr->client_uname = NULL;
710 if (jcr->term_wait_inited) {
711 pthread_cond_destroy(&jcr->term_wait);
713 jcr->job_end_push.destroy();
714 Dmsg0(200, "End dird free_jcr\n");
718 * Set some defaults in the JCR necessary to
719 * run. These items are pulled from the job
720 * definition as defaults, but can be overridden
721 * later either by the Run record in the Schedule resource,
722 * or by the Console program.
724 void set_jcr_defaults(JCR *jcr, JOB *job)
727 jcr->JobType = job->JobType;
728 switch (jcr->JobType) {
731 jcr->JobLevel = L_NONE;
734 jcr->JobLevel = job->level;
737 jcr->JobPriority = job->Priority;
738 jcr->store = job->storage;
739 jcr->client = job->client;
740 if (!jcr->client_name) {
741 jcr->client_name = get_pool_memory(PM_NAME);
743 pm_strcpy(jcr->client_name, jcr->client->hdr.name);
744 jcr->pool = job->pool;
745 jcr->full_pool = job->full_pool;
746 jcr->inc_pool = job->inc_pool;
747 jcr->dif_pool = job->dif_pool;
748 jcr->catalog = job->client->catalog;
749 jcr->fileset = job->fileset;
750 jcr->messages = job->messages;
751 jcr->spool_data = job->spool_data;
752 if (jcr->RestoreBootstrap) {
753 free(jcr->RestoreBootstrap);
754 jcr->RestoreBootstrap = NULL;
756 /* This can be overridden by Console program */
757 if (job->RestoreBootstrap) {
758 jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
760 /* If no default level given, set one */
761 if (jcr->JobLevel == 0) {
762 switch (jcr->JobType) {
764 jcr->JobLevel = L_VERIFY_CATALOG;
767 jcr->JobLevel = L_INCREMENTAL;
771 jcr->JobLevel = L_NONE;