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