TapeReadTask.hpp 12.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/******************************************************************************
 *
 * This file is part of the Castor project.
 * See http://castor.web.cern.ch/castor
 *
 * Copyright (C) 2003  CERN
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * 
 *
 * @author Castor Dev team, castor-dev@cern.ch
 *****************************************************************************/

#pragma once

26

David COME's avatar
David COME committed
27
#include "castor/tape/tapeserver/daemon/DataPipeline.hpp"
28
29
30
#include "castor/tape/tapeserver/daemon/RecallMemoryManager.hpp"
#include "castor/tape/tapeserver/daemon/DataConsumer.hpp"
#include "castor/tape/tapeserver/daemon/AutoReleaseBlock.hpp"
31
#include "castor/tape/tapeserver/daemon/TaskWatchDog.hpp"
32
#include "castor/tape/tapeserver/daemon/TapeSessionStats.hpp"
Victor Kotlyar's avatar
Victor Kotlyar committed
33
#include "common/Timer.hpp"
34
#include "common/exception/Exception.hpp"
35

36
37
38
39
namespace castor {
namespace tape {
namespace tapeserver {
namespace daemon {
40
41
42
43
  /**
   * This class is in charge of 
   * 
   */
44
class TapeReadTask {
45
public:
46
  /**
Michael Davis's avatar
Michael Davis committed
47
   * Constructor
48
49
50
51
   * @param ftr The file being recalled. We acquire the ownership on the pointer
   * @param destination the task that will consume the memory blocks
   * @param mm The memory manager to get free block
   */
52
  TapeReadTask(cta::RetrieveJob *retrieveJob,
53
    DataConsumer & destination, RecallMemoryManager & mm): 
54
    m_retrieveJob(retrieveJob), m_fifo(destination), m_mm(mm) {}
55
    
56
57
58
59
60
61
62
    /**
     * @param rs the read session holding all we need to be able to read from the tape
     * @param lc the log context for .. logging purpose
     * The actual function that will do the job.
     * The main loop is :
     * Acquire a free memory block from the memory manager , fill it, push it 
     */
63
  void execute(castor::tape::tapeFile::ReadSession & rs,
Victor Kotlyar's avatar
Victor Kotlyar committed
64
    cta::log::LogContext & lc,RecallWatchDog& watchdog,
Victor Kotlyar's avatar
Victor Kotlyar committed
65
    TapeSessionStats & stats, cta::utils::Timer & timer) {
66

Victor Kotlyar's avatar
Victor Kotlyar committed
67
    using cta::log::Param;
Michael Davis's avatar
Michael Davis committed
68
69
70

    const bool isRepack = m_retrieveJob->m_dbJob->isRepack;
    const bool isVerifyOnly = m_retrieveJob->retrieveRequest.isVerifyOnly;
71
    // Set the common context for all the coming logs (file info)
Victor Kotlyar's avatar
Victor Kotlyar committed
72
    cta::log::ScopedParamContainer params(lc);
73
    params.add("fileId", m_retrieveJob->archiveFile.archiveFileID)
74
75
          .add("BlockId", m_retrieveJob->selectedTapeFile().blockId)
          .add("fSeq", m_retrieveJob->selectedTapeFile().fSeq)
76
          .add("dstURL", m_retrieveJob->retrieveRequest.dstURL)
Michael Davis's avatar
Michael Davis committed
77
78
          .add("isRepack", isRepack)
          .add("isVerifyOnly", isVerifyOnly);
79
    
80
81
    // We will clock the stats for the file itself, and eventually add those
    // stats to the session's.
82
    TapeSessionStats localStats;
83
    std::string LBPMode;
Victor Kotlyar's avatar
Victor Kotlyar committed
84
85
    cta::utils::Timer localTime;
    cta::utils::Timer totalTime(localTime);
86

87
88
    // Read the file and transmit it
    bool stillReading = true;
89
90
    //for counting how many mem blocks have used and how many tape blocks
    //(because one mem block can hold several tape blocks
91
92
    int fileBlock = 0;
    int tapeBlock = 0;
93
94
95
96
97
    // This out-of-try-catch variables allows us to record the stage of the 
    // process we're in, and to count the error if it occurs.
    // We will not record errors for an empty string. This will allow us to
    // prevent counting where error happened upstream.
    std::string currentErrorToCount = "";
98
99
    MemBlock* mb=NULL;
    try {
100
      currentErrorToCount = "Error_tapePositionForRead";
101
      std::unique_ptr<castor::tape::tapeFile::ReadFile> rf(openReadFile(rs,lc));
102
      LBPMode = rf->getLBPMode();
103
104
105
      // At that point we already read the header.
      localStats.headerVolume += TapeSessionStats::headerVolumePerFile;

Victor Kotlyar's avatar
Victor Kotlyar committed
106
      lc.log(cta::log::INFO, "Successfully positioned for reading");
Victor Kotlyar's avatar
Victor Kotlyar committed
107
      localStats.positionTime += timer.secs(cta::utils::Timer::resetCounter);
108
      watchdog.notifyBeginNewJob(m_retrieveJob->archiveFile.archiveFileID, m_retrieveJob->selectedTapeFile().fSeq);
Victor Kotlyar's avatar
Victor Kotlyar committed
109
      localStats.waitReportingTime += timer.secs(cta::utils::Timer::resetCounter);
110
      currentErrorToCount = "Error_tapeReadData";
Michael Davis's avatar
Michael Davis committed
111
112
      auto checksum_adler32 = Payload::zeroAdler32();
      cta::checksum::ChecksumBlob tapeReadChecksum;
113
114
115
      while (stillReading) {
        // Get a memory block and add information to its metadata
        mb=m_mm.getFreeBlock();
Victor Kotlyar's avatar
Victor Kotlyar committed
116
        localStats.waitFreeMemoryTime += timer.secs(cta::utils::Timer::resetCounter);
117
        
118
        mb->m_fSeq = m_retrieveJob->selectedTapeFile().fSeq;
119
        mb->m_fileBlock = fileBlock++;
120
        mb->m_fileid = m_retrieveJob->retrieveRequest.archiveFileID;
121
122
123
124
125
126
127
        mb->m_tapeFileBlock = tapeBlock;
        mb->m_tapeBlockSize = rf->getBlockSize();
        try {
          // Fill up the memory block with tape block
          // append conveniently returns false when there will not be more space
          // for an extra tape block, and throws an exception if we reached the
          // end of file. append() also protects against reading too big tape blocks.
128
129
130
          while (mb->m_payload.append(*rf)) {
            tapeBlock++;
          }
131
        } catch (const cta::exception::EndOfFile&) {
132
133
134
          // append() signaled the end of the file.
          stillReading = false;
        }
Michael Davis's avatar
Michael Davis committed
135
        checksum_adler32 = mb->m_payload.adler32(checksum_adler32);
Victor Kotlyar's avatar
Victor Kotlyar committed
136
        localStats.readWriteTime += timer.secs(cta::utils::Timer::resetCounter);
137
138
        auto blockSize = mb->m_payload.size();
        localStats.dataVolume += blockSize;
139
140
	if(isRepack){
	  localStats.repackBytesCount += blockSize;
Michael Davis's avatar
Michael Davis committed
141
142
        } else if(isVerifyOnly) {
          localStats.verifiedBytesCount += blockSize;
Michael Davis's avatar
Michael Davis committed
143
144
          // Don't write the file to disk
          mb->markAsVerifyOnly();
145
146
147
	} else {
	  localStats.userBytesCount += blockSize;
	}
Michael Davis's avatar
Michael Davis committed
148
149
150
151
        // If we reached the end of the file, validate the checksum (throws an exception on bad checksum)
        if(!stillReading) {
          tapeReadChecksum.insert(cta::checksum::ADLER32, checksum_adler32);
          m_retrieveJob->archiveFile.checksumBlob.validate(tapeReadChecksum);
Michael Davis's avatar
Michael Davis committed
152
        }
153
154
        // Pass the block to the disk write task
        m_fifo.pushDataBlock(mb);
155
        mb=NULL;
156
        watchdog.notify(blockSize);
Victor Kotlyar's avatar
Victor Kotlyar committed
157
        localStats.waitReportingTime += timer.secs(cta::utils::Timer::resetCounter);
158
      } //end of while(stillReading)
Michael Davis's avatar
Michael Davis committed
159
      // We have to signal the end of the tape read to the disk write task.
160
      m_fifo.pushDataBlock(NULL);
161
      // Log the successful transfer
162
      localStats.totalTime = localTime.secs();
163
164
165
166
      // Count the trailer size
      localStats.headerVolume += TapeSessionStats::trailerVolumePerFile;
      // We now transmitted one file:
      localStats.filesCount++;
167
168
      if(isRepack){
	localStats.repackFilesCount++;
Michael Davis's avatar
Michael Davis committed
169
170
      } else if(isVerifyOnly) {
        localStats.verifiedFilesCount++;
171
172
173
      } else {
	localStats.userFilesCount++;
      }
174
      params.add("positionTime", localStats.positionTime)
175
            .add("readWriteTime", localStats.readWriteTime)
176
177
            .add("waitFreeMemoryTime",localStats.waitFreeMemoryTime)
            .add("waitReportingTime",localStats.waitReportingTime)
178
            .add("transferTime",localStats.transferTime())
179
            .add("totalTime", localStats.totalTime)
180
            .add("dataVolume",localStats.dataVolume)
181
            .add("headerVolume",localStats.headerVolume)
182
            .add("driveTransferSpeedMBps",
183
184
                    localStats.totalTime?(1.0*localStats.dataVolume+1.0*localStats.headerVolume)
                     /1000/1000/localStats.totalTime:0)
185
            .add("payloadTransferSpeedMBps",
186
                     localStats.totalTime?1.0*localStats.dataVolume/1000/1000/localStats.totalTime:0)
187
188
189
190
            .add("LBPMode", LBPMode)
	    .add("repackFilesCount",localStats.repackFilesCount)
	    .add("repackBytesCount",localStats.repackBytesCount)
	    .add("userFilesCount",localStats.userFilesCount)
Michael Davis's avatar
Michael Davis committed
191
192
	    .add("userBytesCount",localStats.userBytesCount)
	    .add("verifiedFilesCount",localStats.verifiedFilesCount)
Michael Davis's avatar
Michael Davis committed
193
194
195
	    .add("verifiedBytesCount",localStats.verifiedBytesCount)
            .add("checksumType", "ADLER32")
            .add("checksumValue", cta::checksum::ChecksumBlob::ByteArrayToHex(tapeReadChecksum.at(cta::checksum::ADLER32)));
Victor Kotlyar's avatar
Victor Kotlyar committed
196
      lc.log(cta::log::INFO, "File successfully read from tape");
197
198
199
      // Add the local counts to the session's
      stats.add(localStats);
    } //end of try
200
    catch (const cta::exception::Exception & ex) {
Michael Davis's avatar
Michael Davis committed
201
202
      // We end up here because:
      //-- openReadFile brought us here (can't position to the file)
203
      //-- m_payload.append brought us here (error while reading the file)
Michael Davis's avatar
Michael Davis committed
204
      //-- checksum validation failed (after reading the last block from tape)
205
206
207
208
      // Record the error in the watchdog
      if (currentErrorToCount.size()) {
        watchdog.addToErrorCount(currentErrorToCount);
      }
209
210
      // This is an error case. Log and signal to the disk write task
      { 
Victor Kotlyar's avatar
Victor Kotlyar committed
211
212
        cta::log::LogContext::ScopedParam sp0(lc, Param("fileBlock", fileBlock));
        cta::log::LogContext::ScopedParam sp1(lc, Param("ErrorMessage", ex.getMessageValue()));
Michael Davis's avatar
Michael Davis committed
213
        lc.log(cta::log::ERR, "Error reading a file in TapeReadFileTask");
214
215
      }
      {
Victor Kotlyar's avatar
Victor Kotlyar committed
216
217
        cta::log::LogContext lc2(lc.logger());
        lc2.logBacktrace(cta::log::ERR, ex.backtrace());
218
219
      }
      
220
221
      // mb might or might not be allocated at this point, but 
      // reportErrorToDiskTask will deal with the allocation if required.
222
      reportErrorToDiskTask(ex.getMessageValue(),666,mb); // TODO - Remove error code
223
    } //end of catch
224
    watchdog.fileFinished();
225
  }
226
227
228
229
  /**
   * Get a valid block and ask to cancel the disk write task
   */
  void reportCancellationToDiskTask(){
230
    MemBlock* mb =m_mm.getFreeBlock();
231
232
    mb->m_fSeq = m_retrieveJob->selectedTapeFile().fSeq;
    mb->m_fileid = m_retrieveJob->retrieveRequest.archiveFileID;
233
234
235
    //mark the block cancelled and push it (plus signal the end)
     mb->markAsCancelled();
     m_fifo.pushDataBlock(mb);
236
  }
237
238
239
private:
  /**
   * Do the actual report to the disk write task
240
241
   * @param errorMsg The error message we will give to the client
   * @param mb The mem block we will use
242
   */
243
  void reportErrorToDiskTask(const std::string& msg,int code,MemBlock* mb = NULL){
244
245
246
247
    //If we are not provided with a block, allocate it and
    // fill it up
    if (!mb) {
      mb=m_mm.getFreeBlock();
248
249
      mb->m_fSeq = m_retrieveJob->selectedTapeFile().fSeq;
      mb->m_fileid = m_retrieveJob->retrieveRequest.archiveFileID;
250
251
    }
    //mark the block failed and push it (plus signal the end)
252
     mb->markAsFailed(msg,code);
253
254
255
     m_fifo.pushDataBlock(mb);
     m_fifo.pushDataBlock(NULL);
   }
256
257
  /** 
   * Open the file on the tape. In case of failure, log and throw
258
   * Copying the unique_ptr on the calling point will give us the ownership of the 
259
   * object.
260
   * @return if successful, return an unique_ptr on the ReadFile we want
261
   */
262
  std::unique_ptr<castor::tape::tapeFile::ReadFile> openReadFile(
Victor Kotlyar's avatar
Victor Kotlyar committed
263
  castor::tape::tapeFile::ReadSession & rs, cta::log::LogContext & lc){
264

Victor Kotlyar's avatar
Victor Kotlyar committed
265
266
    using cta::log::Param;
    typedef cta::log::LogContext::ScopedParam ScopedParam;
267

268
    std::unique_ptr<castor::tape::tapeFile::ReadFile> rf;
269
    try {
270
      rf.reset(new castor::tape::tapeFile::ReadFile(&rs, *m_retrieveJob));
Victor Kotlyar's avatar
Victor Kotlyar committed
271
      lc.log(cta::log::DEBUG, "Successfully opened the tape file");
272
    } catch (cta::exception::Exception & ex) {
273
274
      // Log the error
      ScopedParam sp0(lc, Param("ErrorMessage", ex.getMessageValue()));
Victor Kotlyar's avatar
Victor Kotlyar committed
275
      lc.log(cta::log::ERR, "Failed to open tape file for reading");
276
277
278
279
      throw;
    }
    return rf;
  }
280
281
282
283
  
  /**
   * All we need to know about the file we are recalling
   */
284
  cta::RetrieveJob *m_retrieveJob;
285
286
287
288
  
  /**
   * The task (seen as a Y) that will consume all the blocks we read
   */
289
  DataConsumer & m_fifo;
290
291
292
293
  
  /**
   *  The MemoryManager from whom we get free memory blocks 
   */
294
295
  RecallMemoryManager & m_mm;

296
};
297
298
299
300
}
}
}
}
301