]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/job.c
Complete new job scheduler + fix from Nic Bellamy
[bacula/bacula] / bacula / src / dird / job.c
1 /*
2  *
3  *   Bacula Director Job processing routines
4  *
5  *     Kern Sibbald, October MM
6  *
7  *    Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2003 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "dird.h"
31
32 /* Forward referenced subroutines */
33 static void *job_thread(void *arg);
34 static char *edit_run_codes(JCR *jcr, char *omsg, char *imsg);
35 static void release_resource_locks(JCR *jcr);
36 static int acquire_resource_locks(JCR *jcr);
37 #ifdef USE_SEMAPHORE
38 static void backoff_resource_locks(JCR *jcr, int count);
39 #endif
40
41 /* Exported subroutines */
42 void run_job(JCR *jcr);
43
44
45 /* Imported subroutines */
46 extern void term_scheduler();
47 extern void term_ua_server();
48 extern int do_backup(JCR *jcr);
49 extern int do_admin(JCR *jcr);
50 extern int do_restore(JCR *jcr);
51 extern int do_verify(JCR *jcr);
52
53 #ifdef USE_SEMAPHORE
54 static semlock_t job_lock;
55 static pthread_mutex_t mutex;
56 static pthread_cond_t  resource_wait;
57 static int waiting = 0;               /* count of waiting threads */
58 #else
59 #ifdef JOB_QUEUE  
60 jobq_t  job_queue;
61 #else
62 /* Queue of jobs to be run */
63 workq_t job_wq;                   /* our job work queue */
64 #endif
65 #endif
66
67 void init_job_server(int max_workers)
68 {
69    int stat;
70 #ifdef USE_SEMAPHORE
71    if ((stat = sem_init(&job_lock, max_workers)) != 0) {
72       Emsg1(M_ABORT, 0, _("Could not init job lock: ERR=%s\n"), strerror(stat));
73    }
74    if ((stat = pthread_mutex_init(&mutex, NULL)) != 0) {
75       Emsg1(M_ABORT, 0, _("Could not init resource mutex: ERR=%s\n"), strerror(stat));
76    }
77    if ((stat = pthread_cond_init(&resource_wait, NULL)) != 0) {
78       Emsg1(M_ABORT, 0, _("Could not init resource wait: ERR=%s\n"), strerror(stat));
79    }
80
81 #else
82 #ifdef JOB_QUEUE
83    if ((stat = jobq_init(&job_queue, max_workers, job_thread)) != 0) {
84       Emsg1(M_ABORT, 0, _("Could not init job queue: ERR=%s\n"), strerror(stat));
85    }
86 #else
87    /* This is the OLD work queue code to go away */
88    if ((stat = workq_init(&job_wq, max_workers, job_thread)) != 0) {
89       Emsg1(M_ABORT, 0, _("Could not init job work queue: ERR=%s\n"), strerror(stat));
90    }
91 #endif
92 #endif
93    return;
94 }
95
96 /*
97  * Run a job -- typically called by the scheduler, but may also
98  *              be called by the UA (Console program).
99  *
100  */
101 void run_job(JCR *jcr)
102 {
103    int stat, errstat;
104 #ifdef USE_SEMAPHORE
105    pthread_t tid;
106 #else
107 #ifndef JOB_QUEUE
108    workq_ele_t *work_item;
109 #endif
110 #endif
111
112    sm_check(__FILE__, __LINE__, True);
113    init_msg(jcr, jcr->messages);
114    create_unique_job_name(jcr, jcr->job->hdr.name);
115    set_jcr_job_status(jcr, JS_Created);
116    jcr->jr.SchedTime = jcr->sched_time;
117    jcr->jr.StartTime = jcr->start_time;
118    jcr->jr.Type = jcr->JobType;
119    jcr->jr.Level = jcr->JobLevel;
120    jcr->jr.JobStatus = jcr->JobStatus;
121    bstrncpy(jcr->jr.Name, jcr->job->hdr.name, sizeof(jcr->jr.Name));
122    bstrncpy(jcr->jr.Job, jcr->Job, sizeof(jcr->jr.Job));
123
124    /* Initialize termination condition variable */
125    if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
126       Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
127       set_jcr_job_status(jcr, JS_ErrorTerminated);
128       free_jcr(jcr);
129       return;
130    }
131
132    /*
133     * Open database
134     */
135    Dmsg0(50, "Open database\n");
136    jcr->db=db_init_database(jcr, jcr->catalog->db_name, jcr->catalog->db_user,
137                             jcr->catalog->db_password, jcr->catalog->db_address,
138                             jcr->catalog->db_port, jcr->catalog->db_socket);
139    if (!db_open_database(jcr, jcr->db)) {
140       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
141       set_jcr_job_status(jcr, JS_ErrorTerminated);
142       free_jcr(jcr);
143       return;
144    }
145    Dmsg0(50, "DB opened\n");
146
147    /*
148     * Create Job record  
149     */
150    jcr->jr.JobStatus = jcr->JobStatus;
151    if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
152       Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
153       set_jcr_job_status(jcr, JS_ErrorTerminated);
154       free_jcr(jcr);
155       return;
156    }
157    jcr->JobId = jcr->jr.JobId;
158    ASSERT(jcr->jr.JobId > 0);
159
160    Dmsg4(30, "Created job record JobId=%d Name=%s Type=%c Level=%c\n", 
161        jcr->JobId, jcr->Job, jcr->jr.Type, jcr->jr.Level);
162    Dmsg0(200, "Add jrc to work queue\n");
163
164 #ifdef USE_SEMAPHORE
165   if ((stat = pthread_create(&tid, NULL, job_thread, (void *)jcr)) != 0) {
166       Emsg1(M_ABORT, 0, _("Unable to create job thread: ERR=%s\n"), strerror(stat));
167    }
168 #else
169 #ifdef JOB_QUEUE
170    /* Queue the job to be run */
171    if ((stat = jobq_add(&job_queue, jcr)) != 0) {
172       Emsg1(M_ABORT, 0, _("Could not add job queue: ERR=%s\n"), strerror(stat));
173    }
174 #else
175    /* Queue the job to be run */
176    if ((stat = workq_add(&job_wq, (void *)jcr, &work_item, 0)) != 0) {
177       Emsg1(M_ABORT, 0, _("Could not add job to work queue: ERR=%s\n"), strerror(stat));
178    }
179    jcr->work_item = work_item;
180 #endif
181 #endif
182    Dmsg0(200, "Done run_job()\n");
183 }
184
185 /* 
186  * This is the engine called by workq_add() when we were pulled                
187  *  from the work queue.
188  *  At this point, we are running in our own thread 
189  */
190 static void *job_thread(void *arg)
191 {
192    JCR *jcr = (JCR *)arg;
193
194    pthread_detach(pthread_self());
195    sm_check(__FILE__, __LINE__, True);
196
197    for ( ;; ) {
198       if (!acquire_resource_locks(jcr)) {
199          set_jcr_job_status(jcr, JS_Canceled);
200       }
201
202       Dmsg0(200, "=====Start Job=========\n");
203       jcr->start_time = time(NULL);      /* set the real start time */
204       set_jcr_job_status(jcr, JS_Running);
205
206       if (job_canceled(jcr)) {
207          update_job_end_record(jcr);
208       } else if (jcr->job->MaxStartDelay != 0 && jcr->job->MaxStartDelay <
209           (utime_t)(jcr->start_time - jcr->sched_time)) {
210          Jmsg(jcr, M_FATAL, 0, _("Job canceled because max start delay time exceeded.\n"));
211          set_jcr_job_status(jcr, JS_Canceled);
212          update_job_end_record(jcr);
213       } else {
214
215          /* Run Job */
216          if (jcr->job->RunBeforeJob) {
217             POOLMEM *before = get_pool_memory(PM_FNAME);
218             int status;
219             BPIPE *bpipe;
220             char line[MAXSTRING];
221             
222             before = edit_run_codes(jcr, before, jcr->job->RunBeforeJob);
223             bpipe = open_bpipe(before, 0, "r");
224             free_pool_memory(before);
225             while (fgets(line, sizeof(line), bpipe->rfd)) {
226                Jmsg(jcr, M_INFO, 0, _("RunBefore: %s"), line);
227             }
228             status = close_bpipe(bpipe);
229             if (status != 0) {
230                Jmsg(jcr, M_FATAL, 0, _("RunBeforeJob returned non-zero status=%d\n"),
231                   status);
232                set_jcr_job_status(jcr, JS_FatalError);
233                update_job_end_record(jcr);
234                goto bail_out;
235             }
236          }
237          switch (jcr->JobType) {
238          case JT_BACKUP:
239             do_backup(jcr);
240             if (jcr->JobStatus == JS_Terminated) {
241                do_autoprune(jcr);
242             }
243             break;
244          case JT_VERIFY:
245             do_verify(jcr);
246             if (jcr->JobStatus == JS_Terminated) {
247                do_autoprune(jcr);
248             }
249             break;
250          case JT_RESTORE:
251             do_restore(jcr);
252             if (jcr->JobStatus == JS_Terminated) {
253                do_autoprune(jcr);
254             }
255             break;
256          case JT_ADMIN:
257             do_admin(jcr);
258             if (jcr->JobStatus == JS_Terminated) {
259                do_autoprune(jcr);
260             }
261             break;
262          default:
263             Pmsg1(0, "Unimplemented job type: %d\n", jcr->JobType);
264             break;
265          }
266          if (jcr->job->RunAfterJob) {
267             POOLMEM *after = get_pool_memory(PM_FNAME);
268             int status;
269             BPIPE *bpipe;
270             char line[MAXSTRING];
271             
272             after = edit_run_codes(jcr, after, jcr->job->RunAfterJob);
273             bpipe = open_bpipe(after, 0, "r");
274             free_pool_memory(after);
275             while (fgets(line, sizeof(line), bpipe->rfd)) {
276                Jmsg(jcr, M_INFO, 0, _("RunAfter: %s"), line);
277             }
278             status = close_bpipe(bpipe);
279             if (status != 0) {
280                Jmsg(jcr, M_FATAL, 0, _("RunAfterJob returned non-zero status=%d\n"),
281                   status);
282                set_jcr_job_status(jcr, JS_FatalError);
283                update_job_end_record(jcr);
284             }
285          }
286       }
287 bail_out:
288       release_resource_locks(jcr);
289       if (jcr->job->RescheduleOnError && 
290           jcr->JobStatus != JS_Terminated &&
291           jcr->JobStatus != JS_Canceled && 
292           jcr->job->RescheduleTimes > 0 && 
293           jcr->reschedule_count < jcr->job->RescheduleTimes) {
294
295           /*
296            * Reschedule this job by cleaning it up, but
297            *  reuse the same JobId if possible.
298            */
299          jcr->reschedule_count++;
300          jcr->sched_time = time(NULL) + jcr->job->RescheduleInterval;
301          Dmsg2(100, "Rescheduled Job %s to re-run in %d seconds.\n", jcr->Job,
302             (int)jcr->job->RescheduleInterval);
303          jcr->JobStatus = JS_Created; /* force new status */
304          dird_free_jcr(jcr);          /* partial cleanup old stuff */
305          if (jcr->JobBytes == 0) {
306             continue;                    /* reschedule the job */
307          }
308          /* 
309           * Something was actually backed up, so we cannot reuse
310           *   the old JobId or there will be database record
311           *   conflicts.  We now create a new job, copying the
312           *   appropriate fields.
313           */
314          JCR *njcr = new_jcr(sizeof(JCR), dird_free_jcr);
315          set_jcr_defaults(njcr, jcr->job);
316          njcr->reschedule_count = jcr->reschedule_count;
317          njcr->JobLevel = jcr->JobLevel;
318          njcr->JobStatus = jcr->JobStatus;
319          njcr->pool = jcr->pool;
320          njcr->store = jcr->store;
321          njcr->messages = jcr->messages;
322          run_job(njcr);
323       }
324       break;
325    }
326
327    if (jcr->db) {
328       Dmsg0(200, "Close DB\n");
329       db_close_database(jcr, jcr->db);
330       jcr->db = NULL;
331    }
332 #ifndef JOB_QUEUE
333    free_jcr(jcr);
334 #endif
335    Dmsg0(50, "======== End Job ==========\n");
336    sm_check(__FILE__, __LINE__, True);
337    return NULL;
338 }
339
340 /*
341  * Acquire the resources needed. These locks limit the
342  *  number of jobs by each resource. We have limits on
343  *  Jobs, Clients, Storage, and total jobs.
344  */
345 static int acquire_resource_locks(JCR *jcr)
346 {
347 #ifndef JOB_QUEUE
348    time_t now = time(NULL);
349    time_t wtime = jcr->sched_time - now;
350
351    /* Wait until scheduled time arrives */
352    if (wtime > 0 && verbose) {
353       Jmsg(jcr, M_INFO, 0, _("Job %s waiting %d seconds for scheduled start time.\n"), 
354          jcr->Job, wtime);
355       set_jcr_job_status(jcr, JS_WaitStartTime);
356    }
357    /* Check every 30 seconds if canceled */ 
358    while (wtime > 0) {
359       Dmsg2(100, "Waiting on sched time, jobid=%d secs=%d\n", jcr->JobId, wtime);
360       if (wtime > 30) {
361          wtime = 30;
362       }
363       bmicrosleep(wtime, 0);
364       if (job_canceled(jcr)) {
365          return 0;
366       }
367       wtime = jcr->sched_time - time(NULL);
368    }
369 #endif
370
371
372 #ifdef USE_SEMAPHORE
373    int stat;
374
375    /* Initialize semaphores */
376    if (jcr->store->sem.valid != SEMLOCK_VALID) {
377       if ((stat = sem_init(&jcr->store->sem, jcr->store->MaxConcurrentJobs)) != 0) {
378          Emsg1(M_ABORT, 0, _("Could not init Storage semaphore: ERR=%s\n"), strerror(stat));
379       }
380    }
381    if (jcr->client->sem.valid != SEMLOCK_VALID) {
382       if ((stat = sem_init(&jcr->client->sem, jcr->client->MaxConcurrentJobs)) != 0) {
383          Emsg1(M_ABORT, 0, _("Could not init Client semaphore: ERR=%s\n"), strerror(stat));
384       }
385    }
386    if (jcr->job->sem.valid != SEMLOCK_VALID) {
387       if ((stat = sem_init(&jcr->job->sem, jcr->job->MaxConcurrentJobs)) != 0) {
388          Emsg1(M_ABORT, 0, _("Could not init Job semaphore: ERR=%s\n"), strerror(stat));
389       }
390    }
391
392    for ( ;; ) {
393       /* Acquire semaphore */
394       set_jcr_job_status(jcr, JS_WaitJobRes);
395       if ((stat = sem_lock(&jcr->job->sem)) != 0) {
396          Emsg1(M_ABORT, 0, _("Could not acquire Job max jobs lock: ERR=%s\n"), strerror(stat));
397       }
398       set_jcr_job_status(jcr, JS_WaitClientRes);
399       if ((stat = sem_trylock(&jcr->client->sem)) != 0) {
400          if (stat == EBUSY) {
401             backoff_resource_locks(jcr, 1);
402             goto wait;
403          } else {
404             Emsg1(M_ABORT, 0, _("Could not acquire Client max jobs lock: ERR=%s\n"), strerror(stat));
405          }
406       }
407       set_jcr_job_status(jcr, JS_WaitStoreRes);
408       if ((stat = sem_trylock(&jcr->store->sem)) != 0) {
409          if (stat == EBUSY) {
410             backoff_resource_locks(jcr, 2);
411             goto wait;
412          } else {
413             Emsg1(M_ABORT, 0, _("Could not acquire Storage max jobs lock: ERR=%s\n"), strerror(stat));
414          }
415       }
416       set_jcr_job_status(jcr, JS_WaitMaxJobs);
417       if ((stat = sem_trylock(&job_lock)) != 0) {
418          if (stat == EBUSY) {
419             backoff_resource_locks(jcr, 3);
420             goto wait;
421          } else {
422             Emsg1(M_ABORT, 0, _("Could not acquire max jobs lock: ERR=%s\n"), strerror(stat));
423          }
424       }
425       break;
426
427 wait:
428       if (job_canceled(jcr)) {
429          return 0;
430       }
431       P(mutex);
432       /*
433        * Wait for a resource to be released either by backoff or
434        *  by a job terminating.
435        */
436       waiting++;
437       pthread_cond_wait(&resource_wait, &mutex);
438       waiting--;
439       V(mutex);
440       /* Try again */
441    }
442    jcr->acquired_resource_locks = true;
443 #endif
444    return 1;
445 }
446
447 #ifdef USE_SEMAPHORE
448 /*
449  * We could not get all the resource locks because 
450  *  too many jobs are running, so release any locks
451  *  we did acquire, giving others a chance to use them
452  *  while we wait.
453  */
454 static void backoff_resource_locks(JCR *jcr, int count)
455 {
456    P(mutex);
457    switch (count) {
458    case 3:
459       sem_unlock(&jcr->store->sem);
460       /* Fall through wanted */
461    case 2:
462       sem_unlock(&jcr->client->sem);
463       /* Fall through wanted */
464    case 1:
465       sem_unlock(&jcr->job->sem);
466       break;
467    }
468    /*
469     * Since we released a lock, if there are any threads
470     *  waiting, wake them up so that they can try again.
471     */
472    if (waiting > 0) {
473       pthread_cond_broadcast(&resource_wait);
474    }
475    V(mutex);
476 }
477 #endif
478
479 /*
480  * This is called at the end of the job to release
481  *   any resource limits on the number of jobs. If
482  *   there are any other jobs waiting, we wake them
483  *   up so that they can try again.
484  */
485 static void release_resource_locks(JCR *jcr)
486 {
487    if (!jcr->acquired_resource_locks) {
488       return;                         /* Job canceled, no locks acquired */
489    }
490 #ifdef USE_SEMAPHORE
491    P(mutex);
492    sem_unlock(&jcr->store->sem);
493    sem_unlock(&jcr->client->sem);
494    sem_unlock(&jcr->job->sem);
495    sem_unlock(&job_lock);
496    if (waiting > 0) {
497       pthread_cond_broadcast(&resource_wait);
498    }
499    jcr->acquired_resource_locks = false;
500    V(mutex);
501 #endif
502 }
503
504 /*
505  * Get or create a Client record for this Job
506  */
507 int get_or_create_client_record(JCR *jcr)
508 {
509    CLIENT_DBR cr;
510
511    memset(&cr, 0, sizeof(cr));
512    bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
513    cr.AutoPrune = jcr->client->AutoPrune;
514    cr.FileRetention = jcr->client->FileRetention;
515    cr.JobRetention = jcr->client->JobRetention;
516    if (!jcr->client_name) {
517       jcr->client_name = get_pool_memory(PM_NAME);
518    }
519    pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
520    if (!db_create_client_record(jcr, jcr->db, &cr)) {
521       Jmsg(jcr, M_FATAL, 0, _("Could not create Client record. ERR=%s\n"), 
522          db_strerror(jcr->db));
523       return 0;
524    }
525    jcr->jr.ClientId = cr.ClientId;
526    if (cr.Uname[0]) {
527       if (!jcr->client_uname) {
528          jcr->client_uname = get_pool_memory(PM_NAME);
529       }
530       pm_strcpy(&jcr->client_uname, cr.Uname);
531    }
532    Dmsg2(100, "Created Client %s record %d\n", jcr->client->hdr.name, 
533       jcr->jr.ClientId);
534    return 1;
535 }
536
537
538 /*
539  * Write status and such in DB
540  */
541 void update_job_end_record(JCR *jcr)
542 {
543    if (jcr->jr.EndTime == 0) {
544       jcr->jr.EndTime = time(NULL);
545    }
546    jcr->end_time = jcr->jr.EndTime;
547    jcr->jr.JobId = jcr->JobId;
548    jcr->jr.JobStatus = jcr->JobStatus;
549    jcr->jr.JobFiles = jcr->JobFiles;
550    jcr->jr.JobBytes = jcr->JobBytes;
551    jcr->jr.VolSessionId = jcr->VolSessionId;
552    jcr->jr.VolSessionTime = jcr->VolSessionTime;
553    if (!db_update_job_end_record(jcr, jcr->db, &jcr->jr)) {
554       Jmsg(jcr, M_WARNING, 0, _("Error updating job record. %s"), 
555          db_strerror(jcr->db));
556    }
557 }
558
559 /*
560  * Takes base_name and appends (unique) current
561  *   date and time to form unique job name.
562  *
563  *  Returns: unique job name in jcr->Job
564  *    date/time in jcr->start_time
565  */
566 void create_unique_job_name(JCR *jcr, char *base_name)
567 {
568    /* Job start mutex */
569    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
570    static time_t last_start_time = 0;
571    time_t now;
572    struct tm tm;
573    char dt[MAX_TIME_LENGTH];
574    char name[MAX_NAME_LENGTH];
575    char *p;
576
577    /* Guarantee unique start time -- maximum one per second, and
578     * thus unique Job Name 
579     */
580    P(mutex);                          /* lock creation of jobs */
581    now = time(NULL);
582    while (now == last_start_time) {
583       bmicrosleep(0, 500000);
584       now = time(NULL);
585    }
586    last_start_time = now;
587    V(mutex);                          /* allow creation of jobs */
588    jcr->start_time = now;
589    /* Form Unique JobName */
590    localtime_r(&now, &tm);
591    /* Use only characters that are permitted in Windows filenames */
592    strftime(dt, sizeof(dt), "%Y-%m-%d_%H.%M.%S", &tm); 
593    bstrncpy(name, base_name, sizeof(name));
594    name[sizeof(name)-22] = 0;          /* truncate if too long */
595    bsnprintf(jcr->Job, sizeof(jcr->Job), "%s.%s", name, dt); /* add date & time */
596    /* Convert spaces into underscores */
597    for (p=jcr->Job; *p; p++) {
598       if (*p == ' ') {
599          *p = '_';
600       }
601    }
602 }
603
604 /*
605  * Free the Job Control Record if no one is still using it.
606  *  Called from main free_jcr() routine in src/lib/jcr.c so
607  *  that we can do our Director specific cleanup of the jcr.
608  */
609 void dird_free_jcr(JCR *jcr)
610 {
611    Dmsg0(200, "Start dird free_jcr\n");
612
613    if (jcr->sd_auth_key) {
614       free(jcr->sd_auth_key);
615       jcr->sd_auth_key = NULL;
616    }
617    if (jcr->where) {
618       free(jcr->where);
619       jcr->where = NULL;
620    }
621    if (jcr->file_bsock) {
622       Dmsg0(200, "Close File bsock\n");
623       bnet_close(jcr->file_bsock);
624       jcr->file_bsock = NULL;
625    }
626    if (jcr->store_bsock) {
627       Dmsg0(200, "Close Store bsock\n");
628       bnet_close(jcr->store_bsock);
629       jcr->store_bsock = NULL;
630    }
631    if (jcr->fname) {  
632       Dmsg0(200, "Free JCR fname\n");
633       free_pool_memory(jcr->fname);
634       jcr->fname = NULL;
635    }
636    if (jcr->stime) {
637       Dmsg0(200, "Free JCR stime\n");
638       free_pool_memory(jcr->stime);
639       jcr->stime = NULL;
640    }
641    if (jcr->RestoreBootstrap) {
642       free(jcr->RestoreBootstrap);
643       jcr->RestoreBootstrap = NULL;
644    }
645    if (jcr->client_uname) {
646       free_pool_memory(jcr->client_uname);
647       jcr->client_uname = NULL;
648    }
649    Dmsg0(200, "End dird free_jcr\n");
650 }
651
652 /*
653  * Set some defaults in the JCR necessary to
654  * run. These items are pulled from the job
655  * definition as defaults, but can be overridden
656  * later either by the Run record in the Schedule resource,
657  * or by the Console program.
658  */
659 void set_jcr_defaults(JCR *jcr, JOB *job)
660 {
661    jcr->job = job;
662    jcr->JobType = job->JobType;
663    jcr->JobLevel = job->level;
664    jcr->JobPriority = job->Priority;
665    jcr->store = job->storage;
666    jcr->client = job->client;
667    if (!jcr->client_name) {
668       jcr->client_name = get_pool_memory(PM_NAME);
669    }
670    pm_strcpy(&jcr->client_name, jcr->client->hdr.name);
671    jcr->pool = job->pool;
672    jcr->catalog = job->client->catalog;
673    jcr->fileset = job->fileset;
674    jcr->messages = job->messages; 
675    if (jcr->RestoreBootstrap) {
676       free(jcr->RestoreBootstrap);
677    }
678    /* This can be overridden by Console program */
679    if (job->RestoreBootstrap) {
680       jcr->RestoreBootstrap = bstrdup(job->RestoreBootstrap);
681    }
682    /* If no default level given, set one */
683    if (jcr->JobLevel == 0) {
684       switch (jcr->JobType) {
685       case JT_VERIFY:
686          jcr->JobLevel = L_VERIFY_CATALOG;
687          break;
688       case JT_BACKUP:
689          jcr->JobLevel = L_INCREMENTAL;
690          break;
691       case JT_RESTORE:
692       case JT_ADMIN:
693          jcr->JobLevel = L_FULL;
694          break;
695       default:
696          break;
697       }
698    }
699 }
700
701 /*
702  * Edit codes into Run command
703  *  %% = %
704  *  %c = Client's name
705  *  %d = Director's name
706  *  %i = JobId
707  *  %e = Job Exit
708  *  %j = Job
709  *  %l = Job Level
710  *  %n = Job name
711  *  %t = Job type
712  *
713  *  omsg = edited output message
714  *  imsg = input string containing edit codes (%x)
715  *
716  */
717 static char *edit_run_codes(JCR *jcr, char *omsg, char *imsg) 
718 {
719    char *p;
720    const char *str;
721    char add[20];
722
723    *omsg = 0;
724    Dmsg1(200, "edit_run_codes: %s\n", imsg);
725    for (p=imsg; *p; p++) {
726       if (*p == '%') {
727          switch (*++p) {
728          case '%':
729             str = "%";
730             break;
731          case 'c':
732             str = jcr->client_name;
733             if (!str) {
734                str = "";
735             }
736             break;
737          case 'd':
738             str = my_name;
739             break;
740          case 'e':
741             str = job_status_to_str(jcr->JobStatus);
742             break;
743          case 'i':
744             sprintf(add, "%d", jcr->JobId);
745             str = add;
746             break;
747          case 'j':                    /* Job */
748             str = jcr->Job;
749             break;
750          case 'l':
751             str = job_level_to_str(jcr->JobLevel);
752             break;
753          case 'n':
754             str = jcr->job->hdr.name;
755             break;
756          case 't':
757             str = job_type_to_str(jcr->JobType);
758             break;
759          default:
760             add[0] = '%';
761             add[1] = *p;
762             add[2] = 0;
763             str = add;
764             break;
765          }
766       } else {
767          add[0] = *p;
768          add[1] = 0;
769          str = add;
770       }
771       Dmsg1(200, "add_str %s\n", str);
772       pm_strcat(&omsg, (char *)str);
773       Dmsg1(200, "omsg=%s\n", omsg);
774    }
775    return omsg;
776 }