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) {
62 Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), be.strerror());
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);
76 * Run a job -- typically called by the scheduler, but may also
77 * be called by the UA (Console program).
79 * Returns: 0 on failure
83 JobId_t run_job(JCR *jcr)
89 sm_check(__FILE__, __LINE__, true);
90 init_msg(jcr, jcr->messages);
92 /* Initialize termination condition variable */
93 if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
95 be.set_errno(errstat);
96 Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror());
99 jcr->term_wait_inited = true;
104 Dmsg0(50, "Open database\n");
105 jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
106 jcr->catalog->db_password, jcr->catalog->db_address,
107 jcr->catalog->db_port, jcr->catalog->db_socket);
108 if (!jcr->db || !db_open_database(jcr, jcr->db)) {
109 Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
110 jcr->catalog->db_name);
112 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
116 Dmsg0(50, "DB opened\n");
121 create_unique_job_name(jcr, jcr->job->hdr.name);
122 set_jcr_job_status(jcr, JS_Created);
123 init_jcr_job_record(jcr);
124 if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
125 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
128 JobId = jcr->JobId = jcr->jr.JobId;
130 Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
131 jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);
132 Dmsg0(200, "Add jrc to work queue\n");
134 /* Queue the job to be run */
135 if ((stat = jobq_add(&job_queue, jcr)) != 0) {
138 Jmsg(jcr, M_FATAL, 0, _("Could not add job queue: ERR=%s\n"), be.strerror());
142 Dmsg0(100, "Done run_job()\n");
148 set_jcr_job_status(jcr, JS_ErrorTerminated);
156 * This is the engine called by jobq.c:jobq_add() when we were pulled
157 * from the work queue.
158 * At this point, we are running in our own thread and all
159 * necessary resources are allocated -- see jobq.c
161 static void *job_thread(void *arg)
163 JCR *jcr = (JCR *)arg;
165 jcr->my_thread_id = pthread_self();
166 pthread_detach(jcr->my_thread_id);
167 sm_check(__FILE__, __LINE__, true);
170 Dmsg0(200, "=====Start Job=========\n");
171 jcr->start_time = time(NULL); /* set the real start time */
172 set_jcr_job_status(jcr, JS_Running);
174 if (job_canceled(jcr)) {
175 update_job_end_record(jcr);
176 } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
177 (utime_t)(jcr->start_time - jcr->sched_time)) {
178 Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
179 set_jcr_job_status(jcr, JS_Canceled);
180 update_job_end_record(jcr);
184 if (jcr->job->RunBeforeJob) {
185 POOLMEM *before = get_pool_memory(PM_FNAME);
188 char line[MAXSTRING];
190 before = edit_job_codes(jcr, before, jcr->job->RunBeforeJob, "");
191 bpipe = open_bpipe(before, 0, "r");
192 free_pool_memory(before);
193 while (fgets(line, sizeof(line), bpipe->rfd)) {
194 Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
196 status = close_bpipe(bpipe);
199 be.set_errno(status);
200 Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob error: ERR=%s\n"), be.strerror());
201 set_jcr_job_status(jcr, JS_FatalError);
202 update_job_end_record(jcr);
206 switch (jcr->JobType) {
209 if (jcr->JobStatus == JS_Terminated) {
215 if (jcr->JobStatus == JS_Terminated) {
221 if (jcr->JobStatus == JS_Terminated) {
227 if (jcr->JobStatus == JS_Terminated) {
232 Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
235 if ((jcr->job->RunAfterJob && jcr->JobStatus == JS_Terminated) ||
236 (jcr->job->RunAfterFailedJob && jcr->JobStatus != JS_Terminated)) {
237 POOLMEM *after = get_pool_memory(PM_FNAME);
240 char line[MAXSTRING];
242 if (jcr->JobStatus == JS_Terminated) {
243 after = edit_job_codes(jcr, after, jcr->job->RunAfterJob, "");
245 after = edit_job_codes(jcr, after, jcr->job->RunAfterFailedJob, "");
247 bpipe = open_bpipe(after, 0, "r");
248 free_pool_memory(after);
249 while (fgets(line, sizeof(line), bpipe->rfd)) {
250 Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
252 status = close_bpipe(bpipe);
254 * Note, if we get an error here, do not mark the
255 * job in error, simply report the error condition.
259 be.set_errno(status);
260 if (jcr->JobStatus == JS_Terminated) {
261 Jmsg(jcr, M_WARNING, 0, _("RunAfterJob error: ERR=%s\n"), be.strerror());
263 Jmsg(jcr, M_FATAL, 0, _("RunAfterFailedJob error: ERR=%s\n"), be.strerror());
267 /* Send off any queued messages */
268 if (jcr->msg_queue->size() > 0) {
269 dequeue_messages(jcr);
276 Dmsg0(50, "======== End Job ==========\n");
277 sm_check(__FILE__, __LINE__, true);
283 * Cancel a job -- typically called by the UA (Console program), but may also
284 * be called by the job watchdog.
286 * Returns: 1 if cancel appears to be successful
287 * 0 on failure. Message sent to ua->jcr.
289 int cancel_job(UAContext *ua, JCR *jcr)
293 switch (jcr->JobStatus) {
296 case JS_WaitClientRes:
297 case JS_WaitStoreRes:
298 case JS_WaitPriority:
300 case JS_WaitStartTime:
301 set_jcr_job_status(jcr, JS_Canceled);
302 bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
303 jcr->JobId, jcr->Job);
304 jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
308 set_jcr_job_status(jcr, JS_Canceled);
310 /* Cancel File daemon */
311 if (jcr->file_bsock) {
312 ua->jcr->client = jcr->client;
313 if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
314 bsendmsg(ua, _("Failed to connect to File daemon.\n"));
317 Dmsg0(200, "Connected to file daemon\n");
318 fd = ua->jcr->file_bsock;
319 bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
320 while (bnet_recv(fd) >= 0) {
321 bsendmsg(ua, "%s", fd->msg);
323 bnet_sig(fd, BNET_TERMINATE);
325 ua->jcr->file_bsock = NULL;
328 /* Cancel Storage daemon */
329 if (jcr->store_bsock) {
330 ua->jcr->store = jcr->store;
331 if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
332 bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
335 Dmsg0(200, "Connected to storage daemon\n");
336 sd = ua->jcr->store_bsock;
337 bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
338 while (bnet_recv(sd) >= 0) {
339 bsendmsg(ua, "%s", sd->msg);
341 bnet_sig(sd, BNET_TERMINATE);
343 ua->jcr->store_bsock = NULL;
351 static void job_monitor_destructor(watchdog_t *self)
353 JCR *control_jcr = (JCR *) self->data;
355 free_jcr(control_jcr);
358 static void job_monitor_watchdog(watchdog_t *self)
360 JCR *control_jcr, *jcr;
362 control_jcr = (JCR *)self->data;
364 Dmsg1(400, "job_monitor_watchdog %p called\n", self);
371 if (jcr->JobId == 0) {
372 Dmsg2(400, "Skipping JCR %p (%s) with JobId 0\n",
374 /* Keep reference counts correct */
375 free_locked_jcr(jcr);
379 /* check MaxWaitTime */
380 cancel = job_check_maxwaittime(control_jcr, jcr);
382 /* check MaxRunTime */
383 cancel |= job_check_maxruntime(control_jcr, jcr);
386 Dmsg3(200, "Cancelling JCR %p jobid %d (%s)\n",
387 jcr, jcr->JobId, jcr->Job);
389 UAContext *ua = new_ua_context(jcr);
390 ua->jcr = control_jcr;
394 Dmsg1(200, "Have cancelled JCR %p\n", jcr);
397 /* Keep reference counts correct */
398 free_locked_jcr(jcr);
404 * Check if the maxwaittime has expired and it is possible
407 static bool job_check_maxwaittime(JCR *control_jcr, JCR *jcr)
411 if (jcr->job->MaxWaitTime == 0) {
414 if ((watchdog_time - jcr->start_time) < jcr->job->MaxWaitTime) {
415 Dmsg3(200, "Job %p (%s) with MaxWaitTime %d not expired\n",
416 jcr, jcr->Job, jcr->job->MaxWaitTime);
419 Dmsg3(200, "Job %d (%s): MaxWaitTime of %d seconds exceeded, "
421 jcr->JobId, jcr->Job, jcr->job->MaxWaitTime);
422 switch (jcr->JobStatus) {
427 case JS_WaitStoreRes:
428 case JS_WaitClientRes:
430 case JS_WaitPriority:
432 case JS_WaitStartTime:
434 Dmsg0(200, "JCR blocked in #1\n");
437 Dmsg0(200, "JCR running, checking SD status\n");
438 switch (jcr->SDJobStatus) {
443 Dmsg0(200, "JCR blocked in #2\n");
446 Dmsg0(200, "JCR not blocked in #2\n");
451 case JS_ErrorTerminated:
454 Dmsg0(200, "JCR already dead in #3\n");
457 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
460 Dmsg3(200, "MaxWaitTime result: %scancel JCR %p (%s)\n",
461 cancel ? "" : "do not ", jcr, jcr->job);
467 * Check if maxruntime has expired and if the job can be
470 static bool job_check_maxruntime(JCR *control_jcr, JCR *jcr)
474 if (jcr->job->MaxRunTime == 0) {
477 if ((watchdog_time - jcr->start_time) < jcr->job->MaxRunTime) {
478 Dmsg3(200, "Job %p (%s) with MaxRunTime %d not expired\n",
479 jcr, jcr->Job, jcr->job->MaxRunTime);
483 switch (jcr->JobStatus) {
489 case JS_WaitStoreRes:
490 case JS_WaitClientRes:
492 case JS_WaitPriority:
494 case JS_WaitStartTime:
499 case JS_ErrorTerminated:
505 Jmsg1(jcr, M_ERROR, 0, _("Unhandled job status code %d\n"),
509 Dmsg3(200, "MaxRunTime result: %scancel JCR %p (%s)\n",
510 cancel ? "" : "do not ", jcr, jcr->job);
517 * Get or create a Client record for this Job
519 bool get_or_create_client_record(JCR *jcr)
523 memset(&cr, 0, sizeof(cr));
524 bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
525 cr.AutoPrune = jcr->client->AutoPrune;
526 cr.FileRetention = jcr->client->FileRetention;
527 cr.JobRetention = jcr->client->JobRetention;
528 if (!jcr->client_name) {
529 jcr->client_name = get_pool_memory(PM_NAME);
531 pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
532 if (!db_create_client_record(jcr, jcr->db, &cr)) {
533 Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
534 db_strerror(jcr->db));
537 jcr->jr.ClientId = cr.ClientId;
539 if (!jcr->client_uname) {
540 jcr->client_uname = get_pool_memory(PM_NAME);
542 pm_strcpy(&jcr->client_uname, cr.Uname);
544 Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
549 bool get_or_create_fileset_record(JCR *jcr, FILESET_DBR *fsr)
552 * Get or Create FileSet record
554 memset(fsr, 0, sizeof(FILESET_DBR));
555 bstrncpy(fsr->FileSet, jcr->fileset->hdr.name, sizeof(fsr->FileSet));
556 if (jcr->fileset->have_MD5) {
557 struct MD5Context md5c;
558 unsigned char signature[16];
559 memcpy(&md5c, &jcr->fileset->md5c, sizeof(md5c));
560 MD5Final(signature, &md5c);
561 bin_to_base64(fsr->MD5, (char *)signature, 16); /* encode 16 bytes */
562 bstrncpy(jcr->fileset->MD5, fsr->MD5, sizeof(jcr->fileset->MD5));
564 Jmsg(jcr, M_WARNING, 0, _("FileSet MD5 signature not found.\n"));
566 if (!db_create_fileset_record(jcr, jcr->db, fsr)) {
567 Jmsg(jcr, M_ERROR, 0, _("Could not create FileSet \"%s\" record. ERR=%s\n"),
568 fsr->FileSet, db_strerror(jcr->db));
571 jcr->jr.FileSetId = fsr->FileSetId;
573 Jmsg(jcr, M_INFO, 0, _("Created new FileSet record \"%s\" %s\n"),
574 fsr->FileSet, fsr->cCreateTime);
576 Dmsg2(119, "Created FileSet %s record %u\n", jcr->fileset->hdr.name,
581 void init_jcr_job_record(JCR *jcr)
583 jcr->jr.SchedTime = jcr->sched_time;
584 jcr->jr.StartTime = jcr->start_time;
585 jcr->jr.EndTime = 0; /* perhaps rescheduled, clear it */
586 jcr->jr.JobType = jcr->JobType;
587 jcr->jr.JobLevel = jcr->JobLevel;
588 jcr->jr.JobStatus = jcr->JobStatus;
589 jcr->jr.JobId = jcr->JobId;
590 bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
591 bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
595 * Write status and such in DB
597 void update_job_end_record(JCR *jcr)
599 jcr->jr.EndTime = time(NULL);
600 jcr->end_time = jcr->jr.EndTime;
601 jcr->jr.JobId = jcr->JobId;
602 jcr->jr.JobStatus = jcr->JobStatus;
603 jcr->jr.JobFiles = jcr->JobFiles;
604 jcr->jr.JobBytes = jcr->JobBytes;
605 jcr->jr.VolSessionId = jcr->VolSessionId;
606 jcr->jr.VolSessionTime = jcr->VolSessionTime;
607 if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
608 Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
609 db_strerror(jcr->db));
614 * Takes base_name and appends (unique) current
615 * date and time to form unique job name.
617 * Returns: unique job name in jcr->Job
618 * date/time in jcr->start_time
620 void create_unique_job_name(JCR *jcr, const char *base_name)
622 /* Job start mutex */
623 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
624 static time_t last_start_time = 0;
627 char dt[MAX_TIME_LENGTH];
628 char name[MAX_NAME_LENGTH];
631 /* Guarantee unique start time -- maximum one per second, and
632 * thus unique Job Name
634 P(mutex); /* lock creation of jobs */
636 while (now == last_start_time) {
637 bmicrosleep(0, 500000);
640 last_start_time = now;
641 V(mutex); /* allow creation of jobs */
642 jcr->start_time = now;
643 /* Form Unique JobName */
644 localtime_r(&now, &tm);
645 /* Use only characters that are permitted in Windows filenames */
646 strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
647 bstrncpy(name, base_name, sizeof(name));
648 name[sizeof(name)-22] = 0; /* truncate if too long */
649 bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
650 /* Convert spaces into underscores */
651 for (p=jcr->Job; *p; p++) {
659 * Free the Job Control Record if no one is still using it.
660 * Called from main free_jcr() routine in src/lib/jcr.c so
661 * that we can do our Director specific cleanup of the jcr.
663 void dird_free_jcr(JCR *jcr)
665 Dmsg0(200, "Start dird free_jcr\n");
667 if (jcr->sd_auth_key) {
668 free(jcr->sd_auth_key);
669 jcr->sd_auth_key = NULL;
675 if (jcr->file_bsock) {
676 Dmsg0(200, "Close File bsock\n");
677 bnet_close(jcr->file_bsock);
678 jcr->file_bsock = NULL;
680 if (jcr->store_bsock) {
681 Dmsg0(200, "Close Store bsock\n");
682 bnet_close(jcr->store_bsock);
683 jcr->store_bsock = NULL;
686 Dmsg0(200, "Free JCR fname\n");
687 free_pool_memory(jcr->fname);
691 Dmsg0(200, "Free JCR stime\n");
692 free_pool_memory(jcr->stime);
695 if (jcr->RestoreBootstrap) {
696 free(jcr->RestoreBootstrap);
697 jcr->RestoreBootstrap = NULL;
699 if (jcr->client_uname) {
700 free_pool_memory(jcr->client_uname);
701 jcr->client_uname = NULL;
703 if (jcr->term_wait_inited) {
704 pthread_cond_destroy(&jcr->term_wait);
706 jcr->job_end_push.destroy();
707 Dmsg0(200, "End dird free_jcr\n");
711 * Set some defaults in the JCR necessary to
712 * run. These items are pulled from the job
713 * definition as defaults, but can be overridden
714 * later either by the Run record in the Schedule resource,
715 * or by the Console program.
717 void set_jcr_defaults(JCR *jcr, JOB *job)
720 jcr->JobType = job->JobType;
721 switch (jcr->JobType) {
724 jcr->JobLevel = L_NONE;
727 jcr->JobLevel = job->level;
730 jcr->JobPriority = job->Priority;
731 jcr->store = job->storage;
732 jcr->client = job->client;
733 if (!jcr->client_name) {
734 jcr->client_name = get_pool_memory(PM_NAME);
736 pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
737 jcr->pool = job->pool;
738 jcr->full_pool = job->full_pool;
739 jcr->inc_pool = job->inc_pool;
740 jcr->dif_pool = job->dif_pool;
741 jcr->catalog = job->client->catalog;
742 jcr->fileset = job->fileset;
743 jcr->messages = job->messages;
744 jcr->spool_data = job->spool_data;
745 if (jcr->RestoreBootstrap) {
746 free(jcr->RestoreBootstrap);
747 jcr->RestoreBootstrap = NULL;
749 /* This can be overridden by Console program */
750 if (job->RestoreBootstrap) {
751 jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
753 /* If no default level given, set one */
754 if (jcr->JobLevel == 0) {
755 switch (jcr->JobType) {
757 jcr->JobLevel = L_VERIFY_CATALOG;
760 jcr->JobLevel = L_INCREMENTAL;
764 jcr->JobLevel = L_NONE;