]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/jobq.c
bff56d1ecde27b8d0824741e2c42d74212cf5e7e
[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) 2000-2003 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 #ifdef JOB_QUEUE
44
45 /* Forward referenced functions */
46 static void *jobq_server(void *arg);
47 static int   start_server(jobq_t *jq);
48
49 /*   
50  * Initialize a job queue
51  *
52  *  Returns: 0 on success
53  *           errno on failure
54  */
55 int jobq_init(jobq_t *jq, int threads, void *(*engine)(void *arg))
56 {
57    int stat;
58    jobq_item_t *item = NULL;
59                         
60    if ((stat = pthread_attr_init(&jq->attr)) != 0) {
61       return stat;
62    }
63    if ((stat = pthread_attr_setdetachstate(&jq->attr, PTHREAD_CREATE_DETACHED)) != 0) {
64       pthread_attr_destroy(&jq->attr);
65       return stat;
66    }
67    if ((stat = pthread_mutex_init(&jq->mutex, NULL)) != 0) {
68       pthread_attr_destroy(&jq->attr);
69       return stat;
70    }
71    if ((stat = pthread_cond_init(&jq->work, NULL)) != 0) {
72       pthread_mutex_destroy(&jq->mutex);
73       pthread_attr_destroy(&jq->attr);
74       return stat;
75    }
76    jq->quit = false;
77    jq->max_workers = threads;         /* max threads to create */
78    jq->num_workers = 0;               /* no threads yet */
79    jq->idle_workers = 0;              /* no idle threads */
80    jq->engine = engine;               /* routine to run */
81    jq->valid = JOBQ_VALID; 
82    /* Initialize the job queues */
83    jq->waiting_jobs = new dlist(item, &item->link);
84    jq->running_jobs = new dlist(item, &item->link);
85    jq->ready_jobs = new dlist(item, &item->link);
86    return 0;
87 }
88
89 /*
90  * Destroy the job queue
91  *
92  * Returns: 0 on success
93  *          errno on failure
94  */
95 int jobq_destroy(jobq_t *jq)
96 {
97    int stat, stat1, stat2;
98
99   if (jq->valid != JOBQ_VALID) {
100      return EINVAL;
101   }
102   if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
103      return stat;
104   }
105   jq->valid = 0;                      /* prevent any more operations */
106
107   /* 
108    * If any threads are active, wake them 
109    */
110   if (jq->num_workers > 0) {
111      jq->quit = true;
112      if (jq->idle_workers) {
113         if ((stat = pthread_cond_broadcast(&jq->work)) != 0) {
114            pthread_mutex_unlock(&jq->mutex);
115            return stat;
116         }
117      }
118      while (jq->num_workers > 0) {
119         if ((stat = pthread_cond_wait(&jq->work, &jq->mutex)) != 0) {
120            pthread_mutex_unlock(&jq->mutex);
121            return stat;
122         }
123      }
124   }
125   if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
126      return stat;
127   }
128   stat  = pthread_mutex_destroy(&jq->mutex);
129   stat1 = pthread_cond_destroy(&jq->work);
130   stat2 = pthread_attr_destroy(&jq->attr);
131   delete jq->waiting_jobs;
132   delete jq->running_jobs;
133   delete jq->ready_jobs;
134   return (stat != 0 ? stat : (stat1 != 0 ? stat1 : stat2));
135 }
136
137 struct wait_pkt {
138    JCR *jcr;
139    jobq_t *jq;
140 };
141
142 /*
143  * Wait until schedule time arrives before starting
144  */
145 static void *sched_wait(void *arg)
146 {
147    JCR *jcr = ((wait_pkt *)arg)->jcr;
148    jobq_t *jq = ((wait_pkt *)arg)->jq;
149
150    Dmsg0(100, "Enter sched_wait.\n");
151    free(arg);
152    time_t wtime = jcr->sched_time - time(NULL);
153    /* Wait until scheduled time arrives */
154    if (wtime > 0 && verbose) {
155       Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"), 
156          jcr->Job, wtime);
157       set_jcr_job_status(jcr, JS_WaitStartTime);
158    }
159    /* Check every 30 seconds if canceled */ 
160    while (wtime > 0) {
161       Dmsg2(100, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
162       if (wtime > 30) {
163          wtime = 30;
164       }
165       bmicrosleep(wtime, 0);
166       if (job_canceled(jcr)) {
167          break;
168       }
169       wtime = jcr->sched_time - time(NULL);
170    }
171    jobq_add(jq, jcr);
172    Dmsg0(100, "Exit sched_wait\n");
173    return NULL;
174 }
175
176
177 /*
178  *  Add a job to the queue
179  *    jq is a queue that was created with jobq_init
180  *   
181  */
182 int jobq_add(jobq_t *jq, JCR *jcr)
183 {
184    int stat;
185    jobq_item_t *item, *li;
186    bool inserted = false;
187    time_t wtime = jcr->sched_time - time(NULL);
188    pthread_t id;
189    wait_pkt *sched_pkt;
190     
191     
192    Dmsg1(100, "jobq_add jobid=%d\n", jcr->JobId);
193    if (jq->valid != JOBQ_VALID) {
194       return EINVAL;
195    }
196
197    if (!job_canceled(jcr) && wtime > 0) {
198       set_thread_concurrency(jq->max_workers + 2);
199       sched_pkt = (wait_pkt *)malloc(sizeof(wait_pkt));
200       sched_pkt->jcr = jcr;
201       sched_pkt->jq = jq;
202       if ((stat = pthread_create(&id, &jq->attr, sched_wait, (void *)sched_pkt)) != 0) {
203          return stat;
204       }
205    }
206
207    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
208       return stat;
209    }
210
211    if ((item = (jobq_item_t *)malloc(sizeof(jobq_item_t))) == NULL) {
212       return ENOMEM;
213    }
214    item->jcr = jcr;
215
216    if (job_canceled(jcr)) {
217       /* Add job to ready queue so that it is canceled quickly */
218       jq->ready_jobs->prepend(item);
219       Dmsg1(100, "Prepended job=%d to ready queue\n", jcr->JobId);
220    } else {
221       /* Add this job to the wait queue in priority sorted order */
222       for (li=NULL; (li=(jobq_item_t *)jq->waiting_jobs->next(li)); ) {
223          Dmsg2(100, "waiting item jobid=%d priority=%d\n",
224             li->jcr->JobId, li->jcr->JobPriority);
225          if (li->jcr->JobPriority > jcr->JobPriority) {
226             jq->waiting_jobs->insert_before(item, li);
227             Dmsg2(100, "insert_before jobid=%d before %d\n", 
228                li->jcr->JobId, jcr->JobId);
229             inserted = true;
230             break;
231          }
232       }
233       /* If not jobs in wait queue, append it */
234       if (!inserted) {
235          jq->waiting_jobs->append(item);
236          Dmsg1(100, "Appended item jobid=%d\n", jcr->JobId);
237       }
238    }
239
240    stat = start_server(jq);
241
242    if (stat == 0) {
243       pthread_mutex_unlock(&jq->mutex);
244    }
245    Dmsg0(100, "Return jobq_add\n");
246    return stat;
247 }
248
249 /*
250  *  Remove a job from the job queue
251  *    jq is a queue that was created with jobq_init
252  *    work_item is an element of work
253  *
254  *   Note, it is "removed" by immediately calling a processing routine.
255  *    if you want to cancel it, you need to provide some external means
256  *    of doing so.
257  */
258 int jobq_remove(jobq_t *jq, JCR *jcr)
259 {
260    int stat;
261    bool found = false;
262    jobq_item_t *item;
263     
264    Dmsg1(100, "jobq_remove jobid=%d\n", jcr->JobId);
265    if (jq->valid != JOBQ_VALID) {
266       return EINVAL;
267    }
268
269    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
270       return stat;
271    }
272
273    for (item=NULL; (item=(jobq_item_t *)jq->waiting_jobs->next(item)); ) {
274       if (jcr == item->jcr) {
275          found = true;
276          break;
277       }
278    }
279    if (!found) {
280       return EINVAL;
281    }
282
283    /* Move item to be the first on the list */
284    jq->waiting_jobs->remove(item);
285    jq->ready_jobs->prepend(item);
286    
287    stat = start_server(jq);
288    if (stat != 0) {
289       return stat;
290    }
291    pthread_mutex_unlock(&jq->mutex);
292    Dmsg0(100, "Return jobq_remove\n");
293    return stat;
294 }
295
296
297 /*
298  * Start the server thread 
299  */
300 static int start_server(jobq_t *jq)
301 {
302    int stat = 0;
303    pthread_t id;
304
305    /* if any threads are idle, wake one */
306    if (jq->idle_workers > 0) {
307       Dmsg0(100, "Signal worker to wake up\n");
308       if ((stat = pthread_cond_signal(&jq->work)) != 0) {
309          pthread_mutex_unlock(&jq->mutex);
310          return stat;
311       }
312    } else if (jq->num_workers < jq->max_workers) {
313       Dmsg0(100, "Create worker thread\n");
314       /* No idle threads so create a new one */
315       set_thread_concurrency(jq->max_workers + 1);
316       if ((stat = pthread_create(&id, &jq->attr, jobq_server, (void *)jq)) != 0) {
317          pthread_mutex_unlock(&jq->mutex);
318          return stat;
319       }
320       jq->num_workers++;
321    }
322    return stat;
323 }
324
325
326 /* 
327  * This is the worker thread that serves the job queue.
328  * When all the resources are acquired for the job, 
329  *  it will call the user's engine.
330  */
331 static void *jobq_server(void *arg)
332 {
333    struct timespec timeout;
334    jobq_t *jq = (jobq_t *)arg;
335    jobq_item_t *je;                   /* job entry in queue */
336    int stat;
337    bool timedout;
338    bool work = true;
339
340    Dmsg0(100, "Start jobq_server\n");
341    if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
342       return NULL;
343    }
344
345    for (;;) {
346       struct timeval tv;
347       struct timezone tz;
348
349       Dmsg0(100, "Top of for loop\n");
350       timedout = false;
351       Dmsg0(100, "gettimeofday()\n");
352       gettimeofday(&tv, &tz);
353       timeout.tv_nsec = 0;
354       timeout.tv_sec = tv.tv_sec + 4;
355
356       while (!work && !jq->quit) {
357          /*
358           * Wait 4 seconds, then if no more work, exit
359           */
360          Dmsg0(200, "pthread_cond_timedwait()\n");
361          stat = pthread_cond_timedwait(&jq->work, &jq->mutex, &timeout);
362          Dmsg1(100, "timedwait=%d\n", stat);
363          if (stat == ETIMEDOUT) {
364             timedout = true;
365             break;
366          } else if (stat != 0) {
367             /* This shouldn't happen */
368             Dmsg0(100, "This shouldn't happen\n");
369             jq->num_workers--;
370             pthread_mutex_unlock(&jq->mutex);
371             return NULL;
372          }
373       } 
374       /* 
375        * If anything is in the ready queue, run it
376        */
377       Dmsg0(100, "Checking ready queue.\n");
378       while (!jq->ready_jobs->empty() && !jq->quit) {
379          je = (jobq_item_t *)jq->ready_jobs->first(); 
380          jq->ready_jobs->remove(je);
381          if (!jq->ready_jobs->empty()) {
382             Dmsg0(100, "ready queue not empty start server\n");
383             if (start_server(jq) != 0) {
384                return NULL;
385             }
386          }
387          jq->running_jobs->append(je);
388          Dmsg1(100, "Took jobid=%d from ready and appended to run\n", je->jcr->JobId);
389          if ((stat = pthread_mutex_unlock(&jq->mutex)) != 0) {
390             return NULL;
391          }
392          /* Call user's routine here */
393          Dmsg1(100, "Calling user engine for jobid=%d\n", je->jcr->JobId);
394          jq->engine(je->jcr);
395          Dmsg1(100, "Back from user engine jobid=%d.\n", je->jcr->JobId);
396          if ((stat = pthread_mutex_lock(&jq->mutex)) != 0) {
397             free(je);                 /* release job entry */
398             return NULL;
399          }
400          Dmsg0(200, "Done lock mutex\n");
401          jq->running_jobs->remove(je);
402          /* 
403           * Release locks if acquired. Note, they will not have
404           *  been acquired for jobs canceled before they were
405           *  put into the ready queue.
406           */
407          if (je->jcr->acquired_resource_locks) {
408             je->jcr->store->NumConcurrentJobs--;
409             je->jcr->client->NumConcurrentJobs--;
410             je->jcr->job->NumConcurrentJobs--;
411          }
412          free_jcr(je->jcr);
413          free(je);                    /* release job entry */
414       }
415       /*
416        * If any job in the wait queue can be run,
417        *  move it to the ready queue
418        */
419       Dmsg0(100, "Done check ready, now check wait queue.\n");
420       while (!jq->waiting_jobs->empty() && !jq->quit) {
421          int Priority;
422          je = (jobq_item_t *)jq->waiting_jobs->first(); 
423          jobq_item_t *re = (jobq_item_t *)jq->running_jobs->first();
424          if (re) {
425             Priority = re->jcr->JobPriority;
426             Dmsg1(100, "Set Run pri=%d\n", Priority);
427          } else {
428             Priority = je->jcr->JobPriority;
429             Dmsg1(100, "Set Job pri=%d\n", Priority);
430          }
431          /*
432           * Acquire locks
433           */
434          for ( ; je;  ) {
435             JCR *jcr = je->jcr;
436             jobq_item_t *jn = (jobq_item_t *)jq->waiting_jobs->next(je);
437             Dmsg3(100, "Examining Job=%d JobPri=%d want Pri=%d\n",
438                jcr->JobId, jcr->JobPriority, Priority);
439             /* Take only jobs of correct Priority */
440             if (jcr->JobPriority != Priority) {
441                set_jcr_job_status(jcr, JS_WaitPriority);
442                break;
443             }
444             if (jcr->store->NumConcurrentJobs < jcr->store->MaxConcurrentJobs) {
445                jcr->store->NumConcurrentJobs++;
446             } else {
447                set_jcr_job_status(jcr, JS_WaitStoreRes);
448                je = jn;
449                continue;
450             }
451             if (jcr->client->NumConcurrentJobs < jcr->client->MaxConcurrentJobs) {
452                jcr->client->NumConcurrentJobs++;
453             } else {
454                jcr->store->NumConcurrentJobs--;
455                set_jcr_job_status(jcr, JS_WaitClientRes);
456                je = jn;
457                continue;
458             }
459             if (jcr->job->NumConcurrentJobs < jcr->job->MaxConcurrentJobs) {
460                jcr->job->NumConcurrentJobs++;
461             } else {
462                jcr->store->NumConcurrentJobs--;
463                jcr->client->NumConcurrentJobs--;
464                set_jcr_job_status(jcr, JS_WaitJobRes);
465                je = jn;
466                continue;
467             }
468             jcr->acquired_resource_locks = true;
469             jq->waiting_jobs->remove(je);
470             jq->ready_jobs->append(je);
471             Dmsg1(100, "moved JobId=%d from wait to ready queue\n", je->jcr->JobId);
472             je = jn;
473          } /* end for loop */
474          break;
475       } /* end while loop */
476       Dmsg0(100, "Done checking wait queue.\n");
477       /*
478        * If no more ready work and we are asked to quit, then do it
479        */
480       if (jq->ready_jobs->empty() && jq->quit) {
481          jq->num_workers--;
482          if (jq->num_workers == 0) {
483             Dmsg0(100, "Wake up destroy routine\n");
484             /* Wake up destroy routine if he is waiting */
485             pthread_cond_broadcast(&jq->work);
486          }
487          break;
488       }
489       Dmsg0(100, "Check for work request\n");
490       /* 
491        * If no more work requests, and we waited long enough, quit
492        */
493       Dmsg2(100, "timedout=%d read empty=%d\n", timedout,
494          jq->ready_jobs->empty());
495       if (jq->ready_jobs->empty() && timedout) {
496          Dmsg0(100, "break big loop\n");
497          jq->num_workers--;
498          break;
499       }
500       Dmsg0(100, "Loop again\n");
501       work = false;
502    } /* end of big for loop */
503
504    Dmsg0(200, "unlock mutex\n");
505    pthread_mutex_unlock(&jq->mutex);
506    Dmsg0(100, "End jobq_server\n");
507    return NULL;
508 }
509
510 #endif /* JOB_QUEUE */