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