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 static void *jobq_server(void *arg);
46 static int start_server(jobq_t *jq);
49 * Initialize a job queue
51 * Returns: 0 on success
54 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
57 jobq_item_t *item = NULL;
59 if ((stat = pthread_attr_init(&jq->attr)) != 0) {
60 Jmsg1(NULL, M_ERROR, 0, "pthread_attr_init: ERR=%s\n", strerror(stat));
63 if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
64 pthread_attr_destroy(&jq->attr);
67 if ((stat = pthread_mutex_init(&jq->mutex, NULL)) != 0) {
68 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_init: ERR=%s\n", strerror(stat));
69 pthread_attr_destroy(&jq->attr);
72 if ((stat = pthread_cond_init(&jq->work, NULL)) != 0) {
73 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_init: ERR=%s\n", strerror(stat));
74 pthread_mutex_destroy(&jq->mutex);
75 pthread_attr_destroy(&jq->attr);
79 jq->max_workers = threads; /* max threads to create */
80 jq->num_workers = 0; /* no threads yet */
81 jq->idle_workers = 0; /* no idle threads */
82 jq->engine = engine; /* routine to run */
83 jq->valid = JOBQ_VALID;
84 /* Initialize the job queues */
85 jq->waiting_jobs = new dlist(item, &item->link);
86 jq->running_jobs = new dlist(item, &item->link);
87 jq->ready_jobs = new dlist(item, &item->link);
92 * Destroy the job queue
94 * Returns: 0 on success
97 int jobq_destroy(jobq_t *jq)
99 int stat, stat1, stat2;
101 if (jq->valid != JOBQ_VALID) {
104 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
105 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
108 jq->valid = 0; /* prevent any more operations */
111 * If any threads are active, wake them
113 if (jq->num_workers > 0) {
115 if (jq->idle_workers) {
116 if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
117 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_broadcast: ERR=%s\n", strerror(stat));
118 pthread_mutex_unlock(&jq->mutex);
122 while (jq->num_workers > 0) {
123 if ((stat = pthread_cond_wait(&jq->work, &jq->mutex)) != 0) {
124 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_wait: ERR=%s\n", strerror(stat));
125 pthread_mutex_unlock(&jq->mutex);
130 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
131 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
134 stat = pthread_mutex_destroy(&jq->mutex);
135 stat1 = pthread_cond_destroy(&jq->work);
136 stat2 = pthread_attr_destroy(&jq->attr);
137 delete jq->waiting_jobs;
138 delete jq->running_jobs;
139 delete jq->ready_jobs;
140 return (stat != 0 ? stat : (stat1 != 0 ? stat1 : stat2));
149 * Wait until schedule time arrives before starting. Normally
150 * this routine is only used for jobs started from the console
151 * for which the user explicitly specified a start time. Otherwise
152 * most jobs are put into the job queue only when their
153 * scheduled time arives.
155 static void *sched_wait(void *arg)
157 JCR *jcr = ((wait_pkt *)arg)->jcr;
158 jobq_t *jq = ((wait_pkt *)arg)->jq;
160 Dmsg0(300, "Enter sched_wait.\n");
162 time_t wtime = jcr->sched_time - time(NULL);
163 /* Wait until scheduled time arrives */
164 if (wtime > 0 && verbose) {
165 Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
167 set_jcr_job_status(jcr, JS_WaitStartTime);
169 /* Check every 30 seconds if canceled */
171 Dmsg2(300, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
175 bmicrosleep(wtime, 0);
176 if (job_canceled(jcr)) {
179 wtime = jcr->sched_time - time(NULL);
181 P(jcr->mutex); /* lock jcr */
184 free_jcr(jcr); /* we are done with jcr */
185 Dmsg0(300, "Exit sched_wait\n");
191 * Add a job to the queue
192 * jq is a queue that was created with jobq_init
194 * On entry jcr->mutex must be locked.
197 int jobq_add(jobq_t *jq, JCR *jcr)
200 jobq_item_t *item, *li;
201 bool inserted = false;
202 time_t wtime = jcr->sched_time - time(NULL);
206 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
207 if (jq->valid != JOBQ_VALID) {
208 Jmsg0(jcr, M_ERROR, 0, "Jobq_add queue not initialized.\n");
212 jcr->use_count++; /* mark jcr in use by us */
214 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
215 if (!job_canceled(jcr) && wtime > 0) {
216 set_thread_concurrency(jq->max_workers + 2);
217 sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
218 sched_pkt->jcr = jcr;
220 stat = pthread_create(&id, &jq->attr, sched_wait, (void *)sched_pkt);
221 if (stat != 0) { /* thread not created */
222 Jmsg1(jcr, M_ERROR, 0, "pthread_thread_create: ERR=%s\n", strerror(stat));
223 jcr->use_count--; /* release jcr */
228 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
229 Jmsg1(jcr, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
230 jcr->use_count--; /* release jcr */
234 if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
235 jcr->use_count--; /* release jcr */
240 if (job_canceled(jcr)) {
241 /* Add job to ready queue so that it is canceled quickly */
242 jq->ready_jobs->prepend(item);
243 Dmsg1(300, "Prepended job=%d to ready queue\n", jcr->JobId);
245 /* Add this job to the wait queue in priority sorted order */
246 foreach_dlist(li, jq->waiting_jobs) {
247 Dmsg2(300, "waiting item jobid=%d priority=%d\n",
248 li->jcr->JobId, li->jcr->JobPriority);
249 if (li->jcr->JobPriority > jcr->JobPriority) {
250 jq->waiting_jobs->insert_before(item, li);
251 Dmsg2(300, "insert_before jobid=%d before waiting job=%d\n",
252 li->jcr->JobId, jcr->JobId);
257 /* If not jobs in wait queue, append it */
259 jq->waiting_jobs->append(item);
260 Dmsg1(300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
264 /* Ensure that at least one server looks at the queue. */
265 stat = start_server(jq);
267 pthread_mutex_unlock(&jq->mutex);
268 Dmsg0(300, "Return jobq_add\n");
273 * Remove a job from the job queue. Used only by cancel_job().
274 * jq is a queue that was created with jobq_init
275 * work_item is an element of work
277 * Note, it is "removed" from the job queue.
278 * If you want to cancel it, you need to provide some external means
279 * of doing so (e.g. pthread_kill()).
281 int jobq_remove(jobq_t *jq, JCR *jcr)
287 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
288 if (jq->valid != JOBQ_VALID) {
292 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
293 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
297 foreach_dlist(item, jq->waiting_jobs) {
298 if (jcr == item->jcr) {
304 pthread_mutex_unlock(&jq->mutex);
305 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
309 /* Move item to be the first on the list */
310 jq->waiting_jobs->remove(item);
311 jq->ready_jobs->prepend(item);
312 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x moved to ready queue\n", jcr->JobId, jcr);
314 stat = start_server(jq);
316 pthread_mutex_unlock(&jq->mutex);
317 Dmsg0(300, "Return jobq_remove\n");
323 * Start the server thread if it isn't already running
325 static int start_server(jobq_t *jq)
330 /* if any threads are idle, wake one */
331 if (jq->idle_workers > 0) {
332 Dmsg0(300, "Signal worker to wake up\n");
333 if ((stat = pthread_cond_signal(&jq->work)) != 0) {
334 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_signal: ERR=%s\n", strerror(stat));
337 } else if (jq->num_workers < jq->max_workers) {
338 Dmsg0(300, "Create worker thread\n");
339 /* No idle threads so create a new one */
340 set_thread_concurrency(jq->max_workers + 1);
341 if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
342 Jmsg1(NULL, M_ERROR, 0, "pthread_create: ERR=%s\n", strerror(stat));
351 * This is the worker thread that serves the job queue.
352 * When all the resources are acquired for the job,
353 * it will call the user's engine.
355 static void *jobq_server(void *arg)
357 struct timespec timeout;
358 jobq_t *jq = (jobq_t *)arg;
359 jobq_item_t *je; /* job entry in queue */
361 bool timedout = false;
364 Dmsg0(300, "Start jobq_server\n");
365 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
366 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
375 Dmsg0(300, "Top of for loop\n");
376 if (!work && !jq->quit) {
377 gettimeofday(&tv, &tz);
379 timeout.tv_sec = tv.tv_sec + 4;
383 * Wait 4 seconds, then if no more work, exit
385 Dmsg0(300, "pthread_cond_timedwait()\n");
386 stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
387 if (stat == ETIMEDOUT) {
388 Dmsg0(300, "timedwait timedout.\n");
391 } else if (stat != 0) {
392 /* This shouldn't happen */
393 Dmsg0(300, "This shouldn't happen\n");
395 pthread_mutex_unlock(&jq->mutex);
402 * If anything is in the ready queue, run it
404 Dmsg0(300, "Checking ready queue.\n");
405 while (!jq->ready_jobs->empty() && !jq->quit) {
407 je = (jobq_item_t *)jq->ready_jobs->first();
409 jq->ready_jobs->remove(je);
410 if (!jq->ready_jobs->empty()) {
411 Dmsg0(300, "ready queue not empty start server\n");
412 if (start_server(jq) != 0) {
414 pthread_mutex_unlock(&jq->mutex);
418 jq->running_jobs->append(je);
419 Dmsg1(300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
420 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
421 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
426 /* Call user's routine here */
427 Dmsg1(300, "Calling user engine for jobid=%d\n", jcr->JobId);
430 Dmsg1(300, "Back from user engine jobid=%d.\n", jcr->JobId);
431 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
432 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
434 free(je); /* release job entry */
437 Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
438 jq->running_jobs->remove(je);
440 * Release locks if acquired. Note, they will not have
441 * been acquired for jobs canceled before they were
442 * put into the ready queue.
444 if (jcr->acquired_resource_locks) {
445 jcr->store->NumConcurrentJobs--;
446 if (jcr->JobType == JT_RESTORE) {
447 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
449 jcr->client->NumConcurrentJobs--;
450 jcr->job->NumConcurrentJobs--;
453 if (jcr->job->RescheduleOnError &&
454 jcr->JobStatus != JS_Terminated &&
455 jcr->JobStatus != JS_Canceled &&
456 jcr->job->RescheduleTimes > 0 &&
457 jcr->reschedule_count < jcr->job->RescheduleTimes) {
460 * Reschedule this job by cleaning it up, but
461 * reuse the same JobId if possible.
463 jcr->reschedule_count++;
464 jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
465 Dmsg2(300, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
466 (int)jcr->job->RescheduleInterval);
467 jcr->JobStatus = JS_Created; /* force new status */
468 dird_free_jcr(jcr); /* partial cleanup old stuff */
469 if (jcr->JobBytes == 0) {
470 Dmsg1(300, "Requeue job=%d\n", jcr->JobId);
472 jobq_add(jq, jcr); /* queue the job to run again */
474 free(je); /* free the job entry */
475 continue; /* look for another job to run */
478 * Something was actually backed up, so we cannot reuse
479 * the old JobId or there will be database record
480 * conflicts. We now create a new job, copying the
481 * appropriate fields.
483 JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
484 set_jcr_defaults(njcr, jcr->job);
485 njcr->reschedule_count = jcr->reschedule_count;
486 njcr->JobLevel = jcr->JobLevel;
487 njcr->JobStatus = jcr->JobStatus;
488 njcr->pool = jcr->pool;
489 njcr->store = jcr->store;
490 njcr->messages = jcr->messages;
491 Dmsg0(300, "Call to run new job\n");
493 run_job(njcr); /* This creates a "new" job */
494 free_jcr(njcr); /* release "new" jcr */
496 Dmsg0(300, "Back from running new job.\n");
498 /* Clean up and release old jcr */
500 db_close_database(jcr, jcr->db);
503 Dmsg1(300, "====== Termination job=%d\n", jcr->JobId);
505 free(je); /* release job entry */
508 * If any job in the wait queue can be run,
509 * move it to the ready queue
511 Dmsg0(300, "Done check ready, now check wait queue.\n");
512 while (!jq->waiting_jobs->empty() && !jq->quit) {
514 je = (jobq_item_t *)jq->waiting_jobs->first();
515 jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
517 Priority = re->jcr->JobPriority;
518 Dmsg2(300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
520 Priority = je->jcr->JobPriority;
521 Dmsg1(300, "No job running. Look for Job pri=%d\n", Priority);
524 * Walk down the list of waiting jobs and attempt
525 * to acquire the resources it needs.
528 /* je is current job item on the queue, jn is the next one */
530 jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
531 Dmsg3(300, "Examining Job=%d JobPri=%d want Pri=%d\n",
532 jcr->JobId, jcr->JobPriority, Priority);
533 /* Take only jobs of correct Priority */
534 if (jcr->JobPriority != Priority) {
535 set_jcr_job_status(jcr, JS_WaitPriority);
538 if (jcr->JobType == JT_RESTORE) {
539 /* Let only one Restore job run at a time regardless of MaxConcurrentJobs */
540 if (jcr->store->NumConcurrentJobs == 0) {
541 jcr->store->NumConcurrentJobs++;
542 jcr->saveMaxConcurrentJobs = jcr->store->MaxConcurrentJobs;
543 jcr->store->MaxConcurrentJobs = 1;
545 set_jcr_job_status(jcr, JS_WaitStoreRes);
549 } else if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
550 jcr->store->NumConcurrentJobs++;
552 set_jcr_job_status(jcr, JS_WaitStoreRes);
557 if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
558 jcr->client->NumConcurrentJobs++;
560 /* Back out previous locks */
561 jcr->store->NumConcurrentJobs--;
562 if (jcr->JobType == JT_RESTORE) {
563 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
565 set_jcr_job_status(jcr, JS_WaitClientRes);
569 if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
570 jcr->job->NumConcurrentJobs++;
572 /* Back out previous locks */
573 jcr->store->NumConcurrentJobs--;
574 if (jcr->JobType == JT_RESTORE) {
575 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
577 jcr->client->NumConcurrentJobs--;
578 set_jcr_job_status(jcr, JS_WaitJobRes);
582 /* Got all locks, now remove it from wait queue and append it
585 jcr->acquired_resource_locks = true;
586 jq->waiting_jobs->remove(je);
587 jq->ready_jobs->append(je);
588 Dmsg1(300, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
592 } /* end while loop */
593 Dmsg0(300, "Done checking wait queue.\n");
595 * If no more ready work and we are asked to quit, then do it
597 if (jq->ready_jobs->empty() && jq->quit) {
599 if (jq->num_workers == 0) {
600 Dmsg0(300, "Wake up destroy routine\n");
601 /* Wake up destroy routine if he is waiting */
602 pthread_cond_broadcast(&jq->work);
606 Dmsg0(300, "Check for work request\n");
608 * If no more work requests, and we waited long enough, quit
610 Dmsg2(300, "timedout=%d read empty=%d\n", timedout,
611 jq->ready_jobs->empty());
612 if (jq->ready_jobs->empty() && timedout) {
613 Dmsg0(300, "break big loop\n");
618 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
621 * If a job is waiting on a Resource, don't consume all
622 * the CPU time looping looking for work, and even more
623 * important, release the lock so that a job that has
624 * terminated can give us the resource.
626 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
627 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
631 bmicrosleep(2, 0); /* pause for 2 seconds */
632 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
633 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
637 /* Recompute work as something may have changed in last 2 secs */
638 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
640 Dmsg1(300, "Loop again. work=%d\n", work);
641 } /* end of big for loop */
643 Dmsg0(200, "unlock mutex\n");
644 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
645 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
647 Dmsg0(300, "End jobq_server\n");