]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/askdir.c
Phil's code + rework status command
[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-2004 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 InChanger=%d VolReadTime=%s VolWriteTime=%s\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 InChanger=%d"
51    " VolReadTime=%" lld " VolWriteTime=%" lld;
52
53
54 static char OK_create[] = "1000 OK CreateJobMedia\n";
55
56 /* Forward referenced functions */
57 static int wait_for_sysop(JCR *jcr, DEVICE *dev);
58
59 /*
60  * Send current JobStatus to Director
61  */
62 int dir_send_job_status(JCR *jcr)
63 {
64    return bnet_fsend(jcr->dir_bsock, Job_status, jcr->Job, jcr->JobStatus);
65 }
66
67 /*
68  * Common routine for:
69  *   dir_get_volume_info()
70  * and
71  *   dir_find_next_appendable_volume()
72  * 
73  *  Returns: 1 on success and vol info in jcr->VolCatInfo
74  *           0 on failure
75  */
76 static int do_get_volume_info(JCR *jcr)
77 {
78     BSOCK *dir = jcr->dir_bsock;
79     DCR *dcr = jcr->dcr;
80     VOLUME_CAT_INFO vol;
81     int n;
82
83     jcr->VolumeName[0] = 0;           /* No volume */
84     dcr->VolumeName[0] = 0;           /* No volume */
85     if (bnet_recv(dir) <= 0) {
86        Dmsg0(200, "getvolname error bnet_recv\n");
87        Mmsg(&jcr->errmsg, _("Network error on bnet_recv in req_vol_info.\n"));
88        return 0;
89     }
90     memset(&vol, 0, sizeof(vol));
91     Dmsg1(200, "Get vol info=%s\n", dir->msg);
92     n = sscanf(dir->msg, OK_media, vol.VolCatName, 
93                &vol.VolCatJobs, &vol.VolCatFiles,
94                &vol.VolCatBlocks, &vol.VolCatBytes,
95                &vol.VolCatMounts, &vol.VolCatErrors,
96                &vol.VolCatWrites, &vol.VolCatMaxBytes,
97                &vol.VolCatCapacityBytes, vol.VolCatStatus,
98                &vol.Slot, &vol.VolCatMaxJobs, &vol.VolCatMaxFiles,
99                &vol.InChanger, &vol.VolReadTime, &vol.VolWriteTime);
100     if (n != 17) {
101        Dmsg2(100, "Bad response from Dir fields=%d: %s\n", n, dir->msg);
102        Mmsg(&jcr->errmsg, _("Error getting Volume info: %s\n"), dir->msg);
103        return 0;
104     }
105     unbash_spaces(vol.VolCatName);
106     pm_strcpy(&jcr->VolumeName, vol.VolCatName); /* set desired VolumeName */
107     bstrncpy(dcr->VolumeName, vol.VolCatName, sizeof(dcr->VolumeName));
108     memcpy(&jcr->VolCatInfo, &vol, sizeof(jcr->VolCatInfo));
109     memcpy(&dcr->VolCatInfo, &vol, sizeof(dcr->VolCatInfo));
110     
111     Dmsg2(200, "do_reqest_vol_info got slot=%d Volume=%s\n", 
112           vol.Slot, vol.VolCatName);
113     return 1;
114 }
115
116
117 /*
118  * Get Volume info for a specific volume from the Director's Database
119  *
120  * Returns: 1 on success   (not Director guarantees that Pool and MediaType
121  *                          are correct and VolStatus==Append or
122  *                          VolStatus==Recycle)
123  *          0 on failure
124  *
125  *          Volume information returned in jcr
126  */
127 int dir_get_volume_info(JCR *jcr, enum get_vol_info_rw writing)
128 {
129     BSOCK *dir = jcr->dir_bsock;
130
131     bstrncpy(jcr->VolCatInfo.VolCatName, jcr->VolumeName, sizeof(jcr->VolCatInfo.VolCatName));
132     Dmsg1(200, "dir_get_volume_info=%s\n", jcr->VolCatInfo.VolCatName);
133     bash_spaces(jcr->VolCatInfo.VolCatName);
134     bnet_fsend(dir, Get_Vol_Info, jcr->Job, jcr->VolCatInfo.VolCatName, 
135        writing==GET_VOL_INFO_FOR_WRITE?1:0);
136     return do_get_volume_info(jcr);
137 }
138
139
140
141 /*
142  * Get info on the next appendable volume in the Director's database
143  * Returns: 1 on success
144  *          0 on failure
145  *
146  *          Volume information returned in jcr
147  *
148  */
149 int dir_find_next_appendable_volume(JCR *jcr)
150 {
151     BSOCK *dir = jcr->dir_bsock;
152     JCR *njcr;
153
154     Dmsg0(200, "dir_find_next_appendable_volume\n");
155     for (int vol_index=1;  vol_index < 3; vol_index++) {
156        bnet_fsend(dir, Find_media, jcr->Job, vol_index);
157        if (do_get_volume_info(jcr)) {
158           Dmsg2(200, "JobId=%d got possible Vol=%s\n", jcr->JobId, jcr->VolumeName);
159           bool found = false;
160           /* 
161            * Walk through all jobs and see if the volume is   
162            *  already mounted. If so, try a different one.
163            * This would be better done by walking through  
164            *  all the devices.
165            */
166           lock_jcr_chain();
167           foreach_jcr(njcr) {
168              if (jcr == njcr) {
169                 continue;             /* us */
170              }
171              Dmsg2(200, "Compare to JobId=%d using Vol=%s\n", njcr->JobId, njcr->VolumeName);
172              if (strcmp(jcr->VolumeName, njcr->VolumeName) == 0) {
173                 found = true;
174                 Dmsg1(200, "Vol in use by JobId=%u\n", njcr->JobId);
175                 free_locked_jcr(njcr);
176                 break;
177              }
178              free_locked_jcr(njcr);
179           }
180           unlock_jcr_chain();
181           if (!found) {
182              Dmsg0(200, "dir_find_next_appendable_volume return true\n");
183              return true;             /* Got good Volume */
184           }
185        } else {
186           Dmsg0(200, "No volume info, return false\n");
187           return false;
188        }
189     }
190     Dmsg0(200, "dir_find_next_appendable_volume return true\n");
191     return true; 
192 }
193
194     
195 /*
196  * After writing a Volume, send the updated statistics
197  * back to the director.
198  */
199 int dir_update_volume_info(JCR *jcr, DEVICE *dev, int label)
200 {
201    BSOCK *dir = jcr->dir_bsock;
202    time_t LastWritten = time(NULL);
203    char ed1[50], ed2[50], ed3[50], ed4[50];
204    VOLUME_CAT_INFO *vol = &dev->VolCatInfo;
205
206    if (vol->VolCatName[0] == 0) {
207       Jmsg0(jcr, M_ERROR, 0, _("NULL Volume name. This shouldn't happen!!!\n"));
208       return 0;
209    }
210    if (dev_state(dev, ST_READ)) {
211       Jmsg0(jcr, M_ERROR, 0, _("Attempt to update_volume_info in read mode!!!\n"));
212       return 0;
213    }
214    if (!dev_state(dev, ST_LABEL)) {
215       Jmsg0(jcr, M_ERROR, 0, _("Attempt to update_volume_info on non-labeled Volume!!!\n"));
216       return 0;
217    }
218
219    Dmsg1(100, "Update cat VolFiles=%d\n", dev->file);
220    /* Just labeled or relabeled the tape */
221    if (label) {
222       bstrncpy(vol->VolCatStatus, "Append", sizeof(vol->VolCatStatus));
223       vol->VolCatBytes = 1;           /* indicates tape labeled */
224    }
225    bash_spaces(vol->VolCatName);
226    bnet_fsend(dir, Update_media, jcr->Job, 
227       vol->VolCatName, vol->VolCatJobs, vol->VolCatFiles,
228       vol->VolCatBlocks, edit_uint64(vol->VolCatBytes, ed1),
229       vol->VolCatMounts, vol->VolCatErrors,
230       vol->VolCatWrites, edit_uint64(vol->VolCatMaxBytes, ed2), 
231       LastWritten, vol->VolCatStatus, vol->Slot, label,
232       vol->InChanger,
233       edit_uint64(vol->VolReadTime, ed3), 
234       edit_uint64(vol->VolWriteTime, ed4) );
235
236    Dmsg1(120, "update_volume_info(): %s", dir->msg);
237    unbash_spaces(vol->VolCatName);
238
239    if (!do_get_volume_info(jcr)) {
240       Jmsg(jcr, M_ERROR, 0, "%s", jcr->errmsg);
241       return 0;
242    }
243    Dmsg1(120, "get_volume_info(): %s", dir->msg);
244    /* Update dev Volume info in case something changed (e.g. expired) */
245    memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(dev->VolCatInfo));
246    return 1;
247 }
248
249 /*
250  * After writing a Volume, create the JobMedia record.
251  */
252 int dir_create_jobmedia_record(JCR *jcr)
253 {
254    BSOCK *dir = jcr->dir_bsock;
255    DCR *dcr = jcr->dcr;
256
257    if (!dcr->WroteVol) {
258       return 1;                       /* nothing written to tape */
259    }
260
261    dcr->WroteVol = false;
262    bnet_fsend(dir, Create_job_media, jcr->Job, 
263       dcr->VolFirstIndex, dcr->VolLastIndex,
264       dcr->StartFile, dcr->EndFile,
265       dcr->StartBlock, dcr->EndBlock);
266    Dmsg1(100, "create_jobmedia(): %s", dir->msg);
267    if (bnet_recv(dir) <= 0) {
268       Dmsg0(190, "create_jobmedia error bnet_recv\n");
269       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: ERR=%s\n"), 
270            bnet_strerror(dir));
271       return 0;
272    }
273    Dmsg1(120, "Create_jobmedia: %s", dir->msg);
274    if (strcmp(dir->msg, OK_create) != 0) {
275       Dmsg1(130, "Bad response from Dir: %s\n", dir->msg);
276       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: %s\n"), dir->msg);
277       return 0;
278    }
279    return 1;
280 }
281
282
283 /* 
284  * Update File Attribute data
285  */
286 int dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec)
287 {
288    BSOCK *dir = jcr->dir_bsock;
289    ser_declare;
290
291    dir->msglen = sprintf(dir->msg, FileAttributes, jcr->Job);
292    dir->msg = check_pool_memory_size(dir->msg, dir->msglen + 
293                 sizeof(DEV_RECORD) + rec->data_len);
294    ser_begin(dir->msg + dir->msglen, 0);
295    ser_uint32(rec->VolSessionId);
296    ser_uint32(rec->VolSessionTime);
297    ser_int32(rec->FileIndex);
298    ser_int32(rec->Stream);
299    ser_uint32(rec->data_len);
300    ser_bytes(rec->data, rec->data_len);
301    dir->msglen = ser_length(dir->msg);
302    return bnet_send(dir);
303 }
304
305
306 /*
307  *   Request the sysop to create an appendable volume
308  *
309  *   Entered with device blocked.
310  *   Leaves with device blocked.
311  *
312  *   Returns: 1 on success (operator issues a mount command)
313  *            0 on failure
314  *              Note, must create dev->errmsg on error return.
315  *
316  *    On success, jcr->VolumeName and jcr->VolCatInfo contain
317  *      information on suggested volume, but this may not be the
318  *      same as what is actually mounted.
319  *
320  *    When we return with success, the correct tape may or may not
321  *      actually be mounted. The calling routine must read it and
322  *      verify the label.
323  */
324 int dir_ask_sysop_to_create_appendable_volume(JCR *jcr, DEVICE *dev)
325 {
326    int stat = 0, jstat;
327    bool unmounted;
328    bool first = true;
329
330    Dmsg0(130, "enter dir_ask_sysop_to_create_appendable_volume\n");
331    ASSERT(dev->dev_blocked);
332    for ( ;; ) {
333       if (job_canceled(jcr)) {
334          Mmsg(&dev->errmsg,
335               _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
336               jcr->Job, jcr->dev_name);
337          Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
338          return 0;
339       }
340       /* First pass, we *know* there are no appendable volumes, so no need to call */
341       if (!first && dir_find_next_appendable_volume(jcr)) { /* get suggested volume */
342          jstat = JS_WaitMount;
343          unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
344                      (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
345          /*
346           * If we have a valid volume name and we are not
347           *   removable media, return now, or if we have a
348           *   Slot for an autochanger, otherwise wait
349           *   for the operator to mount the media.
350           */
351          if (!unmounted && ((jcr->VolumeName[0] && !dev_cap(dev, CAP_REM) && 
352                 dev_cap(dev, CAP_LABEL)) ||
353                  (jcr->VolumeName[0] && jcr->VolCatInfo.Slot))) {
354             Dmsg0(100, "Return 1 from mount without wait.\n");
355             return 1;
356          }
357          if (!dev->poll) {
358             Jmsg(jcr, M_MOUNT, 0, _(
359 "Please mount Volume \"%s\" on Storage Device \"%s\" for Job %s\n"
360 "Use \"mount\" command to release Job.\n"),
361               jcr->VolumeName, jcr->dev_name, jcr->Job);
362             Dmsg3(190, "Mount %s on %s for Job %s\n",
363                   jcr->VolumeName, jcr->dev_name, jcr->Job);
364          }
365       } else {
366          jstat = JS_WaitMedia;
367          if (!dev->poll) {
368             Jmsg(jcr, M_MOUNT, 0, _(
369 "Job %s waiting. Cannot find any appendable volumes.\n\
370 Please use the \"label\"  command to create a new Volume for:\n\
371     Storage:      %s\n\
372     Media type:   %s\n\
373     Pool:         %s\n"),
374                jcr->Job, 
375                jcr->dev_name, 
376                jcr->media_type,
377                jcr->pool_name);
378          }
379       }
380       first = false;
381
382       jcr->JobStatus = jstat;
383       dir_send_job_status(jcr);
384
385       stat = wait_for_sysop(jcr, dev);
386       if (dev->poll) {
387          Dmsg1(200, "Poll timeout in create append vol on device %s\n", dev_name(dev));
388          continue;
389       }
390
391       if (stat == ETIMEDOUT) {
392          if (!double_dev_wait_time(dev)) {
393             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
394                dev_name(dev), jcr->Job);
395             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
396             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
397             return 0;                 /* exceeded maximum waits */
398          }
399          continue;
400       }
401       if (stat == EINVAL) {
402          Mmsg2(&dev->errmsg, _("pthread error in mount_next_volume stat=%d ERR=%s\n"),
403                stat, strerror(stat));
404          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
405          return 0;
406       }
407       if (stat != 0) {
408          Jmsg(jcr, M_WARNING, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
409             strerror(stat));
410       }
411       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
412
413       /* If no VolumeName, and cannot get one, try again */
414       if (jcr->VolumeName[0] == 0 && !job_canceled(jcr) &&
415           !dir_find_next_appendable_volume(jcr)) {
416          Jmsg(jcr, M_MOUNT, 0, _(
417 "Someone woke me up, but I cannot find any appendable\n\
418 volumes for Job=%s.\n"), jcr->Job);
419          /* Restart wait counters after user interaction */
420          init_dev_wait_timers(dev);
421          continue;
422       }       
423       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
424                   (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
425       if (unmounted) {
426          continue;                    /* continue to wait */
427       }
428
429       /*
430        * Device mounted, we have a volume, break and return   
431        */
432       break;
433    }
434    set_jcr_job_status(jcr, JS_Running);
435    dir_send_job_status(jcr);
436    Dmsg0(130, "leave dir_ask_sysop_to_mount_create_appendable_volume\n");
437    return 1;
438 }
439
440 /*
441  *   Request to mount specific Volume
442  *
443  *   Entered with device blocked and jcr->VolumeName is desired
444  *      volume.
445  *   Leaves with device blocked.
446  *
447  *   Returns: 1 on success (operator issues a mount command)
448  *            0 on failure
449  *              Note, must create dev->errmsg on error return.
450  *
451  */
452 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
453 {
454    int stat = 0;
455    char *msg;
456
457    Dmsg0(130, "enter dir_ask_sysop_to_mount_volume\n");
458    if (!jcr->VolumeName[0]) {
459       Mmsg0(&dev->errmsg, _("Cannot request another volume: no volume name given.\n"));
460       return 0;
461    }
462    ASSERT(dev->dev_blocked);
463    for ( ;; ) {
464       if (job_canceled(jcr)) {
465          Mmsg(&dev->errmsg, _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
466               jcr->Job, jcr->dev_name);
467          return 0;
468       }
469
470       /*
471        * If we have a valid volume name and we are not
472        *   removable media, return now, or if we have a
473        *   Slot for an autochanger, otherwise wait
474        *   for the operator to mount the media.
475        */
476       if ((jcr->VolumeName[0] && !dev_cap(dev, CAP_REM) && dev_cap(dev, CAP_LABEL)) ||
477           (jcr->VolumeName[0] && jcr->VolCatInfo.Slot)) {
478          Dmsg0(100, "Return 1 from mount without wait.\n");
479          return 1;
480       }
481
482       if (!dev->poll) {
483          msg = _("Please mount");
484          Jmsg(jcr, M_MOUNT, 0, _("%s Volume \"%s\" on Storage Device \"%s\" for Job %s\n"),
485               msg, jcr->VolumeName, jcr->dev_name, jcr->Job);
486          Dmsg3(190, "Mount %s on %s for Job %s\n",
487                jcr->VolumeName, jcr->dev_name, jcr->Job);
488       }
489
490       jcr->JobStatus = JS_WaitMount;
491       dir_send_job_status(jcr);
492
493       stat = wait_for_sysop(jcr, dev);     /* wait on device */
494       if (dev->poll) {
495          Dmsg1(200, "Poll timeout in mount vol on device %s\n", dev_name(dev));
496          Dmsg1(200, "Blocked=%d\n", dev->dev_blocked);
497          return 1;
498       }
499
500       if (stat == ETIMEDOUT) {
501          if (!double_dev_wait_time(dev)) {
502             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
503                dev_name(dev), jcr->Job);
504             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
505             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
506             return 0;                 /* exceeded maximum waits */
507          }
508          continue;
509       }
510       if (stat == EINVAL) {
511          Mmsg2(&dev->errmsg, _("pthread error in mount_volume stat=%d ERR=%s\n"),
512                stat, strerror(stat));
513          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
514          return 0;
515       }
516       if (stat != 0) {
517          Jmsg(jcr, M_ERROR, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
518             strerror(stat));
519       }
520       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
521       break;
522    }
523    set_jcr_job_status(jcr, JS_Running);
524    dir_send_job_status(jcr);
525    Dmsg0(130, "leave dir_ask_sysop_to_mount_volume\n");
526    return 1;
527 }
528
529 /*
530  * Wait for SysOp to mount a tape
531  */
532 static int wait_for_sysop(JCR *jcr, DEVICE *dev)
533 {
534    struct timeval tv;
535    struct timezone tz;
536    struct timespec timeout;
537    time_t last_heartbeat = 0;
538    time_t first_start = time(NULL);
539    int stat = 0;
540    int add_wait;
541    bool unmounted;
542    
543    P(dev->mutex);
544    unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
545                 (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
546
547    dev->poll = false;
548    /*
549     * Wait requested time (dev->rem_wait_sec).  However, we also wake up every
550     *    HB_TIME seconds and send a heartbeat to the FD and the Director
551     *    to keep stateful firewalls from closing them down while waiting
552     *    for the operator.
553     */
554    add_wait = dev->rem_wait_sec;
555    if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
556       add_wait = me->heartbeat_interval;
557    }
558    if (!unmounted && dev->vol_poll_interval && add_wait > dev->vol_poll_interval) {
559       add_wait = dev->vol_poll_interval;
560    }
561    gettimeofday(&tv, &tz);
562    timeout.tv_nsec = tv.tv_usec * 1000;
563    timeout.tv_sec = tv.tv_sec + add_wait;
564
565    if (!unmounted) {
566       dev->dev_prev_blocked = dev->dev_blocked;
567       dev->dev_blocked = BST_WAITING_FOR_SYSOP; /* indicate waiting for mount */
568    }
569
570    for ( ; !job_canceled(jcr); ) {
571       time_t now, start;
572
573       Dmsg3(100, "I'm going to sleep on device %s. HB=%d wait=%d\n", dev_name(dev),
574          (int)me->heartbeat_interval, dev->wait_sec);
575       start = time(NULL);
576       stat = pthread_cond_timedwait(&dev->wait_next_vol, &dev->mutex, &timeout);
577       Dmsg1(100, "Wokeup from sleep on device stat=%d\n", stat);
578
579       now = time(NULL);
580       dev->rem_wait_sec -= (now - start);
581
582       /* Note, this always triggers the first time. We want that. */
583       if (me->heartbeat_interval) {
584          if (now - last_heartbeat >= me->heartbeat_interval) {
585             /* send heartbeats */
586             if (jcr->file_bsock) {
587                bnet_sig(jcr->file_bsock, BNET_HEARTBEAT);
588                Dmsg0(100, "Send heartbeat to FD.\n");
589             }
590             if (jcr->dir_bsock) {
591                bnet_sig(jcr->dir_bsock, BNET_HEARTBEAT);
592             }
593             last_heartbeat = now;
594          }
595       }
596
597       /*
598        * Check if user unmounted the device while we were waiting
599        */
600       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
601                    (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
602
603       if (stat != ETIMEDOUT) {     /* we blocked the device */
604          break;                    /* on error return */
605       }
606       if (dev->rem_wait_sec <= 0) {  /* on exceeding wait time return */
607          Dmsg0(100, "Exceed wait time.\n");
608          break;
609       }
610       
611       if (!unmounted && dev->vol_poll_interval &&       
612           (now - first_start >= dev->vol_poll_interval)) {
613          Dmsg1(200, "In wait blocked=%d\n", dev->dev_blocked);
614          dev->poll = true;
615          break;
616       }
617       /*
618        * Check if user mounted the device while we were waiting
619        */
620       if (dev->dev_blocked == BST_MOUNT) {   /* mount request ? */
621          stat = 0;
622          break;
623       }
624
625       add_wait = dev->wait_sec - (now - start);
626       if (add_wait < 0) {
627          add_wait = 0;
628       }
629       if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
630          add_wait = me->heartbeat_interval;
631       }
632       gettimeofday(&tv, &tz);
633       timeout.tv_nsec = tv.tv_usec * 1000;
634       timeout.tv_sec = tv.tv_sec + add_wait; /* additional wait */
635       Dmsg1(100, "Additional wait %d sec.\n", add_wait);
636    }
637
638    if (!unmounted) {
639       dev->dev_blocked = dev->dev_prev_blocked;    /* restore entry state */
640    }
641    V(dev->mutex);
642    return stat;
643 }