TapeReadTask.hpp 11.1 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
47
48
49
50
51
  /**
   * COnstructor
   * @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;
68
    
69
    bool isRepack = m_retrieveJob->m_dbJob->isRepack;
70
    // Set the common context for all the coming logs (file info)
Victor Kotlyar's avatar
Victor Kotlyar committed
71
    cta::log::ScopedParamContainer params(lc);
72
    params.add("fileId", m_retrieveJob->archiveFile.archiveFileID)
73
74
          .add("BlockId", m_retrieveJob->selectedTapeFile().blockId)
          .add("fSeq", m_retrieveJob->selectedTapeFile().fSeq)
75
76
          .add("dstURL", m_retrieveJob->retrieveRequest.dstURL)
          .add("isRepack",isRepack);
77
    
78
79
    // We will clock the stats for the file itself, and eventually add those
    // stats to the session's.
80
    TapeSessionStats localStats;
81
    std::string LBPMode;
Victor Kotlyar's avatar
Victor Kotlyar committed
82
83
    cta::utils::Timer localTime;
    cta::utils::Timer totalTime(localTime);
84

85
86
    // Read the file and transmit it
    bool stillReading = true;
87
88
    //for counting how many mem blocks have used and how many tape blocks
    //(because one mem block can hold several tape blocks
89
90
    int fileBlock = 0;
    int tapeBlock = 0;
91
92
93
94
95
    // 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 = "";
96
97
    MemBlock* mb=NULL;
    try {
98
      currentErrorToCount = "Error_tapePositionForRead";
99
      std::unique_ptr<castor::tape::tapeFile::ReadFile> rf(openReadFile(rs,lc));
100
      LBPMode = rf->getLBPMode();
101
102
103
      // At that point we already read the header.
      localStats.headerVolume += TapeSessionStats::headerVolumePerFile;

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

Victor Kotlyar's avatar
Victor Kotlyar committed
244
245
    using cta::log::Param;
    typedef cta::log::LogContext::ScopedParam ScopedParam;
246

247
    std::unique_ptr<castor::tape::tapeFile::ReadFile> rf;
248
    try {
249
      rf.reset(new castor::tape::tapeFile::ReadFile(&rs, *m_retrieveJob));
Victor Kotlyar's avatar
Victor Kotlyar committed
250
      lc.log(cta::log::DEBUG, "Successfully opened the tape file");
251
    } catch (cta::exception::Exception & ex) {
252
253
      // Log the error
      ScopedParam sp0(lc, Param("ErrorMessage", ex.getMessageValue()));
Victor Kotlyar's avatar
Victor Kotlyar committed
254
      lc.log(cta::log::ERR, "Failed to open tape file for reading");
255
256
257
258
      throw;
    }
    return rf;
  }
259
260
261
262
  
  /**
   * All we need to know about the file we are recalling
   */
263
  cta::RetrieveJob *m_retrieveJob;
264
265
266
267
  
  /**
   * The task (seen as a Y) that will consume all the blocks we read
   */
268
  DataConsumer & m_fifo;
269
270
271
272
  
  /**
   *  The MemoryManager from whom we get free memory blocks 
   */
273
274
  RecallMemoryManager & m_mm;

275
};
276
277
278
279
}
}
}
}
280