ceda6d77ba07ce2cbe3f294e399b60d03d32e410
[openafs.git] / src / butc / dump.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <roken.h>
14
15 #include <afs/opr.h>
16 #include <rx/xdr.h>
17 #include <rx/rx.h>
18 #include <lwp.h>
19 #include <lock.h>
20 #include <afs/tcdata.h>
21 #include <afs/bubasics.h>
22 #include <afs/budb_client.h>
23 #include <afs/butm_prototypes.h>
24 #include <afs/vldbint.h>
25 #include <afs/ktime.h>
26 #include <afs/vlserver.h>
27 #include <afs/afsint.h>
28 #include <afs/volser.h>
29 #include <afs/volser_prototypes.h>
30 #include <afs/volint.h>
31 #include <afs/cellconfig.h>
32 #include <afs/bucoord_prototypes.h>
33
34 #include "butc_internal.h"
35 #include "error_macros.h"
36 #include "butc_xbsa.h"
37 #include "afs/butx.h"
38
39 /* GLOBAL CONFIGURATION PARAMETERS */
40 extern int dump_namecheck;
41 extern int queryoperator;
42 extern int isafile;
43 extern int forcemultiple;
44
45 extern struct ubik_client *cstruct;
46 extern dlqlinkT savedEntries;
47
48 extern afs_int32 groupId;
49 extern afs_int32 BufferSize;
50 extern afs_int32 statusSize;
51 extern FILE *centralLogIO;
52 afs_int32 lastPass = 0;
53 #ifdef xbsa
54 extern afs_int32 xbsaType;
55 char *butcdumpIdStr = "/backup_afs_volume_dumps";
56 extern struct butx_transactionInfo butxInfo;
57 extern char *xbsaObjectOwner;
58 extern char *appObjectOwner;
59 extern char *xbsaSecToken;
60 extern char *xbsalGName;
61 extern char *globalButcLog;
62 #endif /*xbsa */
63
64 extern afs_int32 dataSize;              /* Size of data to read on each rx_Read() call */
65 extern afs_int32 tapeblocks;            /* Number of 16K tape datablocks in buffer (!CONF_XBSA) */
66
67 /* TBD
68  *
69  * Done 1) dump id generation
70  * Done xx) volume fragment number accounting !!  I think.
71  * 2) check abort - check after subroutine calls
72  * Done 3) trailer anomaly
73  * 4) trailer damage indicator after partial dumps ( affects scandump )
74  * Done 5) Ensure mount failure logged
75  * 6) Ensure bucoord status calls work
76  *
77  * notes
78  * pass 3:
79  *      keep token timeout. If no user reponse (idle time > some period)
80  *      and tokens about to time out, terminate dump. This provides at
81  *      least something usable.
82  */
83
84 struct dumpRock {
85     /* status only */
86     int tapeSeq;
87     int curVolume;              /* index in dumpNode of volume */
88     int curVolumeStatus;        /* more explicit dump state */
89     afs_uint32 curVolStartPos;  /* Starting position of the current volume */
90     afs_uint32 databaseDumpId;  /* real dump id, for db */
91     afs_uint32 initialDumpId;   /* the initial dump, for appended dumps */
92     afs_int32 volumesDumped;    /* # volumes successfully dumped */
93     afs_int32 volumesFailed;    /* # volumes that failed to dump */
94     afs_int32 volumesNotDumped; /* # volumes that were not dumped (didn't fail) */
95
96     /* tape management */
97     char tapeName[TC_MAXTAPENAMELEN];
98     struct butm_tapeInfo *tapeInfoPtr;
99     struct butm_tapeLabel tapeLabel;
100     int wroteLabel;             /* If the tape label is written */
101
102     /* database information */
103     struct budb_dumpEntry lastDump;     /* the last dump of this volset */
104     struct budb_dumpEntry dump; /* current dump */
105     struct budb_tapeEntry tape; /* current tape, not used -VA */
106
107     /* links to existing info */
108     struct dumpNode *node;
109 };
110
111 /* Forward declarations */
112
113 int makeVolumeHeader(struct volumeHeader *, struct dumpRock *, int);
114 int volumeHeader_hton(struct volumeHeader *, struct volumeHeader *);
115 char retryPrompt(char *, afs_int32, afs_uint32);
116 int getDumpTape(struct dumpRock *, int, afs_int32);
117 int getXBSATape(struct dumpRock *);
118 afs_int32 createDump(struct dumpRock *);
119
120 /* configuration variables */
121 #define HITEOT(code) ((code == BUTM_IO) || (code == BUTM_EOT) || (code == BUTM_IOCTL))
122 extern int autoQuery;
123 extern int maxpass;
124
125 afs_int32 tc_EndMargin;
126 afs_int32 tc_KEndMargin;
127 static char *bufferBlock;
128
129 /* compute the absolute expiration date */
130 afs_int32
131 calcExpirationDate(afs_int32 expType, afs_int32 expDate, afs_int32 createTime)
132 {
133     struct ktime_date kd;
134
135     switch (expType) {
136     case BC_REL_EXPDATE:
137         /* expiration date is relative to the creation time of the dump.
138          * This is the only case that requires any work
139          */
140         Int32To_ktimeRelDate(expDate, &kd);
141         return (Add_RelDate_to_Time(&kd, createTime));
142
143     case BC_ABS_EXPDATE:
144         return (expDate);
145
146     case BC_NO_EXPDATE:
147     default:
148         return (0);
149     }
150 }
151
152 afs_uint32 curr_bserver = 0;
153 struct rx_connection *curr_fromconn = (struct rx_connection *)0;
154
155 struct rx_connection *
156 Bind(afs_uint32 server)
157 {
158     if (curr_fromconn) {
159         if (curr_bserver == server)     /* Keep connection if have it */
160             return (curr_fromconn);
161
162         rx_DestroyConnection(curr_fromconn);    /* Otherwise get rid of it */
163         curr_fromconn = (struct rx_connection *)0;
164         curr_bserver = 0;
165     }
166
167     if (server) {
168         curr_fromconn = UV_Bind(server, AFSCONF_VOLUMEPORT);    /* Establish new connection */
169         if (curr_fromconn)
170             curr_bserver = server;
171     }
172
173     return (curr_fromconn);
174 }
175
176 /* notes
177  * 1) save the chunksize or otherwise ensure tape space remaining is
178  *      check frequently enough
179  * 2) This is called once. For partial dumps, need to
180  *      ensure that the tape device is left in the correct state for
181  *      further dumps.
182  *
183  */
184 #define BIGCHUNK 102400
185
186 afs_int32
187 dumpVolume(struct tc_dumpDesc * curDump, struct dumpRock * dparamsPtr)
188 {
189     struct butm_tapeInfo *tapeInfoPtr = dparamsPtr->tapeInfoPtr;
190     struct dumpNode *nodePtr = dparamsPtr->node;
191     afs_int32 taskId = nodePtr->taskID;
192     char *buffer;
193     int fragmentNumber;
194     afs_int32 volumeFlags;
195     afs_int32 kRemaining;
196     afs_int32 rc, code = 0;
197     afs_int32 toread;
198     afs_uint32 volBytesRead;
199     afs_uint32 chunkSize;
200     afs_int32 bytesread;        /* rx reads */
201     int endofvolume = 0;        /* Have we read all volume data */
202     int indump = 0;
203     int fragmentvolume;
204     struct volumeHeader hostVolumeHeader;
205
206     struct rx_call *fromcall = (struct rx_call *)0;
207     struct rx_connection *fromconn;
208     afs_int32 updatedate, fromtid = 0;
209     volEntries volumeInfo;
210     afs_int32 bytesWritten;
211     afs_uint32 statuscount = statusSize, tsize = 0;
212
213     dparamsPtr->curVolumeStatus = DUMP_NOTHING;
214
215     fromconn = Bind(htonl(curDump->hostAddr));  /* get connection to the server */
216
217     /* Determine when the volume was last cloned and updated */
218     volumeInfo.volEntries_val = (volintInfo *) 0;
219     volumeInfo.volEntries_len = 0;
220     rc = AFSVolListOneVolume(fromconn, curDump->partition, curDump->vid,
221                              &volumeInfo);
222     if (rc)
223         ERROR_EXIT(rc);
224     updatedate = volumeInfo.volEntries_val[0].updateDate;
225     curDump->cloneDate =
226         ((curDump->vtype ==
227           RWVOL) ? time(0) : volumeInfo.volEntries_val[0].creationDate);
228
229     if (curDump->date >= curDump->cloneDate)
230         ERROR_EXIT(0);          /* not recloned since last dump */
231     if (curDump->date > updatedate) {
232         dparamsPtr->curVolumeStatus = DUMP_NODUMP;      /* not modified since last dump */
233         ERROR_EXIT(0);
234     }
235
236     /* Start the volserver transaction and dump */
237     rc = AFSVolTransCreate(fromconn, curDump->vid, curDump->partition, ITBusy,
238                            &fromtid);
239     if (rc)
240         ERROR_EXIT(rc);
241     fromcall = rx_NewCall(fromconn);
242
243     rc = StartAFSVolDump(fromcall, fromtid, curDump->date);
244     if (rc)
245         ERROR_EXIT(rc);
246
247     dparamsPtr->curVolumeStatus = DUMP_PARTIAL;
248     dparamsPtr->curVolStartPos = tapeInfoPtr->position;
249
250     /* buffer is place in bufferBlock to write volume data.
251      * butm_writeFileData() assumes the previous BUTM_HDRSIZE bytes
252      * is available to write the tape block header.
253      */
254     buffer = bufferBlock + BUTM_HDRSIZE;
255
256     /* Dump one volume fragment at a time until we dump the full volume.
257      * A volume with more than 1 fragment means the volume will 'span'
258      * 2 or more tapes.
259      */
260     for (fragmentNumber = 1; !endofvolume; fragmentNumber++) {  /*frag */
261         rc = butm_WriteFileBegin(tapeInfoPtr);
262         if (rc) {
263             ErrorLog(1, taskId, rc, tapeInfoPtr->error,
264                      "Can't write FileBegin on tape\n");
265             ERROR_EXIT(rc);
266         }
267         indump = 1;             /* first write to tape */
268
269         /* Create and Write the volume header */
270         makeVolumeHeader(&hostVolumeHeader, dparamsPtr, fragmentNumber);
271         hostVolumeHeader.contd = ((fragmentNumber == 1) ? 0 : TC_VOLCONTD);
272         volumeHeader_hton(&hostVolumeHeader, (struct volumeHeader *)buffer);
273
274         rc = butm_WriteFileData(tapeInfoPtr, buffer, 1,
275                                 sizeof(hostVolumeHeader));
276         if (rc) {
277             ErrorLog(1, taskId, rc, tapeInfoPtr->error,
278                      "Can't write VolumeHeader on tape\n");
279             ERROR_EXIT(rc);
280         }
281
282         bytesWritten = BUTM_BLOCKSIZE;  /* Wrote one tapeblock */
283         tsize += bytesWritten;
284
285         /* Start reading volume data, rx_Read(), and dumping to the tape
286          * until we've dumped the entire volume (endofvolume == 1). We can
287          * exit this loop early if we find we are close to the end of the
288          * tape; in which case we dump the next fragment on the next tape.
289          */
290         volBytesRead = 0;
291         chunkSize = 0;
292         fragmentvolume = 0;
293         while (!endofvolume && !fragmentvolume) {       /*w */
294             /* Check for abort in the middle of writing data */
295             if (volBytesRead >= chunkSize) {
296                 chunkSize += BIGCHUNK;
297                 if (checkAbortByTaskId(taskId))
298                     ABORT_EXIT(TC_ABORTEDBYREQUEST);
299
300                 /* set bytes dumped for backup */
301                 lock_Status();
302                 nodePtr->statusNodePtr->nKBytes = tapeInfoPtr->kBytes;
303                 unlock_Status();
304             }
305
306             /* Determine how much data to read in upcoming RX_Read() call */
307             toread = dataSize;
308             /* Check if we are close to the EOT. There should at least be some
309              * data on the tape before it is switched. HACK: we have to split a
310              * volume across tapes because the volume trailer says the dump
311              * continues on the next tape (and not the filemark). This could
312              * result in a volume starting on one tape (no volume data dumped) and
313              * continued on the next tape. It'll work, just requires restore to
314              * switch tapes. This allows many small volumes (<16K) to be dumped.
315              */
316             kRemaining = butm_remainingKSpace(tapeInfoPtr);
317             if ((kRemaining < tc_KEndMargin)
318                 && (volBytesRead
319                     || (tapeInfoPtr->position > (isafile ? 3 : 2)))) {
320                 fragmentvolume = 1;
321             }
322
323
324             /* Guess at how much data to read. So we don't write off end of tape */
325             if (kRemaining < (tapeblocks * 16)) {
326                 if (kRemaining < 0) {
327                     toread = BUTM_BLKSIZE;
328                 } else {
329                     toread = ((kRemaining / 16) + 1) * BUTM_BLKSIZE;
330                     if (toread > dataSize)
331                         toread = dataSize;
332                 }
333             }
334
335 #ifdef xbsa
336             /* Set aside space for the trailing volume header when using large buffers. */
337             if (XBSAMAXBUFFER < toread + sizeof(hostVolumeHeader)) {
338                 toread = XBSAMAXBUFFER - sizeof(hostVolumeHeader);
339             }
340 #endif
341
342             /* Read some volume data. */
343             if (fragmentvolume) {
344                 bytesread = 0;
345             } else {
346                 bytesread = rx_Read(fromcall, buffer, toread);
347                 volBytesRead += bytesread;
348                 if (bytesread != toread) {
349                     /* Make sure were at end of volume and not a communication error */
350                     rc = rx_Error(fromcall);
351                     if (rc)
352                         ERROR_EXIT(rc);
353                     endofvolume = 1;
354                 }
355             }
356
357             if (fragmentvolume || endofvolume) {
358                 /* Create a volume trailer appending it to this data block */
359                 makeVolumeHeader(&hostVolumeHeader, dparamsPtr,
360                                  fragmentNumber);
361                 hostVolumeHeader.contd = (endofvolume ? 0 : TC_VOLCONTD);
362                 hostVolumeHeader.magic = TC_VOLENDMAGIC;
363                 hostVolumeHeader.endTime = (endofvolume ? time(0) : 0);
364                 volumeHeader_hton(&hostVolumeHeader, (struct volumeHeader *)&buffer[bytesread]);
365                 bytesread += sizeof(hostVolumeHeader);
366             }
367
368             /* Write the datablock out */
369             /* full data buffer - write it to tape */
370             rc = butm_WriteFileData(tapeInfoPtr, buffer, tapeblocks,
371                                     bytesread);
372             if (rc) {
373                 ErrorLog(1, taskId, rc, tapeInfoPtr->error,
374                          "Can't write VolumeData on tape\n");
375                 ERROR_EXIT(rc);
376             }
377             bytesWritten = tapeblocks * BUTM_BLOCKSIZE;
378             tsize += bytesWritten;
379
380             /* Display a status line every statusSize or at end of volume */
381             if (statusSize
382                 && ((tsize >= statuscount) || endofvolume
383                     || fragmentvolume)) {
384                 time_t t = time(0);
385                 struct tm tm;
386                 localtime_r(&t, &tm);
387                 printf("%02d:%02d:%02d: Task %u: %u KB: %s: %u B\n",
388                        tm.tm_hour, tm.tm_min, tm.tm_sec, taskId,
389                        tapeInfoPtr->kBytes, hostVolumeHeader.volumeName,
390                        tsize);
391                 statuscount = tsize + statusSize;
392             }
393         }                       /*w */
394
395         /* End the dump before recording it in BUDB as successfully dumped */
396         rc = butm_WriteFileEnd(tapeInfoPtr);
397         indump = 0;
398         if (rc) {
399             ErrorLog(1, taskId, rc, tapeInfoPtr->error,
400                      "Can't write FileEnd on tape\n");
401             ERROR_EXIT(rc);
402         }
403
404         /* Record in BUDB the volume fragment as succcessfully dumped */
405         volumeFlags = ((fragmentNumber == 1) ? BUDB_VOL_FIRSTFRAG : 0);
406         if (endofvolume)
407             volumeFlags |= BUDB_VOL_LASTFRAG;
408         rc = addVolume(0, dparamsPtr->databaseDumpId, dparamsPtr->tapeName,
409                        nodePtr->dumps[dparamsPtr->curVolume].name,
410                        nodePtr->dumps[dparamsPtr->curVolume].vid,
411                        nodePtr->dumps[dparamsPtr->curVolume].cloneDate,
412                        dparamsPtr->curVolStartPos, volBytesRead,
413                        (fragmentNumber - 1), volumeFlags);
414         if (rc)
415             ABORT_EXIT(rc);
416
417         /* If haven't finished dumping the volume, end this
418          * tape and get the next tape.
419          */
420         if (!endofvolume) {
421             /* Write an EOT marker.
422              * Log the error but ignore it since the dump is effectively done.
423              * Scantape will detect continued volume and not read the EOT.
424              */
425             rc = butm_WriteEOT(tapeInfoPtr);
426             if (rc)
427                 TapeLog(1, taskId, rc, tapeInfoPtr->error,
428                         "Warning: Can't write End-Of-Dump on tape\n");
429
430             /* Unmount the tape */
431             unmountTape(taskId, tapeInfoPtr);
432
433             /* Tell the database the tape is complete (and ok) */
434             rc = finishTape(&dparamsPtr->tape,
435                             dparamsPtr->tapeInfoPtr->kBytes +
436                             (dparamsPtr->tapeInfoPtr->nBytes ? 1 : 0));
437             if (rc)
438                 ABORT_EXIT(rc);
439
440             /* get the next tape. Prompt, mount, and add it into the database */
441             dparamsPtr->tapeSeq++;
442             rc = getDumpTape(dparamsPtr, 1, 0); /* interactive - no append */
443             if (rc)
444                 ABORT_EXIT(rc);
445
446             dparamsPtr->curVolStartPos = tapeInfoPtr->position;
447         }
448     }                           /*frag */
449
450     dparamsPtr->curVolumeStatus = DUMP_SUCCESS;
451
452   error_exit:
453     /*
454      * If we hit the end, see if this is the first volume on the tape or not.
455      * Also, mark the tape as finished if the tape contains other dumps.
456      */
457     if (!code)
458         code = rc;
459     if (HITEOT(code)) {
460         ErrorLog(2, taskId, code, tapeInfoPtr->error,
461                  "Warning: Dump (%s) hit end-of-tape inferred\n",
462                  nodePtr->dumpSetName);
463
464         if (tapeInfoPtr->position == 2) {
465             dparamsPtr->curVolumeStatus = DUMP_NORETRYEOT;
466         } else {
467             dparamsPtr->curVolumeStatus = DUMP_RETRY;
468             rc = finishTape(&dparamsPtr->tape,
469                             dparamsPtr->tapeInfoPtr->kBytes +
470                             (dparamsPtr->tapeInfoPtr->nBytes ? 1 : 0));
471             if (rc)
472                 ABORT_EXIT(rc);
473         }
474     }
475
476     /*
477      * This is used when an error occurs part way into a volume dump. Clean
478      * the tape state by writing an FileEnd mark. Forgo this action if we hit
479      * the end of tape.
480      */
481     else if (indump) {
482         rc = butm_WriteFileEnd(tapeInfoPtr);
483         indump = 0;
484         if (rc) {
485             ErrorLog(1, taskId, rc, tapeInfoPtr->error,
486                      "Can't write FileEnd on tape\n");
487         }
488     }
489
490     if (fromcall) {
491         rc = rx_EndCall(fromcall, 0);
492         if (!code)
493             code = rc;
494     }
495
496     if (fromtid) {
497         afs_int32 rcode;
498         rc = AFSVolEndTrans(fromconn, fromtid, &rcode);
499         if (!code)
500             code = (rc ? rc : rcode);
501     }
502
503     return (code);
504
505   abort_exit:
506     dparamsPtr->curVolumeStatus = DUMP_FAILED;
507     ERROR_EXIT(code);
508 }
509
510 afs_int32
511 xbsaDumpVolume(struct tc_dumpDesc * curDump, struct dumpRock * dparamsPtr)
512 {
513 #ifdef xbsa
514     struct butm_tapeInfo *tapeInfoPtr = dparamsPtr->tapeInfoPtr;
515     struct dumpNode *nodePtr = dparamsPtr->node;
516     char *buffer = bufferBlock;
517     afs_int32 taskId = nodePtr->taskID;
518     afs_int32 rc, code = 0;
519     afs_int32 toread;
520     afs_uint32 volBytesRead;
521     afs_uint32 chunkSize;
522     afs_int32 bytesread;        /* rx reads */
523     int endofvolume = 0;        /* Have we read all volume data */
524     int begindump = 0, indump = 0;      /* if dump transaction started; if dumping data */
525     struct volumeHeader hostVolumeHeader;
526
527     struct rx_call *fromcall = (struct rx_call *)0;
528     struct rx_connection *fromconn;
529     afs_int32 updatedate, fromtid = 0;
530     volEntries volumeInfo;
531     afs_int32 bytesWritten;
532     afs_uint32 statuscount = statusSize, tsize = 0, esize;
533     afs_hyper_t estSize;
534
535     char volumeNameStr[XBSA_MAX_PATHNAME];
536     static char *dumpDescription = "AFS volume dump";
537     static char *objectDescription = "XBSA - butc";
538
539     dparamsPtr->curVolumeStatus = DUMP_NOTHING;
540
541     fromconn = Bind(htonl(curDump->hostAddr));  /* get connection to the server */
542
543     /* Determine when the volume was last cloned and updated */
544     volumeInfo.volEntries_val = (volintInfo *) 0;
545     volumeInfo.volEntries_len = 0;
546     rc = AFSVolListOneVolume(fromconn, curDump->partition, curDump->vid,
547                              &volumeInfo);
548     if (rc)
549         ERROR_EXIT(rc);
550     updatedate = volumeInfo.volEntries_val[0].updateDate;
551     curDump->cloneDate =
552         ((curDump->vtype ==
553           RWVOL) ? time(0) : volumeInfo.volEntries_val[0].creationDate);
554
555     /* Get the volume size (in KB) and increase by 25%. Then set as a hyper */
556     esize = volumeInfo.volEntries_val[0].size;
557     esize += (esize / 4) + 1;
558
559     if (curDump->date >= curDump->cloneDate)
560         ERROR_EXIT(0);          /* not recloned since last dump */
561     if (curDump->date > updatedate) {
562         dparamsPtr->curVolumeStatus = DUMP_NODUMP;      /* not modified since last dump */
563         ERROR_EXIT(0);
564     }
565
566     /* Start a new XBSA Transaction */
567     rc = xbsa_BeginTrans(&butxInfo);
568     if (rc != XBSA_SUCCESS) {
569         ErrorLog(1, taskId, rc, 0, "Unable to create a new transaction\n");
570         ERROR_EXIT(rc);
571     }
572     begindump = 1;              /* Will need to do an xbsa_EndTrans */
573
574     /* Start the volserver transaction and dump. Once started, the
575      * volume status is "partial dump". Also, the transaction with
576      * the volserver is idle until the first read. An idle transaction
577      * will time out in 600 seconds. After the first rx_Read,
578      * the transaction is not idle. See GCTrans().
579      */
580     rc = AFSVolTransCreate(fromconn, curDump->vid, curDump->partition, ITBusy,
581                            &fromtid);
582     if (rc)
583         ERROR_EXIT(rc);
584     fromcall = rx_NewCall(fromconn);
585
586     rc = StartAFSVolDump(fromcall, fromtid, curDump->date);
587     if (rc)
588         ERROR_EXIT(rc);
589
590     dparamsPtr->curVolumeStatus = DUMP_PARTIAL;
591     dparamsPtr->curVolStartPos = tapeInfoPtr->position;
592
593     /* Tell XBSA what the name and size of volume to write */
594     snprintf(volumeNameStr, sizeof(volumeNameStr), "/%d/%s",
595              dparamsPtr->databaseDumpId, curDump->name);
596     hset32(estSize, esize);
597     hshlft(estSize, 10);        /* Multiply by 1024 so its in KB */
598
599     rc = xbsa_WriteObjectBegin(&butxInfo, butcdumpIdStr, volumeNameStr,
600                                xbsalGName, estSize, dumpDescription,
601                                objectDescription);
602     if (rc != XBSA_SUCCESS) {
603         ErrorLog(1, taskId, rc, 0,
604                  "Unable to begin writing of the fileset data to the server\n");
605         ERROR_EXIT(rc);
606     }
607     indump = 1;                 /* Will need to do an xbsa_WriteObjectEnd */
608
609     /* Create and Write the volume header */
610     makeVolumeHeader(&hostVolumeHeader, dparamsPtr, 1);
611     hostVolumeHeader.contd = 0;
612     volumeHeader_hton(&hostVolumeHeader, (struct volumeHeader *)buffer);
613
614     rc = xbsa_WriteObjectData(&butxInfo, buffer,
615                               sizeof(struct volumeHeader), &bytesWritten);
616     if (rc != XBSA_SUCCESS) {
617         ErrorLog(1, taskId, rc, 0,
618                  "Unable to write VolumeHeader data to the server\n");
619         ERROR_EXIT(rc);
620     }
621     /* There is a bug in the ADSM library where the bytesWritten is
622      * not filled in, so we set it as correct anyway.
623      */
624     bytesWritten = sizeof(struct volumeHeader);
625     if (bytesWritten != sizeof(struct volumeHeader)) {
626         ErrorLog(1, taskId, rc, 0,
627                  "The size of VolumeHeader written (%d) does not equal its actual size (%" AFS_SIZET_FMT ")\n",
628                  bytesWritten, sizeof(struct volumeHeader));
629         ERROR_EXIT(TC_INTERNALERROR);
630     }
631
632     incSize(tapeInfoPtr, sizeof(struct volumeHeader));  /* Increment amount we've written */
633     tsize += bytesWritten;
634
635     /* Start reading volume data, rx_Read(), and dumping to the tape
636      * until we've dumped the entire volume (endofvolume == 1).
637      */
638     volBytesRead = 0;
639     chunkSize = 0;
640     while (!endofvolume) {      /*w */
641         /* Check for abort in the middle of writing data */
642         if (volBytesRead >= chunkSize) {
643             chunkSize += BIGCHUNK;
644             if (checkAbortByTaskId(taskId))
645                 ABORT_EXIT(TC_ABORTEDBYREQUEST);
646
647             /* set bytes dumped for backup */
648             lock_Status();
649             nodePtr->statusNodePtr->nKBytes = tapeInfoPtr->kBytes;
650             unlock_Status();
651         }
652
653         /* Determine how much data to read in upcoming RX_Read() call */
654         toread = dataSize;
655
656         /* Read some volume data. */
657         bytesread = rx_Read(fromcall, buffer, toread);
658         volBytesRead += bytesread;
659         if (bytesread != toread) {
660             afs_int32 rcode;
661
662             /* Make sure were at end of volume and not a communication error */
663             rc = rx_Error(fromcall);
664             if (rc)
665                 ERROR_EXIT(rc);
666
667             endofvolume = 1;
668
669             /* Create a volume trailer appending it to this data block (if not XBSA) */
670             makeVolumeHeader(&hostVolumeHeader, dparamsPtr, 1);
671             hostVolumeHeader.contd = 0;
672             hostVolumeHeader.magic = TC_VOLENDMAGIC;
673             hostVolumeHeader.endTime = time(0);
674             volumeHeader_hton(&hostVolumeHeader, (struct volumeHeader *)&buffer[bytesread]);
675             bytesread += sizeof(hostVolumeHeader);
676
677             /* End the dump and transaction with the volserver. We end it now, before
678              * we make the XBSA call because if XBSA blocks, we could time out on the
679              * volserver (After last read, the transaction with the volserver is idle).
680              */
681             rc = rx_EndCall(fromcall, 0);
682             fromcall = 0;
683             if (rc)
684                 ERROR_EXIT(rc);
685
686             rc = AFSVolEndTrans(fromconn, fromtid, &rcode);
687             fromtid = 0;
688             if (rc)
689                 ERROR_EXIT(rc);
690         }
691
692         /* Write the datablock out */
693         rc = xbsa_WriteObjectData(&butxInfo, buffer, bytesread,
694                                   &bytesWritten);
695         if (rc != XBSA_SUCCESS) {
696             ErrorLog(1, taskId, rc, 0,
697                      "Unable to write data to the server\n");
698             ERROR_EXIT(rc);
699         }
700         /* There is a bug in the ADSM library where the bytesWritten is
701          * not filled in, so we set it as correct anyway.
702          */
703         bytesWritten = bytesread;
704         if (bytesWritten != bytesread) {
705             ErrorLog(1, taskId, rc, 0,
706                      "The size of data written (%d) does not equal size read (%d)\n",
707                      bytesWritten, bytesread);
708             ERROR_EXIT(TC_INTERNALERROR);
709         }
710
711         incSize(tapeInfoPtr, bytesread);        /* Increment amount we've written */
712         tsize += bytesWritten;
713
714         /* Display a status line every statusSize or at end of volume */
715         if (statusSize && ((tsize >= statuscount) || endofvolume)) {
716             time_t t = time(0);
717             struct tm tm;
718             localtime_r(&t, &tm);
719             printf("%02d:%02d:%02d: Task %u: %u KB: %s: %u B\n", tm.tm_hour,
720                    tm.tm_min, tm.tm_sec, taskId, tapeInfoPtr->kBytes,
721                    hostVolumeHeader.volumeName, tsize);
722             statuscount = tsize + statusSize;
723         }
724     }                           /*w */
725
726     /* End the XBSA transaction before recording it in BUDB as successfully dumped */
727     rc = xbsa_WriteObjectEnd(&butxInfo);
728     indump = 0;
729     if (rc != XBSA_SUCCESS) {
730         ErrorLog(1, taskId, rc, 0,
731                  "Unable to terminate writing of the volume data to the server");
732         ERROR_EXIT(rc);
733     }
734     rc = xbsa_EndTrans(&butxInfo);
735     begindump = 0;
736     tapeInfoPtr->position++;
737     if (rc != XBSA_SUCCESS) {
738         ErrorLog(1, taskId, rc, 0,
739                  "Unable to terminate the current transaction");
740         ERROR_EXIT(rc);
741     }
742
743     /* Record in BUDB the volume fragment as succcessfully dumped */
744     rc = addVolume(0, dparamsPtr->databaseDumpId, dparamsPtr->tapeName,
745                    nodePtr->dumps[dparamsPtr->curVolume].name,
746                    nodePtr->dumps[dparamsPtr->curVolume].vid,
747                    nodePtr->dumps[dparamsPtr->curVolume].cloneDate,
748                    dparamsPtr->curVolStartPos, volBytesRead, 0 /*frag0 */ ,
749                    (BUDB_VOL_FIRSTFRAG | BUDB_VOL_LASTFRAG));
750     if (rc)
751         ABORT_EXIT(rc);
752
753     dparamsPtr->curVolumeStatus = DUMP_SUCCESS;
754
755   error_exit:
756     /* Cleanup after an error occurs part way into a volume dump */
757     if (fromcall) {
758         rc = rx_EndCall(fromcall, 0);
759         if (!code)
760             code = rc;
761     }
762
763     if (fromtid) {
764         afs_int32 rcode;
765         rc = AFSVolEndTrans(fromconn, fromtid, &rcode);
766         if (!code)
767             code = (rc ? rc : rcode);
768     }
769
770     /* If this dump failed, what happens to successive retries
771      * of the volume? How do they get recorded in the XBSA database
772      * (overwritten)? If not, we don't record this in the BUDB database
773      * so it will not be removed when we delete the dump. What to do?
774      * Also if the volume was never recorded in the DB (partial dump).
775      */
776     if (indump) {
777         /* End the Write */
778         rc = xbsa_WriteObjectEnd(&butxInfo);
779         indump = 0;
780         if (rc != XBSA_SUCCESS) {
781             ErrorLog(1, taskId, rc, 0,
782                      "Unable to terminate writing of the volume data to the server");
783         }
784         tapeInfoPtr->position++;
785     }
786
787     if (begindump) {
788         /* End the XBSA Transaction */
789         rc = xbsa_EndTrans(&butxInfo);
790         begindump = 0;
791         if (rc != XBSA_SUCCESS) {
792             ErrorLog(1, taskId, rc, 0,
793                      "Unable to terminate the current transaction");
794         }
795     }
796
797     return (code);
798
799   abort_exit:
800     dparamsPtr->curVolumeStatus = DUMP_FAILED;
801     ERROR_EXIT(code);
802 #else
803     return 0;
804 #endif
805 }
806
807 #define HOSTADDR(sockaddr) (sockaddr)->sin_addr.s_addr
808
809 /* dumpPass
810  *      Go through the list of volumes to dump, dumping each one. The action
811  *      taken when a volume dump fails, depends on the passNumber. At minimum,
812  *      the failed volume is remembered.
813  * notes:
814  *      flushSavedEntries - inconsistent treatment for errors. What should
815  *              be done for user aborts?
816  */
817
818 afs_int32
819 dumpPass(struct dumpRock * dparamsPtr, int passNumber)
820 {
821     struct dumpNode *nodePtr = dparamsPtr->node;
822     struct butm_tapeInfo *tapeInfoPtr = dparamsPtr->tapeInfoPtr;
823     afs_int32 taskId = nodePtr->taskID;
824     struct tc_dumpDesc *curDump;
825     int action, e;
826     afs_int32 code = 0, tcode, dvcode;
827     char ch;
828     struct vldbentry vldbEntry;
829     struct sockaddr_in server;
830     afs_int32 tapepos;
831
832     TapeLog(2, taskId, 0, 0, "Starting pass %d\n", passNumber);
833
834     /* while there are more volumes to dump */
835     for (dparamsPtr->curVolume = 0; dparamsPtr->curVolume < nodePtr->arraySize; dparamsPtr->curVolume++) {      /*w */
836         curDump = &nodePtr->dumps[dparamsPtr->curVolume];
837         if (curDump->hostAddr == 0)
838             continue;
839
840         /* set name of current volume being dumped */
841         lock_Status();
842         strcpy(nodePtr->statusNodePtr->volumeName, curDump->name);
843         unlock_Status();
844
845         /* Determine location of the volume.
846          * In case the volume moved has moved.
847          */
848         if (passNumber > 1) {   /*pass */
849             tcode =
850                 bc_GetEntryByID(cstruct, curDump->vid, curDump->vtype,
851                                 &vldbEntry);
852             if (tcode) {
853                 ErrorLog(0, taskId, tcode, 0,
854                          "Volume %s (%u) failed - Can't find volume in VLDB\n",
855                          curDump->name, curDump->vid);
856                 curDump->hostAddr = 0;
857                 dparamsPtr->volumesFailed++;
858                 continue;
859             }
860
861             switch (curDump->vtype) {
862             case BACKVOL:
863                 if (!(vldbEntry.flags & VLF_BACKEXISTS)) {
864                     ErrorLog(0, taskId, 0, 0,
865                              "Volume %s (%u) failed - Backup volume no longer exists\n",
866                              curDump->name, curDump->vid);
867                     curDump->hostAddr = 0;
868                     dparamsPtr->volumesFailed++;
869                     continue;
870                 }
871                 /* fall through */
872             case RWVOL:
873                 for (e = 0; e < vldbEntry.nServers; e++) {      /* Find the RW volume */
874                     if (vldbEntry.serverFlags[e] & VLSF_RWVOL)
875                         break;
876                 }
877                 break;
878
879             case ROVOL:
880                 /* Try to use the server and partition we found the volume on
881                  * Otherwise, use the first RO volume.
882                  */
883                 for (e = 0; e < vldbEntry.nServers; e++) {      /* Find the RO volume */
884                     if ((curDump->hostAddr == vldbEntry.serverNumber[e])
885                         && (curDump->partition ==
886                             vldbEntry.serverPartition[e]))
887                         break;
888                 }
889
890                 if (e >= vldbEntry.nServers) {  /* Didn't find RO volume */
891                     for (e = 0; e < vldbEntry.nServers; e++) {  /* Find the first RO volume */
892                         if (vldbEntry.serverFlags[e] & VLSF_ROVOL)
893                             break;
894                     }
895                 }
896                 break;
897
898             default:
899                 ErrorLog(0, taskId, 0, 0,
900                          "Volume %s (%u) failed - Unknown volume type\n",
901                          curDump->name, curDump->vid);
902                 curDump->hostAddr = 0;
903                 continue;
904             }
905
906             if (e >= vldbEntry.nServers) {
907                 ErrorLog(0, taskId, 0, 0,
908                          "Volume %s (%u) failed - Can't find volume entry in VLDB\n",
909                          curDump->name, curDump->vid);
910                 curDump->hostAddr = 0;
911                 dparamsPtr->volumesFailed++;
912                 continue;
913             }
914
915             /* Remember the server and partition the volume exists on */
916             memset(&server, 0, sizeof(server));
917             server.sin_addr.s_addr = vldbEntry.serverNumber[e];
918             server.sin_port = 0;
919             server.sin_family = AF_INET;
920 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
921             server.sin_len = sizeof(struct sockaddr_in);
922 #endif
923             curDump->hostAddr = HOSTADDR(&server);
924             curDump->partition = vldbEntry.serverPartition[e];
925
926             /* Determine date from which to do an incremental dump
927              */
928             if (nodePtr->parent) {
929                 tcode =
930                     bcdb_FindClone(nodePtr->parent, curDump->name,
931                                    &curDump->date);
932                 if (tcode)
933                     curDump->date = 0;
934             } else {
935                 curDump->date = 0;      /* do a full dump */
936             }
937         }
938         /*pass */
939         if (checkAbortByTaskId(taskId))
940             ERROR_EXIT(TC_ABORTEDBYREQUEST);
941
942         /* Establish connection to volume - UV_ routine expects
943          * host address in network order
944          */
945         if (CONF_XBSA) {
946             dvcode = xbsaDumpVolume(curDump, dparamsPtr);
947         } else {
948             dvcode = dumpVolume(curDump, dparamsPtr);
949         }
950         action = dparamsPtr->curVolumeStatus;
951
952         /* Flush volume and tape entries to the database */
953         tcode = flushSavedEntries(action);
954         if (tcode)
955             ERROR_EXIT(tcode);
956
957         switch (action) {
958         case DUMP_SUCCESS:
959             TapeLog(1, taskId, 0, 0, "Volume %s (%u) successfully dumped\n",
960                     curDump->name, curDump->vid);
961             if (dvcode)
962                 ErrorLog(1, taskId, dvcode, 0,
963                          "Warning: Termination processing error on volume %s (%u)\n",
964                          curDump->name, curDump->vid);
965
966             curDump->hostAddr = 0;
967             dparamsPtr->volumesDumped++;
968             break;
969
970         case DUMP_PARTIAL:
971         case DUMP_NOTHING:
972             if (action == DUMP_PARTIAL) {
973                 ErrorLog(1, taskId, dvcode, 0,
974                          "Volume %s (%u) failed - partially dumped\n",
975                          curDump->name, curDump->vid);
976             } else if (dvcode) {
977                 ErrorLog(0, taskId, dvcode, 0, "Volume %s (%u) failed\n",
978                          curDump->name, curDump->vid);
979             } else {
980                 ErrorLog(0, taskId, dvcode, 0,
981                          "Volume %s (%u) not dumped - has not been re-cloned since last dump\n",
982                          curDump->name, curDump->vid);
983             }
984
985             if (passNumber == maxpass) {
986                 if (!queryoperator)
987                     ch = 'o';
988                 else
989                     ch = retryPrompt(curDump->name, curDump->vid, taskId);
990
991                 switch (ch) {
992                 case 'r':       /* retry */
993                     dparamsPtr->curVolume--;    /* redump this volume */
994                     continue;
995                 case 'o':       /* omit */
996                     ErrorLog(1, taskId, 0, 0, "Volume %s (%u) omitted\n",
997                              curDump->name, curDump->vid);
998                     dparamsPtr->volumesFailed++;
999                     break;
1000                 case 'a':       /* abort */
1001                     TapeLog(1, taskId, 0, 0, "Dump aborted\n");
1002                     ERROR_EXIT(TC_ABORTEDBYREQUEST);
1003                     break;
1004                 default:
1005                     ERROR_EXIT(TC_INTERNALERROR);
1006                     break;
1007                 }
1008             }
1009             break;
1010
1011         case DUMP_RETRY:
1012             TapeLog(1, taskId, dvcode, 0,
1013                     "Volume %s (%u) hit end-of-tape inferred - will retry on next tape\n",
1014                     curDump->name, curDump->vid);
1015
1016             /* Get the next tape */
1017             unmountTape(taskId, tapeInfoPtr);
1018
1019             dparamsPtr->tapeSeq++;
1020             tcode = getDumpTape(dparamsPtr, 1, 0);      /* interactive - no appends */
1021             if (tcode)
1022                 ERROR_EXIT(tcode);
1023
1024             dparamsPtr->curVolume--;    /* redump this volume */
1025             continue;
1026
1027         case DUMP_NORETRYEOT:
1028             ErrorLog(1, taskId, 0, 0,
1029                      "Volume %s (%u) failed - volume larger than tape\n",
1030                      curDump->name, curDump->vid);
1031
1032             /* rewrite the label on the tape - rewind - no need to switch tapes */
1033             tcode = butm_Create(tapeInfoPtr, &dparamsPtr->tapeLabel, 1);
1034             if (tcode) {
1035                 ErrorLog(0, taskId, tcode, tapeInfoPtr->error,
1036                          "Can't relabel tape\n");
1037
1038                 unmountTape(taskId, tapeInfoPtr);
1039                 tcode = getDumpTape(dparamsPtr, 1, 0);  /* interactive - no appends */
1040                 if (tcode)
1041                     ERROR_EXIT(tcode);
1042             } else {            /* Record the tape in database */
1043                 tapepos = tapeInfoPtr->position;
1044                 tcode =
1045                     useTape(&dparamsPtr->tape, dparamsPtr->databaseDumpId,
1046                             dparamsPtr->tapeName,
1047                             (dparamsPtr->tapeSeq + dparamsPtr->dump.tapes.b),
1048                             dparamsPtr->tapeLabel.useCount,
1049                             dparamsPtr->tapeLabel.creationTime,
1050                             dparamsPtr->tapeLabel.expirationDate, tapepos);
1051             }
1052
1053             curDump->hostAddr = 0;
1054             dparamsPtr->volumesFailed++;
1055             break;
1056
1057         case DUMP_NODUMP:
1058             TapeLog(1, taskId, dvcode, 0,
1059                     "Volume %s (%u) not dumped - has not been modified since last dump\n",
1060                     curDump->name, curDump->vid);
1061
1062             curDump->hostAddr = 0;
1063             dparamsPtr->volumesNotDumped++;
1064             break;
1065
1066         default:
1067             ErrorLog(1, taskId, dvcode, 0, "Volume %s (%u) failed\n",
1068                      curDump->name, curDump->vid);
1069             ERROR_EXIT(dvcode);
1070             break;
1071         }
1072     }                           /*w */
1073
1074   error_exit:
1075     /* check if we terminated while processing a volume */
1076     if (dparamsPtr->curVolume < nodePtr->arraySize) {
1077         TapeLog(2, taskId, 0, 0,
1078                 "Terminated while processing Volume %s (%u)\n", curDump->name,
1079                 curDump->vid);
1080     }
1081
1082     /* print a summary of this pass */
1083     TapeLog(2, taskId, 0, 0, "End of pass %d: Volumes remaining = %d\n",
1084             passNumber,
1085             nodePtr->arraySize - (dparamsPtr->volumesDumped +
1086                                   dparamsPtr->volumesFailed +
1087                                   dparamsPtr->volumesNotDumped));
1088     return (code);
1089 }
1090
1091 void *
1092 Dumper(void *param)
1093 {
1094     struct dumpNode *nodePtr = (struct dumpNode *)param;
1095     struct dumpRock dparams;
1096     struct butm_tapeInfo tapeInfo;
1097     int pass;
1098     int action;
1099     afs_int32 taskId;
1100     afs_int32 code = 0;
1101
1102     /* for volume setup */
1103     int i;
1104     int failedvolumes = 0;
1105     int dumpedvolumes = 0;
1106     int nodumpvolumes = 0;
1107     char strlevel[5];
1108     char msg[128];
1109     char finishedMsg1[128];
1110     char finishedMsg2[128];
1111     time_t startTime = 0;
1112     time_t endTime = 0;
1113     afs_int32 allocbufferSize;
1114
1115     extern struct deviceSyncNode *deviceLatch;
1116     extern struct tapeConfig globalTapeConfig;
1117
1118     opr_threadname_set("dumper");
1119     taskId = nodePtr->taskID;   /* Get task Id */
1120     setStatus(taskId, DRIVE_WAIT);
1121     EnterDeviceQueue(deviceLatch);
1122     clearStatus(taskId, DRIVE_WAIT);
1123
1124     printf("\n\n");
1125     TapeLog(2, taskId, 0, 0, "Dump %s\n", nodePtr->dumpSetName);
1126
1127     /* setup the dump parameters */
1128     memset(&dparams, 0, sizeof(dparams));
1129     dparams.node = nodePtr;
1130     dparams.tapeInfoPtr = &tapeInfo;
1131     dlqInit(&savedEntries);
1132
1133     if (!CONF_XBSA) {
1134         /* Instantiate the tape module */
1135         tapeInfo.structVersion = BUTM_MAJORVERSION;
1136         code = butm_file_Instantiate(&tapeInfo, &globalTapeConfig);
1137         if (code) {
1138             ErrorLog(0, taskId, code, tapeInfo.error,
1139                      "Can't initialize the tape module\n");
1140             ERROR_EXIT(code);
1141         }
1142     }
1143
1144     /* check if abort requested while waiting on device latch */
1145     if (checkAbortByTaskId(taskId))
1146         ERROR_EXIT(TC_ABORTEDBYREQUEST);
1147
1148     /* Are there volumes to dump */
1149     if (nodePtr->arraySize == 0) {
1150         TLog(taskId, "Dump (%s), no volumes to dump\n", nodePtr->dumpSetName);
1151         ERROR_EXIT(0);
1152     }
1153
1154     /* Allocate a buffer for the dumps. Leave room for header and vol-trailer.
1155      * dataSize is amount of data to read in each rx_Read() call.
1156      */
1157     if (CONF_XBSA) {
1158         /* XBSA dumps have not header */
1159         dataSize = BufferSize;
1160         allocbufferSize = dataSize + sizeof(struct volumeHeader);
1161     } else {
1162         tapeblocks = BufferSize / BUTM_BLOCKSIZE;       /* # of 16K tapeblocks */
1163         dataSize = (tapeblocks * BUTM_BLKSIZE);
1164         allocbufferSize =
1165             BUTM_HDRSIZE + dataSize + sizeof(struct volumeHeader);
1166     }
1167     bufferBlock = NULL;
1168     bufferBlock = malloc(allocbufferSize);
1169     if (!bufferBlock) {
1170         ErrorLog(0, taskId, TC_NOMEMORY, 0,
1171                  "Can't allocate BUFFERSIZE for dumps\n");
1172         ERROR_EXIT(TC_NOMEMORY);
1173     }
1174
1175     /* Determine the dumpid of the most recent dump of this volumeset and dumplevel
1176      * Used when requesting a tape. Done now because once we create the dump, the
1177      * routine will then find the newly created dump.
1178      */
1179     snprintf(strlevel, sizeof(strlevel), "%d", nodePtr->level);
1180     code =
1181         bcdb_FindLatestDump(nodePtr->volumeSetName, strlevel,
1182                             &dparams.lastDump);
1183     if (code) {
1184         if (code != BUDB_NODUMPNAME) {
1185             ErrorLog(0, taskId, code, 0, "Can't read backup database\n");
1186             ERROR_EXIT(code);
1187         }
1188         memset(&dparams.lastDump, 0, sizeof(dparams.lastDump));
1189     }
1190
1191     code = createDump(&dparams);        /* enter dump into database */
1192     if (code) {
1193         ErrorLog(0, taskId, code, 0, "Can't create dump in database\n");
1194         ERROR_EXIT(code);
1195     }
1196
1197     TLog(taskId, "Dump %s (DumpID %u)\n", nodePtr->dumpSetName,
1198          dparams.databaseDumpId);
1199
1200     if (!CONF_XBSA) {
1201         /* mount the tape and write its label */
1202         code = getDumpTape(&dparams, autoQuery, nodePtr->doAppend);
1203     } else {
1204         /* Create a dummy tape to satisfy backup databae */
1205         code = getXBSATape(&dparams);
1206         tapeInfo.position = 1;
1207     }
1208     if (code) {
1209         /* If didn't write the label, remove dump from the database */
1210         if (!dparams.wroteLabel) {
1211             i = bcdb_deleteDump(dparams.databaseDumpId, 0, 0, 0);
1212             if (i && (i != BUDB_NOENT))
1213                 ErrorLog(1, taskId, i, 0,
1214                          "Warning: Can't delete dump %u from database\n",
1215                          dparams.databaseDumpId);
1216             else
1217                 dparams.databaseDumpId = 0;
1218         }
1219         ERROR_EXIT(code);       /* exit with code from getTape */
1220     }
1221
1222     startTime = time(0);
1223     for (pass = 1; pass <= maxpass; pass++) {
1224         lastPass = (pass == maxpass);
1225         code = dumpPass(&dparams, pass);
1226         if (code)
1227             ERROR_EXIT(code);
1228
1229         /* if no failed volumes, we're done */
1230         if ((dparams.volumesDumped + dparams.volumesFailed +
1231              dparams.volumesNotDumped) == nodePtr->arraySize)
1232             break;
1233     }
1234
1235     /*
1236      * Log the error but ignore it since the dump is effectively done.
1237      * Scantape may assume another volume and ask for next tape.
1238      */
1239     if (!CONF_XBSA) {
1240         code = butm_WriteEOT(&tapeInfo);
1241         if (code)
1242             TapeLog(0, taskId, code, tapeInfo.error,
1243                     "Warning: Can't write end-of-dump on tape\n");
1244     }
1245
1246     code =
1247         finishTape(&dparams.tape,
1248                    dparams.tapeInfoPtr->kBytes +
1249                    (dparams.tapeInfoPtr->nBytes ? 1 : 0));
1250     if (code)
1251         ERROR_EXIT(code);
1252
1253     code = finishDump(&dparams.dump);
1254     if (code)
1255         ERROR_EXIT(code);
1256
1257     action = dparams.curVolumeStatus;
1258     code = flushSavedEntries(action);
1259     if (code)
1260         ERROR_EXIT(code);
1261
1262   error_exit:
1263     endTime = time(0);
1264     Bind(0);
1265     if (bufferBlock)
1266         free(bufferBlock);
1267
1268     if (!CONF_XBSA) {
1269         unmountTape(taskId, &tapeInfo);
1270     }
1271     waitDbWatcher();
1272
1273     dumpedvolumes = dparams.volumesDumped;
1274     nodumpvolumes = dparams.volumesNotDumped;
1275     failedvolumes = nodePtr->arraySize - (dumpedvolumes + nodumpvolumes);
1276
1277     /* pass back the number of volumes we failed to dump */
1278     lock_Status();
1279     nodePtr->statusNodePtr->volsFailed = failedvolumes;
1280     unlock_Status();
1281
1282     lastPass = 1;               /* In case we aborted */
1283
1284     /* Format and log finished message. */
1285     snprintf(finishedMsg1, sizeof(finishedMsg1), "%s", nodePtr->dumpSetName);
1286     if (dparams.databaseDumpId != 0) {
1287         snprintf(msg, sizeof(msg), " (DumpId %u)", dparams.databaseDumpId);
1288         strlcat(finishedMsg1, msg, sizeof(finishedMsg1));
1289     }
1290     snprintf(finishedMsg2, sizeof(finishedMsg2),
1291              "%d volumes dumped", dumpedvolumes);
1292     if (failedvolumes) {
1293         snprintf(msg, sizeof(msg), ", %d failed", failedvolumes);
1294         strlcat(finishedMsg2, msg, sizeof(finishedMsg2));
1295     }
1296     if (nodumpvolumes) {
1297         snprintf(msg, sizeof(msg), ", %d unchanged", nodumpvolumes);
1298         strlcat(finishedMsg2, msg, sizeof(finishedMsg2));
1299     }
1300
1301     if (code == TC_ABORTEDBYREQUEST) {
1302         ErrorLog(0, taskId, 0, 0, "%s: Aborted by request. %s\n",
1303                  finishedMsg1, finishedMsg2);
1304         clearStatus(taskId, ABORT_REQUEST);
1305         setStatus(taskId, ABORT_DONE);
1306     } else if (code) {
1307         ErrorLog(0, taskId, code, 0, "%s: Finished with errors. %s\n",
1308                  finishedMsg1, finishedMsg2);
1309         setStatus(taskId, TASK_ERROR);
1310     } else {
1311         TLog(taskId, "%s: Finished. %s\n", finishedMsg1, finishedMsg2);
1312     }
1313     lastPass = 0;
1314
1315     /* Record how long the dump took */
1316     if (centralLogIO && startTime) {
1317         long timediff;
1318         afs_int32 hrs, min, sec, tmp;
1319         char *line = NULL;
1320         struct tm tmstart, tmend;
1321
1322         localtime_r(&startTime, &tmstart);
1323         localtime_r(&endTime, &tmend);
1324         timediff = (int)endTime - (int)startTime;
1325         hrs = timediff / 3600;
1326         tmp = timediff % 3600;
1327         min = tmp / 60;
1328         sec = tmp % 60;
1329
1330         code = asprintf(&line,
1331                 "%-5d  %02d/%02d/%04d %02d:%02d:%02d  "
1332                 "%02d/%02d/%04d %02d:%02d:%02d  " "%02d:%02d:%02d  "
1333                 "%s %d of %d volumes dumped (%lu KB)\n", taskId,
1334                 tmstart.tm_mon + 1, tmstart.tm_mday, tmstart.tm_year + 1900,
1335                 tmstart.tm_hour, tmstart.tm_min, tmstart.tm_sec,
1336                 tmend.tm_mon + 1, tmend.tm_mday, tmend.tm_year + 1900,
1337                 tmend.tm_hour, tmend.tm_min, tmend.tm_sec, hrs, min, sec,
1338                 nodePtr->volumeSetName, dumpedvolumes,
1339                 dumpedvolumes + failedvolumes,
1340                 afs_printable_uint32_lu(dparams.tapeInfoPtr->kBytes + 1));
1341         if (code < 0)
1342             line = NULL;
1343         if (line != NULL) {
1344             fwrite(line, strlen(line), 1, centralLogIO);
1345             fflush(centralLogIO);
1346         }
1347         free(line);
1348     }
1349
1350     setStatus(taskId, TASK_DONE);
1351
1352     FreeNode(taskId);           /* free the dump node */
1353     LeaveDeviceQueue(deviceLatch);
1354     return (void *)(intptr_t)(code);
1355 }
1356
1357 #define BELLTIME 60             /* 60 seconds before a bell rings */
1358 #define BELLCHAR 7              /* ascii for bell */
1359
1360 /* retryPrompt
1361  *      prompt the user to decide how to handle a failed volume dump. The
1362  *      volume parameters describe the volume that failed
1363  * entry:
1364  *      volumeName - name of volume
1365  *      volumeId - volume id
1366  *      taskId - for job contrl
1367  * fn return:
1368  *      character typed by user, one of r, o or a
1369  */
1370
1371 char
1372 retryPrompt(char *volumeName, afs_int32 volumeId, afs_uint32 taskId)
1373 {
1374     afs_int32 start;
1375     char ch;
1376     afs_int32 code = 0;
1377
1378     setStatus(taskId, OPR_WAIT);
1379     printf("\nDump of volume %s (%u) failed\n\n", volumeName, volumeId);
1380
1381     printf("Please select action to be taken for this volume\n");
1382
1383   again:
1384     printf("r - retry, try dumping this volume again\n");
1385     printf("o - omit,  this volume from this dump\n");
1386     printf("a - abort, the entire dump\n");
1387
1388     while (1) {
1389         FFlushInput();
1390         putchar(BELLCHAR);
1391         fflush(stdout);
1392
1393         start = time(0);
1394         while (1) {
1395             code = LWP_GetResponseKey(5, &ch);  /* ch stores key pressed */
1396             if (code == 1)
1397                 break;          /* input is available */
1398
1399             if (checkAbortByTaskId(taskId)) {
1400                 clearStatus(taskId, OPR_WAIT);
1401                 printf
1402                     ("This tape operation has been aborted by the coordinator\n");
1403                 return 'a';
1404             }
1405
1406             if (time(0) > start + BELLTIME)
1407                 break;
1408         }
1409         /* otherwise, we should beep again, check for abort and go back,
1410          * since the GetResponseKey() timed out.
1411          */
1412         if (code == 1)
1413             break;              /* input is available */
1414     }
1415     clearStatus(taskId, OPR_WAIT);
1416     if (ch != 'r' && ch != 'o' && ch != 'a') {
1417         printf("Please select one of the 3 options, r, o or a\n");
1418         goto again;
1419     }
1420
1421     return ch;
1422 }
1423
1424 /* For testing: it prints the tape label */
1425 int
1426 printTapeLabel(struct butm_tapeLabel *tl)
1427 {
1428     printf("Tape Label\n");
1429     printf("   structVersion  = %d\n", tl->structVersion);
1430     printf("   creationTime   = %u\n", tl->creationTime);
1431     printf("   expirationDate = %u\n", tl->expirationDate);
1432     printf("   AFSName        = %s\n", tl->AFSName);
1433     printf("   cell           = %s\n", tl->cell);
1434     printf("   dumpid         = %d\n", tl->dumpid);
1435     printf("   useCount       = %d\n", tl->useCount);
1436     printf("   comment        = %s\n", tl->comment);
1437     printf("   pName          = %s\n", tl->pName);
1438     printf("   size           = %u\n", tl->size);
1439     printf("   dumpPath       = %s\n", tl->dumpPath);
1440     return 0;
1441 }
1442
1443 /* getXBSATape
1444  *      Create a tape structure to be satisfy the backup database
1445  *      even though we don't really use a tape with XBSA.
1446  */
1447 int
1448 getXBSATape(struct dumpRock *dparamsPtr)
1449 {
1450     struct dumpNode *nodePtr = dparamsPtr->node;
1451     struct butm_tapeInfo *tapeInfoPtr = dparamsPtr->tapeInfoPtr;
1452     struct butm_tapeLabel *tapeLabelPtr = &dparamsPtr->tapeLabel;
1453     afs_int32 code = 0;
1454
1455     tc_MakeTapeName(dparamsPtr->tapeName, &nodePtr->tapeSetDesc,
1456                     dparamsPtr->tapeSeq);
1457
1458     GetNewLabel(tapeInfoPtr, "" /*pName */ , dparamsPtr->tapeName,
1459                 tapeLabelPtr);
1460     strcpy(tapeLabelPtr->dumpPath, nodePtr->dumpName);
1461     tapeLabelPtr->dumpid = dparamsPtr->databaseDumpId;
1462     tapeLabelPtr->expirationDate =
1463         calcExpirationDate(nodePtr->tapeSetDesc.expType,
1464                            nodePtr->tapeSetDesc.expDate, time(0));
1465
1466     /* printTapeLabel(tapeLabelPtr); For testing */
1467
1468     code =
1469         useTape(&dparamsPtr->tape, dparamsPtr->databaseDumpId,
1470                 dparamsPtr->tapeName,
1471                 (dparamsPtr->tapeSeq + dparamsPtr->dump.tapes.b),
1472                 tapeLabelPtr->useCount, tapeLabelPtr->creationTime,
1473                 tapeLabelPtr->expirationDate, 0 /*tape position */ );
1474     return (code);
1475 }
1476
1477 /* getDumpTape
1478  *      iterate until the desired tape (as specified by the dump structures)
1479  *      is mounted.
1480  * entry:
1481  *      interactiveFlag
1482  *              0 - assume the tape is there. Prompt if assumption false
1483  *              1 - prompt regardless
1484  */
1485
1486 int
1487 getDumpTape(struct dumpRock *dparamsPtr, int interactiveFlag,
1488             afs_int32 append)
1489 {
1490     struct dumpNode *nodePtr = dparamsPtr->node;
1491     struct butm_tapeInfo *tapeInfoPtr = dparamsPtr->tapeInfoPtr;
1492     struct butm_tapeLabel *newTapeLabelPtr = &dparamsPtr->tapeLabel;
1493     char AFSTapeName[TC_MAXTAPENAMELEN];
1494     afs_int32 taskId = nodePtr->taskID;
1495     struct butm_tapeLabel oldTapeLabel;
1496     struct budb_dumpEntry dumpEntry;
1497     struct budb_tapeEntry tapeEntry;
1498     struct budb_volumeEntry volEntry;
1499     Date expir;
1500     afs_int32 doAppend;
1501     afs_int32 code = 0;
1502     int askForTape;
1503     int tapecount = 1;
1504     char strlevel[5];
1505     afs_int32 tapepos, lastpos;
1506
1507     extern struct tapeConfig globalTapeConfig;
1508
1509     askForTape = interactiveFlag;
1510     dparamsPtr->wroteLabel = 0;
1511
1512     /* Keep prompting for a tape until we get it right */
1513     while (1) {
1514         /* What the name of the tape would be if not appending to it */
1515         tc_MakeTapeName(AFSTapeName, &nodePtr->tapeSetDesc,
1516                         dparamsPtr->tapeSeq);
1517
1518         doAppend = append;
1519
1520         if (askForTape) {
1521             code =
1522                 PromptForTape((doAppend ? APPENDOPCODE : WRITEOPCODE),
1523                               AFSTapeName, dparamsPtr->databaseDumpId, taskId,
1524                               tapecount);
1525             if (code)
1526                 ERROR_EXIT(code);
1527         }
1528         askForTape = 1;
1529         tapecount++;
1530
1531         /* open the tape device */
1532         code = butm_Mount(tapeInfoPtr, AFSTapeName);
1533         if (code) {
1534             TapeLog(0, taskId, code, tapeInfoPtr->error, "Can't open tape\n");
1535             goto getNewTape;
1536         }
1537
1538         /* Read the tape label */
1539         code = butm_ReadLabel(tapeInfoPtr, &oldTapeLabel, 1);   /* rewind */
1540         if (code) {
1541             if (tapeInfoPtr->error) {
1542                 ErrorLog(0, taskId, code, tapeInfoPtr->error,
1543                          "Warning: Tape error while reading label (will proceed with dump)\n");
1544             }
1545             memset(&oldTapeLabel, 0, sizeof(oldTapeLabel));
1546         }
1547
1548         /* Check if null tape. Prior 3.3, backup tapes have no dump id */
1549         if ((strcmp(oldTapeLabel.AFSName, "") == 0)
1550             && (oldTapeLabel.dumpid == 0)) {
1551             if (doAppend) {
1552                 TLog(taskId,
1553                      "Dump not found on tape. Proceeding with initial dump\n");
1554                 doAppend = 0;
1555             }
1556         } else if (doAppend) {  /* appending */
1557             /* Check that we don't have a database dump tape */
1558             if (databaseTape(oldTapeLabel.AFSName)) {
1559                 char gotName[BU_MAXTAPELEN + 32];
1560
1561                 /* label does not match */
1562                 LABELNAME(gotName, &oldTapeLabel);
1563                 TLog(taskId, "Can't append to database tape %s\n", gotName);
1564                 goto getNewTape;
1565             }
1566
1567             /* Verify that the tape is of version 4 (AFS 3.3) or greater */
1568             if (oldTapeLabel.structVersion < TAPE_VERSION_4) {
1569                 TLog(taskId,
1570                      "Can't append: requires tape version %d or greater\n",
1571                      TAPE_VERSION_4);
1572                 goto getNewTape;
1573             }
1574
1575             /* Verify that the last tape of the dump set is in the drive.
1576              * volEntry will be zeroed if last dump has no volume entries.
1577              */
1578             code =
1579                 bcdb_FindLastTape(oldTapeLabel.dumpid, &dumpEntry, &tapeEntry,
1580                                   &volEntry);
1581             if (code) {
1582                 ErrorLog(0, taskId, code, 0,
1583                          "Can't append: Can't find last volume of dumpId %u in database\n",
1584                          oldTapeLabel.dumpid);
1585                 printf("Please scan the dump in or choose another tape\n");
1586                 goto getNewTape;
1587             }
1588             lastpos =
1589                 (volEntry.position ? volEntry.position : tapeEntry.labelpos);
1590
1591             if (strcmp(TNAME(&oldTapeLabel), tapeEntry.name)) {
1592                 char expName[BU_MAXTAPELEN + 32], gotName[BU_MAXTAPELEN + 32];
1593
1594                 TAPENAME(expName, tapeEntry.name, oldTapeLabel.dumpid);
1595                 LABELNAME(gotName, &oldTapeLabel);
1596
1597                 TLog(taskId,
1598                      "Can't append: Last tape in dump-set is %s, label seen %s\n",
1599                      expName, gotName);
1600                 goto getNewTape;
1601             }
1602
1603             /* After reading the tape label, we now know what it is */
1604             strcpy(AFSTapeName, oldTapeLabel.AFSName);  /* the real name */
1605             strcpy(tapeInfoPtr->name, oldTapeLabel.AFSName);    /* the real name */
1606
1607             /* Position after last volume on the tape */
1608             code = butm_SeekEODump(tapeInfoPtr, lastpos);
1609             if (code) {
1610                 ErrorLog(0, taskId, code, tapeInfoPtr->error,
1611                          "Can't append: Can't position to end of dump on tape %s\n",
1612                          tapeEntry.name);
1613                 goto getNewTape;
1614             }
1615
1616             /* Track size of tape - set after seek since seek changes the value */
1617             tapeInfoPtr->kBytes = tapeEntry.useKBytes;
1618         } else {                /* not appending */
1619
1620             afs_uint32 tapeid;
1621             afs_uint32 dmp;
1622             struct budb_dumpEntry de, de2;
1623
1624             /* Check if tape name is not what expected - null tapes are acceptable
1625              * Don't do check if the tape has a user defined label.
1626              */
1627             if (dump_namecheck && (strcmp(oldTapeLabel.pName, "") == 0)) {
1628                 if (strcmp(oldTapeLabel.AFSName, "") && /* not null tape */
1629                     strcmp(oldTapeLabel.AFSName, AFSTapeName)) {        /* not expected name */
1630                     TLog(taskId, "Tape label expected %s, label seen %s\n",
1631                          AFSTapeName, oldTapeLabel.AFSName);
1632                     goto getNewTape;
1633                 }
1634
1635                 /* Check that we don't have a database dump tape */
1636                 if (databaseTape(oldTapeLabel.AFSName)) {
1637                     /* label does not match */
1638                     TLog(taskId,
1639                          "Tape label expected %s, can't dump to database tape %s\n",
1640                          AFSTapeName, oldTapeLabel.AFSName);
1641                     goto getNewTape;
1642                 }
1643             }
1644
1645             /* Verify the tape has not expired - only check if not appending */
1646             if (!tapeExpired(&oldTapeLabel)) {
1647                 TLog(taskId, "This tape has not expired\n");
1648                 goto getNewTape;
1649             }
1650
1651             /* Given a tape dump with good data, verify we don't overwrite recent dumps
1652              * and also verify that the volume will be restorable - if not print warnings
1653              */
1654             if (oldTapeLabel.dumpid) {
1655                 /* Do not overwrite a tape that belongs to the dump's dumpset */
1656                 tapeid =
1657                     (dparamsPtr->initialDumpId ? dparamsPtr->
1658                      initialDumpId : dparamsPtr->databaseDumpId);
1659                 if (oldTapeLabel.dumpid == tapeid) {
1660                     ErrorLog(0, taskId, 0, 0,
1661                              "Can't overwrite tape containing the dump in progress\n");
1662                     goto getNewTape;
1663                 }
1664
1665                 /* Since the dumpset on this tape will be deleted from database, check if
1666                  * any of the dump's parent-dumps are on this tape.
1667                  */
1668                 for (dmp = nodePtr->parent; dmp; dmp = de.parent) {
1669                     code = bcdb_FindDumpByID(dmp, &de);
1670                     if (code) {
1671                         ErrorLog(0, taskId, 0, 0,
1672                                  "Warning: Can't find parent dump %u in backup database\n",
1673                                  dmp);
1674                         break;
1675                     }
1676
1677                     tapeid = (de.initialDumpID ? de.initialDumpID : de.id);
1678                     if (oldTapeLabel.dumpid == tapeid) {
1679                         ErrorLog(0, taskId, 0, 0,
1680                                  "Can't overwrite the parent dump %s (DumpID %u)\n",
1681                                  de.name, de.id);
1682                         goto getNewTape;
1683                     }
1684                 }
1685
1686                 /* Since the dumpset on this tape will be deleted from database, check if
1687                  * any of the dumps in this dumpset are most-recent-dumps.
1688                  */
1689                 for (dmp = oldTapeLabel.dumpid; dmp; dmp = de.appendedDumpID) {
1690                     if (dmp == dparamsPtr->lastDump.id) {
1691                         memcpy(&de, &dparamsPtr->lastDump, sizeof(de));
1692                         memcpy(&de2, &dparamsPtr->lastDump, sizeof(de2));
1693                     } else {
1694                         code = bcdb_FindDumpByID(dmp, &de);
1695                         if (code)
1696                             break;
1697                         snprintf(strlevel, sizeof(strlevel), "%d", de.level);
1698                         code =
1699                             bcdb_FindLatestDump(de.volumeSetName, strlevel,
1700                                                 &de2);
1701                         if (code)
1702                             continue;
1703                     }
1704
1705                     /* If dump on the tape is the latest dump at this level */
1706                     if (de.id == de2.id) {
1707                         if (strcmp(DUMP_TAPE_NAME, de2.name) == 0) {
1708                             ErrorLog(0, taskId, 0, 0,
1709                                      "Warning: Overwriting most recent dump %s (DumpID %u)\n",
1710                                      de.name, de.id);
1711                         } else {
1712                             ErrorLog(0, taskId, 0, 0,
1713                                      "Warning: Overwriting most recent dump of the '%s' volumeset: %s (DumpID %u)\n",
1714                                      de.volumeSetName, de.name, de.id);
1715                         }
1716                     }
1717                 }
1718             }                   /* if (oldTapeLabel.dumpid) */
1719         }                       /* else not appending */
1720
1721         /*
1722          * Now have the right tape. Create a new label for the tape
1723          * Appended labels have the dump's dumpId - labels at beginnings of
1724          *     tape have the initial dump's dumpId.
1725          * Appended labels do not increment the useCount.
1726          * Labels at beginnings of tape use the most future expiration of the dump set.
1727          */
1728         GetNewLabel(tapeInfoPtr, oldTapeLabel.pName, AFSTapeName,
1729                     newTapeLabelPtr);
1730         strcpy(newTapeLabelPtr->dumpPath, nodePtr->dumpName);
1731         newTapeLabelPtr->expirationDate =
1732             calcExpirationDate(nodePtr->tapeSetDesc.expType,
1733                                nodePtr->tapeSetDesc.expDate, time(0));
1734         newTapeLabelPtr->dumpid = dparamsPtr->databaseDumpId;
1735         newTapeLabelPtr->useCount = oldTapeLabel.useCount;
1736
1737         if (!doAppend) {
1738             newTapeLabelPtr->useCount++;
1739             if (dparamsPtr->initialDumpId) {
1740                 newTapeLabelPtr->dumpid = dparamsPtr->initialDumpId;
1741                 expir = ExpirationDate(dparamsPtr->initialDumpId);
1742                 if (expir > newTapeLabelPtr->expirationDate)
1743                     newTapeLabelPtr->expirationDate = expir;
1744             }
1745         }
1746
1747         /* write the label on the tape - rewind if not appending and vice-versa */
1748         code = butm_Create(tapeInfoPtr, newTapeLabelPtr, !doAppend);
1749         if (code) {
1750             char gotName[BU_MAXTAPELEN + 32];
1751
1752             LABELNAME(gotName, newTapeLabelPtr);
1753             TapeLog(0, taskId, code, tapeInfoPtr->error,
1754                     "Can't label tape as %s\n", gotName);
1755             goto getNewTape;
1756         }
1757         dparamsPtr->wroteLabel = 1;     /* Remember we wrote the label */
1758         tapepos = tapeInfoPtr->position - 1;
1759
1760         strcpy(dparamsPtr->tapeName, TNAME(newTapeLabelPtr));
1761
1762         /* If appending, set dumpentry in the database as appended. */
1763         if (doAppend) {
1764             char gotName[BU_MAXTAPELEN + 32];
1765
1766             nodePtr->tapeSetDesc.b = extractTapeSeq(AFSTapeName);
1767             dparamsPtr->dump.tapes.b = nodePtr->tapeSetDesc.b;
1768             dparamsPtr->initialDumpId = oldTapeLabel.dumpid;
1769             strcpy(nodePtr->tapeSetDesc.format, dumpEntry.tapes.format);
1770
1771             code =
1772                 bcdb_MakeDumpAppended(dparamsPtr->databaseDumpId,
1773                                       dparamsPtr->initialDumpId,
1774                                       nodePtr->tapeSetDesc.b);
1775             if (code)
1776                 ErrorLog(2, taskId, code, 0,
1777                          "Warning: Can't append dump %u to dump %u in database\n",
1778                          dparamsPtr->databaseDumpId,
1779                          dparamsPtr->initialDumpId);
1780
1781             LABELNAME(gotName, &oldTapeLabel);
1782             TLog(taskId, "Appending dump %s (DumpID %u) to tape %s\n",
1783                  nodePtr->dumpSetName, dparamsPtr->databaseDumpId, gotName);
1784         }
1785
1786         /* If not appending, delete overwritten dump from the database */
1787         else {
1788             if ((oldTapeLabel.structVersion >= TAPE_VERSION_3)
1789                 && oldTapeLabel.dumpid) {
1790                 code = bcdb_deleteDump(oldTapeLabel.dumpid, 0, 0, 0);
1791                 if (code && (code != BUDB_NOENT))
1792                     ErrorLog(0, taskId, code, 0,
1793                              "Warning: Can't delete old dump %u from database\n",
1794                              oldTapeLabel.dumpid);
1795             }
1796         }
1797
1798         code =
1799             useTape(&dparamsPtr->tape, dparamsPtr->databaseDumpId,
1800                     dparamsPtr->tapeName,
1801                     (dparamsPtr->tapeSeq + dparamsPtr->dump.tapes.b),
1802                     newTapeLabelPtr->useCount, newTapeLabelPtr->creationTime,
1803                     newTapeLabelPtr->expirationDate, tapepos);
1804
1805         /*
1806          * The margin of space to check for end of tape is set to the
1807          * amount of space used to write an end-of-tape multiplied by 2.
1808          * The amount of space is size of a 16K volume trailer, a 16K File
1809          * End mark, its EOF marker, a 16K EODump marker, its EOF marker,
1810          * and up to two EOF markers done on close (3 16K blocks + 4 EOF
1811          * markers).
1812          */
1813         tc_EndMargin = (3 * 16384 + 4 * globalTapeConfig.fileMarkSize) * 2;
1814         tc_KEndMargin = tc_EndMargin / 1024;
1815         break;
1816
1817       getNewTape:
1818         unmountTape(taskId, tapeInfoPtr);
1819     }
1820
1821   error_exit:
1822     return (code);
1823 }
1824
1825 int
1826 makeVolumeHeader(struct volumeHeader *vhptr, struct dumpRock *dparamsPtr,
1827                  int fragmentNumber)
1828 {
1829     struct dumpNode *nodePtr = dparamsPtr->node;
1830     struct tc_dumpDesc *curDump;
1831     afs_int32 code = 0;
1832
1833     curDump = &nodePtr->dumps[dparamsPtr->curVolume];
1834
1835     memset(vhptr, 0, sizeof(*vhptr));
1836     strcpy(vhptr->volumeName, curDump->name);
1837     vhptr->volumeID = curDump->vid;
1838     vhptr->cloneDate = curDump->cloneDate;
1839     vhptr->server = curDump->hostAddr;
1840     vhptr->part = curDump->partition;
1841     vhptr->from = curDump->date;
1842     vhptr->frag = fragmentNumber;
1843     vhptr->contd = 0;
1844     vhptr->magic = TC_VOLBEGINMAGIC;
1845     vhptr->dumpID = dparamsPtr->databaseDumpId; /* real dump id */
1846     vhptr->level = nodePtr->level;
1847     vhptr->parentID = nodePtr->parent;
1848     vhptr->endTime = 0;
1849     vhptr->versionflags = CUR_TAPE_VERSION;
1850     strcpy(vhptr->dumpSetName, nodePtr->dumpSetName);
1851     strcpy(vhptr->preamble, "H++NAME#");
1852     strcpy(vhptr->postamble, "T--NAME#");
1853
1854     return (code);
1855 }
1856
1857 int
1858 volumeHeader_hton(struct volumeHeader *hostPtr, struct volumeHeader *netPtr)
1859 {
1860     struct volumeHeader volHdr;
1861
1862     memset(&volHdr, 0, sizeof(volHdr));
1863
1864     strcpy(volHdr.preamble, hostPtr->preamble);
1865     strcpy(volHdr.postamble, hostPtr->postamble);
1866     strcpy(volHdr.volumeName, hostPtr->volumeName);
1867     strcpy(volHdr.dumpSetName, hostPtr->dumpSetName);
1868     volHdr.volumeID = htonl(hostPtr->volumeID);
1869     volHdr.server = htonl(hostPtr->server);
1870     volHdr.part = htonl(hostPtr->part);
1871     volHdr.from = htonl(hostPtr->from);
1872     volHdr.frag = htonl(hostPtr->frag);
1873     volHdr.magic = htonl(hostPtr->magic);
1874     volHdr.contd = htonl(hostPtr->contd);
1875     volHdr.dumpID = htonl(hostPtr->dumpID);
1876     volHdr.level = htonl(hostPtr->level);
1877     volHdr.parentID = htonl(hostPtr->parentID);
1878     volHdr.endTime = htonl(hostPtr->endTime);
1879     volHdr.versionflags = htonl(hostPtr->versionflags);
1880     volHdr.cloneDate = htonl(hostPtr->cloneDate);
1881
1882     memcpy(netPtr, &volHdr, sizeof(struct volumeHeader));
1883     return 0;
1884 }
1885
1886 /* database related routines */
1887
1888 afs_int32
1889 createDump(struct dumpRock *dparamsPtr)
1890 {
1891     struct dumpNode *nodePtr = dparamsPtr->node;
1892     struct budb_dumpEntry *dumpPtr;
1893     afs_int32 code = 0;
1894
1895     dumpPtr = &dparamsPtr->dump;
1896     memset(dumpPtr, 0, sizeof(*dumpPtr));
1897
1898     /* id filled in by database */
1899     dumpPtr->parent = nodePtr->parent;
1900     dumpPtr->level = nodePtr->level;
1901     dumpPtr->flags = 0;
1902 #ifdef xbsa
1903     if (CONF_XBSA) {
1904         if (xbsaType == XBSA_SERVER_TYPE_ADSM) {
1905             strcpy(dumpPtr->tapes.tapeServer, butxInfo.serverName);
1906             dumpPtr->flags = BUDB_DUMP_ADSM;
1907         }
1908         if (!(butxInfo.serverType & XBSA_SERVER_FLAG_MULTIPLE)) {
1909             /* The current server (API) doesn't provide the function required
1910              * to specify a server at startup time.  For that reason, we can't
1911              * be sure that the server name supplied by the user in the user-
1912              * defined configuration file is correct.  We set a flag here so
1913              * we know at restore time that the servername info in the backup
1914              * database may be incorrect.  We will not allow a server switch
1915              * at that time, even if the server at restore time supports
1916              * multiple servers.
1917              */
1918             dumpPtr->flags |= BUDB_DUMP_XBSA_NSS;
1919         }
1920     }
1921 #endif
1922     strcpy(dumpPtr->volumeSetName, nodePtr->volumeSetName);
1923     strcpy(dumpPtr->dumpPath, nodePtr->dumpName);
1924     strcpy(dumpPtr->name, nodePtr->dumpSetName);
1925     dumpPtr->created = 0;       /* let database assign it */
1926     dumpPtr->incTime = 0;       /* not really used */
1927     dumpPtr->nVolumes = 0;
1928     dumpPtr->initialDumpID = 0;
1929
1930     dumpPtr->tapes.id = groupId;
1931     dumpPtr->tapes.b = 1;
1932     dumpPtr->tapes.maxTapes = 0;
1933     strcpy(dumpPtr->tapes.format, nodePtr->tapeSetDesc.format);
1934
1935     /* principal filled in by database */
1936
1937     /* now call the database to create the entry */
1938     code = bcdb_CreateDump(dumpPtr);
1939     if (code == 0)
1940         dparamsPtr->databaseDumpId = dumpPtr->id;
1941
1942     return (code);
1943 }
1944
1945 #ifdef xbsa
1946 /* InitToServer:
1947  * Initialize to a specific server. The first time, we remember the
1948  * server as the original server and go back to it each time we pass 0
1949  * as the server.
1950  */
1951 afs_int32
1952 InitToServer(afs_int32 taskId, struct butx_transactionInfo * butxInfoP,
1953              char *server)
1954 {
1955     static char origserver[BSA_MAX_DESC];
1956     static int init = 0;
1957     afs_int32 rc, code = 0;
1958
1959     if (!init) {
1960         strcpy(origserver, "");
1961         init = 1;
1962     }
1963
1964     if (!server)
1965         server = origserver;    /* return to original server */
1966     if (strcmp(server, "") == 0)
1967         return 0;               /* No server, do nothing */
1968     if (strcmp(butxInfoP->serverName, server) == 0)
1969         return 0;               /* same server, do nothing */
1970     if (strcmp(origserver, "") == 0)
1971         strcpy(origserver, server);     /* remember original server */
1972
1973     if (strcmp(butxInfoP->serverName, "") != 0) {
1974         /* If already connected to a server, disconnect from it.
1975          * Check to see if our server does not support switching.
1976          */
1977         if (!(butxInfo.serverType & XBSA_SERVER_FLAG_MULTIPLE)) {
1978             ErrorLog(0, taskId, TC_BADTASK, 0,
1979                      "This version of XBSA libraries does not support switching "
1980                      "from server %s to server %s\n", butxInfoP->serverName,
1981                      server);
1982             return (TC_BADTASK);
1983         }
1984
1985         rc = xbsa_Finalize(&butxInfo);
1986         if (rc != XBSA_SUCCESS) {
1987             ErrorLog(0, taskId, rc, 0,
1988                      "InitToServer: Unable to terminate the connection to server %s\n",
1989                      butxInfoP->serverName);
1990             ERROR_EXIT(rc);
1991         }
1992     }
1993
1994     /* initialize to the new server */
1995     rc = xbsa_Initialize(&butxInfo, xbsaObjectOwner, appObjectOwner,
1996                          xbsaSecToken, server);
1997     if (rc != XBSA_SUCCESS) {
1998         ErrorLog(0, taskId, rc, 0,
1999                  "InitToServer: Unable to initialize the XBSA library to server %s\n",
2000                  server);
2001         ERROR_EXIT(rc);
2002     }
2003
2004   error_exit:
2005     return (code);
2006 }
2007
2008
2009 /* DeleteDump
2010  *
2011  */
2012 void *
2013 DeleteDump(void *param)
2014 {
2015     struct deleteDumpIf *ptr = (struct deleteDumpIf *)param;
2016
2017     afs_int32 taskId;
2018     afs_int32 rc, code = 0;
2019     afs_uint32 dumpid;
2020     afs_int32 index, next, dbTime;
2021     budb_volumeList vl;
2022     struct budb_dumpEntry dumpEntry;
2023     char tapeName[BU_MAXTAPELEN];
2024     char dumpIdStr[XBSA_MAX_OSNAME];
2025     char volumeNameStr[XBSA_MAX_PATHNAME];
2026     afs_int32 i;
2027     int intrans = 0;
2028     int allnotfound = 1, onenotfound = 0;
2029     extern struct udbHandleS udbHandle;
2030     extern struct deviceSyncNode *deviceLatch;
2031
2032     dumpid = ptr->dumpID;
2033     taskId = ptr->taskId;       /* Get task Id */
2034
2035     opr_threadname_set("deletedump");
2036     setStatus(taskId, DRIVE_WAIT);
2037     EnterDeviceQueue(deviceLatch);
2038     clearStatus(taskId, DRIVE_WAIT);
2039
2040     printf("\n\n");
2041     TapeLog(2, taskId, 0, 0, "Delete Dump %u\n", dumpid);
2042
2043     vl.budb_volumeList_len = 0;
2044     vl.budb_volumeList_val = 0;
2045     tapeName[0] = '\0';
2046
2047     /* Get the dump info for the dump we are deleting */
2048     rc = bcdb_FindDumpByID(dumpid, &dumpEntry);
2049     if (rc) {
2050         ErrorLog(0, taskId, rc, 0,
2051                  "Unable to locate dump ID %u in database\n", dumpid);
2052         setStatus(taskId, TASK_ERROR);
2053         ERROR_EXIT(rc);
2054     }
2055
2056     /* we must make sure that we are configured with the correct type of
2057      * XBSA server for this dump delete! Only those dumped to an ADSM server.
2058      */
2059     if ((xbsaType == XBSA_SERVER_TYPE_ADSM)
2060         && !((dumpEntry.flags & (BUDB_DUMP_ADSM | BUDB_DUMP_BUTA)))) {
2061         ErrorLog(0, taskId, TC_BADTASK, 0,
2062                  "The dump %u requested for deletion is incompatible with this instance of butc\n",
2063                  dumpid);
2064         setStatus(taskId, TASK_ERROR);
2065         ERROR_EXIT(TC_BADTASK);
2066     }
2067
2068     /* Make sure we are connected to the correct server. If not, switch to it if appropriate */
2069     if ((strlen((char *)dumpEntry.tapes.tapeServer) != 0)
2070         && (strcmp((char *)dumpEntry.tapes.tapeServer, butxInfo.serverName) !=
2071             0)) {
2072
2073         /* Check to see if the tapeServer name is trustworthy */
2074         if ((dumpEntry.flags & (BUDB_DUMP_XBSA_NSS | BUDB_DUMP_BUTA))
2075             && !forcemultiple) {
2076             /* The dump was made with a version of the XBSA interface
2077              * that didn't allow switching of servers, we can't be sure
2078              * that the servername in the backup database is correct.  So,
2079              * we will check the servername and log it if they don't match;
2080              * but we will try to do the delete without switching servers.
2081              */
2082             TLog(taskId,
2083                  "The dump %d requested for deletion is on server %s "
2084                  "but butc is connected to server %s "
2085                  "(Attempting to delete the dump anyway)\n", dumpid,
2086                  (char *)dumpEntry.tapes.tapeServer, butxInfo.serverName);
2087         } else {
2088             TLog(taskId,
2089                  "The dump %u requested for deletion is on server %s "
2090                  "but butc is connected to server %s "
2091                  "(switching servers)\n", dumpid,
2092                  (char *)dumpEntry.tapes.tapeServer, butxInfo.serverName);
2093
2094             rc = InitToServer(taskId, &butxInfo,
2095                               (char *)dumpEntry.tapes.tapeServer);
2096             if (rc != XBSA_SUCCESS) {
2097                 setStatus(taskId, TASK_ERROR);
2098                 ERROR_EXIT(rc);
2099             }
2100         }
2101     }
2102
2103     /* Start a new Transaction */
2104     rc = xbsa_BeginTrans(&butxInfo);
2105     if (rc != XBSA_SUCCESS) {
2106         ErrorLog(0, taskId, rc, 0, "Unable to create a new transaction\n");
2107         setStatus(taskId, TASK_ERROR);
2108         ERROR_EXIT(rc);
2109     }
2110     intrans = 1;
2111
2112     /* Query the backup database for list of volumes to delete */
2113     for (index = next = 0; index != -1; index = next) {
2114         rc = ubik_Call_SingleServer(BUDB_GetVolumes, udbHandle.uh_client,
2115                                     UF_SINGLESERVER, BUDB_MAJORVERSION,
2116                                     BUDB_OP_DUMPID, tapeName, dumpid, 0,
2117                                     index, &next, &dbTime, &vl);
2118         if (rc) {
2119             if (rc == BUDB_ENDOFLIST)
2120                 break;
2121             ErrorLog(0, taskId, rc, 0, "Can't find volume info for dump %d\n",
2122                      dumpid);
2123             setStatus(taskId, TASK_ERROR);
2124             ERROR_EXIT(rc);
2125         }
2126
2127         /* Delete all volumes on the list */
2128         for (i = 0; i < vl.budb_volumeList_len; i++) {
2129             if (dumpEntry.flags & BUDB_DUMP_BUTA) {
2130                 /* dump was from buta, use old buta style names */
2131                 snprintf(dumpIdStr, sizeof(dumpIdStr), "/%d", dumpid);
2132                 snprintf(volumeNameStr, sizeof(volumeNameStr), "/%s",
2133                          (char *)vl.budb_volumeList_val[i].name);
2134             } else {            /* BUDB_DUMP_ADSM */
2135                 /* dump was from butc to ADSM, use butc names */
2136                 snprintf(dumpIdStr, sizeof(dumpIdStr), "%s", butcdumpIdStr);
2137                 snprintf(volumeNameStr, sizeof(volumeNameStr), "/%d/%s",
2138                          dumpid, (char *)vl.budb_volumeList_val[i].name);
2139             }
2140
2141             rc = xbsa_DeleteObject(&butxInfo, dumpIdStr, volumeNameStr);
2142             if (rc != XBSA_SUCCESS) {
2143                 ErrorLog(0, taskId, rc, 0,
2144                          "Unable to delete the object %s of dump %s from the server\n",
2145                          volumeNameStr, dumpIdStr);
2146                 /* Don't exit if volume was not found */
2147                 if (rc != BUTX_DELETENOVOL) {
2148                     allnotfound = 0;
2149                     ERROR_EXIT(rc);
2150                 }
2151                 onenotfound = 1;
2152             } else {
2153                 allnotfound = 0;
2154                 TLog(0,
2155                      "Deleted volume %s (%u) in dumpID %u from the backup server\n",
2156                      vl.budb_volumeList_val[i].name,
2157                      vl.budb_volumeList_val[i].id, dumpid);
2158             }
2159         }
2160
2161         /* free the memory allocated by RPC for this list */
2162         if (vl.budb_volumeList_val)
2163             free(vl.budb_volumeList_val);
2164         vl.budb_volumeList_len = 0;
2165         vl.budb_volumeList_val = 0;
2166     }
2167
2168   error_exit:
2169     if (intrans) {
2170         rc = xbsa_EndTrans(&butxInfo);
2171         if (rc != XBSA_SUCCESS) {
2172             ErrorLog(0, taskId, rc, 0,
2173                      "Unable to terminate the current transaction\n");
2174             setStatus(taskId, TASK_ERROR);
2175             ERROR_EXIT(rc);
2176         }
2177     }
2178
2179     /* Switch back to the original server */
2180     rc = InitToServer(taskId, &butxInfo, NULL);
2181
2182     if (vl.budb_volumeList_val)
2183         free(vl.budb_volumeList_val);
2184
2185     setStatus(taskId, TASK_DONE);
2186     FreeNode(taskId);           /* free the dump node */
2187     LeaveDeviceQueue(deviceLatch);
2188
2189     /* If we don't find any dumps on the server, rather than returning
2190      * a success, return a failure.
2191      */
2192     if (!code && onenotfound && allnotfound) {
2193         code = BUTX_DELETENOVOL;
2194         setStatus(taskId, TASK_ERROR);
2195     }
2196     return (void *)(uintptr_t)(code);
2197 }
2198 #endif