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 set_jcr_job_status(jcr, JS_WaitStartTime);
167 /* Wait until scheduled time arrives */
169 Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
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 */
215 Dmsg3(300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count);
216 if (!job_canceled(jcr) && wtime > 0) {
217 set_thread_concurrency(jq->max_workers + 2);
218 sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
219 sched_pkt->jcr = jcr;
221 jcr->use_count--; /* release our use of 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));
229 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
230 Jmsg1(jcr, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
231 jcr->use_count--; /* release jcr */
235 if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
236 jcr->use_count--; /* release jcr */
241 if (job_canceled(jcr)) {
242 /* Add job to ready queue so that it is canceled quickly */
243 jq->ready_jobs->prepend(item);
244 Dmsg1(300, "Prepended job=%d to ready queue\n", jcr->JobId);
246 /* Add this job to the wait queue in priority sorted order */
247 foreach_dlist(li, jq->waiting_jobs) {
248 Dmsg2(300, "waiting item jobid=%d priority=%d\n",
249 li->jcr->JobId, li->jcr->JobPriority);
250 if (li->jcr->JobPriority > jcr->JobPriority) {
251 jq->waiting_jobs->insert_before(item, li);
252 Dmsg2(300, "insert_before jobid=%d before waiting job=%d\n",
253 li->jcr->JobId, jcr->JobId);
258 /* If not jobs in wait queue, append it */
260 jq->waiting_jobs->append(item);
261 Dmsg1(300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
265 /* Ensure that at least one server looks at the queue. */
266 stat = start_server(jq);
268 pthread_mutex_unlock(&jq->mutex);
269 Dmsg0(300, "Return jobq_add\n");
274 * Remove a job from the job queue. Used only by cancel_job().
275 * jq is a queue that was created with jobq_init
276 * work_item is an element of work
278 * Note, it is "removed" from the job queue.
279 * If you want to cancel it, you need to provide some external means
280 * of doing so (e.g. pthread_kill()).
282 int jobq_remove(jobq_t *jq, JCR *jcr)
288 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
289 if (jq->valid != JOBQ_VALID) {
293 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
294 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
298 foreach_dlist(item, jq->waiting_jobs) {
299 if (jcr == item->jcr) {
305 pthread_mutex_unlock(&jq->mutex);
306 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
310 /* Move item to be the first on the list */
311 jq->waiting_jobs->remove(item);
312 jq->ready_jobs->prepend(item);
313 Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x moved to ready queue\n", jcr->JobId, jcr);
315 stat = start_server(jq);
317 pthread_mutex_unlock(&jq->mutex);
318 Dmsg0(300, "Return jobq_remove\n");
324 * Start the server thread if it isn't already running
326 static int start_server(jobq_t *jq)
331 /* if any threads are idle, wake one */
332 if (jq->idle_workers > 0) {
333 Dmsg0(300, "Signal worker to wake up\n");
334 if ((stat = pthread_cond_signal(&jq->work)) != 0) {
335 Jmsg1(NULL, M_ERROR, 0, "pthread_cond_signal: ERR=%s\n", strerror(stat));
338 } else if (jq->num_workers < jq->max_workers) {
339 Dmsg0(300, "Create worker thread\n");
340 /* No idle threads so create a new one */
341 set_thread_concurrency(jq->max_workers + 1);
342 if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
343 Jmsg1(NULL, M_ERROR, 0, "pthread_create: ERR=%s\n", strerror(stat));
352 * This is the worker thread that serves the job queue.
353 * When all the resources are acquired for the job,
354 * it will call the user's engine.
357 void *jobq_server(void *arg)
359 struct timespec timeout;
360 jobq_t *jq = (jobq_t *)arg;
361 jobq_item_t *je; /* job entry in queue */
363 bool timedout = false;
366 Dmsg0(300, "Start jobq_server\n");
367 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
368 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
377 Dmsg0(300, "Top of for loop\n");
378 if (!work && !jq->quit) {
379 gettimeofday(&tv, &tz);
381 timeout.tv_sec = tv.tv_sec + 4;
385 * Wait 4 seconds, then if no more work, exit
387 Dmsg0(300, "pthread_cond_timedwait()\n");
388 stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
389 if (stat == ETIMEDOUT) {
390 Dmsg0(300, "timedwait timedout.\n");
393 } else if (stat != 0) {
394 /* This shouldn't happen */
395 Dmsg0(300, "This shouldn't happen\n");
397 pthread_mutex_unlock(&jq->mutex);
404 * If anything is in the ready queue, run it
406 Dmsg0(300, "Checking ready queue.\n");
407 while (!jq->ready_jobs->empty() && !jq->quit) {
409 je = (jobq_item_t *)jq->ready_jobs->first();
411 jq->ready_jobs->remove(je);
412 if (!jq->ready_jobs->empty()) {
413 Dmsg0(300, "ready queue not empty start server\n");
414 if (start_server(jq) != 0) {
416 pthread_mutex_unlock(&jq->mutex);
420 jq->running_jobs->append(je);
421 Dmsg1(300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
423 /* Release job queue lock */
424 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
425 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
430 /* Call user's routine here */
431 Dmsg1(300, "Calling user engine for jobid=%d\n", jcr->JobId);
434 Dmsg1(300, "Back from user engine jobid=%d.\n", jcr->JobId);
436 /* Reacquire job queue lock */
437 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
438 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
440 free(je); /* release job entry */
443 Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
444 jq->running_jobs->remove(je);
446 * Release locks if acquired. Note, they will not have
447 * been acquired for jobs canceled before they were
448 * put into the ready queue.
450 if (jcr->acquired_resource_locks) {
451 jcr->store->NumConcurrentJobs--;
452 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
453 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
455 jcr->client->NumConcurrentJobs--;
456 jcr->job->NumConcurrentJobs--;
460 * Reschedule the job if necessary and requested
462 if (jcr->job->RescheduleOnError &&
463 jcr->JobStatus != JS_Terminated &&
464 jcr->JobStatus != JS_Canceled &&
465 jcr->job->RescheduleTimes > 0 &&
466 jcr->reschedule_count < jcr->job->RescheduleTimes) {
470 * Reschedule this job by cleaning it up, but
471 * reuse the same JobId if possible.
473 jcr->reschedule_count++;
474 jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
475 Dmsg2(300, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
476 (int)jcr->job->RescheduleInterval);
477 bstrftime(dt, sizeof(dt), time(NULL));
478 Jmsg(jcr, M_INFO, 0, _("Rescheduled Job %s at %s to re-run in %d seconds.\n"),
479 jcr->Job, dt, (int)jcr->job->RescheduleInterval);
480 dird_free_jcr(jcr); /* partial cleanup old stuff */
481 jcr->JobStatus = JS_WaitStartTime;
482 jcr->SDJobStatus = 0;
483 if (jcr->JobBytes == 0) {
484 Dmsg1(300, "Requeue job=%d\n", jcr->JobId);
485 jcr->JobStatus = JS_WaitStartTime;
487 jobq_add(jq, jcr); /* queue the job to run again */
489 free(je); /* free the job entry */
490 continue; /* look for another job to run */
493 * Something was actually backed up, so we cannot reuse
494 * the old JobId or there will be database record
495 * conflicts. We now create a new job, copying the
496 * appropriate fields.
498 JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
499 set_jcr_defaults(njcr, jcr->job);
500 njcr->reschedule_count = jcr->reschedule_count;
501 njcr->JobLevel = jcr->JobLevel;
502 njcr->JobStatus = jcr->JobStatus;
503 copy_storage(njcr, jcr);
504 njcr->messages = jcr->messages;
505 Dmsg0(300, "Call to run new job\n");
507 run_job(njcr); /* This creates a "new" job */
508 free_jcr(njcr); /* release "new" jcr */
510 Dmsg0(300, "Back from running new job.\n");
512 /* Clean up and release old jcr */
514 db_close_database(jcr, jcr->db);
517 Dmsg2(300, "====== Termination job=%d use_cnt=%d\n", jcr->JobId, jcr->use_count);
518 jcr->SDJobStatus = 0;
519 V(jq->mutex); /* release internal lock */
521 free(je); /* release job entry */
522 P(jq->mutex); /* reacquire job queue lock */
525 * If any job in the wait queue can be run,
526 * move it to the ready queue
528 Dmsg0(300, "Done check ready, now check wait queue.\n");
529 while (!jq->waiting_jobs->empty() && !jq->quit) {
531 je = (jobq_item_t *)jq->waiting_jobs->first();
532 jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
534 Priority = re->jcr->JobPriority;
535 Dmsg2(300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
537 Priority = je->jcr->JobPriority;
538 Dmsg1(300, "No job running. Look for Job pri=%d\n", Priority);
541 * Walk down the list of waiting jobs and attempt
542 * to acquire the resources it needs.
545 /* je is current job item on the queue, jn is the next one */
547 jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
548 Dmsg3(300, "Examining Job=%d JobPri=%d want Pri=%d\n",
549 jcr->JobId, jcr->JobPriority, Priority);
550 /* Take only jobs of correct Priority */
551 if (jcr->JobPriority != Priority) {
552 set_jcr_job_status(jcr, JS_WaitPriority);
555 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
556 /* Let only one Restore/verify job run at a time regardless of MaxConcurrentJobs */
557 if (jcr->store->NumConcurrentJobs == 0) {
558 jcr->store->NumConcurrentJobs++;
559 jcr->saveMaxConcurrentJobs = jcr->store->MaxConcurrentJobs;
560 jcr->store->MaxConcurrentJobs = 1;
562 set_jcr_job_status(jcr, JS_WaitStoreRes);
566 } else if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
567 jcr->store->NumConcurrentJobs++;
569 set_jcr_job_status(jcr, JS_WaitStoreRes);
574 if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
575 jcr->client->NumConcurrentJobs++;
577 /* Back out previous locks */
578 jcr->store->NumConcurrentJobs--;
579 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
580 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
582 set_jcr_job_status(jcr, JS_WaitClientRes);
586 if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
587 jcr->job->NumConcurrentJobs++;
589 /* Back out previous locks */
590 jcr->store->NumConcurrentJobs--;
591 if (jcr->JobType == JT_RESTORE || jcr->JobType == JT_VERIFY) {
592 jcr->store->MaxConcurrentJobs = jcr->saveMaxConcurrentJobs;
594 jcr->client->NumConcurrentJobs--;
595 set_jcr_job_status(jcr, JS_WaitJobRes);
599 /* Got all locks, now remove it from wait queue and append it
602 jcr->acquired_resource_locks = true;
603 jq->waiting_jobs->remove(je);
604 jq->ready_jobs->append(je);
605 Dmsg1(300, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
609 } /* end while loop */
610 Dmsg0(300, "Done checking wait queue.\n");
612 * If no more ready work and we are asked to quit, then do it
614 if (jq->ready_jobs->empty() && jq->quit) {
616 if (jq->num_workers == 0) {
617 Dmsg0(300, "Wake up destroy routine\n");
618 /* Wake up destroy routine if he is waiting */
619 pthread_cond_broadcast(&jq->work);
623 Dmsg0(300, "Check for work request\n");
625 * If no more work requests, and we waited long enough, quit
627 Dmsg2(300, "timedout=%d read empty=%d\n", timedout,
628 jq->ready_jobs->empty());
629 if (jq->ready_jobs->empty() && timedout) {
630 Dmsg0(300, "break big loop\n");
635 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
638 * If a job is waiting on a Resource, don't consume all
639 * the CPU time looping looking for work, and even more
640 * important, release the lock so that a job that has
641 * terminated can give us the resource.
643 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
644 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
648 bmicrosleep(2, 0); /* pause for 2 seconds */
649 if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
650 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
654 /* Recompute work as something may have changed in last 2 secs */
655 work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
657 Dmsg1(300, "Loop again. work=%d\n", work);
658 } /* end of big for loop */
660 Dmsg0(200, "unlock mutex\n");
661 if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
662 Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
664 Dmsg0(300, "End jobq_server\n");