2 * Bacula job queue routines.
4 * This code consists of three queues, the waiting_jobs
5 * queue, where jobs are initially queued, the ready_jobs
6 * queue, where jobs are placed when all the resources are
7 * allocated and they can immediately be run, and the
8 * running queue where jobs are placed when they are
11 * Kern Sibbald, July MMIII
15 * This code was adapted from the Bacula workq, which was
16 * adapted from "Programming with POSIX Threads", by
21 Copyright (C) 2003-2004 Kern Sibbald and John Walker
23 This program is free software; you can redistribute it and/or
24 modify it under the terms of the GNU General Public License as
25 published by the Free Software Foundation; either version 2 of
26 the License, or (at your option) any later version.
28 This program is distributed in the hope that it will be useful,
29 but WITHOUT ANY WARRANTY; without even the implied warranty of
30 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
31 General Public License for more details.
33 You should have received a copy of the GNU General Public
34 License along with this program; if not, write to the Free
35 Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
44 /* Forward referenced functions */
45 extern "C" void *jobq_server(void *arg);
46 extern "C" void *sched_wait(void *arg);
48 static int start_server(jobq_t *jq);
51 * Initialize a job queue
53 * Returns: 0 on success
56 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
59 jobq_item_t *item = NULL;
61 if ((stat = pthread_attr_init(&jq->attr)) != 0) {
62 Jmsg1(NULL, M_ERROR, 0, "pthread_attr_init: ERR=%s\n", strerror(stat));
65 if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
66 pthread_attr_destroy(&jq->attr);
69 if ((stat = pthread_mutex_init(&jq->mutex, NULL)) != 0) {
70 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_init: ERR=%s\n", strerror(stat));
71 pthread_attr_destroy(&jq->attr);
74 if ((stat = pthread_cond_init(&jq->work, NULL)) != 0) {
75 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_init: ERR=%s\n", strerror(stat));
76 pthread_mutex_destroy(&jq->mutex);
77 pthread_attr_destroy(&jq->attr);
81 jq->max_workers = threads; /* max threads to create */
82 jq->num_workers = 0; /* no threads yet */
83 jq->idle_workers = 0; /* no idle threads */
84 jq->engine = engine; /* routine to run */
85 jq->valid = JOBQ_VALID;
86 /* Initialize the job queues */
87 jq->waiting_jobs = new dlist(item, &item->link);
88 jq->running_jobs = new dlist(item, &item->link);
89 jq->ready_jobs = new dlist(item, &item->link);
94 * Destroy the job queue
96 * Returns: 0 on success
99 int jobq_destroy(jobq_t *jq)
101 int stat, stat1, stat2;
103 if (jq->valid != JOBQ_VALID) {
106 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
107 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
110 jq->valid = 0; /* prevent any more operations */
113 * If any threads are active, wake them
115 if (jq->num_workers > 0) {
117 if (jq->idle_workers) {
118 if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
119 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_broadcast: ERR=%s\n", strerror(stat));
120 pthread_mutex_unlock(&jq->mutex);
124 while (jq->num_workers > 0) {
125 if ((stat = pthread_cond_wait(&jq->work, &jq->mutex)) != 0) {
126 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_wait: ERR=%s\n", strerror(stat));
127 pthread_mutex_unlock(&jq->mutex);
132 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
133 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
136 stat = pthread_mutex_destroy(&jq->mutex);
137 stat1 = pthread_cond_destroy(&jq->work);
138 stat2 = pthread_attr_destroy(&jq->attr);
139 delete jq->waiting_jobs;
140 delete jq->running_jobs;
141 delete jq->ready_jobs;
142 return (stat != 0 ? stat : (stat1 != 0 ? stat1 : stat2));
151 * Wait until schedule time arrives before starting. Normally
152 * this routine is only used for jobs started from the console
153 * for which the user explicitly specified a start time. Otherwise
154 * most jobs are put into the job queue only when their
155 * scheduled time arives.
158 void *sched_wait(void *arg)
160 JCR *jcr = ((wait_pkt *)arg)->jcr;
161 jobq_t *jq = ((wait_pkt *)arg)->jq;
163 Dmsg0(300, "Enter sched_wait.\n");
165 time_t wtime = jcr->sched_time - time(NULL);
166 /* Wait until scheduled time arrives */
167 if (wtime > 0 && verbose) {
168 Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
170 set_jcr_job_status(jcr, JS_WaitStartTime);
172 /* Check every 30 seconds if canceled */
174 Dmsg2(300, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
178 bmicrosleep(wtime, 0);
179 if (job_canceled(jcr)) {
182 wtime = jcr->sched_time - time(NULL);
184 P(jcr->mutex); /* lock jcr */
187 free_jcr(jcr); /* we are done with jcr */
188 Dmsg0(300, "Exit sched_wait\n");
193 * Add a job to the queue
194 * jq is a queue that was created with jobq_init
196 * On entry jcr->mutex must be locked.
199 int jobq_add(jobq_t *jq, JCR *jcr)
202 jobq_item_t *item, *li;
203 bool inserted = false;
204 time_t wtime = jcr->sched_time - time(NULL);
208 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
209 if (jq->valid != JOBQ_VALID) {
210 Jmsg0(jcr, M_ERROR, 0, "Jobq_add queue not initialized.\n");
214 jcr->use_count++; /* mark jcr in use by us */
216 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
217 if (!job_canceled(jcr) && wtime > 0) {
218 set_thread_concurrency(jq->max_workers + 2);
219 sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
220 sched_pkt->jcr = jcr;
222 stat = pthread_create(&id, &jq->attr, sched_wait, (void *)sched_pkt);
223 if (stat != 0) { /* thread not created */
224 Jmsg1(jcr, M_ERROR, 0, "pthread_thread_create: ERR=%s\n", strerror(stat));
225 jcr->use_count--; /* release jcr */
230 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
231 Jmsg1(jcr, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
232 jcr->use_count--; /* release jcr */
236 if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
237 jcr->use_count--; /* release jcr */
242 if (job_canceled(jcr)) {
243 /* Add job to ready queue so that it is canceled quickly */
244 jq->ready_jobs->prepend(item);
245 Dmsg1(300, "Prepended job=%d to ready queue\n", jcr->JobId);
247 /* Add this job to the wait queue in priority sorted order */
248 foreach_dlist(li, jq->waiting_jobs) {
249 Dmsg2(300, "waiting item jobid=%d priority=%d\n",
250 li->jcr->JobId, li->jcr->JobPriority);
251 if (li->jcr->JobPriority > jcr->JobPriority) {
252 jq->waiting_jobs->insert_before(item, li);
253 Dmsg2(300, "insert_before jobid=%d before waiting job=%d\n",
254 li->jcr->JobId, jcr->JobId);
259 /* If not jobs in wait queue, append it */
261 jq->waiting_jobs->append(item);
262 Dmsg1(300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
266 /* Ensure that at least one server looks at the queue. */
267 stat = start_server(jq);
269 pthread_mutex_unlock(&jq->mutex);
270 Dmsg0(300, "Return jobq_add\n");
275 * Remove a job from the job queue. Used only by cancel_job().
276 * jq is a queue that was created with jobq_init
277 * work_item is an element of work
279 * Note, it is "removed" from the job queue.
280 * If you want to cancel it, you need to provide some external means
281 * of doing so (e.g. pthread_kill()).
283 int jobq_remove(jobq_t *jq, JCR *jcr)
289 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
290 if (jq->valid != JOBQ_VALID) {
294 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
295 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
299 foreach_dlist(item, jq->waiting_jobs) {
300 if (jcr == item->jcr) {
306 pthread_mutex_unlock(&jq->mutex);
307 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
311 /* Move item to be the first on the list */
312 jq->waiting_jobs->remove(item);
313 jq->ready_jobs->prepend(item);
314 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x moved to ready queue\n", jcr->JobId, jcr);
316 stat = start_server(jq);
318 pthread_mutex_unlock(&jq->mutex);
319 Dmsg0(300, "Return jobq_remove\n");
325 * Start the server thread if it isn't already running
327 static int start_server(jobq_t *jq)
332 /* if any threads are idle, wake one */
333 if (jq->idle_workers > 0) {
334 Dmsg0(300, "Signal worker to wake up\n");
335 if ((stat = pthread_cond_signal(&jq->work)) != 0) {
336 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_signal: ERR=%s\n", strerror(stat));
339 } else if (jq->num_workers < jq->max_workers) {
340 Dmsg0(300, "Create worker thread\n");
341 /* No idle threads so create a new one */
342 set_thread_concurrency(jq->max_workers + 1);
343 if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
344 Jmsg1(NULL, M_ERROR, 0, "pthread_create: ERR=%s\n", strerror(stat));
353 * This is the worker thread that serves the job queue.
354 * When all the resources are acquired for the job,
355 * it will call the user's engine.
358 void *jobq_server(void *arg)
360 struct timespec timeout;
361 jobq_t *jq = (jobq_t *)arg;
362 jobq_item_t *je; /* job entry in queue */
364 bool timedout = false;
367 Dmsg0(300, "Start jobq_server\n");
368 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
369 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
378 Dmsg0(300, "Top of for loop\n");
379 if (!work && !jq->quit) {
380 gettimeofday(&tv, &tz);
382 timeout.tv_sec = tv.tv_sec + 4;
386 * Wait 4 seconds, then if no more work, exit
388 Dmsg0(300, "pthread_cond_timedwait()\n");
389 stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
390 if (stat == ETIMEDOUT) {
391 Dmsg0(300, "timedwait timedout.\n");
394 } else if (stat != 0) {
395 /* This shouldn't happen */
396 Dmsg0(300, "This shouldn't happen\n");
398 pthread_mutex_unlock(&jq->mutex);
405 * If anything is in the ready queue, run it
407 Dmsg0(300, "Checking ready queue.\n");
408 while (!jq->ready_jobs->empty() && !jq->quit) {
410 je = (jobq_item_t *)jq->ready_jobs->first();
412 jq->ready_jobs->remove(je);
413 if (!jq->ready_jobs->empty()) {
414 Dmsg0(300, "ready queue not empty start server\n");
415 if (start_server(jq) != 0) {
417 pthread_mutex_unlock(&jq->mutex);
421 jq->running_jobs->append(je);
422 Dmsg1(300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
423 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
424 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
429 /* Call user's routine here */
430 Dmsg1(300, "Calling user engine for jobid=%d\n", jcr->JobId);
433 Dmsg1(300, "Back from user engine jobid=%d.\n", jcr->JobId);
434 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
435 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
437 free(je); /* release job entry */
440 Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
441 jq->running_jobs->remove(je);
443 * Release locks if acquired. Note, they will not have
444 * been acquired for jobs canceled before they were
445 * put into the ready queue.
447 if (jcr->acquired_resource_locks) {
448 jcr->store->NumConcurrentJobs--;
449 if (jcr->JobType == JT_RESTORE) {
450 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
452 jcr->client->NumConcurrentJobs--;
453 jcr->job->NumConcurrentJobs--;
456 if (jcr->job->RescheduleOnError &&
457 jcr->JobStatus != JS_Terminated &&
458 jcr->JobStatus != JS_Canceled &&
459 jcr->job->RescheduleTimes > 0 &&
460 jcr->reschedule_count < jcr->job->RescheduleTimes) {
463 * Reschedule this job by cleaning it up, but
464 * reuse the same JobId if possible.
466 jcr->reschedule_count++;
467 jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
468 Dmsg2(300, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
469 (int)jcr->job->RescheduleInterval);
470 jcr->JobStatus = JS_Created; /* force new status */
471 dird_free_jcr(jcr); /* partial cleanup old stuff */
472 if (jcr->JobBytes == 0) {
473 Dmsg1(300, "Requeue job=%d\n", jcr->JobId);
475 jobq_add(jq, jcr); /* queue the job to run again */
477 free(je); /* free the job entry */
478 continue; /* look for another job to run */
481 * Something was actually backed up, so we cannot reuse
482 * the old JobId or there will be database record
483 * conflicts. We now create a new job, copying the
484 * appropriate fields.
486 JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
487 set_jcr_defaults(njcr, jcr->job);
488 njcr->reschedule_count = jcr->reschedule_count;
489 njcr->JobLevel = jcr->JobLevel;
490 njcr->JobStatus = jcr->JobStatus;
491 njcr->pool = jcr->pool;
492 njcr->store = jcr->store;
493 njcr->messages = jcr->messages;
494 Dmsg0(300, "Call to run new job\n");
496 run_job(njcr); /* This creates a "new" job */
497 free_jcr(njcr); /* release "new" jcr */
499 Dmsg0(300, "Back from running new job.\n");
501 /* Clean up and release old jcr */
503 db_close_database(jcr, jcr->db);
506 Dmsg1(300, "====== Termination job=%d\n", jcr->JobId);
508 free(je); /* release job entry */
511 * If any job in the wait queue can be run,
512 * move it to the ready queue
514 Dmsg0(300, "Done check ready, now check wait queue.\n");
515 while (!jq->waiting_jobs->empty() && !jq->quit) {
517 je = (jobq_item_t *)jq->waiting_jobs->first();
518 jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
520 Priority = re->jcr->JobPriority;
521 Dmsg2(300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
523 Priority = je->jcr->JobPriority;
524 Dmsg1(300, "No job running. Look for Job pri=%d\n", Priority);
527 * Walk down the list of waiting jobs and attempt
528 * to acquire the resources it needs.
531 /* je is current job item on the queue, jn is the next one */
533 jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
534 Dmsg3(300, "Examining Job=%d JobPri=%d want Pri=%d\n",
535 jcr->JobId, jcr->JobPriority, Priority);
536 /* Take only jobs of correct Priority */
537 if (jcr->JobPriority != Priority) {
538 set_jcr_job_status(jcr, JS_WaitPriority);
541 if (jcr->JobType == JT_RESTORE) {
542 /* Let only one Restore job run at a time regardless of MaxConcurrentJobs */
543 if (jcr->store->NumConcurrentJobs == 0) {
544 jcr->store->NumConcurrentJobs++;
545 jcr->saveMaxConcurrentJobs = jcr->store->MaxConcurrentJobs;
546 jcr->store->MaxConcurrentJobs = 1;
548 set_jcr_job_status(jcr, JS_WaitStoreRes);
552 } else if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
553 jcr->store->NumConcurrentJobs++;
555 set_jcr_job_status(jcr, JS_WaitStoreRes);
560 if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
561 jcr->client->NumConcurrentJobs++;
563 /* Back out previous locks */
564 jcr->store->NumConcurrentJobs--;
565 if (jcr->JobType == JT_RESTORE) {
566 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
568 set_jcr_job_status(jcr, JS_WaitClientRes);
572 if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
573 jcr->job->NumConcurrentJobs++;
575 /* Back out previous locks */
576 jcr->store->NumConcurrentJobs--;
577 if (jcr->JobType == JT_RESTORE) {
578 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
580 jcr->client->NumConcurrentJobs--;
581 set_jcr_job_status(jcr, JS_WaitJobRes);
585 /* Got all locks, now remove it from wait queue and append it
588 jcr->acquired_resource_locks = true;
589 jq->waiting_jobs->remove(je);
590 jq->ready_jobs->append(je);
591 Dmsg1(300, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
595 } /* end while loop */
596 Dmsg0(300, "Done checking wait queue.\n");
598 * If no more ready work and we are asked to quit, then do it
600 if (jq->ready_jobs->empty() && jq->quit) {
602 if (jq->num_workers == 0) {
603 Dmsg0(300, "Wake up destroy routine\n");
604 /* Wake up destroy routine if he is waiting */
605 pthread_cond_broadcast(&jq->work);
609 Dmsg0(300, "Check for work request\n");
611 * If no more work requests, and we waited long enough, quit
613 Dmsg2(300, "timedout=%d read empty=%d\n", timedout,
614 jq->ready_jobs->empty());
615 if (jq->ready_jobs->empty() && timedout) {
616 Dmsg0(300, "break big loop\n");
621 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
624 * If a job is waiting on a Resource, don't consume all
625 * the CPU time looping looking for work, and even more
626 * important, release the lock so that a job that has
627 * terminated can give us the resource.
629 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
630 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
634 bmicrosleep(2, 0); /* pause for 2 seconds */
635 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
636 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
640 /* Recompute work as something may have changed in last 2 secs */
641 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
643 Dmsg1(300, "Loop again. work=%d\n", work);
644 } /* end of big for loop */
646 Dmsg0(200, "unlock mutex\n");
647 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
648 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
650 Dmsg0(300, "End jobq_server\n");