]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/jobq.c
- Modify the depend section of each Makefile.in to reference
[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    Copyright (C) 2003-2004 Kern Sibbald and John Walker
22
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.
27
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.
32
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,
36    MA 02111-1307, USA.
37
38  */
39
40 #include "bacula.h"
41 #include "dird.h"
42
43
44 /* Forward referenced functions */
45 extern "C" void *jobq_server(void *arg);
46 extern "C" void *sched_wait(void *arg);
47
48 static int   start_server(jobq_t *jq);
49
50 /*   
51  * Initialize a job queue
52  *
53  *  Returns: 0 on success
54  *           errno on failure
55  */
56 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
57 {
58    int stat;
59    jobq_item_t *item = NULL;
60                         
61    if ((stat = pthread_attr_init(&jq->attr)) != 0) {
62       Jmsg1(NULL, M_ERROR, 0, "pthread_attr_init: ERR=%s\n", strerror(stat));
63       return stat;
64    }
65    if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
66       pthread_attr_destroy(&jq->attr);
67       return stat;
68    }
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);
72       return stat;
73    }
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);
78       return stat;
79    }
80    jq->quit = false;
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));
90    return 0;
91 }
92
93 /*
94  * Destroy the job queue
95  *
96  * Returns: 0 on success
97  *          errno on failure
98  */
99 int jobq_destroy(jobq_t *jq)
100 {
101    int stat, stat1, stat2;
102
103   if (jq->valid != JOBQ_VALID) {
104      return EINVAL;
105   }
106   if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
107      Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
108      return stat;
109   }
110   jq->valid = 0;                      /* prevent any more operations */
111
112   /* 
113    * If any threads are active, wake them 
114    */
115   if (jq->num_workers > 0) {
116      jq->quit = true;
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);
121            return stat;
122         }
123      }
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);
128            return stat;
129         }
130      }
131   }
132   if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
133      Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
134      return stat;
135   }
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));
143 }
144
145 struct wait_pkt {
146    JCR *jcr;
147    jobq_t *jq;
148 };
149
150 /*
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.
156  */
157 extern "C"  
158 void *sched_wait(void *arg)
159 {
160    JCR *jcr = ((wait_pkt *)arg)->jcr;
161    jobq_t *jq = ((wait_pkt *)arg)->jq;
162
163    Dmsg0(300, "Enter sched_wait.\n");
164    free(arg);
165    time_t wtime = jcr->sched_time - time(NULL);
166    set_jcr_job_status(jcr, JS_WaitStartTime);
167    /* Wait until scheduled time arrives */
168    if (wtime > 0) {
169       Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"), 
170          jcr->Job, wtime);
171    }
172    /* Check every 30 seconds if canceled */ 
173    while (wtime > 0) {
174       Dmsg2(300, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
175       if (wtime > 30) {
176          wtime = 30;
177       }
178       bmicrosleep(wtime, 0);
179       if (job_canceled(jcr)) {
180          break;
181       }
182       wtime = jcr->sched_time - time(NULL);
183    }
184    P(jcr->mutex);                     /* lock jcr */
185    jobq_add(jq, jcr);
186    V(jcr->mutex);
187    free_jcr(jcr);                     /* we are done with jcr */
188    Dmsg0(300, "Exit sched_wait\n");
189    return NULL;
190 }
191
192 /*
193  *  Add a job to the queue
194  *    jq is a queue that was created with jobq_init
195  * 
196  *  On entry jcr->mutex must be locked.
197  *   
198  */
199 int jobq_add(jobq_t *jq, JCR *jcr)
200 {
201    int stat;
202    jobq_item_t *item, *li;
203    bool inserted = false;
204    time_t wtime = jcr->sched_time - time(NULL);
205    pthread_t id;
206    wait_pkt *sched_pkt;
207     
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");
211       return EINVAL;
212    }
213
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;
220       sched_pkt->jq = jq;
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));
225       }
226       return stat;
227    }
228
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 */
232       return stat;
233    }
234
235    if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
236       jcr->use_count--;               /* release jcr */
237       return ENOMEM;
238    }
239    item->jcr = jcr;
240
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);
245    } else {
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);
254             inserted = true;
255             break;
256          }
257       }
258       /* If not jobs in wait queue, append it */
259       if (!inserted) {
260          jq->waiting_jobs->append(item);
261          Dmsg1(300, "Appended item jobid=%d to waiting queue\n", jcr->JobId);
262       }
263    }
264
265    /* Ensure that at least one server looks at the queue. */
266    stat = start_server(jq);
267
268    pthread_mutex_unlock(&jq->mutex);
269    Dmsg0(300, "Return jobq_add\n");
270    return stat;
271 }
272
273 /*
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
277  *
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()).
281  */
282 int jobq_remove(jobq_t *jq, JCR *jcr)
283 {
284    int stat;
285    bool found = false;
286    jobq_item_t *item;
287     
288    Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x\n", jcr->JobId, jcr);
289    if (jq->valid != JOBQ_VALID) {
290       return EINVAL;
291    }
292
293    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
294       Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_lock: ERR=%s\n", strerror(stat));
295       return stat;
296    }
297
298    foreach_dlist(item, jq->waiting_jobs) {
299       if (jcr == item->jcr) {
300          found = true;
301          break;
302       }
303    }
304    if (!found) {
305       pthread_mutex_unlock(&jq->mutex);
306       Dmsg2(300, "jobq_remove jobid=%d jcr=0x%x not in wait queue\n", jcr->JobId, jcr);
307       return EINVAL;
308    }
309
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);
314    
315    stat = start_server(jq);
316
317    pthread_mutex_unlock(&jq->mutex);
318    Dmsg0(300, "Return jobq_remove\n");
319    return stat;
320 }
321
322
323 /*
324  * Start the server thread if it isn't already running
325  */
326 static int start_server(jobq_t *jq)
327 {
328    int stat = 0;
329    pthread_t id;
330
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));
336          return stat;
337       }
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));
344          return stat;
345       }
346    }
347    return stat;
348 }
349
350
351 /* 
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.
355  */
356 extern "C"  
357 void *jobq_server(void *arg)
358 {
359    struct timespec timeout;
360    jobq_t *jq = (jobq_t *)arg;
361    jobq_item_t *je;                   /* job entry in queue */
362    int stat;
363    bool timedout = false;
364    bool work = true;
365
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));
369       return NULL;
370    }
371    jq->num_workers++;
372
373    for (;;) {
374       struct timeval tv;
375       struct timezone tz;
376
377       Dmsg0(300, "Top of for loop\n");
378       if (!work && !jq->quit) {
379          gettimeofday(&tv, &tz);
380          timeout.tv_nsec = 0;
381          timeout.tv_sec = tv.tv_sec + 4;
382
383          while (!jq->quit) {
384             /*
385              * Wait 4 seconds, then if no more work, exit
386              */
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");
391                timedout = true;
392                break;
393             } else if (stat != 0) {
394                /* This shouldn't happen */
395                Dmsg0(300, "This shouldn't happen\n");
396                jq->num_workers--;
397                pthread_mutex_unlock(&jq->mutex);
398                return NULL;
399             }
400             break;
401          } 
402       }
403       /* 
404        * If anything is in the ready queue, run it
405        */
406       Dmsg0(300, "Checking ready queue.\n");
407       while (!jq->ready_jobs->empty() && !jq->quit) {
408          JCR *jcr;
409          je = (jobq_item_t *)jq->ready_jobs->first(); 
410          jcr = je->jcr;
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) {
415                jq->num_workers--;
416                pthread_mutex_unlock(&jq->mutex);
417                return NULL;
418             }
419          }
420          jq->running_jobs->append(je);
421          Dmsg1(300, "Took jobid=%d from ready and appended to run\n", jcr->JobId);
422
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));
426             jq->num_workers--;
427             return NULL;
428          }
429
430          /* Call user's routine here */
431          Dmsg1(300, "Calling user engine for jobid=%d\n", jcr->JobId);
432          jq->engine(je->jcr);
433
434          Dmsg1(300, "Back from user engine jobid=%d.\n", jcr->JobId);
435
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));
439             jq->num_workers--;
440             free(je);                 /* release job entry */
441             return NULL;
442          }
443          Dmsg0(200, "Done lock mutex after running job. Release locks.\n");
444          jq->running_jobs->remove(je);
445          /* 
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.
449           */
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;  
454             }
455             jcr->client->NumConcurrentJobs--;
456             jcr->job->NumConcurrentJobs--;
457          }
458
459          /*
460           * Reschedule the job if necessary and requested
461           */
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) {
467              char dt[50];
468
469              /*
470               * Reschedule this job by cleaning it up, but
471               *  reuse the same JobId if possible.
472               */
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;
486                V(jq->mutex);
487                jobq_add(jq, jcr);     /* queue the job to run again */
488                P(jq->mutex);
489                free(je);              /* free the job entry */
490                continue;              /* look for another job to run */
491             }
492             /* 
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.
497              */
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");
506             V(jq->mutex);
507             run_job(njcr);            /* This creates a "new" job */
508             free_jcr(njcr);           /* release "new" jcr */
509             P(jq->mutex);
510             Dmsg0(300, "Back from running new job.\n");
511          }
512          /* Clean up and release old jcr */
513          if (jcr->db) {
514             db_close_database(jcr, jcr->db);
515             jcr->db = NULL;
516          }
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 */
520          free_jcr(jcr);
521          free(je);                    /* release job entry */
522          P(jq->mutex);                /* reacquire job queue lock */
523       }
524       /*
525        * If any job in the wait queue can be run,
526        *  move it to the ready queue
527        */
528       Dmsg0(300, "Done check ready, now check wait queue.\n");
529       while (!jq->waiting_jobs->empty() && !jq->quit) {
530          int Priority;
531          je = (jobq_item_t *)jq->waiting_jobs->first(); 
532          jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
533          if (re) {
534             Priority = re->jcr->JobPriority;
535             Dmsg2(300, "JobId %d is running. Look for pri=%d\n", re->jcr->JobId, Priority);
536          } else {
537             Priority = je->jcr->JobPriority;
538             Dmsg1(300, "No job running. Look for Job pri=%d\n", Priority);
539          }
540          /*
541           * Walk down the list of waiting jobs and attempt
542           *   to acquire the resources it needs.
543           */
544          for ( ; je;  ) {
545             /* je is current job item on the queue, jn is the next one */
546             JCR *jcr = je->jcr;
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);
553                break;
554             }
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;
561                } else {
562                   set_jcr_job_status(jcr, JS_WaitStoreRes);
563                   je = jn;
564                   continue;
565                }
566             } else if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
567                jcr->store->NumConcurrentJobs++;
568             } else {
569                set_jcr_job_status(jcr, JS_WaitStoreRes);
570                je = jn;
571                continue;
572             }
573
574             if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
575                jcr->client->NumConcurrentJobs++;
576             } else {
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;  
581                }
582                set_jcr_job_status(jcr, JS_WaitClientRes);
583                je = jn;
584                continue;
585             }
586             if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
587                jcr->job->NumConcurrentJobs++;
588             } else {
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;  
593                }
594                jcr->client->NumConcurrentJobs--;
595                set_jcr_job_status(jcr, JS_WaitJobRes);
596                je = jn;
597                continue;
598             }
599             /* Got all locks, now remove it from wait queue and append it
600              *   to the ready queue  
601              */
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);
606             je = jn;
607          } /* end for loop */
608          break;
609       } /* end while loop */
610       Dmsg0(300, "Done checking wait queue.\n");
611       /*
612        * If no more ready work and we are asked to quit, then do it
613        */
614       if (jq->ready_jobs->empty() && jq->quit) {
615          jq->num_workers--;
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);
620          }
621          break;
622       }
623       Dmsg0(300, "Check for work request\n");
624       /* 
625        * If no more work requests, and we waited long enough, quit
626        */
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");
631          jq->num_workers--;
632          break;
633       }
634
635       work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
636       if (work) {
637          /*          
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.
642           */
643          if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
644             Jmsg1(NULL, M_ERROR, 0, "pthread_mutex_unlock: ERR=%s\n", strerror(stat));
645             jq->num_workers--;
646             return NULL;
647          }
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));
651             jq->num_workers--;
652             return NULL;
653          }
654          /* Recompute work as something may have changed in last 2 secs */
655          work = !jq->ready_jobs->empty() || !jq->waiting_jobs->empty();
656       }
657       Dmsg1(300, "Loop again. work=%d\n", work);
658    } /* end of big for loop */
659
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));
663    }
664    Dmsg0(300, "End jobq_server\n");
665    return NULL;
666 }