]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/job.c
a99dbb7b4073e1917982cc1151c8a817e593ecae
[bacula/bacula] / bacula / src / stored / job.c
1 /*
2  *   Job control and execution for Storage Daemon
3  *
4  *   Kern Sibbald, MM
5  *
6  *   Version $Id$
7  *
8  */
9 /*
10    Copyright (C) 2000-2005 Kern Sibbald
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 "stored.h"
31
32 /* Imported variables */
33 extern uint32_t VolSessionTime;
34
35 /* Imported functions */
36 extern uint32_t newVolSessionId();
37
38 /* Forward referenced functions */
39 static bool use_device_cmd(JCR *jcr);
40
41 /* Requests from the Director daemon */
42 static char jobcmd[] = "JobId=%d job=%127s job_name=%127s client_name=%127s "
43       "type=%d level=%d FileSet=%127s NoAttr=%d SpoolAttr=%d FileSetMD5=%127s "
44       "SpoolData=%d  WritePartAfterJob=%d";
45 static char use_device[]  = "use device=%127s media_type=%127s "
46    "pool_name=%127s pool_type=%127s PoolId=%lld append=%d";
47 static char query_device[] = "query device=%127s";
48
49
50 /* Responses sent to Director daemon */
51 static char OKjob[]     = "3000 OK Job SDid=%u SDtime=%u Authorization=%s\n";
52 static char OK_device[] = "3000 OK use device device=%s\n";
53 static char NO_device[] = "3924 Device \"%s\" not in SD Device resources.\n";
54 static char NOT_open[]  = "3925 Device \"%s\" could not be opened or does not exist.\n";
55 static char BAD_use[]   = "3913 Bad use command: %s\n";
56 static char BAD_job[]   = "3915 Bad Job command: %s\n";
57 static char OK_query[]  = "3001 OK query "
58    "append=%d read=%d num_writers=%d "
59    "open=%d labeled=%d offline=%d "
60    "reserved=%d max_writers=%d "
61    "autoselect=%d autochanger=%d "
62    "poolid=%s "
63    "changer_name=%s media_type=%s volume_name=%s";
64 static char BAD_query[]   = "3917 Bad query command: %s\n";
65
66 /*
67  * Director requests us to start a job
68  * Basic tasks done here:
69  *  - We pickup the JobId to be run from the Director.
70  *  - We pickup the device, media, and pool from the Director
71  *  - Wait for a connection from the File Daemon (FD)
72  *  - Accept commands from the FD (i.e. run the job)
73  *  - Return when the connection is terminated or
74  *    there is an error.
75  */
76 bool job_cmd(JCR *jcr)
77 {
78    int JobId;
79    char auth_key[100];
80    BSOCK *dir = jcr->dir_bsock;
81    POOL_MEM job_name, client_name, job, fileset_name, fileset_md5;
82    int JobType, level, spool_attributes, no_attributes, spool_data, write_part_after_job;
83    JCR *ojcr;
84
85    /*
86     * Get JobId and permissions from Director
87     */
88    Dmsg1(100, "<dird: %s\n", dir->msg);
89    if (sscanf(dir->msg, jobcmd, &JobId, job.c_str(), job_name.c_str(),
90               client_name.c_str(),
91               &JobType, &level, fileset_name.c_str(), &no_attributes,
92               &spool_attributes, fileset_md5.c_str(), &spool_data, &write_part_after_job) != 12) {
93       pm_strcpy(jcr->errmsg, dir->msg);
94       bnet_fsend(dir, BAD_job, jcr->errmsg);
95       Dmsg1(100, ">dird: %s\n", dir->msg);
96       Emsg1(M_FATAL, 0, _("Bad Job Command from Director: %s\n"), jcr->errmsg);
97       set_jcr_job_status(jcr, JS_ErrorTerminated);
98       return false;
99    }
100    /*
101     * Since this job could be rescheduled, we
102     *  check to see if we have it already. If so
103     *  free the old jcr and use the new one.
104     */
105    ojcr = get_jcr_by_full_name(job.c_str());
106    if (ojcr && !ojcr->authenticated) {
107       Dmsg2(100, "Found ojcr=0x%x Job %s\n", (unsigned)(long)ojcr, job.c_str());
108       free_jcr(ojcr);
109    }
110    jcr->JobId = JobId;
111    jcr->VolSessionId = newVolSessionId();
112    jcr->VolSessionTime = VolSessionTime;
113    bstrncpy(jcr->Job, job, sizeof(jcr->Job));
114    unbash_spaces(job_name);
115    jcr->job_name = get_pool_memory(PM_NAME);
116    pm_strcpy(jcr->job_name, job_name);
117    unbash_spaces(client_name);
118    jcr->client_name = get_pool_memory(PM_NAME);
119    pm_strcpy(jcr->client_name, client_name);
120    unbash_spaces(fileset_name);
121    jcr->fileset_name = get_pool_memory(PM_NAME);
122    pm_strcpy(jcr->fileset_name, fileset_name);
123    jcr->JobType = JobType;
124    jcr->JobLevel = level;
125    jcr->no_attributes = no_attributes;
126    jcr->spool_attributes = spool_attributes;
127    jcr->spool_data = spool_data;
128    jcr->write_part_after_job = write_part_after_job;
129    jcr->fileset_md5 = get_pool_memory(PM_NAME);
130    pm_strcpy(jcr->fileset_md5, fileset_md5);
131
132    jcr->authenticated = false;
133
134    /*
135     * Pass back an authorization key for the File daemon
136     */
137    make_session_key(auth_key, NULL, 1);
138    bnet_fsend(dir, OKjob, jcr->VolSessionId, jcr->VolSessionTime, auth_key);
139    Dmsg1(100, ">dird: %s", dir->msg);
140    jcr->sd_auth_key = bstrdup(auth_key);
141    memset(auth_key, 0, sizeof(auth_key));
142    return true;
143 }
144
145 bool use_cmd(JCR *jcr) 
146 {
147    /*
148     * Wait for the device, media, and pool information
149     */
150    if (!use_device_cmd(jcr)) {
151       set_jcr_job_status(jcr, JS_ErrorTerminated);
152       memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
153       return false;
154    }
155    return true;
156 }
157
158 bool run_cmd(JCR *jcr)
159 {
160    struct timeval tv;
161    struct timezone tz;
162    struct timespec timeout;
163    int errstat;
164
165    Dmsg1(100, "Run_cmd: %s\n", jcr->dir_bsock->msg);
166    /* The following jobs don't need the FD */
167    switch (jcr->JobType) {
168    case JT_MIGRATION:
169    case JT_COPY:
170    case JT_ARCHIVE:
171       jcr->authenticated = true;
172       run_job(jcr);
173       return false;
174    }
175
176    set_jcr_job_status(jcr, JS_WaitFD);          /* wait for FD to connect */
177    dir_send_job_status(jcr);
178
179    gettimeofday(&tv, &tz);
180    timeout.tv_nsec = tv.tv_usec * 1000;
181    timeout.tv_sec = tv.tv_sec + 30 * 60;        /* wait 30 minutes */
182
183    Dmsg1(100, "%s waiting on FD to contact SD\n", jcr->Job);
184    /*
185     * Wait for the File daemon to contact us to start the Job,
186     *  when he does, we will be released, unless the 30 minutes
187     *  expires.
188     */
189    P(jcr->mutex);
190    for ( ;!job_canceled(jcr); ) {
191       errstat = pthread_cond_timedwait(&jcr->job_start_wait, &jcr->mutex, &timeout);
192       if (errstat == 0 || errstat == ETIMEDOUT) {
193          break;
194       }
195    }
196    V(jcr->mutex);
197
198    memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
199
200    if (jcr->authenticated && !job_canceled(jcr)) {
201       Dmsg1(100, "Running job %s\n", jcr->Job);
202       run_job(jcr);                   /* Run the job */
203    }
204    return false;
205 }
206
207 /*
208  * After receiving a connection (in job.c) if it is
209  *   from the File daemon, this routine is called.
210  */
211 void handle_filed_connection(BSOCK *fd, char *job_name)
212 {
213    JCR *jcr;
214
215    bmicrosleep(0, 50000);             /* wait 50 millisecs */
216    if (!(jcr=get_jcr_by_full_name(job_name))) {
217       Jmsg1(NULL, M_FATAL, 0, _("Job name not found: %s\n"), job_name);
218       Dmsg1(100, "Job name not found: %s\n", job_name);
219       return;
220    }
221
222    jcr->file_bsock = fd;
223    jcr->file_bsock->jcr = jcr;
224
225    Dmsg1(110, "Found Job %s\n", job_name);
226
227    if (jcr->authenticated) {
228       Jmsg2(jcr, M_FATAL, 0, "Hey!!!! JobId %u Job %s already authenticated.\n",
229          jcr->JobId, jcr->Job);
230       free_jcr(jcr);
231       return;
232    }
233
234    /*
235     * Authenticate the File daemon
236     */
237    if (jcr->authenticated || !authenticate_filed(jcr)) {
238       Dmsg1(100, "Authentication failed Job %s\n", jcr->Job);
239       Jmsg(jcr, M_FATAL, 0, _("Unable to authenticate File daemon\n"));
240    } else {
241       jcr->authenticated = true;
242       Dmsg1(110, "OK Authentication Job %s\n", jcr->Job);
243    }
244
245    P(jcr->mutex);
246    if (!jcr->authenticated) {
247       set_jcr_job_status(jcr, JS_ErrorTerminated);
248    }
249    pthread_cond_signal(&jcr->job_start_wait); /* wake waiting job */
250    V(jcr->mutex);
251    free_jcr(jcr);
252    return;
253 }
254
255
256 /*
257  *   Use Device command from Director
258  *   He tells is what Device Name to use, the Media Type,
259  *      the Pool Name, and the Pool Type.
260  *
261  *    Ensure that the device exists and is opened, then store
262  *      the media and pool info in the JCR.
263  */
264 static bool use_device_cmd(JCR *jcr)
265 {
266    POOL_MEM dev_name, media_type, pool_name, pool_type;
267    BSOCK *dir = jcr->dir_bsock;
268    DEVRES *device;
269    uint64_t PoolId;
270    AUTOCHANGER *changer;
271    int append;
272    bool ok;
273
274    /*
275     * If there are multiple devices, the director sends us
276     *   use_device for each device that it wants to use.
277     */
278    Dmsg1(100, "<dird: %s", dir->msg);
279    ok = sscanf(dir->msg, use_device, dev_name.c_str(), media_type.c_str(),
280                pool_name.c_str(), pool_type.c_str(), &PoolId, &append) == 6;
281    if (ok) {
282       unbash_spaces(dev_name);
283       unbash_spaces(media_type);
284       unbash_spaces(pool_name);
285       unbash_spaces(pool_type);
286       LockRes();
287       foreach_res(device, R_DEVICE) {
288          /* Find resource, and make sure we were able to open it */
289          if (fnmatch(dev_name.c_str(), device->hdr.name, 0) == 0 &&
290              strcmp(device->media_type, media_type.c_str()) == 0) {
291             const int name_len = MAX_NAME_LENGTH;
292             DCR *dcr;
293             UnlockRes();
294             if (!device->dev) {
295                device->dev = init_dev(jcr, NULL, device);
296             }
297             if (!device->dev) {
298                Jmsg(jcr, M_WARNING, 0, _("\n"
299                   "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
300                     dev_name.c_str());
301                bnet_fsend(dir, NOT_open, dev_name.c_str());
302                Dmsg1(100, ">dird: %s\n", dir->msg);
303                return false;
304             }  
305             dcr = new_dcr(jcr, device->dev);
306             if (!dcr) {
307                bnet_fsend(dir, _("3926 Could not get dcr for device: %s\n"), dev_name.c_str());
308                Dmsg1(100, ">dird: %s\n", dir->msg);
309                return false;
310             }
311             Dmsg1(100, "Found device %s\n", device->hdr.name);
312             bstrncpy(dcr->pool_name, pool_name, name_len);
313             bstrncpy(dcr->pool_type, pool_type, name_len);
314             bstrncpy(dcr->media_type, media_type, name_len);
315             bstrncpy(dcr->dev_name, dev_name, name_len);
316             dcr->PoolId = PoolId;
317             jcr->dcr = dcr;
318             if (append == SD_APPEND) {
319                ok = reserve_device_for_append(jcr, device->dev);
320             } else {
321                ok = reserve_device_for_read(jcr, device->dev);
322             }
323             if (!ok) {
324                bnet_fsend(dir, _("3927 Could not reserve device: %s\n"), dev_name.c_str());
325                Dmsg1(100, ">dird: %s\n", dir->msg);
326                free_dcr(jcr->dcr);
327                return false;
328             }
329             Dmsg1(220, "Got: %s", dir->msg);
330             bash_spaces(dev_name);
331             ok = bnet_fsend(dir, OK_device, dev_name.c_str());
332             Dmsg1(100, ">dird: %s\n", dir->msg);
333             return ok;
334          }
335       }
336
337       foreach_res(changer, R_AUTOCHANGER) {
338          /* Find resource, and make sure we were able to open it */
339          if (fnmatch(dev_name.c_str(), changer->hdr.name, 0) == 0) {
340             const int name_len = MAX_NAME_LENGTH;
341             DCR *dcr;
342             /* Try each device in this AutoChanger */
343             foreach_alist(device, changer->device) {
344                Dmsg1(100, "Try changer device %s\n", device->hdr.name);
345                if (!device->dev) {
346                   device->dev = init_dev(jcr, NULL, device);
347                }
348                if (!device->dev) {
349                   Dmsg1(100, "Device %s could not be opened. Skipped\n", dev_name.c_str());
350                   Jmsg(jcr, M_WARNING, 0, _("\n"
351                      "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
352                        device->hdr.name, dev_name.c_str());
353                   continue;
354                }
355                if (!device->dev->autoselect) {
356                   continue;           /* device is not available */
357                }
358                dcr = new_dcr(jcr, device->dev);
359                if (!dcr) {
360                   bnet_fsend(dir, _("3926 Could not get dcr for device: %s\n"), dev_name.c_str());
361                   Dmsg1(100, ">dird: %s\n", dir->msg);
362                   UnlockRes();
363                   return false;
364                }
365                Dmsg1(100, "Found changer device %s\n", device->hdr.name);
366                bstrncpy(dcr->pool_name, pool_name, name_len);
367                bstrncpy(dcr->pool_type, pool_type, name_len);
368                bstrncpy(dcr->media_type, media_type, name_len);
369                bstrncpy(dcr->dev_name, dev_name, name_len);
370                jcr->dcr = dcr;
371                if (append == SD_APPEND) {
372                   ok = reserve_device_for_append(jcr, device->dev);
373                } else {
374                   ok = reserve_device_for_read(jcr, device->dev);
375                }
376                if (!ok) {
377                   Jmsg(jcr, M_WARNING, 0, _("Could not reserve device: %s\n"), dev_name.c_str());
378                   free_dcr(jcr->dcr);
379                   continue;
380                }
381                Dmsg1(100, "Device %s opened.\n", dev_name.c_str());
382                UnlockRes();
383                pm_strcpy(dev_name, device->hdr.name);
384                bash_spaces(dev_name);
385                ok = bnet_fsend(dir, OK_device, dev_name.c_str());
386                Dmsg1(100, ">dird: %s\n", dir->msg);
387                return ok;
388             }
389             break;                    /* we found it but could not open a device */
390          }
391       }
392
393       UnlockRes();
394       if (verbose) {
395          unbash_spaces(dir->msg);
396          pm_strcpy(jcr->errmsg, dir->msg);
397          Jmsg(jcr, M_INFO, 0, _("Failed command: %s\n"), jcr->errmsg);
398       }
399       Jmsg(jcr, M_FATAL, 0, _("\n"
400          "     Device \"%s\" with MediaType \"%s\" requested by DIR not found in SD Device resources.\n"),
401            dev_name.c_str(), media_type.c_str());
402       bnet_fsend(dir, NO_device, dev_name.c_str());
403       Dmsg1(100, ">dird: %s\n", dir->msg);
404    } else {
405       unbash_spaces(dir->msg);
406       pm_strcpy(jcr->errmsg, dir->msg);
407       if (verbose) {
408          Jmsg(jcr, M_INFO, 0, _("Failed command: %s\n"), jcr->errmsg);
409       }
410       Jmsg(jcr, M_FATAL, 0, _("Bad Use Device command: %s\n"), jcr->errmsg);
411       bnet_fsend(dir, BAD_use, jcr->errmsg);
412       Dmsg1(100, ">dird: %s\n", dir->msg);
413    }
414
415    return false;                      /* ERROR return */
416 }
417
418 /*
419  *   Query Device command from Director
420  *   Sends Storage Daemon's information on the device to the
421  *    caller (presumably the Director).
422  *   This command always returns "true" so that the line is
423  *    not closed on an error.
424  *
425  */
426 bool query_cmd(JCR *jcr)
427 {
428    POOL_MEM dev_name;              
429    BSOCK *dir = jcr->dir_bsock;
430    DEVRES *device;
431    AUTOCHANGER *changer;
432    bool ok;
433    char ed1[50];
434
435    Dmsg1(100, "Query_cmd: %s", dir->msg);
436    ok = sscanf(dir->msg, query_device, dev_name.c_str()) == 1;
437    Dmsg1(100, "<dird: %s\n", dir->msg);
438    if (ok) {
439       unbash_spaces(dev_name);
440       LockRes();
441       foreach_res(device, R_DEVICE) {
442          /* Find resource, and make sure we were able to open it */
443          if (fnmatch(dev_name.c_str(), device->hdr.name, 0) == 0) {
444             if (!device->dev) {
445                device->dev = init_dev(jcr, NULL, device);
446             }
447             if (!device->dev) {
448                break;
449             }  
450             DEVICE *dev = device->dev;
451             POOL_MEM VolumeName, MediaType, ChangerName;
452             UnlockRes();
453             if (dev->is_labeled()) {
454                pm_strcpy(VolumeName, dev->VolHdr.VolName);
455             } else {
456                pm_strcpy(VolumeName, "*");
457             }
458             bash_spaces(VolumeName);
459             pm_strcpy(MediaType, device->media_type);
460             bash_spaces(MediaType);
461             if (device->changer_res) {
462                pm_strcpy(ChangerName, device->changer_res->hdr.name);
463                bash_spaces(ChangerName);
464             } else {
465                pm_strcpy(ChangerName, "*");
466             }
467             ok =bnet_fsend(dir, OK_query, 
468                dev->can_append()!=0,
469                dev->can_read()!=0, dev->num_writers, 
470                dev->is_open()!=0, dev->is_labeled()!=0,
471                dev->is_offline()!=0, dev->reserved_device, 
472                dev->is_tape()?100000:1,
473                dev->autoselect, 0, 
474                edit_uint64(dev->PoolId, ed1),
475                ChangerName.c_str(), MediaType.c_str(), VolumeName.c_str());
476             Dmsg1(100, ">dird: %s\n", dir->msg);
477             return ok;
478          }
479       }
480       foreach_res(changer, R_AUTOCHANGER) {
481          /* Find resource, and make sure we were able to open it */
482          if (fnmatch(dev_name.c_str(), changer->hdr.name, 0) == 0) {
483             UnlockRes();
484             /* This is mostly to indicate that we are here */
485             ok = bnet_fsend(dir, OK_query, 
486                0, 0, 0,                  /* append, read, num_writers */
487                0, 0, 0,                  /* is_open, is_labeled, offline */
488                0, 0,                     /* reserved, max_writers */
489                0, 1,                     /* autoselect, AutoChanger = 1 */   
490                "0",                      /* PoolId */
491                "*", "*", "*");           /* ChangerName, MediaType, VolName */
492             Dmsg1(100, ">dird: %s\n", dir->msg);
493             return ok;
494          }
495       }
496       /* If we get here, the device/autochanger was not found */
497       UnlockRes();
498       unbash_spaces(dir->msg);
499       pm_strcpy(jcr->errmsg, dir->msg);
500       bnet_fsend(dir, NO_device, dev_name.c_str());
501       Dmsg1(100, ">dird: %s\n", dir->msg);
502    } else {
503       unbash_spaces(dir->msg);
504       pm_strcpy(jcr->errmsg, dir->msg);
505       bnet_fsend(dir, BAD_query, jcr->errmsg);
506       Dmsg1(100, ">dird: %s\n", dir->msg);
507    }
508
509    return true;
510 }
511
512
513 /*
514  * Destroy the Job Control Record and associated
515  * resources (sockets).
516  */
517 void stored_free_jcr(JCR *jcr)
518 {
519    if (jcr->file_bsock) {
520       bnet_close(jcr->file_bsock);
521       jcr->file_bsock = NULL;
522    }
523    if (jcr->job_name) {
524       free_pool_memory(jcr->job_name);
525    }
526    if (jcr->client_name) {
527       free_memory(jcr->client_name);
528       jcr->client_name = NULL;
529    }
530    if (jcr->fileset_name) {
531       free_memory(jcr->fileset_name);
532    }
533    if (jcr->fileset_md5) {
534       free_memory(jcr->fileset_md5);
535    }
536    if (jcr->bsr) {
537       free_bsr(jcr->bsr);
538       jcr->bsr = NULL;
539    }
540    if (jcr->RestoreBootstrap) {
541       unlink(jcr->RestoreBootstrap);
542       free_pool_memory(jcr->RestoreBootstrap);
543       jcr->RestoreBootstrap = NULL;
544    }
545    if (jcr->next_dev || jcr->prev_dev) {
546       Emsg0(M_FATAL, 0, _("In free_jcr(), but still attached to device!!!!\n"));
547    }
548    pthread_cond_destroy(&jcr->job_start_wait);
549    if (jcr->dcrs) {
550       delete jcr->dcrs;
551    }
552    jcr->dcrs = NULL;
553    if (jcr->dcr) {
554       free_dcr(jcr->dcr);
555       jcr->dcr = NULL;
556    }
557    return;
558 }