]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/jobq.c
02Mar07
[bacula/bacula] / bacula / src / dird / jobq.c
1 /*
2  * Bacula job queue routines.
3  *
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
9  *  running.
10  *
11  *  Kern Sibbald, July MMIII
12  *
13  *   Version $Id$
14  *
15  *  This code was adapted from the Bacula workq, which was
16  *    adapted from "Programming with POSIX Threads", by
17  *    David R. Butenhof
18  *
19  */
20 /*
21    Bacula® - The Network Backup Solution
22
23    Copyright (C) 2003-2007 Free Software Foundation Europe e.V.
24
25    The main author of Bacula is Kern Sibbald, with contributions from
26    many others, a complete list can be found in the file AUTHORS.
27    This program is Free Software; you can redistribute it and/or
28    modify it under the terms of version two of the GNU General Public
29    License as published by the Free Software Foundation plus additions
30    that are listed in the file LICENSE.
31
32    This program is distributed in the hope that it will be useful, but
33    WITHOUT ANY WARRANTY; without even the implied warranty of
34    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
35    General Public License for more details.
36
37    You should have received a copy of the GNU General Public License
38    along with this program; if not, write to the Free Software
39    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
40    02110-1301, USA.
41
42    Bacula® is a registered trademark of John Walker.
43    The licensor of Bacula is the Free Software Foundation Europe
44    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
45    Switzerland, email:ftf@fsfeurope.org.
46 */
47
48 #include "bacula.h"
49 #include "dird.h"
50
51 extern JCR *jobs;
52
53 /* Forward referenced functions */
54 extern "C" void *jobq_server(void *arg);
55 extern "C" void *sched_wait(void *arg);
56
57 static int  start_server(jobq_t *jq);
58 static bool acquire_resources(JCR *jcr);
59
60
61
62 /*
63  * Initialize a job queue
64  *
65  *  Returns: 0 on success
66  *           errno on failure
67  */
68 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
69 {
70    int stat;
71    jobq_item_t *item = NULL;
72
73    if ((stat = pthread_attr_init(&jq->attr)) != 0) {
74       berrno be;
75       Jmsg1(NULL, M_ERROR, 0, _("pthread_attr_init: ERR=%s\n"), be.strerror(stat));
76       return stat;
77    }
78    if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
79       pthread_attr_destroy(&jq->attr);
80       return stat;
81    }
82    if ((stat = pthread_mutex_init(&jq->mutex, NULL)) != 0) {
83       berrno be;
84       Jmsg1(NULL, M_ERROR, 0, _("pthread_mutex_init: ERR=%s\n"), be.strerror(stat));
85       pthread_attr_destroy(&jq->attr);
86       return stat;
87    }
88    if ((stat = pthread_cond_init(&jq->work, NULL)) != 0) {
89       berrno be;
90       Jmsg1(NULL, M_ERROR, 0, _("pthread_cond_init: ERR=%s\n"), be.strerror(stat));
91       pthread_mutex_destroy(&jq->mutex);
92       pthread_attr_destroy(&jq->attr);
93       return stat;
94    }
95    jq->quit = false;
96    jq->max_workers = threads;         /* max threads to create */
97    jq->num_workers = 0;               /* no threads yet */
98    jq->idle_workers = 0;              /* no idle threads */
99    jq->engine = engine;               /* routine to run */
100    jq->valid = JOBQ_VALID;
101    /* Initialize the job queues */
102    jq->waiting_jobs = New(dlist(item, &item->link));
103    jq->running_jobs = New(dlist(item, &item->link));
104    jq->ready_jobs = New(dlist(item, &item->link));
105    return 0;
106 }
107
108 /*
109  * Destroy the job queue
110  *
111  * Returns: 0 on success
112  *          errno on failure
113  */
114 int jobq_destroy(jobq_t *jq)
115 {
116    int stat, stat1, stat2;
117
118    if (jq->valid != JOBQ_VALID) {
119       return EINVAL;
120    }
121    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
122       berrno be;
123       Jmsg1(NULL, M_ERROR, 0, _("pthread_mutex_lock: ERR=%s\n"), be.strerror(stat));
124       return stat;
125    }
126    jq->valid = 0;                      /* prevent any more operations */
127
128    /* 
129     * If any threads are active, wake them 
130     */
131    if (jq->num_workers > 0) {
132       jq->quit = true;
133       if (jq->idle_workers) {
134          if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
135             berrno be;
136             Jmsg1(NULL, M_ERROR, 0, _("pthread_cond_broadcast: ERR=%s\n"), be.strerror(stat));
137             pthread_mutex_unlock(&jq->mutex);
138             return stat;
139          }
140       }
141       while (jq->num_workers > 0) {
142          if ((stat = pthread_cond_wait(&jq->work, &jq->mutex)) != 0) {
143             berrno be;
144             Jmsg1(NULL, M_ERROR, 0, _("pthread_cond_wait: ERR=%s\n"), be.strerror(stat));
145             pthread_mutex_unlock(&jq->mutex);
146             return stat;
147          }
148       }
149    }
150    if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
151       berrno be;
152       Jmsg1(NULL, M_ERROR, 0, _("pthread_mutex_unlock: ERR=%s\n"), be.strerror(stat));
153       return stat;
154    }
155    stat  = pthread_mutex_destroy(&jq->mutex);
156    stat1 = pthread_cond_destroy(&jq->work);
157    stat2 = pthread_attr_destroy(&jq->attr);
158    delete jq->waiting_jobs;
159    delete jq->running_jobs;
160    delete jq->ready_jobs;
161    return (stat != 0 ? stat : (stat1 != 0 ? stat1 : stat2));
162 }
163
164 struct wait_pkt {
165    JCR *jcr;
166    jobq_t *jq;
167 };
168
169 /*
170  * Wait until schedule time arrives before starting. Normally
171  *  this routine is only used for jobs started from the console
172  *  for which the user explicitly specified a start time. Otherwise
173  *  most jobs are put into the job queue only when their
174  *  scheduled time arives.
175  */
176 extern "C"
177 void *sched_wait(void *arg)
178 {
179    JCR *jcr = ((wait_pkt *)arg)->jcr;
180    jobq_t *jq = ((wait_pkt *)arg)->jq;
181
182    Dmsg0(2300, "Enter sched_wait.\n");
183    free(arg);
184    time_t wtime = jcr->sched_time - time(NULL);
185    set_jcr_job_status(jcr, JS_WaitStartTime);
186    /* Wait until scheduled time arrives */
187    if (wtime > 0) {
188       Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"),
189          jcr->Job, wtime);
190    }
191    /* Check every 30 seconds if canceled */
192    while (wtime > 0) {
193       Dmsg3(2300, "Waiting on sched time, jobid=%d secs=%d use=%d\n", 
194          jcr->JobId, wtime, jcr->use_count());
195       if (wtime > 30) {
196          wtime = 30;
197       }
198       bmicrosleep(wtime, 0);
199       if (job_canceled(jcr)) {
200          break;
201       }
202       wtime = jcr->sched_time - time(NULL);
203    }
204    Dmsg1(200, "resched use=%d\n", jcr->use_count());
205    jobq_add(jq, jcr);
206    free_jcr(jcr);                     /* we are done with jcr */
207    Dmsg0(2300, "Exit sched_wait\n");
208    return NULL;
209 }
210
211 /*
212  *  Add a job to the queue
213  *    jq is a queue that was created with jobq_init
214  */
215 int jobq_add(jobq_t *jq, JCR *jcr)
216 {
217    int stat;
218    jobq_item_t *item, *li;
219    bool inserted = false;
220    time_t wtime = jcr->sched_time - time(NULL);
221    pthread_t id;
222    wait_pkt *sched_pkt;
223
224    if (!jcr->term_wait_inited) { 
225       /* Initialize termination condition variable */
226       if ((stat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
227          berrno be;
228          Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.strerror(stat));
229          return stat;
230       }
231       jcr->term_wait_inited = true;
232    }                           
233                              
234    Dmsg3(2300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count());
235    if (jq->valid != JOBQ_VALID) {
236       Jmsg0(jcr, M_ERROR, 0, "Jobq_add queue not initialized.\n");
237       return EINVAL;
238    }
239
240    jcr->inc_use_count();                 /* mark jcr in use by us */
241    Dmsg3(2300, "jobq_add jobid=%d jcr=0x%x use_count=%d\n", jcr->JobId, jcr, jcr->use_count());
242    if (!job_canceled(jcr) && wtime > 0) {
243       set_thread_concurrency(jq->max_workers + 2);
244       sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
245       sched_pkt->jcr = jcr;
246       sched_pkt->jq = jq;
247       stat = pthread_create(&id, &jq->attr, sched_wait, (void *)sched_pkt);        
248       if (stat != 0) {                /* thread not created */
249          berrno be;
250          Jmsg1(jcr, M_ERROR, 0, _("pthread_thread_create: ERR=%s\n"), be.strerror(stat));
251       }
252       return stat;
253    }
254
255    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
256       berrno be;
257       Jmsg1(jcr, M_ERROR, 0, _("pthread_mutex_lock: ERR=%s\n"), be.strerror(stat));
258       free_jcr(jcr);                    /* release jcr */
259       return stat;
260    }
261
262    if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
263       free_jcr(jcr);                    /* release jcr */
264       return ENOMEM;
265    }
266    item->jcr = jcr;
267
268    if (job_canceled(jcr)) {
269       /* Add job to ready queue so that it is canceled quickly */
270       jq->ready_jobs->prepend(item);
271       Dmsg1(2300, "Prepended job=%d to ready queue\n", jcr->JobId);
272    } else {
273       /* Add this job to the wait queue in priority sorted order */
274       foreach_dlist(li, jq->waiting_jobs) {
275          Dmsg2(2300, "waiting item jobid=%d priority=%d\n",
276             li->jcr->JobId, li->jcr->JobPriority);
277          if (li->jcr->JobPriority > jcr->JobPriority) {
278             jq->waiting_jobs->insert_before(item, li);
279             Dmsg2(2300, "insert_before jobid=%d before waiting job=%d\n",
280                li->jcr->JobId, jcr->JobId);
281             inserted = true;
282             break;
283          }
284       }
285       /* If not jobs in wait queue, append it */
286       if (!inserted) {
287          jq->waiting_jobs->append(item);
288          Dmsg1(2300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
289       }
290    }
291
292    /* Ensure that at least one server looks at the queue. */
293    stat = start_server(jq);
294
295    pthread_mutex_unlock(&jq->mutex);
296    Dmsg0(2300, "Return jobq_add\n");
297    return stat;
298 }
299
300 /*
301  *  Remove a job from the job queue. Used only by cancel_job().
302  *    jq is a queue that was created with jobq_init
303  *    work_item is an element of work
304  *
305  *   Note, it is "removed" from the job queue.
306  *    If you want to cancel it, you need to provide some external means
307  *    of doing so (e.g. pthread_kill()).
308  */
309 int jobq_remove(jobq_t *jq, JCR *jcr)
310 {
311    int stat;
312    bool found = false;
313    jobq_item_t *item;
314
315    Dmsg2(2300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
316    if (jq->valid != JOBQ_VALID) {
317       return EINVAL;
318    }
319
320    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
321       berrno be;
322       Jmsg1(NULL, M_ERROR, 0, _("pthread_mutex_lock: ERR=%s\n"), be.strerror(stat));
323       return stat;
324    }
325
326    foreach_dlist(item, jq->waiting_jobs) {
327       if (jcr == item->jcr) {
328          found = true;
329          break;
330       }
331    }
332    if (!found) {
333       pthread_mutex_unlock(&jq->mutex);
334       Dmsg2(2300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
335       return EINVAL;
336    }
337
338    /* Move item to be the first on the list */
339    jq->waiting_jobs->remove(item);
340    jq->ready_jobs->prepend(item);
341    Dmsg2(2300, "jobq_remove jobid=%d jcr=0x%x moved to ready queue\n", jcr->JobId, jcr);
342
343    stat = start_server(jq);
344
345    pthread_mutex_unlock(&jq->mutex);
346    Dmsg0(2300, "Return jobq_remove\n");
347    return stat;
348 }
349
350
351 /*
352  * Start the server thread if it isn't already running
353  */
354 static int start_server(jobq_t *jq)
355 {
356    int stat = 0;
357    pthread_t id;
358
359    /*
360     * if any threads are idle, wake one --                
361     *   actually we do a broadcast because on /lib/tls 
362     *   these signals seem to get lost from time to time.
363     */
364    if (jq->idle_workers > 0) {
365       Dmsg0(2300, "Signal worker to wake up\n");
366       if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
367          berrno be;
368          Jmsg1(NULL, M_ERROR, 0, _("pthread_cond_signal: ERR=%s\n"), be.strerror(stat));
369          return stat;
370       }
371    } else if (jq->num_workers < jq->max_workers) {
372       Dmsg0(2300, "Create worker thread\n");
373       /* No idle threads so create a new one */
374       set_thread_concurrency(jq->max_workers + 1);
375       if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
376          berrno be;
377          Jmsg1(NULL, M_ERROR, 0, _("pthread_create: ERR=%s\n"), be.strerror(stat));
378          return stat;
379       }
380    }
381    return stat;
382 }
383
384
385 /*
386  * This is the worker thread that serves the job queue.
387  * When all the resources are acquired for the job,
388  *  it will call the user's engine.
389  */
390 extern "C"
391 void *jobq_server(void *arg)
392 {
393    struct timespec timeout;
394    jobq_t *jq = (jobq_t *)arg;
395    jobq_item_t *je;                   /* job entry in queue */
396    int stat;
397    bool timedout = false;
398    bool work = true;
399
400    Dmsg0(2300, "Start jobq_server\n");
401    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
402       berrno be;
403       Jmsg1(NULL, M_ERROR, 0, _("pthread_mutex_lock: ERR=%s\n"), be.strerror(stat));
404       return NULL;
405    }
406    jq->num_workers++;
407
408    for (;;) {
409       struct timeval tv;
410       struct timezone tz;
411
412       Dmsg0(2300, "Top of for loop\n");
413       if (!work && !jq->quit) {
414          gettimeofday(&tv, &tz);
415          timeout.tv_nsec = 0;
416          timeout.tv_sec = tv.tv_sec + 4;
417
418          while (!jq->quit) {
419             /*
420              * Wait 4 seconds, then if no more work, exit
421              */
422             Dmsg0(2300, "pthread_cond_timedwait()\n");
423             stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
424             if (stat == ETIMEDOUT) {
425                Dmsg0(2300, "timedwait timedout.\n");
426                timedout = true;
427                break;
428             } else if (stat != 0) {
429                /* This shouldn't happen */
430                Dmsg0(2300, "This shouldn't happen\n");
431                jq->num_workers--;
432                pthread_mutex_unlock(&jq->mutex);
433                return NULL;
434             }
435             break;
436          }
437       }
438       /*
439        * If anything is in the ready queue, run it
440        */
441       Dmsg0(2300, "Checking ready queue.\n");
442       while (!jq->ready_jobs->empty() && !jq->quit) {
443          JCR *jcr;
444          je = (jobq_item_t *)jq->ready_jobs->first();
445          jcr = je->jcr;
446          jq->ready_jobs->remove(je);
447          if (!jq->ready_jobs->empty()) {
448             Dmsg0(2300, "ready queue not empty start server\n");
449             if (start_server(jq) != 0) {
450                jq->num_workers--;
451                pthread_mutex_unlock(&jq->mutex);
452                return NULL;
453             }
454          }
455          jq->running_jobs->append(je);
456          Dmsg1(2300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
457
458          /* Release job queue lock */
459          V(jq->mutex);
460
461          /* Call user's routine here */
462          Dmsg2(2300, "Calling user engine for jobid=%d use=%d\n", jcr->JobId,
463             jcr->use_count());
464          jq->engine(je->jcr);
465
466          Dmsg2(2300, "Back from user engine jobid=%d use=%d.\n", jcr->JobId,
467             jcr->use_count());
468
469          /* Reacquire job queue lock */
470          P(jq->mutex);
471          Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
472          jq->running_jobs->remove(je);
473          /*
474           * Release locks if acquired. Note, they will not have
475           *  been acquired for jobs canceled before they were
476           *  put into the ready queue.
477           */
478          if (jcr->acquired_resource_locks) {
479             if (jcr->rstore) {
480                jcr->rstore->NumConcurrentJobs = 0;
481                Dmsg1(200, "Dec rncj=%d\n", jcr->rstore->NumConcurrentJobs);
482             }
483             if (jcr->wstore) {
484                jcr->wstore->NumConcurrentJobs--;
485                Dmsg1(200, "Dec wncj=%d\n", jcr->wstore->NumConcurrentJobs);
486             }
487             jcr->client->NumConcurrentJobs--;
488             jcr->job->NumConcurrentJobs--;
489             jcr->acquired_resource_locks = false;
490          }
491
492          /*
493           * Reschedule the job if necessary and requested
494           */
495          if (jcr->job->RescheduleOnError &&
496              jcr->JobStatus != JS_Terminated &&
497              jcr->JobStatus != JS_Canceled &&
498              jcr->JobType == JT_BACKUP &&
499              (jcr->job->RescheduleTimes == 0 ||
500               jcr->reschedule_count < jcr->job->RescheduleTimes)) {
501              char dt[50], dt2[50];
502
503              /*
504               * Reschedule this job by cleaning it up, but
505               *  reuse the same JobId if possible.
506               */
507             time_t now = time(NULL);
508             jcr->reschedule_count++;
509             jcr->sched_time = now + jcr->job->RescheduleInterval;
510             bstrftime(dt, sizeof(dt), now);
511             bstrftime(dt2, sizeof(dt2), jcr->sched_time);
512             Dmsg4(2300, "Rescheduled Job %s to re-run in %d seconds.(now=%u,then=%u)\n", jcr->Job,
513                   (int)jcr->job->RescheduleInterval, now, jcr->sched_time);
514             Jmsg(jcr, M_INFO, 0, _("Rescheduled Job %s at %s to re-run in %d seconds (%s).\n"),
515                  jcr->Job, dt, (int)jcr->job->RescheduleInterval, dt2);
516             dird_free_jcr_pointers(jcr);     /* partial cleanup old stuff */
517             jcr->JobStatus = -1;
518             set_jcr_job_status(jcr, JS_WaitStartTime);
519             jcr->SDJobStatus = 0;
520             if (jcr->JobBytes == 0) {
521                Dmsg2(2300, "Requeue job=%d use=%d\n", jcr->JobId, jcr->use_count());
522                V(jq->mutex);
523                jobq_add(jq, jcr);     /* queue the job to run again */
524                P(jq->mutex);
525                free_jcr(jcr);         /* release jcr */
526                free(je);              /* free the job entry */
527                continue;              /* look for another job to run */
528             }
529             /*
530              * Something was actually backed up, so we cannot reuse
531              *   the old JobId or there will be database record
532              *   conflicts.  We now create a new job, copying the
533              *   appropriate fields.
534              */           
535             JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
536             set_jcr_defaults(njcr, jcr->job);
537             njcr->reschedule_count = jcr->reschedule_count;
538             njcr->sched_time = jcr->sched_time;
539             njcr->JobLevel = jcr->JobLevel;
540             njcr->JobStatus = -1;
541             set_jcr_job_status(njcr, jcr->JobStatus);
542             if (jcr->rstore) {
543                copy_rstorage(njcr, jcr->rstorage, _("previous Job"));
544             } else {
545                free_rstorage(njcr);
546             }
547             if (jcr->wstore) {
548                copy_wstorage(njcr, jcr->wstorage, _("previous Job"));
549             } else {
550                free_wstorage(njcr);
551             }
552             njcr->messages = jcr->messages;
553             Dmsg0(2300, "Call to run new job\n");
554             V(jq->mutex);
555             run_job(njcr);            /* This creates a "new" job */
556             free_jcr(njcr);           /* release "new" jcr */
557             P(jq->mutex);
558             Dmsg0(2300, "Back from running new job.\n");
559          }
560          /* Clean up and release old jcr */
561          Dmsg2(2300, "====== Termination job=%d use_cnt=%d\n", jcr->JobId, jcr->use_count());
562          jcr->SDJobStatus = 0;
563          V(jq->mutex);                /* release internal lock */
564          free_jcr(jcr);
565          free(je);                    /* release job entry */
566          P(jq->mutex);                /* reacquire job queue lock */
567       }
568       /*
569        * If any job in the wait queue can be run,
570        *  move it to the ready queue
571        */
572       Dmsg0(2300, "Done check ready, now check wait queue.\n");
573       if (!jq->waiting_jobs->empty() && !jq->quit) {
574          int Priority;
575          je = (jobq_item_t *)jq->waiting_jobs->first();
576          jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
577          if (re) {
578             Priority = re->jcr->JobPriority;
579             Dmsg2(2300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
580          } else {
581             Priority = je->jcr->JobPriority;
582             Dmsg1(2300, "No job running. Look for Job pri=%d\n", Priority);
583          }
584          /*
585           * Walk down the list of waiting jobs and attempt
586           *   to acquire the resources it needs.
587           */
588          for ( ; je;  ) {
589             /* je is current job item on the queue, jn is the next one */
590             JCR *jcr = je->jcr;
591             jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
592
593             Dmsg3(2300, "Examining Job=%d JobPri=%d want Pri=%d\n",
594                jcr->JobId, jcr->JobPriority, Priority);
595
596             /* Take only jobs of correct Priority */
597             if (jcr->JobPriority != Priority) {
598                set_jcr_job_status(jcr, JS_WaitPriority);
599                break;
600             }
601
602             if (!acquire_resources(jcr)) {
603                /* If resource conflict, job is canceled */
604                if (!job_canceled(jcr)) {
605                   je = jn;            /* point to next waiting job */
606                   continue;
607                }
608             }
609
610             /*
611              * Got all locks, now remove it from wait queue and append it
612              *   to the ready queue.  Note, we may also get here if the
613              *    job was canceled.  Once it is "run", it will quickly
614              *    terminate.
615              */
616             jq->waiting_jobs->remove(je);
617             jq->ready_jobs->append(je);
618             Dmsg1(2300, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
619             je = jn;                  /* Point to next waiting job */
620          } /* end for loop */
621
622       } /* end if */
623
624       Dmsg0(2300, "Done checking wait queue.\n");
625       /*
626        * If no more ready work and we are asked to quit, then do it
627        */
628       if (jq->ready_jobs->empty() && jq->quit) {
629          jq->num_workers--;
630          if (jq->num_workers == 0) {
631             Dmsg0(2300, "Wake up destroy routine\n");
632             /* Wake up destroy routine if he is waiting */
633             pthread_cond_broadcast(&jq->work);
634          }
635          break;
636       }
637       Dmsg0(2300, "Check for work request\n");
638       /*
639        * If no more work requests, and we waited long enough, quit
640        */
641       Dmsg2(2300, "timedout=%d read empty=%d\n", timedout,
642          jq->ready_jobs->empty());
643       if (jq->ready_jobs->empty() && timedout) {
644          Dmsg0(2300, "break big loop\n");
645          jq->num_workers--;
646          break;
647       }
648
649       work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
650       if (work) {
651          /*
652           * If a job is waiting on a Resource, don't consume all
653           *   the CPU time looping looking for work, and even more
654           *   important, release the lock so that a job that has
655           *   terminated can give us the resource.
656           */
657          V(jq->mutex);
658          bmicrosleep(2, 0);              /* pause for 2 seconds */
659          P(jq->mutex);
660          /* Recompute work as something may have changed in last 2 secs */
661          work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
662       }
663       Dmsg1(2300, "Loop again. work=%d\n", work);
664    } /* end of big for loop */
665
666    Dmsg0(200, "unlock mutex\n");
667    V(jq->mutex);
668    Dmsg0(2300, "End jobq_server\n");
669    return NULL;
670 }
671
672 /*
673  * See if we can acquire all the necessary resources for the job (JCR)
674  *
675  *  Returns: true  if successful
676  *           false if resource failure
677  */
678 static bool acquire_resources(JCR *jcr)
679 {
680    bool skip_this_jcr = false;
681
682    jcr->acquired_resource_locks = false;
683    if (jcr->rstore) {
684       Dmsg1(200, "Rstore=%s\n", jcr->rstore->name());
685       if (jcr->rstore->NumConcurrentJobs == 0 &&
686           jcr->rstore->NumConcurrentJobs < jcr->rstore->MaxConcurrentJobs) {
687          /* Simple case, first job */
688          jcr->rstore->NumConcurrentJobs = 1;
689          Dmsg0(200, "Set rncj=1\n");
690       } else if (jcr->rstore->NumConcurrentJobs < jcr->rstore->MaxConcurrentJobs) {
691          jcr->rstore->NumConcurrentJobs++;
692          Dmsg1(200, "Inc rncj=%d\n", jcr->rstore->NumConcurrentJobs);
693       } else {
694          Dmsg1(200, "Fail rncj=%d\n", jcr->rstore->NumConcurrentJobs);
695          set_jcr_job_status(jcr, JS_WaitStoreRes);
696          return false;
697       }
698    }
699    
700    if (jcr->wstore) {
701       Dmsg1(200, "Wstore=%s\n", jcr->wstore->name());
702       if (jcr->rstore == jcr->wstore) {           /* deadlock */
703          jcr->rstore->NumConcurrentJobs--;        /* back out rstore */
704          Jmsg(jcr, M_FATAL, 0, _("Job canceled. Attempt to read and write same device.\n"
705             "    Read storage \"%s\" (From %s) -- Write storage \"%s\" (From %s)\n"), 
706             jcr->rstore->name(), jcr->rstore_source, jcr->wstore->name(), jcr->wstore_source);
707          set_jcr_job_status(jcr, JS_Canceled);
708          return false;
709       }
710       if (jcr->wstore->NumConcurrentJobs == 0 &&
711           jcr->wstore->NumConcurrentJobs < jcr->wstore->MaxConcurrentJobs) {
712          /* Simple case, first job */
713          jcr->wstore->NumConcurrentJobs = 1;
714          Dmsg0(200, "Set wncj=1\n");
715       } else if (jcr->wstore->NumConcurrentJobs < jcr->wstore->MaxConcurrentJobs) {
716          jcr->wstore->NumConcurrentJobs++;
717          Dmsg1(200, "Inc wncj=%d\n", jcr->wstore->NumConcurrentJobs);
718       } else if (jcr->rstore) {
719          jcr->rstore->NumConcurrentJobs--;        /* back out rstore */
720          Dmsg1(200, "Fail wncj=%d\n", jcr->wstore->NumConcurrentJobs);
721          skip_this_jcr = true;
722       } else {
723          Dmsg1(200, "Fail wncj=%d\n", jcr->wstore->NumConcurrentJobs);
724          skip_this_jcr = true;
725       }
726    }
727    if (skip_this_jcr) {
728       set_jcr_job_status(jcr, JS_WaitStoreRes);
729       return false;
730    }
731
732    if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
733       jcr->client->NumConcurrentJobs++;
734    } else {
735       /* Back out previous locks */
736       if (jcr->wstore) {
737          jcr->wstore->NumConcurrentJobs--;
738          Dmsg1(200, "Dec wncj=%d\n", jcr->wstore->NumConcurrentJobs);
739       }
740       if (jcr->rstore) {
741          jcr->rstore->NumConcurrentJobs--;  
742          Dmsg1(200, "Dec rncj=%d\n", jcr->rstore->NumConcurrentJobs);
743       }
744       set_jcr_job_status(jcr, JS_WaitClientRes);
745       return false;
746    }
747    if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
748       jcr->job->NumConcurrentJobs++;
749    } else {
750       /* Back out previous locks */
751       if (jcr->wstore) {
752          jcr->wstore->NumConcurrentJobs--;
753          Dmsg1(200, "Dec wncj=%d\n", jcr->wstore->NumConcurrentJobs);
754       }
755       if (jcr->rstore) {
756          jcr->rstore->NumConcurrentJobs--;
757          Dmsg1(200, "Dec rncj=%d\n", jcr->rstore->NumConcurrentJobs);
758       }
759       jcr->client->NumConcurrentJobs--;
760       set_jcr_job_status(jcr, JS_WaitJobRes);
761       return false;
762    }
763
764    jcr->acquired_resource_locks = true;
765    return true;
766 }