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
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,
45 /* Forward referenced functions */
46 extern "C" void *jobq_server(void *arg);
47 extern "C" void *sched_wait(void *arg);
49 static int start_server(jobq_t *jq);
54 * Initialize a job queue
56 * Returns: 0 on success
59 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
62 jobq_item_t *item = NULL;
64 if ((stat = pthread_attr_init(&jq->attr)) != 0) {
66 Jmsg1(NULL, M_ERROR, 0, "pthread_attr_init: ERR=%s\n", be.strerror(stat));
69 if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
70 pthread_attr_destroy(&jq->attr);
73 if ((stat = pthread_mutex_init(&jq->mutex, NULL)) != 0) {
75 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_init: ERR=%s\n", be.strerror(stat));
76 pthread_attr_destroy(&jq->attr);
79 if ((stat = pthread_cond_init(&jq->work, NULL)) != 0) {
81 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_init: ERR=%s\n", be.strerror(stat));
82 pthread_mutex_destroy(&jq->mutex);
83 pthread_attr_destroy(&jq->attr);
87 jq->max_workers = threads; /* max threads to create */
88 jq->num_workers = 0; /* no threads yet */
89 jq->idle_workers = 0; /* no idle threads */
90 jq->engine = engine; /* routine to run */
91 jq->valid = JOBQ_VALID;
92 /* Initialize the job queues */
93 jq->waiting_jobs = New(dlist(item, &item->link));
94 jq->running_jobs = New(dlist(item, &item->link));
95 jq->ready_jobs = New(dlist(item, &item->link));
100 * Destroy the job queue
102 * Returns: 0 on success
105 int jobq_destroy(jobq_t *jq)
107 int stat, stat1, stat2;
109 if (jq->valid != JOBQ_VALID) {
112 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
114 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
117 jq->valid = 0; /* prevent any more operations */
120 * If any threads are active, wake them
122 if (jq->num_workers > 0) {
124 if (jq->idle_workers) {
125 if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
127 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_broadcast: ERR=%s\n", be.strerror(stat));
128 pthread_mutex_unlock(&jq->mutex);
132 while (jq->num_workers > 0) {
133 if ((stat = pthread_cond_wait(&jq->work, &jq->mutex)) != 0) {
135 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_wait: ERR=%s\n", be.strerror(stat));
136 pthread_mutex_unlock(&jq->mutex);
141 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
143 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", be.strerror(stat));
146 stat = pthread_mutex_destroy(&jq->mutex);
147 stat1 = pthread_cond_destroy(&jq->work);
148 stat2 = pthread_attr_destroy(&jq->attr);
149 delete jq->waiting_jobs;
150 delete jq->running_jobs;
151 delete jq->ready_jobs;
152 return (stat != 0 ? stat : (stat1 != 0 ? stat1 : stat2));
161 * Wait until schedule time arrives before starting. Normally
162 * this routine is only used for jobs started from the console
163 * for which the user explicitly specified a start time. Otherwise
164 * most jobs are put into the job queue only when their
165 * scheduled time arives.
168 void *sched_wait(void *arg)
170 JCR *jcr = ((wait_pkt *)arg)->jcr;
171 jobq_t *jq = ((wait_pkt *)arg)->jq;
173 Dmsg0(300, "Enter sched_wait.\n");
175 time_t wtime = jcr->sched_time - time(NULL);
176 set_jcr_job_status(jcr, JS_WaitStartTime);
177 /* Wait until scheduled time arrives */
179 Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
182 /* Check every 30 seconds if canceled */
184 Dmsg2(300, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
188 bmicrosleep(wtime, 0);
189 if (job_canceled(jcr)) {
192 wtime = jcr->sched_time - time(NULL);
194 P(jcr->mutex); /* lock jcr */
197 free_jcr(jcr); /* we are done with jcr */
198 Dmsg0(300, "Exit sched_wait\n");
203 * Add a job to the queue
204 * jq is a queue that was created with jobq_init
206 * On entry jcr->mutex must be locked.
209 int jobq_add(jobq_t *jq, JCR *jcr)
212 jobq_item_t *item, *li;
213 bool inserted = false;
214 time_t wtime = jcr->sched_time - time(NULL);
218 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
219 if (jq->valid != JOBQ_VALID) {
220 Jmsg0(jcr, M_ERROR, 0, "Jobq_add queue not initialized.\n");
224 jcr->use_count++; /* mark jcr in use by us */
225 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
226 if (!job_canceled(jcr) && wtime > 0) {
227 set_thread_concurrency(jq->max_workers + 2);
228 sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
229 sched_pkt->jcr = jcr;
231 // jcr->use_count--; /* release our use of jcr */
232 stat = pthread_create(&id, &jq->attr, sched_wait, (void *)sched_pkt);
233 if (stat != 0) { /* thread not created */
235 Jmsg1(jcr, M_ERROR, 0, "pthread_thread_create: ERR=%s\n", be.strerror(stat));
240 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
242 Jmsg1(jcr, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
243 jcr->use_count--; /* release jcr */
247 if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
248 jcr->use_count--; /* release jcr */
253 if (job_canceled(jcr)) {
254 /* Add job to ready queue so that it is canceled quickly */
255 jq->ready_jobs->prepend(item);
256 Dmsg1(300, "Prepended job=%d to ready queue\n", jcr->JobId);
258 /* Add this job to the wait queue in priority sorted order */
259 foreach_dlist(li, jq->waiting_jobs) {
260 Dmsg2(300, "waiting item jobid=%d priority=%d\n",
261 li->jcr->JobId, li->jcr->JobPriority);
262 if (li->jcr->JobPriority > jcr->JobPriority) {
263 jq->waiting_jobs->insert_before(item, li);
264 Dmsg2(300, "insert_before jobid=%d before waiting job=%d\n",
265 li->jcr->JobId, jcr->JobId);
270 /* If not jobs in wait queue, append it */
272 jq->waiting_jobs->append(item);
273 Dmsg1(300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
277 /* Ensure that at least one server looks at the queue. */
278 stat = start_server(jq);
280 pthread_mutex_unlock(&jq->mutex);
281 Dmsg0(300, "Return jobq_add\n");
286 * Remove a job from the job queue. Used only by cancel_job().
287 * jq is a queue that was created with jobq_init
288 * work_item is an element of work
290 * Note, it is "removed" from the job queue.
291 * If you want to cancel it, you need to provide some external means
292 * of doing so (e.g. pthread_kill()).
294 int jobq_remove(jobq_t *jq, JCR *jcr)
300 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
301 if (jq->valid != JOBQ_VALID) {
305 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
307 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
311 foreach_dlist(item, jq->waiting_jobs) {
312 if (jcr == item->jcr) {
318 pthread_mutex_unlock(&jq->mutex);
319 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
323 /* Move item to be the first on the list */
324 jq->waiting_jobs->remove(item);
325 jq->ready_jobs->prepend(item);
326 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x moved to ready queue\n", jcr->JobId, jcr);
328 stat = start_server(jq);
330 pthread_mutex_unlock(&jq->mutex);
331 Dmsg0(300, "Return jobq_remove\n");
337 * Start the server thread if it isn't already running
339 static int start_server(jobq_t *jq)
344 /* if any threads are idle, wake one */
345 if (jq->idle_workers > 0) {
346 Dmsg0(300, "Signal worker to wake up\n");
347 if ((stat = pthread_cond_signal(&jq->work)) != 0) {
349 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_signal: ERR=%s\n", be.strerror(stat));
352 } else if (jq->num_workers < jq->max_workers) {
353 Dmsg0(300, "Create worker thread\n");
354 /* No idle threads so create a new one */
355 set_thread_concurrency(jq->max_workers + 1);
356 if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
358 Jmsg1(NULL, M_ERROR, 0, "pthread_create: ERR=%s\n", be.strerror(stat));
367 * This is the worker thread that serves the job queue.
368 * When all the resources are acquired for the job,
369 * it will call the user's engine.
372 void *jobq_server(void *arg)
374 struct timespec timeout;
375 jobq_t *jq = (jobq_t *)arg;
376 jobq_item_t *je; /* job entry in queue */
378 bool timedout = false;
381 Dmsg0(300, "Start jobq_server\n");
382 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
384 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
393 Dmsg0(300, "Top of for loop\n");
394 if (!work && !jq->quit) {
395 gettimeofday(&tv, &tz);
397 timeout.tv_sec = tv.tv_sec + 4;
401 * Wait 4 seconds, then if no more work, exit
403 Dmsg0(300, "pthread_cond_timedwait()\n");
404 stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
405 if (stat == ETIMEDOUT) {
406 Dmsg0(300, "timedwait timedout.\n");
409 } else if (stat != 0) {
410 /* This shouldn't happen */
411 Dmsg0(300, "This shouldn't happen\n");
413 pthread_mutex_unlock(&jq->mutex);
420 * If anything is in the ready queue, run it
422 Dmsg0(300, "Checking ready queue.\n");
423 while (!jq->ready_jobs->empty() && !jq->quit) {
425 je = (jobq_item_t *)jq->ready_jobs->first();
427 jq->ready_jobs->remove(je);
428 if (!jq->ready_jobs->empty()) {
429 Dmsg0(300, "ready queue not empty start server\n");
430 if (start_server(jq) != 0) {
432 pthread_mutex_unlock(&jq->mutex);
436 jq->running_jobs->append(je);
437 Dmsg1(300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
439 /* Release job queue lock */
440 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
442 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", be.strerror(stat));
447 /* Call user's routine here */
448 Dmsg1(300, "Calling user engine for jobid=%d\n", jcr->JobId);
451 Dmsg1(300, "Back from user engine jobid=%d.\n", jcr->JobId);
453 /* Reacquire job queue lock */
454 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
456 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
458 free(je); /* release job entry */
461 Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
462 jq->running_jobs->remove(je);
464 * Release locks if acquired. Note, they will not have
465 * been acquired for jobs canceled before they were
466 * put into the ready queue.
468 if (jcr->acquired_resource_locks) {
469 jcr->store->NumConcurrentJobs--;
470 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
471 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
473 jcr->client->NumConcurrentJobs--;
474 jcr->job->NumConcurrentJobs--;
478 * Reschedule the job if necessary and requested
480 if (jcr->job->RescheduleOnError &&
481 jcr->JobStatus != JS_Terminated &&
482 jcr->JobStatus != JS_Canceled &&
483 jcr->job->RescheduleTimes > 0 &&
484 jcr->reschedule_count < jcr->job->RescheduleTimes) {
488 * Reschedule this job by cleaning it up, but
489 * reuse the same JobId if possible.
491 jcr->reschedule_count++;
492 jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
493 Dmsg2(300, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
494 (int)jcr->job->RescheduleInterval);
495 bstrftime(dt, sizeof(dt), time(NULL));
496 Jmsg(jcr, M_INFO, 0, _("Rescheduled Job %s at %s to re-run in %d seconds.\n"),
497 jcr->Job, dt, (int)jcr->job->RescheduleInterval);
498 dird_free_jcr(jcr); /* partial cleanup old stuff */
499 jcr->JobStatus = JS_WaitStartTime;
500 jcr->SDJobStatus = 0;
501 if (jcr->JobBytes == 0) {
502 Dmsg1(300, "Requeue job=%d\n", jcr->JobId);
503 jcr->JobStatus = JS_WaitStartTime;
505 jobq_add(jq, jcr); /* queue the job to run again */
507 free(je); /* free the job entry */
508 continue; /* look for another job to run */
511 * Something was actually backed up, so we cannot reuse
512 * the old JobId or there will be database record
513 * conflicts. We now create a new job, copying the
514 * appropriate fields.
516 JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
517 set_jcr_defaults(njcr, jcr->job);
518 njcr->reschedule_count = jcr->reschedule_count;
519 njcr->JobLevel = jcr->JobLevel;
520 njcr->JobStatus = jcr->JobStatus;
521 copy_storage(njcr, jcr);
522 njcr->messages = jcr->messages;
523 Dmsg0(300, "Call to run new job\n");
525 run_job(njcr); /* This creates a "new" job */
526 free_jcr(njcr); /* release "new" jcr */
528 Dmsg0(300, "Back from running new job.\n");
530 /* Clean up and release old jcr */
532 db_close_database(jcr, jcr->db);
535 Dmsg2(300, "====== Termination job=%d use_cnt=%d\n", jcr->JobId, jcr->use_count);
536 jcr->SDJobStatus = 0;
537 V(jq->mutex); /* release internal lock */
539 free(je); /* release job entry */
540 P(jq->mutex); /* reacquire job queue lock */
543 * If any job in the wait queue can be run,
544 * move it to the ready queue
546 Dmsg0(300, "Done check ready, now check wait queue.\n");
547 while (!jq->waiting_jobs->empty() && !jq->quit) {
549 je = (jobq_item_t *)jq->waiting_jobs->first();
550 jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
552 Priority = re->jcr->JobPriority;
553 Dmsg2(300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
555 Priority = je->jcr->JobPriority;
556 Dmsg1(300, "No job running. Look for Job pri=%d\n", Priority);
559 * Walk down the list of waiting jobs and attempt
560 * to acquire the resources it needs.
563 /* je is current job item on the queue, jn is the next one */
565 bool skip_this_jcr = false;
566 jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
567 Dmsg3(300, "Examining Job=%d JobPri=%d want Pri=%d\n",
568 jcr->JobId, jcr->JobPriority, Priority);
569 /* Take only jobs of correct Priority */
570 if (jcr->JobPriority != Priority) {
571 set_jcr_job_status(jcr, JS_WaitPriority);
574 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
575 /* Let only one Restore/verify job run at a time regardless of MaxConcurrentJobs */
576 if (jcr->store->NumConcurrentJobs == 0) {
577 jcr->store->NumConcurrentJobs++;
578 jcr->saveMaxConcurrentJobs = jcr->store->MaxConcurrentJobs;
579 jcr->store->MaxConcurrentJobs = 1;
581 set_jcr_job_status(jcr, JS_WaitStoreRes);
582 je = jn; /* point to next waiting job */
585 /* We are not doing a Restore or Verify */
586 } else if (jcr->store->NumConcurrentJobs == 0 &&
587 jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
588 /* Simple case, first job */
589 jcr->store->NumConcurrentJobs = 1;
590 } else if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
592 * At this point, we already have at least one Job running
593 * for this Storage daemon, so we must ensure that there
594 * is no Volume conflict. In general, it should be OK, if
595 * all Jobs pull from the same Pool, so we check the Pools.
599 for (njcr=jobs; njcr; njcr=njcr->next) {
600 if (njcr->JobId == 0 || njcr == jcr) {
603 if (njcr->pool != jcr->pool) {
604 skip_this_jcr = true;
609 if (!skip_this_jcr) {
610 jcr->store->NumConcurrentJobs++;
614 set_jcr_job_status(jcr, JS_WaitStoreRes);
615 je = jn; /* point to next waiting job */
619 if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
620 jcr->client->NumConcurrentJobs++;
622 /* Back out previous locks */
623 jcr->store->NumConcurrentJobs--;
624 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
625 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
627 set_jcr_job_status(jcr, JS_WaitClientRes);
628 je = jn; /* point to next waiting job */
631 if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
632 jcr->job->NumConcurrentJobs++;
634 /* Back out previous locks */
635 jcr->store->NumConcurrentJobs--;
636 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
637 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
639 jcr->client->NumConcurrentJobs--;
640 set_jcr_job_status(jcr, JS_WaitJobRes);
641 je = jn; /* Point to next waiting job */
644 /* Got all locks, now remove it from wait queue and append it
647 jcr->acquired_resource_locks = true;
648 jq->waiting_jobs->remove(je);
649 jq->ready_jobs->append(je);
650 Dmsg1(300, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
651 je = jn; /* Point to next waiting job */
654 } /* end while loop */
655 Dmsg0(300, "Done checking wait queue.\n");
657 * If no more ready work and we are asked to quit, then do it
659 if (jq->ready_jobs->empty() && jq->quit) {
661 if (jq->num_workers == 0) {
662 Dmsg0(300, "Wake up destroy routine\n");
663 /* Wake up destroy routine if he is waiting */
664 pthread_cond_broadcast(&jq->work);
668 Dmsg0(300, "Check for work request\n");
670 * If no more work requests, and we waited long enough, quit
672 Dmsg2(300, "timedout=%d read empty=%d\n", timedout,
673 jq->ready_jobs->empty());
674 if (jq->ready_jobs->empty() && timedout) {
675 Dmsg0(300, "break big loop\n");
680 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
683 * If a job is waiting on a Resource, don't consume all
684 * the CPU time looping looking for work, and even more
685 * important, release the lock so that a job that has
686 * terminated can give us the resource.
688 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
690 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", be.strerror(stat));
694 bmicrosleep(2, 0); /* pause for 2 seconds */
695 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
697 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", be.strerror(stat));
701 /* Recompute work as something may have changed in last 2 secs */
702 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
704 Dmsg1(300, "Loop again. work=%d\n", work);
705 } /* end of big for loop */
707 Dmsg0(200, "unlock mutex\n");
708 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
710 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", be.strerror(stat));
712 Dmsg0(300, "End jobq_server\n");