3 * Bacula Director Job processing routines
5 * Kern Sibbald, October MM
10 Copyright (C) 2000-2003 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 char *edit_run_codes(JCR *jcr, char *omsg, char *imsg);
35 static void release_resource_locks(JCR *jcr);
36 static int acquire_resource_locks(JCR *jcr);
38 static void backoff_resource_locks(JCR *jcr, int count);
41 /* Exported subroutines */
42 void run_job(JCR *jcr);
45 /* Imported subroutines */
46 extern void term_scheduler();
47 extern void term_ua_server();
48 extern int do_backup(JCR *jcr);
49 extern int do_admin(JCR *jcr);
50 extern int do_restore(JCR *jcr);
51 extern int do_verify(JCR *jcr);
54 static semlock_t job_lock;
55 static pthread_mutex_t mutex;
56 static pthread_cond_t resource_wait;
57 static int waiting = 0; /* count of waiting threads */
62 /* Queue of jobs to be run */
63 workq_t job_wq; /* our job work queue */
67 void init_job_server(int max_workers)
71 if ((stat = sem_init(&job_lock, max_workers)) != 0) {
72 Emsg1(M_ABORT, 0, _("Could not init job lock: ERR=%s\n"), strerror(stat));
74 if ((stat = pthread_mutex_init(&mutex, NULL)) != 0) {
75 Emsg1(M_ABORT, 0, _("Could not init resource mutex: ERR=%s\n"), strerror(stat));
77 if ((stat = pthread_cond_init(&resource_wait, NULL)) != 0) {
78 Emsg1(M_ABORT, 0, _("Could not init resource wait: ERR=%s\n"), strerror(stat));
83 if ((stat = job_init(&job_queue, max_workers, job_thread)) != 0) {
84 Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), strerror(stat));
87 /* This is the OLD work queue code to go away */
88 if ((stat = workq_init(&job_wq, max_workers, job_thread)) != 0) {
89 Emsg1(M_ABORT, 0, _("Could not init job work queue: ERR=%s\n"), strerror(stat));
97 * Run a job -- typically called by the scheduler, but may also
98 * be called by the UA (Console program).
101 void run_job(JCR *jcr)
108 workq_ele_t *work_item;
112 sm_check(__FILE__, __LINE__, True);
113 init_msg(jcr, jcr->messages);
114 create_unique_job_name(jcr, jcr->job->hdr.name);
115 set_jcr_job_status(jcr, JS_Created);
116 jcr->jr.SchedTime = jcr->sched_time;
117 jcr->jr.StartTime = jcr->start_time;
118 jcr->jr.Type = jcr->JobType;
119 jcr->jr.Level = jcr->JobLevel;
120 jcr->jr.JobStatus = jcr->JobStatus;
121 bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
122 bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
124 /* Initialize termination condition variable */
125 if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
126 Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
127 set_jcr_job_status(jcr, JS_ErrorTerminated);
135 Dmsg0(50, "Open database\n");
136 jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
137 jcr->catalog->db_password, jcr->catalog->db_address,
138 jcr->catalog->db_port, jcr->catalog->db_socket);
139 if (!db_open_database(jcr, jcr->db)) {
140 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
141 set_jcr_job_status(jcr, JS_ErrorTerminated);
145 Dmsg0(50, "DB opened\n");
150 jcr->jr.JobStatus = jcr->JobStatus;
151 if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
152 Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
153 set_jcr_job_status(jcr, JS_ErrorTerminated);
157 jcr->JobId = jcr->jr.JobId;
158 ASSERT(jcr->jr.JobId > 0);
160 Dmsg4(30, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
161 jcr->JobId, jcr->Job, jcr->jr.Type, jcr->jr.Level);
162 Dmsg0(200, "Add jrc to work queue\n");
165 if ((stat = pthread_create(&tid, NULL, job_thread, (void *)jcr)) != 0) {
166 Emsg1(M_ABORT, 0, _("Unable to create job thread: ERR=%s\n"), strerror(stat));
170 /* Queue the job to be run */
171 if ((stat = jobq_add(&job_queue, jcr)) != 0) {
172 Emsg1(M_ABORT, 0, _("Could not add job queue: ERR=%s\n"), strerror(stat));
175 /* Queue the job to be run */
176 if ((stat = workq_add(&job_wq, (void *)jcr, &work_item, 0)) != 0) {
177 Emsg1(M_ABORT, 0, _("Could not add job to work queue: ERR=%s\n"), strerror(stat));
179 jcr->work_item = work_item;
182 Dmsg0(200, "Done run_job()\n");
186 * This is the engine called by workq_add() when we were pulled
187 * from the work queue.
188 * At this point, we are running in our own thread
190 static void *job_thread(void *arg)
192 JCR *jcr = (JCR *)arg;
194 pthread_detach(pthread_self());
195 sm_check(__FILE__, __LINE__, True);
198 if (!acquire_resource_locks(jcr)) {
199 set_jcr_job_status(jcr, JS_Canceled);
202 Dmsg0(200, "=====Start Job=========\n");
203 jcr->start_time = time(NULL); /* set the real start time */
204 set_jcr_job_status(jcr, JS_Running);
206 if (job_canceled(jcr)) {
207 update_job_end_record(jcr);
208 } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
209 (utime_t)(jcr->start_time - jcr->sched_time)) {
210 Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
211 set_jcr_job_status(jcr, JS_Canceled);
212 update_job_end_record(jcr);
216 if (jcr->job->RunBeforeJob) {
217 POOLMEM *before = get_pool_memory(PM_FNAME);
220 char line[MAXSTRING];
222 before = edit_run_codes(jcr, before, jcr->job->RunBeforeJob);
223 bpipe = open_bpipe(before, 0, "r");
224 free_pool_memory(before);
225 while (fgets(line, sizeof(line), bpipe->rfd)) {
226 Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
228 status = close_bpipe(bpipe);
230 Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob returned non-zero status=%d\n"),
232 set_jcr_job_status(jcr, JS_FatalError);
233 update_job_end_record(jcr);
237 switch (jcr->JobType) {
240 if (jcr->JobStatus == JS_Terminated) {
246 if (jcr->JobStatus == JS_Terminated) {
252 if (jcr->JobStatus == JS_Terminated) {
258 if (jcr->JobStatus == JS_Terminated) {
263 Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
266 if (jcr->job->RunAfterJob) {
267 POOLMEM *after = get_pool_memory(PM_FNAME);
270 char line[MAXSTRING];
272 after = edit_run_codes(jcr, after, jcr->job->RunAfterJob);
273 bpipe = open_bpipe(after, 0, "r");
274 free_pool_memory(after);
275 while (fgets(line, sizeof(line), bpipe->rfd)) {
276 Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
278 status = close_bpipe(bpipe);
280 Jmsg(jcr, M_FATAL, 0, _("RunAfterJob returned non-zero status=%d\n"),
282 set_jcr_job_status(jcr, JS_FatalError);
283 update_job_end_record(jcr);
288 release_resource_locks(jcr);
289 if (jcr->job->RescheduleOnError &&
290 jcr->JobStatus != JS_Terminated &&
291 jcr->JobStatus != JS_Canceled &&
292 jcr->job->RescheduleTimes > 0 &&
293 jcr->reschedule_count < jcr->job->RescheduleTimes) {
296 * Reschedule this job by cleaning it up, but
297 * reuse the same JobId if possible.
299 jcr->reschedule_count++;
300 jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
301 Dmsg2(100, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
302 (int)jcr->job->RescheduleInterval);
303 jcr->JobStatus = JS_Created; /* force new status */
304 dird_free_jcr(jcr); /* partial cleanup old stuff */
305 if (jcr->JobBytes == 0) {
306 continue; /* reschedule the job */
309 * Something was actually backed up, so we cannot reuse
310 * the old JobId or there will be database record
311 * conflicts. We now create a new job, copying the
312 * appropriate fields.
314 JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
315 set_jcr_defaults(njcr, jcr->job);
316 njcr->reschedule_count = jcr->reschedule_count;
317 njcr->JobLevel = jcr->JobLevel;
318 njcr->JobStatus = jcr->JobStatus;
319 njcr->pool = jcr->pool;
320 njcr->store = jcr->store;
321 njcr->messages = jcr->messages;
328 Dmsg0(200, "Close DB\n");
329 db_close_database(jcr, jcr->db);
333 Dmsg0(50, "======== End Job ==========\n");
334 sm_check(__FILE__, __LINE__, True);
339 * Acquire the resources needed. These locks limit the
340 * number of jobs by each resource. We have limits on
341 * Jobs, Clients, Storage, and total jobs.
343 static int acquire_resource_locks(JCR *jcr)
345 time_t now = time(NULL);
346 time_t wtime = jcr->sched_time - now;
348 /* Wait until scheduled time arrives */
349 if (wtime > 0 && verbose) {
350 Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
352 set_jcr_job_status(jcr, JS_WaitStartTime);
354 /* Check every 30 seconds if canceled */
356 Dmsg2(100, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
360 bmicrosleep(wtime, 0);
361 if (job_canceled(jcr)) {
364 wtime = jcr->sched_time - time(NULL);
371 /* Initialize semaphores */
372 if (jcr->store->sem.valid != SEMLOCK_VALID) {
373 if ((stat = sem_init(&jcr->store->sem, jcr->store->MaxConcurrentJobs)) != 0) {
374 Emsg1(M_ABORT, 0, _("Could not init Storage semaphore: ERR=%s\n"), strerror(stat));
377 if (jcr->client->sem.valid != SEMLOCK_VALID) {
378 if ((stat = sem_init(&jcr->client->sem, jcr->client->MaxConcurrentJobs)) != 0) {
379 Emsg1(M_ABORT, 0, _("Could not init Client semaphore: ERR=%s\n"), strerror(stat));
382 if (jcr->job->sem.valid != SEMLOCK_VALID) {
383 if ((stat = sem_init(&jcr->job->sem, jcr->job->MaxConcurrentJobs)) != 0) {
384 Emsg1(M_ABORT, 0, _("Could not init Job semaphore: ERR=%s\n"), strerror(stat));
389 /* Acquire semaphore */
390 set_jcr_job_status(jcr, JS_WaitJobRes);
391 if ((stat = sem_lock(&jcr->job->sem)) != 0) {
392 Emsg1(M_ABORT, 0, _("Could not acquire Job max jobs lock: ERR=%s\n"), strerror(stat));
394 set_jcr_job_status(jcr, JS_WaitClientRes);
395 if ((stat = sem_trylock(&jcr->client->sem)) != 0) {
397 backoff_resource_locks(jcr, 1);
400 Emsg1(M_ABORT, 0, _("Could not acquire Client max jobs lock: ERR=%s\n"), strerror(stat));
403 set_jcr_job_status(jcr, JS_WaitStoreRes);
404 if ((stat = sem_trylock(&jcr->store->sem)) != 0) {
406 backoff_resource_locks(jcr, 2);
409 Emsg1(M_ABORT, 0, _("Could not acquire Storage max jobs lock: ERR=%s\n"), strerror(stat));
412 set_jcr_job_status(jcr, JS_WaitMaxJobs);
413 if ((stat = sem_trylock(&job_lock)) != 0) {
415 backoff_resource_locks(jcr, 3);
418 Emsg1(M_ABORT, 0, _("Could not acquire max jobs lock: ERR=%s\n"), strerror(stat));
424 if (job_canceled(jcr)) {
429 * Wait for a resource to be released either by backoff or
430 * by a job terminating.
433 pthread_cond_wait(&resource_wait, &mutex);
438 jcr->acquired_resource_locks = true;
445 * We could not get all the resource locks because
446 * too many jobs are running, so release any locks
447 * we did acquire, giving others a chance to use them
450 static void backoff_resource_locks(JCR *jcr, int count)
455 sem_unlock(&jcr->store->sem);
456 /* Fall through wanted */
458 sem_unlock(&jcr->client->sem);
459 /* Fall through wanted */
461 sem_unlock(&jcr->job->sem);
465 * Since we released a lock, if there are any threads
466 * waiting, wake them up so that they can try again.
469 pthread_cond_broadcast(&resource_wait);
476 * This is called at the end of the job to release
477 * any resource limits on the number of jobs. If
478 * there are any other jobs waiting, we wake them
479 * up so that they can try again.
481 static void release_resource_locks(JCR *jcr)
483 if (!jcr->acquired_resource_locks) {
484 return; /* Job canceled, no locks acquired */
488 sem_unlock(&jcr->store->sem);
489 sem_unlock(&jcr->client->sem);
490 sem_unlock(&jcr->job->sem);
491 sem_unlock(&job_lock);
493 pthread_cond_broadcast(&resource_wait);
495 jcr->acquired_resource_locks = false;
501 * Get or create a Client record for this Job
503 int get_or_create_client_record(JCR *jcr)
507 memset(&cr, 0, sizeof(cr));
508 bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
509 cr.AutoPrune = jcr->client->AutoPrune;
510 cr.FileRetention = jcr->client->FileRetention;
511 cr.JobRetention = jcr->client->JobRetention;
512 if (!jcr->client_name) {
513 jcr->client_name = get_pool_memory(PM_NAME);
515 pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
516 if (!db_create_client_record(jcr, jcr->db, &cr)) {
517 Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"),
518 db_strerror(jcr->db));
521 jcr->jr.ClientId = cr.ClientId;
523 if (!jcr->client_uname) {
524 jcr->client_uname = get_pool_memory(PM_NAME);
526 pm_strcpy(&jcr->client_uname, cr.Uname);
528 Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name,
535 * Write status and such in DB
537 void update_job_end_record(JCR *jcr)
539 if (jcr->jr.EndTime == 0) {
540 jcr->jr.EndTime = time(NULL);
542 jcr->end_time = jcr->jr.EndTime;
543 jcr->jr.JobId = jcr->JobId;
544 jcr->jr.JobStatus = jcr->JobStatus;
545 jcr->jr.JobFiles = jcr->JobFiles;
546 jcr->jr.JobBytes = jcr->JobBytes;
547 jcr->jr.VolSessionId = jcr->VolSessionId;
548 jcr->jr.VolSessionTime = jcr->VolSessionTime;
549 if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
550 Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"),
551 db_strerror(jcr->db));
556 * Takes base_name and appends (unique) current
557 * date and time to form unique job name.
559 * Returns: unique job name in jcr->Job
560 * date/time in jcr->start_time
562 void create_unique_job_name(JCR *jcr, char *base_name)
564 /* Job start mutex */
565 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
566 static time_t last_start_time = 0;
569 char dt[MAX_TIME_LENGTH];
570 char name[MAX_NAME_LENGTH];
573 /* Guarantee unique start time -- maximum one per second, and
574 * thus unique Job Name
576 P(mutex); /* lock creation of jobs */
578 while (now == last_start_time) {
579 bmicrosleep(0, 500000);
582 last_start_time = now;
583 V(mutex); /* allow creation of jobs */
584 jcr->start_time = now;
585 /* Form Unique JobName */
586 localtime_r(&now, &tm);
587 /* Use only characters that are permitted in Windows filenames */
588 strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm);
589 bstrncpy(name, base_name, sizeof(name));
590 name[sizeof(name)-22] = 0; /* truncate if too long */
591 bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
592 /* Convert spaces into underscores */
593 for (p=jcr->Job; *p; p++) {
601 * Free the Job Control Record if no one is still using it.
602 * Called from main free_jcr() routine in src/lib/jcr.c so
603 * that we can do our Director specific cleanup of the jcr.
605 void dird_free_jcr(JCR *jcr)
607 Dmsg0(200, "Start dird free_jcr\n");
609 if (jcr->sd_auth_key) {
610 free(jcr->sd_auth_key);
611 jcr->sd_auth_key = NULL;
617 if (jcr->file_bsock) {
618 Dmsg0(200, "Close File bsock\n");
619 bnet_close(jcr->file_bsock);
620 jcr->file_bsock = NULL;
622 if (jcr->store_bsock) {
623 Dmsg0(200, "Close Store bsock\n");
624 bnet_close(jcr->store_bsock);
625 jcr->store_bsock = NULL;
628 Dmsg0(200, "Free JCR fname\n");
629 free_pool_memory(jcr->fname);
633 Dmsg0(200, "Free JCR stime\n");
634 free_pool_memory(jcr->stime);
637 if (jcr->RestoreBootstrap) {
638 free(jcr->RestoreBootstrap);
639 jcr->RestoreBootstrap = NULL;
641 if (jcr->client_uname) {
642 free_pool_memory(jcr->client_uname);
643 jcr->client_uname = NULL;
645 Dmsg0(200, "End dird free_jcr\n");
649 * Set some defaults in the JCR necessary to
650 * run. These items are pulled from the job
651 * definition as defaults, but can be overridden
652 * later either by the Run record in the Schedule resource,
653 * or by the Console program.
655 void set_jcr_defaults(JCR *jcr, JOB *job)
658 jcr->JobType = job->JobType;
659 jcr->JobLevel = job->level;
660 jcr->store = job->storage;
661 jcr->client = job->client;
662 if (!jcr->client_name) {
663 jcr->client_name = get_pool_memory(PM_NAME);
665 pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
666 jcr->pool = job->pool;
667 jcr->catalog = job->client->catalog;
668 jcr->fileset = job->fileset;
669 jcr->messages = job->messages;
670 if (jcr->RestoreBootstrap) {
671 free(jcr->RestoreBootstrap);
673 /* This can be overridden by Console program */
674 if (job->RestoreBootstrap) {
675 jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
677 /* If no default level given, set one */
678 if (jcr->JobLevel == 0) {
679 switch (jcr->JobType) {
681 jcr->JobLevel = L_VERIFY_CATALOG;
684 jcr->JobLevel = L_INCREMENTAL;
688 jcr->JobLevel = L_FULL;
697 * Edit codes into Run command
700 * %d = Director's name
708 * omsg = edited output message
709 * imsg = input string containing edit codes (%x)
712 static char *edit_run_codes(JCR *jcr, char *omsg, char *imsg)
719 Dmsg1(200, "edit_run_codes: %s\n", imsg);
720 for (p=imsg; *p; p++) {
727 str = jcr->client_name;
736 str = job_status_to_str(jcr->JobStatus);
739 sprintf(add, "%d", jcr->JobId);
746 str = job_level_to_str(jcr->JobLevel);
749 str = jcr->job->hdr.name;
752 str = job_type_to_str(jcr->JobType);
766 Dmsg1(200, "add_str %s\n", str);
767 pm_strcat(&omsg, (char *)str);
768 Dmsg1(200, "omsg=%s\n", omsg);