]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/askdir.c
Rtn oldest Lastwritten for find_next_vol+remove bad ASSERT+add more SD status if...
[bacula/bacula] / bacula / src / stored / askdir.c
1 /*
2  *  Subroutines to handle Catalog reqests sent to the Director
3  *   Reqests/commands from the Director are handled in dircmd.c
4  *
5  *   Kern Sibbald, December 2000
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"                   /* pull in global headers */
30 #include "stored.h"                   /* pull in Storage Deamon headers */
31
32 /* Requests sent to the Director */
33 static char Find_media[]   = "CatReq Job=%s FindMedia=%d\n";
34 static char Get_Vol_Info[] = "CatReq Job=%s GetVolInfo VolName=%s write=%d\n";
35 static char Update_media[] = "CatReq Job=%s UpdateMedia VolName=%s"
36    " VolJobs=%u VolFiles=%u VolBlocks=%u VolBytes=%s VolMounts=%u"
37    " VolErrors=%u VolWrites=%u MaxVolBytes=%s EndTime=%d VolStatus=%s"
38    " Slot=%d relabel=%d Drive=%d InChanger=%d\n";
39 static char Create_job_media[] = "CatReq Job=%s CreateJobMedia" 
40    " FirstIndex=%u LastIndex=%u StartFile=%u EndFile=%u" 
41    " StartBlock=%u EndBlock=%u\n";
42 static char FileAttributes[] = "UpdCat Job=%s FileAttributes ";
43 static char Job_status[]     = "3012 Job %s jobstatus %d\n";
44
45
46 /* Responses received from the Director */
47 static char OK_media[] = "1000 OK VolName=%127s VolJobs=%u VolFiles=%u"
48    " VolBlocks=%u VolBytes=%" lld " VolMounts=%u VolErrors=%u VolWrites=%u"
49    " MaxVolBytes=%" lld " VolCapacityBytes=%" lld " VolStatus=%20s"
50    " Slot=%d MaxVolJobs=%u MaxVolFiles=%u Drive=%d InChanger=%d";
51
52 static char OK_create[] = "1000 OK CreateJobMedia\n";
53
54 /* Forward referenced functions */
55 static int wait_for_sysop(JCR *jcr, DEVICE *dev, int wait_sec);
56
57 /*
58  * Send current JobStatus to Director
59  */
60 int dir_send_job_status(JCR *jcr)
61 {
62    return bnet_fsend(jcr->dir_bsock, Job_status, jcr->Job, jcr->JobStatus);
63 }
64
65 /*
66  * Common routine for:
67  *   dir_get_volume_info()
68  * and
69  *   dir_find_next_appendable_volume()
70  * 
71  *  Returns: 1 on success and vol info in jcr->VolCatInfo
72  *           0 on failure
73  */
74 static int do_get_volume_info(JCR *jcr)
75 {
76     BSOCK *dir = jcr->dir_bsock;
77     VOLUME_CAT_INFO vol;
78
79     jcr->VolumeName[0] = 0;           /* No volume */
80     if (bnet_recv(dir) <= 0) {
81        Dmsg0(200, "getvolname error bnet_recv\n");
82        Mmsg(&jcr->errmsg, _("Network error on bnet_recv in req_vol_info.\n"));
83        return 0;
84     }
85     memset(&vol, 0, sizeof(vol));
86     if (sscanf(dir->msg, OK_media, vol.VolCatName, 
87                &vol.VolCatJobs, &vol.VolCatFiles,
88                &vol.VolCatBlocks, &vol.VolCatBytes,
89                &vol.VolCatMounts, &vol.VolCatErrors,
90                &vol.VolCatWrites, &vol.VolCatMaxBytes,
91                &vol.VolCatCapacityBytes, vol.VolCatStatus,
92                &vol.Slot, &vol.VolCatMaxJobs, &vol.VolCatMaxFiles,
93                &vol.Drive, &vol.InChanger) != 16) {
94
95        Dmsg1(200, "Bad response from Dir: %s\n", dir->msg);
96        Mmsg(&jcr->errmsg, _("Error getting Volume info: %s\n"), dir->msg);
97        return 0;
98     }
99     unbash_spaces(vol.VolCatName);
100     pm_strcpy(&jcr->VolumeName, vol.VolCatName); /* set desired VolumeName */
101     memcpy(&jcr->VolCatInfo, &vol, sizeof(jcr->VolCatInfo));
102     
103     Dmsg2(200, "do_reqest_vol_info got slot=%d Volume=%s\n", 
104           vol.Slot, vol.VolCatName);
105     return 1;
106 }
107
108
109 /*
110  * Get Volume info for a specific volume from the Director's Database
111  *
112  * Returns: 1 on success   (not Director guarantees that Pool and MediaType
113  *                          are correct and VolStatus==Append or
114  *                          VolStatus==Recycle)
115  *          0 on failure
116  *
117  *          Volume information returned in jcr
118  */
119 int dir_get_volume_info(JCR *jcr, enum get_vol_info_rw writing)
120 {
121     BSOCK *dir = jcr->dir_bsock;
122
123     bstrncpy(jcr->VolCatInfo.VolCatName, jcr->VolumeName, sizeof(jcr->VolCatInfo.VolCatName));
124     Dmsg1(200, "dir_get_volume_info=%s\n", jcr->VolCatInfo.VolCatName);
125     bash_spaces(jcr->VolCatInfo.VolCatName);
126     bnet_fsend(dir, Get_Vol_Info, jcr->Job, jcr->VolCatInfo.VolCatName, 
127        writing==GET_VOL_INFO_FOR_WRITE?1:0);
128     return do_get_volume_info(jcr);
129 }
130
131
132
133 /*
134  * Get info on the next appendable volume in the Director's database
135  * Returns: 1 on success
136  *          0 on failure
137  *
138  *          Volume information returned in jcr
139  *
140  */
141 int dir_find_next_appendable_volume(JCR *jcr)
142 {
143     BSOCK *dir = jcr->dir_bsock;
144
145     Dmsg0(200, "dir_find_next_appendable_volume\n");
146     bnet_fsend(dir, Find_media, jcr->Job, 1);
147     return do_get_volume_info(jcr);
148 }
149
150     
151 /*
152  * After writing a Volume, send the updated statistics
153  * back to the director.
154  */
155 int dir_update_volume_info(JCR *jcr, DEVICE *dev, int label)
156 {
157    BSOCK *dir = jcr->dir_bsock;
158    time_t EndTime = time(NULL);
159    char ed1[50], ed2[50];
160    VOLUME_CAT_INFO *vol = &dev->VolCatInfo;
161
162    if (vol->VolCatName[0] == 0) {
163       Jmsg0(jcr, M_ERROR, 0, _("NULL Volume name. This shouldn't happen!!!\n"));
164       return 0;
165    }
166    if (dev_state(dev, ST_READ)) {
167       Jmsg0(jcr, M_ERROR, 0, _("Attempt to update_volume_info in read mode!!!\n"));
168       return 0;
169    }
170    if (!dev_state(dev, ST_LABEL)) {
171       Jmsg0(jcr, M_ERROR, 0, _("Attempt to update_volume_info on non-labeled Volume!!!\n"));
172       return 0;
173    }
174
175    dev->VolCatInfo.VolCatFiles = dev->file;   /* set number of files */
176    Dmsg1(100, "Update cat VolFiles=%d\n", dev->file);
177    /* Just labeled or relabeled the tape */
178    if (label) {
179       bstrncpy(vol->VolCatStatus, "Append", sizeof(vol->VolCatStatus));
180       vol->VolCatBytes = 1;           /* indicates tape labeled */
181    }
182    bash_spaces(vol->VolCatName);
183    bnet_fsend(dir, Update_media, jcr->Job, 
184       vol->VolCatName, vol->VolCatJobs, vol->VolCatFiles,
185       vol->VolCatBlocks, edit_uint64(vol->VolCatBytes, ed1),
186       vol->VolCatMounts, vol->VolCatErrors,
187       vol->VolCatWrites, edit_uint64(vol->VolCatMaxBytes, ed2), 
188       EndTime, vol->VolCatStatus, vol->Slot, label, vol->Drive, 
189       vol->InChanger);
190    Dmsg1(120, "update_volume_info(): %s", dir->msg);
191    unbash_spaces(vol->VolCatName);
192
193    if (!do_get_volume_info(jcr)) {
194       Jmsg(jcr, M_ERROR, 0, "%s", jcr->errmsg);
195       return 0;
196    }
197    Dmsg1(120, "get_volume_info(): %s", dir->msg);
198    /* Update dev Volume info in case something changed (e.g. expired) */
199    memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(dev->VolCatInfo));
200    return 1;
201 }
202
203 /*
204  * After writing a Volume, create the JobMedia record.
205  */
206 int dir_create_jobmedia_record(JCR *jcr)
207 {
208    BSOCK *dir = jcr->dir_bsock;
209
210    if (!jcr->WroteVol) {
211       return 1;                       /* nothing written to tape */
212    }
213
214    jcr->WroteVol = false;
215    bnet_fsend(dir, Create_job_media, jcr->Job, 
216       jcr->VolFirstIndex, jcr->VolLastIndex,
217       jcr->StartFile, jcr->EndFile,
218       jcr->StartBlock, jcr->EndBlock);
219    Dmsg1(100, "create_jobmedia(): %s", dir->msg);
220    if (bnet_recv(dir) <= 0) {
221       Dmsg0(190, "create_jobmedia error bnet_recv\n");
222       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: ERR=%s\n"), 
223            bnet_strerror(dir));
224       return 0;
225    }
226    Dmsg1(120, "Create_jobmedia: %s", dir->msg);
227    if (strcmp(dir->msg, OK_create) != 0) {
228       Dmsg1(130, "Bad response from Dir: %s\n", dir->msg);
229       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: %s\n"), dir->msg);
230       return 0;
231    }
232    return 1;
233 }
234
235
236 /* 
237  * Update File Attribute data
238  */
239 int dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec)
240 {
241    BSOCK *dir = jcr->dir_bsock;
242    ser_declare;
243
244    dir->msglen = sprintf(dir->msg, FileAttributes, jcr->Job);
245    dir->msg = check_pool_memory_size(dir->msg, dir->msglen + 
246                 sizeof(DEV_RECORD) + rec->data_len);
247    ser_begin(dir->msg + dir->msglen, 0);
248    ser_uint32(rec->VolSessionId);
249    ser_uint32(rec->VolSessionTime);
250    ser_int32(rec->FileIndex);
251    ser_int32(rec->Stream);
252    ser_uint32(rec->data_len);
253    ser_bytes(rec->data, rec->data_len);
254    dir->msglen = ser_length(dir->msg);
255    return bnet_send(dir);
256 }
257
258
259 /*
260  *   Request to mount next Volume, which Volume not specified
261  *
262  *   Entered with device blocked.
263  *   Leaves with device blocked.
264  *
265  *   Returns: 1 on success (operator issues a mount command)
266  *            0 on failure
267  *              Note, must create dev->errmsg on error return.
268  *
269  *    On success, jcr->VolumeName and jcr->VolCatInfo contain
270  *      information on suggested volume, but this may not be the
271  *      same as what is actually mounted.
272  *
273  *    When we return with success, the correct tape may or may not
274  *      actually be mounted. The calling routine must read it and
275  *      verify the label.
276  */
277 int dir_ask_sysop_to_mount_next_volume(JCR *jcr, DEVICE *dev)
278 {
279    int stat = 0, jstat;
280    /* ******FIXME******* put these on config variable */
281    int min_wait = 60 * 60;
282    int max_wait = 24 * 60 * 60;
283    int max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
284
285    int wait_sec;
286    int num_wait = 0;
287
288    Dmsg0(130, "enter dir_ask_sysop_to_mount_next_volume\n");
289    ASSERT(dev->dev_blocked);
290    wait_sec = min_wait;
291    for ( ;; ) {
292       if (job_canceled(jcr)) {
293          Mmsg(&dev->errmsg, _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
294               jcr->Job, jcr->dev_name);
295          Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
296          return 0;
297       }
298       if (dir_find_next_appendable_volume(jcr)) {    /* get suggested volume */
299          jstat = JS_WaitMount;
300          /*
301           * If we have a valid volume name and we are not
302           *   removable media, return now, or if we have a
303           *   Slot for an autochanger, otherwise wait
304           *   for the operator to mount the media.
305           */
306          if ((jcr->VolumeName[0] && !dev_cap(dev, CAP_REM) && dev_cap(dev, CAP_LABEL)) ||
307              (jcr->VolumeName[0] && jcr->VolCatInfo.Slot)) {
308             Dmsg0(100, "Return 1 from mount without wait.\n");
309             return 1;
310          }
311          Jmsg(jcr, M_MOUNT, 0, _(
312 "Please mount Volume \"%s\" on Storage Device \"%s\" for Job %s\n"
313 "Use \"mount\" command to release Job.\n"),
314               jcr->VolumeName, jcr->dev_name, jcr->Job);
315          Dmsg3(190, "Mount %s on %s for Job %s\n",
316                 jcr->VolumeName, jcr->dev_name, jcr->Job);
317       } else {
318          jstat = JS_WaitMedia;
319          Jmsg(jcr, M_MOUNT, 0, _(
320 "Job %s waiting. Cannot find any appendable volumes.\n\
321 Please use the \"label\"  command to create a new Volume for:\n\
322     Storage:      %s\n\
323     Media type:   %s\n\
324     Pool:         %s\n"),
325               jcr->Job, 
326               jcr->dev_name, 
327               jcr->media_type,
328               jcr->pool_name);
329       }
330
331       jcr->JobStatus = jstat;
332       dir_send_job_status(jcr);
333
334       stat = wait_for_sysop(jcr, dev, wait_sec);
335
336       if (stat == ETIMEDOUT) {
337          wait_sec *= 2;               /* double wait time */
338          if (wait_sec > max_wait) {   /* but not longer than maxtime */
339             wait_sec = max_wait;
340          }
341          num_wait++;
342          if (num_wait >= max_num_wait) {
343             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
344                  jcr->dev_name, jcr->Job);
345             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
346             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
347             return 0;                 /* exceeded maximum waits */
348          }
349          continue;
350       }
351       if (stat == EINVAL) {
352          Mmsg2(&dev->errmsg, _("pthread error in mount_next_volume stat=%d ERR=%s\n"),
353                stat, strerror(stat));
354          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
355          return 0;
356       }
357       if (stat != 0) {
358          Jmsg(jcr, M_WARNING, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
359             strerror(stat));
360       }
361       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
362
363       /* Restart wait counters */
364       wait_sec = min_wait;
365       num_wait = 0;
366       /* If no VolumeName, and cannot get one, try again */
367       if (jcr->VolumeName[0] == 0 && !job_canceled(jcr) &&
368           !dir_find_next_appendable_volume(jcr)) {
369          Jmsg(jcr, M_MOUNT, 0, _(
370 "Someone woke me up, but I cannot find any appendable\n\
371 volumes for Job=%s.\n"), jcr->Job);
372          continue;
373       }       
374       break;
375    }
376    set_jcr_job_status(jcr, JS_Running);
377    dir_send_job_status(jcr);
378    Dmsg0(130, "leave dir_ask_sysop_to_mount_next_volume\n");
379    return 1;
380 }
381
382 /*
383  *   Request to mount specific Volume
384  *
385  *   Entered with device blocked and jcr->VolumeName is desired
386  *      volume.
387  *   Leaves with device blocked.
388  *
389  *   Returns: 1 on success (operator issues a mount command)
390  *            0 on failure
391  *              Note, must create dev->errmsg on error return.
392  *
393  */
394 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
395 {
396    int stat = 0;
397    /* ******FIXME******* put these on config variable */
398    int min_wait = 60 * 60;
399    int max_wait = 24 * 60 * 60;
400    int max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
401    int wait_sec;
402    int num_wait = 0;
403    char *msg;
404
405    Dmsg0(130, "enter dir_ask_sysop_to_mount_next_volume\n");
406    if (!jcr->VolumeName[0]) {
407       Mmsg0(&dev->errmsg, _("Cannot request another volume: no volume name given.\n"));
408       return 0;
409    }
410    ASSERT(dev->dev_blocked);
411    wait_sec = min_wait;
412    for ( ;; ) {
413       if (job_canceled(jcr)) {
414          Mmsg(&dev->errmsg, _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
415               jcr->Job, jcr->dev_name);
416          return 0;
417       }
418       msg = _("Please mount");
419       Jmsg(jcr, M_MOUNT, 0, _("%s Volume \"%s\" on Storage Device \"%s\" for Job %s\n"),
420            msg, jcr->VolumeName, jcr->dev_name, jcr->Job);
421       Dmsg3(190, "Mount %s on %s for Job %s\n",
422             jcr->VolumeName, jcr->dev_name, jcr->Job);
423
424       jcr->JobStatus = JS_WaitMount;
425       dir_send_job_status(jcr);
426
427       stat = wait_for_sysop(jcr, dev, wait_sec); /* wait on device */
428
429       if (stat == ETIMEDOUT) {
430          wait_sec *= 2;               /* double wait time */
431          if (wait_sec > max_wait) {   /* but not longer than maxtime */
432             wait_sec = max_wait;
433          }
434          num_wait++;
435          if (num_wait >= max_num_wait) {
436             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
437                  jcr->dev_name, jcr->Job);
438             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
439             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
440             return 0;                 /* exceeded maximum waits */
441          }
442          continue;
443       }
444       if (stat == EINVAL) {
445          Mmsg2(&dev->errmsg, _("pthread error in mount_volume stat=%d ERR=%s\n"),
446                stat, strerror(stat));
447          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
448          return 0;
449       }
450       if (stat != 0) {
451          Jmsg(jcr, M_ERROR, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
452             strerror(stat));
453       }
454       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
455
456       /* Restart wait counters */
457       wait_sec = min_wait;
458       num_wait = 0;
459       break;
460    }
461    set_jcr_job_status(jcr, JS_Running);
462    dir_send_job_status(jcr);
463    Dmsg0(130, "leave dir_ask_sysop_to_mount_next_volume\n");
464    return 1;
465 }
466
467 /*
468  * Wait for SysOp to mount a tape
469  */
470 static int wait_for_sysop(JCR *jcr, DEVICE *dev, int wait_sec)
471 {
472    struct timeval tv;
473    struct timezone tz;
474    struct timespec timeout;
475    int dev_blocked;
476    time_t start = time(NULL);
477    time_t last_heartbeat = 0;
478    int stat = 0;
479    int add_wait;
480    
481    /*
482     * Wait requested time (wait_sec).  However, we also wake up every
483     *    HB_TIME seconds and send a heartbeat to the FD and the Director
484     *    to keep stateful firewalls from closing them down while waiting
485     *    for the operator.
486     */
487    add_wait = wait_sec;
488    if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
489       add_wait = me->heartbeat_interval;
490    }
491    gettimeofday(&tv, &tz);
492    timeout.tv_nsec = tv.tv_usec * 1000;
493    timeout.tv_sec = tv.tv_sec + add_wait;
494
495    P(dev->mutex);
496    dev_blocked = dev->dev_blocked;
497    dev->dev_blocked = BST_WAITING_FOR_SYSOP; /* indicate waiting for mount */
498
499    for ( ; !job_canceled(jcr); ) {
500       time_t now;
501
502       Dmsg3(100, "I'm going to sleep on device %s. HB=%d wait=%d\n", dev_name(dev),
503          (int)me->heartbeat_interval, wait_sec);
504       stat = pthread_cond_timedwait(&dev->wait_next_vol, &dev->mutex, &timeout);
505       Dmsg1(100, "Wokeup from sleep on device stat=%d\n", stat);
506
507       now = time(NULL);
508
509       /* Note, this always triggers the first time. We want that. */
510       if (me->heartbeat_interval) {
511          if (now - last_heartbeat >= me->heartbeat_interval) {
512             /* send heartbeats */
513             if (jcr->file_bsock) {
514                bnet_sig(jcr->file_bsock, BNET_HEARTBEAT);
515                Dmsg0(100, "Send heartbeat to FD.\n");
516             }
517             if (jcr->dir_bsock) {
518                bnet_sig(jcr->dir_bsock, BNET_HEARTBEAT);
519             }
520             last_heartbeat = now;
521          }
522       }
523
524       if (dev->dev_blocked == BST_MOUNT) {   /* mount request ? */
525          stat = 0;
526          break;
527       }
528
529       if (stat != ETIMEDOUT) {     /* we blocked the device */
530          break;                    /* on error return */
531       }
532       if (now - start >= wait_sec) {  /* on exceeding wait time return */
533          Dmsg0(100, "Exceed wait time.\n");
534          break;
535       }
536       add_wait = wait_sec - (now - start);
537       if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
538          add_wait = me->heartbeat_interval;
539       }
540       gettimeofday(&tv, &tz);
541       timeout.tv_nsec = tv.tv_usec * 1000;
542       timeout.tv_sec = tv.tv_sec + add_wait; /* additional wait */
543       Dmsg1(100, "Additional wait %d sec.\n", add_wait);
544    }
545
546    dev->dev_blocked = dev_blocked;    /* restore entry state */
547    V(dev->mutex);
548    return stat;
549 }