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