DataTransferSessionTest.cpp 114 KB
Newer Older
1
2
/*
 * @project        The CERN Tape Archive (CTA)
3
 * @copyright      Copyright(C) 2003-2021 CERN
4
5
6
7
 * @license        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 3 of the License, or
 *                 (at your option) any later version.
8
 *
9
10
11
12
 *                 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.
13
 *
14
15
16
 *                 You should have received a copy of the GNU General Public License
 *                 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
17

18
19
20
21
#define __STDC_CONSTANT_MACROS // For using stdint macros (stdint is included
// by inttypes.h, so we shoot first)
#include <stdint.h>
#include <inttypes.h>
22
#include <gtest/gtest.h>
23

24
#include "castor/messages/TapeserverProxyDummy.hpp"
25
#include "castor/tape/tapeserver/daemon/DataTransferSession.hpp"
26
#include "castor/tape/tapeserver/daemon/VolumeInfo.hpp"
27
28
#include "castor/tape/tapeserver/system/Wrapper.hpp"
#include "castor/tape/tapeserver/file/File.hpp"
29
#include "castor/tape/tapeserver/drive/FakeDrive.hpp"
30
#include "catalogue/InMemoryCatalogue.hpp"
31
32
#include "catalogue/OracleCatalogue.hpp"
#include "catalogue/OracleCatalogueSchema.hpp"
33
#include "common/exception/Exception.hpp"
34
#include "common/log/DummyLogger.hpp"
35
#include "common/log/StringLogger.hpp"
36
#include "common/log/StdoutLogger.hpp"
37
#include "common/make_unique.hpp"
38
#include "common/processCap/ProcessCapDummy.hpp"
39
#include "common/threading/Thread.hpp"
40
#include "common/utils/utils.hpp"
41
#include "mediachanger/MediaChangerFacade.hpp"
42
43
//#include "smc_struct.h"
//#include "scheduler/DummyScheduler.hpp"
44
#include "scheduler/OStoreDB/OStoreDBFactory.hpp"
45
#include "scheduler/MountType.hpp"
46
//#include "nameserver/NameServer.hpp"
47
#include "scheduler/Scheduler.hpp"
48
49
50
#include "scheduler/testingMocks/MockRetrieveMount.hpp"
#include "scheduler/testingMocks/MockArchiveJob.hpp"
#include "scheduler/testingMocks/MockArchiveMount.hpp"
51
#include "tests/TempFile.hpp"
52
#include "objectstore/BackendRadosTestSwitch.hpp"
53
#include "CleanerSession.hpp"
54

55
#include <dirent.h>
56
#include <fcntl.h>
57
#include <stdexcept>
Eric Cano's avatar
Eric Cano committed
58
59
60
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
61
62
#include <unistd.h>
#include <zlib.h>
Eric Cano's avatar
Eric Cano committed
63

64
using namespace castor::tape::tapeserver;
65
using namespace castor::tape::tapeserver::daemon;
66

Eric Cano's avatar
Eric Cano committed
67
namespace unitTests {
68

69
70
71
72
73
const uint32_t DISK_FILE_OWNER_UID = 9751;
const uint32_t DISK_FILE_GID = 9752;
const uint32_t DISK_FILE_SOME_USER = 9753;
const uint32_t DISK_FILE_SOME_GROUP = 9754;

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
namespace {

/**
 * This structure is used to parameterize scheduler tests.
 */
struct DataTransferSessionTestParam {
  cta::SchedulerDatabaseFactory &dbFactory;

  DataTransferSessionTestParam(
    cta::SchedulerDatabaseFactory &dbFactory):
    dbFactory(dbFactory) {
 }
}; // struct DataTransferSessionTest

}

/**
 * The data transfer test is a parameterized test.  It takes a pair of name server
 * and scheduler database factories as a parameter.
 */
class DataTransferSessionTest: public ::testing::TestWithParam<DataTransferSessionTestParam> {
public:
  
97
  DataTransferSessionTest():
98
    m_dummyLog("dummy", "dummy"){
99
  }
100

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

  class FailedToGetCatalogue: public std::exception {
  public:
    const char *what() const throw() {
      return "Failed to get catalogue";
    }
  };

  class FailedToGetScheduler: public std::exception {
  public:
    const char *what() const throw() {
      return "Failed to get scheduler";
    }
  };

116
117
118
119
120
121
122
123
124
#undef USE_ORACLE_CATALOGUE
#ifdef USE_ORACLE_CATALOGUE
  class OracleCatalogueExposingConnection: public cta::catalogue::OracleCatalogue {
  public:
    template <typename...Ts> OracleCatalogueExposingConnection(Ts&...args): cta::catalogue::OracleCatalogue(args...) {}
    cta::rdbms::Conn getConn() { return m_connPool.getConn(); }
  };
#endif
  
125
126
127
128
    virtual void SetUp() {
    using namespace cta;

    const DataTransferSessionTestParam &param = GetParam();
129
    const uint64_t nbConns = 1;
130
    const uint64_t nbArchiveFileListingConns = 1;
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#ifdef USE_ORACLE_CATALOGUE
    cta::rdbms::Login login=cta::rdbms::Login::parseFile("/etc/cta/cta-catalogue.conf");
    
    m_catalogue = cta::make_unique<OracleCatalogueExposingConnection>(m_dummyLog, login.username, login.password, login.database,
        nbConns, nbArchiveFileListingConns, maxTriesToConnect);
    try {
      // If we decide to create an oracle catalogue, we have to prepare it.
      // This is a striped down version of CreateSchemaCmd.
      OracleCatalogueExposingConnection & oracleCatalogue = dynamic_cast<OracleCatalogueExposingConnection &>(*m_catalogue);
      auto conn=oracleCatalogue.getConn();
      for (auto &name: conn.getTableNames())
        if (name=="CTA_CATALOGUE") throw cta::exception::Exception("In SetUp(): schema is already populated.");
      cta::catalogue::OracleCatalogueSchema schema;
      conn.executeNonQueries(schema.sql);
    } catch (std::bad_cast &) {}
#else
147
    //m_catalogue = cta::make_unique<catalogue::SchemaCreatingSqliteCatalogue>(m_tempSqliteFile.path(), nbConns);
148
    m_catalogue = cta::make_unique<catalogue::InMemoryCatalogue>(m_dummyLog, nbConns, nbArchiveFileListingConns);
149
#endif
150
    m_db = param.dbFactory.create(m_catalogue);
151
    m_scheduler = cta::make_unique<Scheduler>(*m_catalogue, *m_db, 5, 2*1000*1000);
152
    
153
154
    strncpy(m_tmpDir, "/tmp/DataTransferSessionTestXXXXXX", sizeof(m_tmpDir));
    if(!mkdtemp(m_tmpDir)) {
155
      const std::string errMsg = cta::utils::errnoToString(errno);
156
157
158
159
160
161
      std::ostringstream msg;
      msg << "Failed to create directory with template"
        " /tmp/DataTransferSessionTestXXXXXX: " << errMsg;
      bzero(m_tmpDir, sizeof(m_tmpDir));
      throw cta::exception::Exception(msg.str());
    }
162
    
163
164
165
    struct stat statBuf;
    bzero(&statBuf, sizeof(statBuf));
    if(stat(m_tmpDir, &statBuf)) {
166
      const std::string errMsg = cta::utils::errnoToString(errno);
167
168
169
170
171
172
173
174
      std::ostringstream msg;
      msg << "Failed to stat directory " << m_tmpDir << ": " << errMsg;
      throw cta::exception::Exception(msg.str());
    }

    std::ostringstream cmd;
    cmd << "touch " << m_tmpDir << "/hello";
    system(cmd.str().c_str());
175
176
  }

177
178
179
180
181
  virtual void TearDown() {
    m_scheduler.reset();
    m_catalogue.reset();
    m_db.reset();
    
182
183
184
185
186
187
188
    // If Setup() created a temporary directory
    if(m_tmpDir) {

      // Openn the directory
      std::unique_ptr<DIR, std::function<int(DIR*)>>
        dir(opendir(m_tmpDir), closedir);
      if(NULL == dir.get()) {
189
        const std::string errMsg = cta::utils::errnoToString(errno);
190
191
192
193
194
195
196
197
198
199
200
201
        std::ostringstream msg;
        msg << "Failed to open directory " << m_tmpDir << ": " << errMsg;
        throw cta::exception::Exception(msg.str());
      }

      // Delete each of the files within the directory
      struct dirent *entry = NULL;
      while((entry = readdir(dir.get()))) {
        const std::string entryName(entry->d_name);
        if(entryName != "." && entryName != "..") {
          const std::string entryPath = std::string(m_tmpDir) + "/" + entryName;
          if(unlink(entryPath.c_str())) {
202
            const std::string errMsg = cta::utils::errnoToString(errno);
203
204
205
206
207
208
209
210
211
            std::ostringstream msg;
            msg << "Failed to unlink " << entryPath;
            throw cta::exception::Exception(msg.str());
          }
        }
      }

      // Delete the now empty directory
      if(rmdir(m_tmpDir)) {
212
        const std::string errMsg = cta::utils::errnoToString(errno);
213
214
215
216
217
        std::ostringstream msg;
        msg << "Failed to delete directory " << m_tmpDir << ": " << errMsg;
        throw cta::exception::Exception(msg.str());
      }
    }
218
  }
219

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  cta::catalogue::Catalogue &getCatalogue() {
    cta::catalogue::Catalogue *const ptr = m_catalogue.get();
    if(NULL == ptr) {
      throw FailedToGetCatalogue();
    }
    return *ptr;
  }
    
  cta::Scheduler &getScheduler() {
    cta::Scheduler *const ptr = m_scheduler.get();
    if(NULL == ptr) {
      throw FailedToGetScheduler();
    }
    return *ptr;
  }
  
236
237
238
239
240
241
242
243
  cta::catalogue::CreateTapeAttributes getDefaultTape(){
    cta::catalogue::CreateTapeAttributes tape;
    tape.vid = s_vid;
    tape.mediaType = s_mediaType;
    tape.vendor = s_vendor;
    tape.logicalLibraryName = s_libraryName;
    tape.tapePoolName = s_tapePoolName;
    tape.full = false;
244
    tape.state = cta::common::dataStructures::Tape::ACTIVE;
245
246
247
248
    tape.comment = "Comment";
    return tape;
  }
  
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  cta::catalogue::CreateMountPolicyAttributes getDefaultMountPolicy() {
    cta::catalogue::CreateMountPolicyAttributes mountPolicy;
    mountPolicy.name = "mount_group";
    mountPolicy.archivePriority = 1;
    mountPolicy.minArchiveRequestAge = 2;
    mountPolicy.retrievePriority = 3;
    mountPolicy.minRetrieveRequestAge = 4;
    mountPolicy.comment = "create mount group";
    return mountPolicy; 
  }
  
  cta::catalogue::CreateMountPolicyAttributes getImmediateMountMountPolicy() {
    cta::catalogue::CreateMountPolicyAttributes mountPolicy;
    mountPolicy.name = "immediateMount";
    mountPolicy.archivePriority = 1000;
    mountPolicy.minArchiveRequestAge = 0;
    mountPolicy.retrievePriority = 1000;
    mountPolicy.minRetrieveRequestAge = 0;
    mountPolicy.comment = "Immediate mount";
    return mountPolicy; 
  }
  
271
272
273
274
275
276
277
278
279
  cta::common::dataStructures::VirtualOrganization getDefaultVirtualOrganization() {
    cta::common::dataStructures::VirtualOrganization vo;
    vo.name = "vo";
    vo.readMaxDrives = 1;
    vo.writeMaxDrives = 1;
    vo.comment = "comment";
    return vo;
  }
  
280
281
282
283
  void setupDefaultCatalogue() {
    using namespace cta;
    auto & catalogue=getCatalogue();

284
285
286
287
288
289
290
    auto mountPolicy = getDefaultMountPolicy();
    
    const std::string mountPolicyName = mountPolicy.name;
    const uint64_t archivePriority = mountPolicy.archivePriority;
    const uint64_t minArchiveRequestAge = mountPolicy.minArchiveRequestAge;
    const uint64_t retrievePriority = mountPolicy.retrievePriority;
    const uint64_t minRetrieveRequestAge = mountPolicy.minRetrieveRequestAge;
291
292
293
294
295
296
    const std::string mountPolicyComment = "create mount group";

    ASSERT_TRUE(catalogue.getMountPolicies().empty());

    catalogue.createMountPolicy(
      s_adminOnAdminHost,
297
      mountPolicy);
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

    const std::list<common::dataStructures::MountPolicy> groups = catalogue.getMountPolicies();
    ASSERT_EQ(1, groups.size());
    const common::dataStructures::MountPolicy group = groups.front();
    ASSERT_EQ(mountPolicyName, group.name);
    ASSERT_EQ(archivePriority, group.archivePriority);
    ASSERT_EQ(minArchiveRequestAge, group.archiveMinRequestAge);
    ASSERT_EQ(retrievePriority, group.retrievePriority);
    ASSERT_EQ(minRetrieveRequestAge, group.retrieveMinRequestAge);
    ASSERT_EQ(mountPolicyComment, group.comment);

    const std::string ruleComment = "create requester mount-rule";
    catalogue.createRequesterMountRule(s_adminOnAdminHost, mountPolicyName, s_diskInstance, s_userName, ruleComment);

    const std::list<common::dataStructures::RequesterMountRule> rules = catalogue.getRequesterMountRules();
    ASSERT_EQ(1, rules.size());

    const common::dataStructures::RequesterMountRule rule = rules.front();

    ASSERT_EQ(s_userName, rule.name);
    ASSERT_EQ(mountPolicyName, rule.mountPolicy);
    ASSERT_EQ(ruleComment, rule.comment);
    ASSERT_EQ(s_adminOnAdminHost.username, rule.creationLog.username);
    ASSERT_EQ(s_adminOnAdminHost.host, rule.creationLog.host);
    ASSERT_EQ(rule.creationLog, rule.lastModificationLog);

324
    cta::common::dataStructures::VirtualOrganization vo = getDefaultVirtualOrganization();
325
326
    catalogue.createVirtualOrganization(s_adminOnAdminHost,vo);
    
327
328
329
    common::dataStructures::StorageClass storageClass;
    storageClass.name = s_storageClassName;
    storageClass.nbCopies = 1;
330
    storageClass.vo.name = vo.name;
331
332
333
334
335
336
    storageClass.comment = "create storage class";
    m_catalogue->createStorageClass(s_adminOnAdminHost, storageClass);

    const uint16_t nbPartialTapes = 1;
    const std::string tapePoolComment = "Tape-pool comment";
    const bool tapePoolEncryption = false;
337
    const cta::optional<std::string> tapePoolSupply("value for the supply pool mechanism");
338
339
    
    ASSERT_NO_THROW(catalogue.createTapePool(s_adminOnAdminHost, s_tapePoolName, vo.name, nbPartialTapes, tapePoolEncryption,
340
      tapePoolSupply, tapePoolComment));
341
    const uint32_t copyNb = 1;
342
    const std::string archiveRouteComment = "Archive-route comment";
343
    catalogue.createArchiveRoute(s_adminOnAdminHost, s_storageClassName, copyNb, s_tapePoolName,
344
      archiveRouteComment);
345
346
347
    
    cta::catalogue::MediaType mediaType;
    mediaType.name = s_mediaType;
348
    mediaType.capacityInBytes = 12345678;
349
    mediaType.cartridge = "cartridge";
350
351
352
    mediaType.minLPos = 2696;
    mediaType.maxLPos = 171097;
    mediaType.nbWraps = 112;
353
354
    mediaType.comment = "comment";
    catalogue.createMediaType(s_adminOnAdminHost,mediaType);
355
  }
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
  
  /**
   * Returns the map of Fseqs given by RAO from a string containing CTA logs
   * @param log the string containing the CTA logs
   * @return the map that gives for each RAO call, the associated ordered Fseqs according to the RAO algorithm result
   */
  std::map<size_t, std::vector<std::string>> getRAOFseqs(const std::string & log){
    std::map<size_t,std::vector<std::string>> ret;
    std::string logCopy = log;
    std::string recallRAOOrderMsg = "Recall order of FSEQs using RAO: ";
    size_t recallRAOOrderMsgSize = recallRAOOrderMsg.size();
    size_t posRAOMsg = logCopy.find(recallRAOOrderMsg);
    size_t i = 0;
    while(posRAOMsg != std::string::npos){
      size_t posFirstFseq = posRAOMsg + recallRAOOrderMsgSize;
      size_t posLastFseq = logCopy.find("\"",posFirstFseq);
      std::string stringFseq = logCopy.substr(posFirstFseq,posLastFseq - posFirstFseq);
      cta::utils::splitString(stringFseq,' ',ret[i]);
      logCopy = logCopy.substr(posLastFseq);
      posRAOMsg = logCopy.find(recallRAOOrderMsg);
      i++;
    }
    return ret;
  }
380
381
382
383
384
385
386
387
388
389
390
391
392
393

private:

  // Prevent copying
  DataTransferSessionTest(const DataTransferSessionTest &) = delete;

  // Prevent assignment
  DataTransferSessionTest & operator= (const DataTransferSessionTest &) = delete;

  std::unique_ptr<cta::SchedulerDatabase> m_db;
  std::unique_ptr<cta::catalogue::Catalogue> m_catalogue;
  std::unique_ptr<cta::Scheduler> m_scheduler;
  
protected:
394
395
  cta::log::DummyLogger m_dummyLog;

396
397
398
399
400
401
402
  // Default parameters for storage classes, etc...
  const std::string s_userName = "user_name";
  const std::string s_diskInstance = "disk_instance";
  const std::string s_storageClassName = "TestStorageClass";
  const cta::common::dataStructures::SecurityIdentity s_adminOnAdminHost = { "admin1", "host1" };
  const std::string s_tapePoolName = "TestTapePool";
  const std::string s_libraryName = "TestLogicalLibrary";
403
  const std::string s_vid = "TstVid"; // We really need size <= 6 characters due to tape label format.
404
  const std::string s_mediaType = "LTO7M";
405
  const std::string s_vendor = "TestVendor";
406
  //TempFile m_tempSqliteFile;
407
408
409
410
411
412
413
  /**
   * Temporary directory created with mkdtemp that will be used to contain the
   * destination remote files of the tests that need to create them.
   *
   * Please note that a new temporary directory is created and deleted for each
   * test by the Setup() and TearDown() methods.
   */
414
  char m_tmpDir[100];
415

416
417
}; // class DataTransferSessionTest

418
TEST_P(DataTransferSessionTest, DataTransferSessionGooddayRecall) {
Eric Cano's avatar
Eric Cano committed
419
  // 0) Prepare the logger for everyone
420
  cta::log::StringLogger logger("dummy", "tapeServerUnitTest",cta::log::DEBUG);
421
  cta::log::LogContext logContext(logger);
Eric Cano's avatar
Eric Cano committed
422
  
423
  setupDefaultCatalogue();
424
  // 1) prepare the fake scheduler
425
  std::string vid = s_vid;
426
427
  // cta::MountType::Enum mountType = cta::MountType::RETRIEVE;

428
429
  // 3) Prepare the necessary environment (logger, plus system wrapper), 
  castor::tape::System::mockWrapper mockSys;
430
431
  mockSys.delegateToFake();
  mockSys.disableGMockCallsCounting();
432
  mockSys.fake.setupForVirtualDriveSLC6();
433
434
435
  //delete is unnecessary
  //pointer with ownership will be passed to the application,
  //which will do the delete 
436
  mockSys.fake.m_pathToDrive["/dev/nst0"] = new castor::tape::tapeserver::drive::FakeDrive;
437
438

  // 4) Create the scheduler
439
440
  auto & catalogue = getCatalogue();
  auto & scheduler = getScheduler();
441
  
442
  // Always use the same requester
443
  const cta::common::dataStructures::SecurityIdentity requester;
444
445
446
447

  // List to remember the path of each remote file so that the existance of the
  // files can be tested for at the end of the test
  std::list<std::string> remoteFilePaths;
448
  
449
450
  // 5) Create the environment for the migration to happen (library + tape) 
    const std::string libraryComment = "Library comment";
451
  const bool libraryIsDisabled = false;
452
  catalogue.createLogicalLibrary(s_adminOnAdminHost, s_libraryName,
453
    libraryIsDisabled, libraryComment);
454
455
456
457
458
459
  {
    auto libraries = catalogue.getLogicalLibraries();
    ASSERT_EQ(1, libraries.size());
    ASSERT_EQ(s_libraryName, libraries.front().name);
    ASSERT_EQ(libraryComment, libraries.front().comment);
  }
460
461

  {
462
    auto tape = getDefaultTape();
463
464
    catalogue.createTape(s_adminOnAdminHost, tape);
  }
465
  
466
  // 6) Prepare files for reading by writing them to the mock system
467
468
469
  {
    // Label the tape
    castor::tape::tapeFile::LabelSession ls(*mockSys.fake.m_pathToDrive["/dev/nst0"], 
470
        s_vid, false);
471
472
    mockSys.fake.m_pathToDrive["/dev/nst0"]->rewind();
    // And write to it
473
    castor::tape::tapeserver::daemon::VolumeInfo volInfo;
474
    volInfo.vid=s_vid;
475
    castor::tape::tapeFile::WriteSession ws(*mockSys.fake.m_pathToDrive["/dev/nst0"],
476
       volInfo , 0, true, false);
477
478
479

    // Write a few files on the virtual tape and modify the archive name space
    // so that it is in sync
480
    uint8_t data[1000];
481
    size_t archiveFileSize=sizeof(data);
482
483
    castor::tape::SCSI::Structures::zeroStruct(&data);
    for (int fseq=1; fseq <= 10 ; fseq ++) {
484
485
      // Create a path to a remote destination file
      std::ostringstream remoteFilePath;
486
      remoteFilePath << "file://" << m_tmpDir << "/test" << fseq;
487
488
      remoteFilePaths.push_back(remoteFilePath.str());

489
      // Create an archive file entry in the archive namespace
490
491
492
493
      auto tapeFileWrittenUP = cta::make_unique<cta::catalogue::TapeFileWritten>();
      auto &tapeFileWritten=*tapeFileWrittenUP;
      std::set<cta::catalogue::TapeItemWrittenPointer> tapeFileWrittenSet;
      tapeFileWrittenSet.insert(tapeFileWrittenUP.release());
494
      
495
      // Write the file to tape
496
      cta::MockArchiveMount mam(catalogue);
Eric Cano's avatar
Eric Cano committed
497
      std::unique_ptr<cta::ArchiveJob> aj(new cta::MockArchiveJob(&mam, catalogue));
498
499
500
      aj->tapeFile.fSeq = fseq;
      aj->archiveFile.archiveFileID = fseq;
      castor::tape::tapeFile::WriteFile wf(&ws, *aj, archiveFileSize);
501
      tapeFileWritten.blockId = wf.getBlockId();
502
      // Write the data (one block)
503
      wf.write(data, archiveFileSize);
504
505
      // Close the file
      wf.close();
506

507
508
      // Create file entry in the archive namespace
      tapeFileWritten.archiveFileId=fseq;
Michael Davis's avatar
Michael Davis committed
509
      tapeFileWritten.checksumBlob.insert(cta::checksum::ADLER32, cta::utils::getAdler32(data, archiveFileSize));
510
511
512
513
      tapeFileWritten.vid=volInfo.vid;
      tapeFileWritten.size=archiveFileSize;
      tapeFileWritten.fSeq=fseq;
      tapeFileWritten.copyNb=1;
514
515
      tapeFileWritten.diskInstance = s_diskInstance;
      tapeFileWritten.diskFileId = fseq;
516
      
517
518
      tapeFileWritten.diskFileOwnerUid = DISK_FILE_SOME_USER;
      tapeFileWritten.diskFileGid = DISK_FILE_SOME_GROUP;
519
520
      tapeFileWritten.storageClassName = s_storageClassName;
      tapeFileWritten.tapeDrive = "drive0";
521
      catalogue.filesWrittenToTape(tapeFileWrittenSet);
522

523
      // Schedule the retrieval of the file
Daniele Kruse's avatar
Daniele Kruse committed
524
      std::string diskInstance="disk_instance";
525
526
      cta::common::dataStructures::RetrieveRequest rReq;
      rReq.archiveFileID=fseq;
527
528
      rReq.requester.name = s_userName;
      rReq.requester.group = "someGroup";
529
      rReq.dstURL = remoteFilePaths.back();
530
      rReq.diskFileInfo.path = "path/to/file";
Michael Davis's avatar
Michael Davis committed
531
      rReq.isVerifyOnly = false;
532
      std::list<std::string> archiveFilePaths;
533
      scheduler.queueRetrieve(diskInstance, rReq, logContext);
534
535
    }
  }
536
  scheduler.waitSchedulerDbSubthreadsComplete();
537
538
    
  // 6) Report the drive's existence and put it up in the drive register.
539
  cta::tape::daemon::TpconfigLine driveConfig("T10D6116", "TestLogicalLibrary", "/dev/tape_T10D6116", "manual");
540
  cta::common::dataStructures::DriveInfo driveInfo;
541
  driveInfo.driveName=driveConfig.unitName;
542
543
  driveInfo.logicalLibrary=driveConfig.logicalLibrary;
  driveInfo.host=="host";
544
  // We need to create the drive in the registry before being able to put it up.
545
  scheduler.reportDriveStatus(driveInfo, cta::common::dataStructures::MountType::NoMount, cta::common::dataStructures::DriveStatus::Down, logContext);
546
547
548
549
  cta::common::dataStructures::DesiredDriveState driveState;
  driveState.up = true;
  driveState.forceDown = false;
  scheduler.setDesiredDriveState(s_adminOnAdminHost, driveConfig.unitName, driveState, logContext);
550
551

  // 7) Create the data transfer session
552
553
554
555
556
557
  DataTransferConfig castorConf;
  castorConf.bufsz = 1024*1024; // 1 MB memory buffers
  castorConf.nbBufs = 10;
  castorConf.bulkRequestRecallMaxBytes = UINT64_C(100)*1000*1000*1000;
  castorConf.bulkRequestRecallMaxFiles = 1000;
  castorConf.nbDiskThreads = 1;
558
  castorConf.tapeLoadTimeout = 300;
559
  cta::log::DummyLogger dummyLog("dummy", "dummy");
560
  cta::mediachanger::MediaChangerFacade mc(dummyLog);
561
  cta::server::ProcessCap capUtils;
562
  castor::messages::TapeserverProxyDummy initialProcess;
563
  castor::tape::tapeserver::daemon::DataTransferSession sess("tapeHost", logger, mockSys,
564
    driveConfig, mc, initialProcess, capUtils, castorConf, scheduler);
565

566
  // 8) Run the data transfer session
567
  sess.execute();
568

569
  // 9) Check the session git the correct VID
570
  ASSERT_EQ(s_vid, sess.getVid());
571

572
  // 10) Check the remote files exist and have the correct size
573
  for(auto & path: remoteFilePaths) {
574
575
    struct stat statBuf;
    bzero(&statBuf, sizeof(statBuf));
576
    const int statRc = stat(path.substr(7).c_str(), &statBuf); //remove the "file://" for stat-ing
577
    ASSERT_EQ(0, statRc);
578
    ASSERT_EQ(1000, statBuf.st_size); //same size of data
579
  }
580
581
582
583

  // 10) Check logs
  std::string logToCheck = logger.getLog();
  logToCheck += "";
584
  ASSERT_NE(std::string::npos,logToCheck.find("MSG=\"Tape session started\" thread=\"TapeRead\" tapeDrive=\"T10D6116\" tapeVid=\"TstVid\" "
585
                                              "mountId=\"1\" vo=\"vo\" mediaType=\"LTO7M\" tapePool=\"TestTapePool\" "
586
587
                                              "logicalLibrary=\"TestLogicalLibrary\" mountType=\"Retrieve\" vendor=\"TestVendor\" "
                                              "capacityInBytes=\"12345678\""));
588
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" "
589
590
                                               "mountTotalCorrectedReadErrors=\"5\" mountTotalReadBytesProcessed=\"4096\" "
                                               "mountTotalUncorrectedReadErrors=\"1\" mountTotalNonMediumErrorCounts=\"2\""));
591
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" lifetimeMediumEfficiencyPrct=\"100\" "
592
593
594
595
                                               "mountReadEfficiencyPrct=\"100\" mountWriteEfficiencyPrct=\"100\" "
                                               "mountReadTransients=\"10\" "
                                               "mountServoTemps=\"10\" mountServoTransients=\"5\" mountTemps=\"100\" "
                                               "mountTotalReadRetries=\"25\" mountTotalWriteRetries=\"25\" mountWriteTransients=\"10\""));
596
}
597
598
599
600
601
602
603

TEST_P(DataTransferSessionTest, DataTransferSessionWrongRecall) {
  // This test is the same as the previous one, with 
  // wrong parameters set for the recall, so that we fail 
  // to recall the first file and cancel the second.

  // 0) Prepare the logger for everyone
604
  cta::log::StringLogger logger("dummy","tapeServerUnitTest",cta::log::DEBUG);
605
  cta::log::LogContext logContext(logger);
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
  
  setupDefaultCatalogue();
  // 1) prepare the fake scheduler
  std::string vid = s_vid;
  // cta::MountType::Enum mountType = cta::MountType::RETRIEVE;

  // 3) Prepare the necessary environment (logger, plus system wrapper), 
  castor::tape::System::mockWrapper mockSys;
  mockSys.delegateToFake();
  mockSys.disableGMockCallsCounting();
  mockSys.fake.setupForVirtualDriveSLC6();
  //delete is unnecessary
  //pointer with ownership will be passed to the application,
  //which will do the delete 
  mockSys.fake.m_pathToDrive["/dev/nst0"] = new castor::tape::tapeserver::drive::FakeDrive;

  // 4) Create the scheduler
  auto & catalogue = getCatalogue();
  auto & scheduler = getScheduler();

  // Always use the same requester
  const cta::common::dataStructures::SecurityIdentity requester;

  // List to remember the path of each remote file so that the existance of the
  // files can be tested for at the end of the test
  std::list<std::string> remoteFilePaths;
  
  // 5) Create the environment for the migration to happen (library + tape) 
    const std::string libraryComment = "Library comment";
635
  const bool libraryIsDisabled = false;
636
  catalogue.createLogicalLibrary(s_adminOnAdminHost, s_libraryName,
637
    libraryIsDisabled, libraryComment);
638
639
640
641
642
643
  {
    auto libraries = catalogue.getLogicalLibraries();
    ASSERT_EQ(1, libraries.size());
    ASSERT_EQ(s_libraryName, libraries.front().name);
    ASSERT_EQ(libraryComment, libraries.front().comment);
  }
644
645

  {
646
    auto tape = getDefaultTape();
647
648
    catalogue.createTape(s_adminOnAdminHost, tape);
  }
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
  
  // 6) Prepare files for reading by writing them to the mock system
  {
    // Label the tape
    castor::tape::tapeFile::LabelSession ls(*mockSys.fake.m_pathToDrive["/dev/nst0"], 
        s_vid, false);
    mockSys.fake.m_pathToDrive["/dev/nst0"]->rewind();
    // And write to it
    castor::tape::tapeserver::daemon::VolumeInfo volInfo;
    volInfo.vid=s_vid;
    castor::tape::tapeFile::WriteSession ws(*mockSys.fake.m_pathToDrive["/dev/nst0"],
       volInfo , 0, true, false);

    // Write a few files on the virtual tape and modify the archive name space
    // so that it is in sync
    uint8_t data[1000];
    castor::tape::SCSI::Structures::zeroStruct(&data);
    int fseq=1;
    {
      // Create a path to a remote destination file
      std::ostringstream remoteFilePath;
      remoteFilePath << "file://" << m_tmpDir << "/test" << fseq;
      remoteFilePaths.push_back(remoteFilePath.str());
      
      // Write the file to tape
      const uint64_t archiveFileSize = 1000;
      cta::MockArchiveMount mam(catalogue);
676
      cta::MockRetrieveMount mrm(catalogue);
Eric Cano's avatar
Eric Cano committed
677
      std::unique_ptr<cta::ArchiveJob> aj(new cta::MockArchiveJob(&mam, catalogue));
678
679
680
681
682
683
684
685
      aj->tapeFile.fSeq = fseq;
      aj->archiveFile.archiveFileID = 1000 + fseq;
      castor::tape::tapeFile::WriteFile wf(&ws, *aj, archiveFileSize);
      // Write the data (one block)
      wf.write(data, sizeof(data));
      // Close the file
      wf.close();
      
686
687
688
689
690
691
692
      {
        // Create a fictious file record on the tape to allow adding one to fseq=2 afterwards.
        auto tapeFileWrittenUP = cta::make_unique<cta::catalogue::TapeFileWritten>();
        auto &tapeFileWritten=*tapeFileWrittenUP;
        std::set<cta::catalogue::TapeItemWrittenPointer> tapeFileWrittenSet;
        tapeFileWrittenSet.insert(tapeFileWrittenUP.release());
        tapeFileWritten.archiveFileId=666;
Michael Davis's avatar
Michael Davis committed
693
        tapeFileWritten.checksumBlob.insert(cta::checksum::ADLER32, cta::checksum::ChecksumBlob::HexToByteArray("0xDEADBEEF"));
694
695
696
697
698
699
700
        tapeFileWritten.vid=volInfo.vid;
        tapeFileWritten.size=archiveFileSize;
        tapeFileWritten.fSeq=fseq;
        tapeFileWritten.blockId=0;
        tapeFileWritten.copyNb=1;
        tapeFileWritten.diskInstance = s_diskInstance;
        tapeFileWritten.diskFileId = std::to_string(fseq);
701
702
        tapeFileWritten.diskFileOwnerUid = DISK_FILE_SOME_USER;
        tapeFileWritten.diskFileGid = DISK_FILE_SOME_GROUP;
703
704
705
706
        tapeFileWritten.storageClassName = s_storageClassName;
        tapeFileWritten.tapeDrive = "drive0";
        catalogue.filesWrittenToTape(tapeFileWrittenSet);
      }
707
      
708
709
710
711
712
713
714
      {
        // Create an archive file entry in the archive catalogue
        auto tapeFileWrittenUP = cta::make_unique<cta::catalogue::TapeFileWritten>();
        auto &tapeFileWritten=*tapeFileWrittenUP;
        std::set<cta::catalogue::TapeItemWrittenPointer> tapeFileWrittenSet;
        tapeFileWrittenSet.insert(tapeFileWrittenUP.release());
        tapeFileWritten.archiveFileId=1000 + fseq;
Michael Davis's avatar
Michael Davis committed
715
        tapeFileWritten.checksumBlob.insert(cta::checksum::ADLER32, cta::utils::getAdler32(data, archiveFileSize));
716
717
718
719
720
721
722
        tapeFileWritten.vid=volInfo.vid;
        tapeFileWritten.size=archiveFileSize;
        tapeFileWritten.fSeq=fseq + 1;
        tapeFileWritten.blockId=wf.getBlockId() + 10000;
        tapeFileWritten.copyNb=1;
        tapeFileWritten.diskInstance = s_diskInstance;
        tapeFileWritten.diskFileId = std::to_string(fseq + 1);
723
        
724
725
        tapeFileWritten.diskFileOwnerUid = DISK_FILE_SOME_USER;
        tapeFileWritten.diskFileGid = DISK_FILE_SOME_GROUP;
726
727
728
729
        tapeFileWritten.storageClassName = s_storageClassName;
        tapeFileWritten.tapeDrive = "drive0";
        catalogue.filesWrittenToTape(tapeFileWrittenSet);
      }
730
731
732
733
734
735
736
737
738

      // Schedule the retrieval of the file
      std::string diskInstance="disk_instance";
      cta::common::dataStructures::RetrieveRequest rReq;
      rReq.archiveFileID=1000 + fseq;
      rReq.requester.name = s_userName;
      rReq.requester.group = "someGroup";
      rReq.dstURL = remoteFilePaths.back();
      std::list<std::string> archiveFilePaths;
739
      scheduler.queueRetrieve(diskInstance, rReq, logContext);
740
741
    }
  }
742
  scheduler.waitSchedulerDbSubthreadsComplete();
743
744
  
  // 6) Report the drive's existence and put it up in the drive register.
745
  cta::tape::daemon::TpconfigLine driveConfig("T10D6116", "TestLogicalLibrary", "/dev/tape_T10D6116", "manual");
746
  cta::common::dataStructures::DriveInfo driveInfo;
747
  driveInfo.driveName=driveConfig.unitName;
748
749
  driveInfo.logicalLibrary=driveConfig.logicalLibrary;
  driveInfo.host=="host";
750
  // We need to create the drive in the registry before being able to put it up.
751
  scheduler.reportDriveStatus(driveInfo, cta::common::dataStructures::MountType::NoMount, cta::common::dataStructures::DriveStatus::Down, logContext);
752
753
754
755
  cta::common::dataStructures::DesiredDriveState driveState;
  driveState.up = true;
  driveState.forceDown = false;
  scheduler.setDesiredDriveState(s_adminOnAdminHost, driveConfig.unitName, driveState, logContext);
756
757
758
759
760
761
762
763

  // 7) Create the data transfer session
  DataTransferConfig castorConf;
  castorConf.bufsz = 1024*1024; // 1 MB memory buffers
  castorConf.nbBufs = 10;
  castorConf.bulkRequestRecallMaxBytes = UINT64_C(100)*1000*1000*1000;
  castorConf.bulkRequestRecallMaxFiles = 1000;
  castorConf.nbDiskThreads = 1;
764
  castorConf.tapeLoadTimeout = 300;
765
  cta::log::DummyLogger dummyLog("dummy", "dummy");
766
  cta::mediachanger::MediaChangerFacade mc(dummyLog);
767
  cta::server::ProcessCap capUtils;
768
769
  castor::messages::TapeserverProxyDummy initialProcess;
  DataTransferSession sess("tapeHost", logger, mockSys,
770
    driveConfig, mc, initialProcess, capUtils, castorConf, scheduler);
771
772

  // 8) Run the data transfer session
773
  sess.execute();
774
775
776
777
778
779
780

  // 9) Check the session git the correct VID
  ASSERT_EQ(s_vid, sess.getVid());

  // 10) Check the remote files exist and have the correct size
  std::string temp = logger.getLog();
  ASSERT_NE(std::string::npos, logger.getLog().find("trying to position beyond the end of data"));
781
782
783
784

  // 11) Check logs for drive statistics
  std::string logToCheck = logger.getLog();
  logToCheck += "";
785
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" "
786
787
                                               "mountTotalCorrectedReadErrors=\"5\" mountTotalReadBytesProcessed=\"4096\" "
                                               "mountTotalUncorrectedReadErrors=\"1\" mountTotalNonMediumErrorCounts=\"2\""));
788
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" lifetimeMediumEfficiencyPrct=\"100\" "
789
790
791
792
                                               "mountReadEfficiencyPrct=\"100\" mountWriteEfficiencyPrct=\"100\" "
                                               "mountReadTransients=\"10\" "
                                               "mountServoTemps=\"10\" mountServoTransients=\"5\" mountTemps=\"100\" "
                                               "mountTotalReadRetries=\"25\" mountTotalWriteRetries=\"25\" mountWriteTransients=\"10\""));
793
794
}

795
796
TEST_P(DataTransferSessionTest, DataTransferSessionRAORecall) {
  // 0) Prepare the logger for everyone
797
  cta::log::StringLogger logger("dummy","tapeServerUnitTest",cta::log::DEBUG);
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
  cta::log::LogContext logContext(logger);
  
  setupDefaultCatalogue();
  // 1) prepare the fake scheduler
  std::string vid = s_vid;
  // cta::MountType::Enum mountType = cta::MountType::RETRIEVE;

  // 3) Prepare the necessary environment (logger, plus system wrapper), 
  castor::tape::System::mockWrapper mockSys;
  mockSys.delegateToFake();
  mockSys.disableGMockCallsCounting();
  mockSys.fake.setupForVirtualDriveSLC6();
  //delete is unnecessary
  //pointer with ownership will be passed to the application,
  //which will do the delete 
  mockSys.fake.m_pathToDrive["/dev/nst0"] = new castor::tape::tapeserver::drive::FakeDrive;

  // 4) Create the scheduler
  auto & catalogue = getCatalogue();
  auto & scheduler = getScheduler();
  
  // Always use the same requester
  const cta::common::dataStructures::SecurityIdentity requester;

  // List to remember the path of each remote file so that the existance of the
  // files can be tested for at the end of the test
  std::list<std::string> remoteFilePaths;
  
  // 5) Create the environment for the migration to happen (library + tape) 
    const std::string libraryComment = "Library comment";
828
  const bool libraryIsDisabled = false;
829
  catalogue.createLogicalLibrary(s_adminOnAdminHost, s_libraryName,
830
    libraryIsDisabled, libraryComment);
831
832
833
834
835
836
  {
    auto libraries = catalogue.getLogicalLibraries();
    ASSERT_EQ(1, libraries.size());
    ASSERT_EQ(s_libraryName, libraries.front().name);
    ASSERT_EQ(libraryComment, libraries.front().comment);
  }
837
838

  {
839
    auto tape = getDefaultTape();
840
841
    catalogue.createTape(s_adminOnAdminHost, tape);
  }
842

Cristina Moraru's avatar
Cristina Moraru committed
843
844
  int MAX_RECALLS = 50;
  int MAX_BULK_RECALLS = 31;
845
846
  std::map<size_t,std::vector<std::string>> expectedRAOFseqOrder;
  //RAO for the fake drive is a std::reverse
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
  // 6) Prepare files for reading by writing them to the mock system
  {
    // Label the tape
    castor::tape::tapeFile::LabelSession ls(*mockSys.fake.m_pathToDrive["/dev/nst0"], 
        s_vid, false);
    mockSys.fake.m_pathToDrive["/dev/nst0"]->rewind();
    // And write to it
    castor::tape::tapeserver::daemon::VolumeInfo volInfo;
    volInfo.vid=s_vid;
    castor::tape::tapeFile::WriteSession ws(*mockSys.fake.m_pathToDrive["/dev/nst0"],
       volInfo , 0, true, false);

    // Write a few files on the virtual tape and modify the archive name space
    // so that it is in sync
    uint8_t data[1000];
    size_t archiveFileSize=sizeof(data);
    castor::tape::SCSI::Structures::zeroStruct(&data);
    int fseq;
    for (fseq=1; fseq <= MAX_RECALLS ; fseq ++) {
866
      expectedRAOFseqOrder[fseq / MAX_BULK_RECALLS].push_back(std::to_string(fseq));
867
868
869
870
871
872
      // Create a path to a remote destination file
      std::ostringstream remoteFilePath;
      remoteFilePath << "file://" << m_tmpDir << "/test" << fseq;
      remoteFilePaths.push_back(remoteFilePath.str());

      // Create an archive file entry in the archive namespace
873
874
875
876
      auto tapeFileWrittenUP = cta::make_unique<cta::catalogue::TapeFileWritten>();
      auto &tapeFileWritten=*tapeFileWrittenUP;
      std::set<cta::catalogue::TapeItemWrittenPointer> tapeFileWrittenSet;
      tapeFileWrittenSet.insert(tapeFileWrittenUP.release());
877
878
879
      
      // Write the file to tape
      cta::MockArchiveMount mam(catalogue);
Eric Cano's avatar
Eric Cano committed
880
      std::unique_ptr<cta::ArchiveJob> aj(new cta::MockArchiveJob(&mam, catalogue));
881
882
883
884
885
886
887
888
889
890
891
      aj->tapeFile.fSeq = fseq;
      aj->archiveFile.archiveFileID = fseq;
      castor::tape::tapeFile::WriteFile wf(&ws, *aj, archiveFileSize);
      tapeFileWritten.blockId = wf.getBlockId();
      // Write the data (one block)
      wf.write(data, archiveFileSize);
      // Close the file
      wf.close();

      // Create file entry in the archive namespace
      tapeFileWritten.archiveFileId=fseq;
Michael Davis's avatar
Michael Davis committed
892
      tapeFileWritten.checksumBlob.insert(cta::checksum::ADLER32, cta::utils::getAdler32(data, archiveFileSize));
893
894
895
896
897
898
      tapeFileWritten.vid=volInfo.vid;
      tapeFileWritten.size=archiveFileSize;
      tapeFileWritten.fSeq=fseq;
      tapeFileWritten.copyNb=1;
      tapeFileWritten.diskInstance = s_diskInstance;
      tapeFileWritten.diskFileId = fseq;
899
      
900
901
      tapeFileWritten.diskFileOwnerUid = DISK_FILE_SOME_USER;
      tapeFileWritten.diskFileGid = DISK_FILE_SOME_GROUP;
902
903
      tapeFileWritten.storageClassName = s_storageClassName;
      tapeFileWritten.tapeDrive = "drive0";
904
      catalogue.filesWrittenToTape(tapeFileWrittenSet);
905
906
907
908
909
910
911
912

      // Schedule the retrieval of the file
      std::string diskInstance="disk_instance";
      cta::common::dataStructures::RetrieveRequest rReq;
      rReq.archiveFileID=fseq;
      rReq.requester.name = s_userName;
      rReq.requester.group = "someGroup";
      rReq.dstURL = remoteFilePaths.back();
Michael Davis's avatar
Michael Davis committed
913
      rReq.isVerifyOnly = false;
914
915
916
      std::list<std::string> archiveFilePaths;
      scheduler.queueRetrieve(diskInstance, rReq, logContext);

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
    }
  }
  //As RAO with the fakedrive is a std::reverse of the vector of the files given in parameter,
  //we reverse all expected fseqs vectors
  std::reverse(expectedRAOFseqOrder[0].begin(),expectedRAOFseqOrder[0].end());
  std::reverse(expectedRAOFseqOrder[1].begin(),expectedRAOFseqOrder[1].end());
  scheduler.waitSchedulerDbSubthreadsComplete();
    
  // 6) Report the drive's existence and put it up in the drive register.
  cta::tape::daemon::TpconfigLine driveConfig("T10D6116", "TestLogicalLibrary", "/dev/tape_T10D6116", "manual");
  cta::common::dataStructures::DriveInfo driveInfo;
  driveInfo.driveName=driveConfig.unitName;
  driveInfo.logicalLibrary=driveConfig.rawLibrarySlot;
  // We need to create the drive in the registry before being able to put it up.
  scheduler.reportDriveStatus(driveInfo, cta::common::dataStructures::MountType::NoMount, cta::common::dataStructures::DriveStatus::Down, logContext);
  cta::common::dataStructures::DesiredDriveState driveState;
  driveState.up = true;
  driveState.forceDown = false;
  scheduler.setDesiredDriveState(s_adminOnAdminHost, driveConfig.unitName, driveState, logContext);
936

937
938
939
940
941
942
943
944
  // 7) Create the data transfer session
  DataTransferConfig castorConf;
  castorConf.bufsz = 1024*1024; // 1 MB memory buffers
  castorConf.nbBufs = 10;
  castorConf.bulkRequestRecallMaxBytes = UINT64_C(100)*1000*1000*1000;
  castorConf.bulkRequestRecallMaxFiles = MAX_BULK_RECALLS - 1;
  castorConf.nbDiskThreads = 1;
  castorConf.useRAO = true;
945
  castorConf.tapeLoadTimeout = 300;
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
  cta::log::DummyLogger dummyLog("dummy", "dummy");
  cta::mediachanger::MediaChangerFacade mc(dummyLog);
  cta::server::ProcessCap capUtils;
  castor::messages::TapeserverProxyDummy initialProcess;
  castor::tape::tapeserver::daemon::DataTransferSession sess("tapeHost", logger, mockSys,
    driveConfig, mc, initialProcess, capUtils, castorConf, scheduler);

  // 8) Run the data transfer session
  sess.execute();

  // 9) Check the session git the correct VID
  ASSERT_EQ(s_vid, sess.getVid());

  // 10) Check the remote files exist and have the correct size
  for(auto & path: remoteFilePaths) {
    struct stat statBuf;
    bzero(&statBuf, sizeof(statBuf));
    const int statRc = stat(path.substr(7).c_str(), &statBuf); //remove the "file://" for stat-ing
    ASSERT_EQ(0, statRc);
    ASSERT_EQ(1000, statBuf.st_size); //same size of data
  }

  // 10) Check logs
  std::string logToCheck = logger.getLog();
  logToCheck += "";
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" "
                                               "mountTotalCorrectedReadErrors=\"5\" mountTotalReadBytesProcessed=\"4096\" "
                                               "mountTotalUncorrectedReadErrors=\"1\" mountTotalNonMediumErrorCounts=\"2\""));
  ASSERT_NE(std::string::npos, logToCheck.find("firmwareVersion=\"123A\" serialNumber=\"123456\" lifetimeMediumEfficiencyPrct=\"100\" "
                                               "mountReadEfficiencyPrct=\"100\" mountWriteEfficiencyPrct=\"100\" "
                                               "mountReadTransients=\"10\" "
                                               "mountServoTemps=\"10\" mountServoTransients=\"5\" mountTemps=\"100\" "
                                               "mountTotalReadRetries=\"25\" mountTotalWriteRetries=\"25\" mountWriteTransients=\"10\""));
  
  ASSERT_EQ(expectedRAOFseqOrder,getRAOFseqs(logToCheck));
}

TEST_P(DataTransferSessionTest, DataTransferSessionRAORecallLinearAlgorithm) {
  // 0) Prepare the logger for everyone
  cta::log::StringLogger logger("dummy","tapeServerUnitTest",cta::log::DEBUG);
  cta::log::LogContext logContext(logger);
  
  setupDefaultCatalogue();
  // 1) prepare the fake scheduler
  std::string vid = s_vid;
  // cta::MountType::Enum mountType = cta::MountType::RETRIEVE;

  // 3) Prepare the necessary environment (logger, plus system wrapper), 
  castor::tape::System::mockWrapper mockSys;
  mockSys.delegateToFake();
  mockSys.disableGMockCallsCounting();
  mockSys.fake.setupForVirtualDriveSLC6();
  //delete is unnecessary
  //pointer with ownership will be passed to the application,
  //which will do the delete 
  mockSys.fake.m_pathToDrive["/dev/nst0"] = new castor::tape::tapeserver::drive::FakeNonRAODrive;

  // 4) Create the scheduler
  auto & catalogue = getCatalogue();
  auto & scheduler = getScheduler();
  
  // Always use the same requester
  const cta::common::dataStructures::SecurityIdentity requester;

  // List to remember the path of each remote file so that the existance of the
  // files can be tested for at the end of the test
  std::list<std::string> remoteFilePaths;
  
  // 5) Create the environment for the migration to happen (library + tape) 
    const std::string libraryComment = "Library comment";
  const bool libraryIsDisabled = false;
  catalogue.createLogicalLibrary(s_adminOnAdminHost, s_libraryName,
    libraryIsDisabled, libraryComment);
  {
    auto libraries = catalogue.getLogicalLibraries();
    ASSERT_EQ(1, libraries.size());
    ASSERT_EQ(s_libraryName, libraries.front().name);
    ASSERT_EQ(libraryComment, libraries.front().comment);
  }

  {
1027
    auto tape = getDefaultTape();
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    catalogue.createTape(s_adminOnAdminHost, tape);
  }

  int MAX_RECALLS = 50;
  int MAX_BULK_RECALLS = 31;
  std::map<size_t,std::vector<std::string>> expectedRAOOrder;
  // 6) Prepare files for reading by writing them to the mock system
  {
    // Label the tape
    castor::tape::tapeFile::LabelSession ls(*mockSys.fake.m_pathToDrive["/dev/nst0"], 
        s_vid, false);
    mockSys.fake.m_pathToDrive["/dev/nst0"]->rewind();
    // And write to it
    castor::tape::tapeserver::daemon::VolumeInfo volInfo;
    volInfo.vid=s_vid;
    castor::tape::tapeFile::WriteSession ws(*mockSys.fake.m_pathToDrive["/dev/nst0"],
       volInfo , 0, true, false);

    // Write a few files on the virtual tape and modify the archive name space
    // so that it is in sync
    uint8_t data[1000];
    size_t archiveFileSize=sizeof(data);
    castor::tape::SCSI::Structures::zeroStruct(&data);
    int fseq;
    //For the RAO orders we will have two rao calls : first with 30 files,
    //the second with 20 files
    for (fseq=1; fseq <= MAX_RECALLS ; fseq ++) {
      expectedRAOOrder[fseq / MAX_BULK_RECALLS].push_back(std::to_string(fseq));
      // Create a path to a remote destination file
      std::ostringstream remoteFilePath;
      remoteFilePath << "file://" << m_tmpDir << "/test" << fseq;
      remoteFilePaths.push_back(remoteFilePath.str());

      // Create an archive file entry in the archive namespace
      auto tapeFileWrittenUP = cta::make_unique<cta::catalogue::TapeFileWritten>();
      auto &tapeFileWritten=*tapeFileWrittenUP;
      std::set<cta::catalogue::TapeItemWrittenPointer> tapeFileWrittenSet;
      tapeFileWrittenSet.insert(tapeFileWrittenUP.release());
      
      // Write the file to tape
      cta::MockArchiveMount mam(catalogue);
      std::unique_ptr<cta::ArchiveJob> aj(new cta::MockArchiveJob(&mam, catalogue));
      aj->tapeFile.fSeq = fseq;
      aj->archiveFile.archiveFileID = fseq;
      castor::tape::tapeFile::WriteFile wf(&ws, *aj, archiveFileSize);
      tapeFileWritten.blockId = wf.getBlockId();
      // Write the data (one block)
      wf.write(data, archiveFileSize);
      // Close the file
      wf.close();

      // Create file entry in the archive namespace
      tapeFileWritten.archiveFileId=fseq;
      tapeFileWritten.checksumBlob.insert(cta::checksum::ADLER32, cta::utils::getAdler32(data, archiveFileSize));
      tapeFileWritten.vid=volInfo.vid;
      tapeFileWritten.size=archiveFileSize;
      tapeFileWritten.fSeq=fseq;
      tapeFileWritten.copyNb=1;
      tapeFileWritten.diskInstance = s_diskInstance;
      tapeFileWritten.diskFileId = fseq;
      
      tapeFileWritten.diskFileOwnerUid = DISK_FILE_SOME_USER;
      tapeFileWritten.diskFileGid = DISK_FILE_SOME_GROUP;
      tapeFileWritten.storageClassName = s_storageClassName;
      tapeFileWritten.tapeDrive = "drive0";
      catalogue.filesWrittenToTape(tapeFileWrittenSet);

      // Schedule the retrieval of the file
      std::string diskInstance="disk_instance";
      cta::common::dataStructures::RetrieveRequest rReq;
      rReq.archiveFileID=fseq;
      rReq.requester.name = s_userName;
      rReq.requester.group = "someGroup";
      rReq.dstURL = remoteFilePaths.back();
Michael Davis's avatar
Michael Davis committed
1102
      rReq.isVerifyOnly = false;
1103
1104
      std::list<std::string> archiveFilePaths;
      scheduler.queueRetrieve(diskInstance, rReq, logContext);
1105
1106
    }
  }
1107
  scheduler.waitSchedulerDbSubthreadsComplete();
1108
1109
1110
1111
1112
1113
1114
    
  // 6) Report the drive's existence and put it up in the drive register.
  cta::tape::daemon::TpconfigLine driveConfig("T10D6116", "TestLogicalLibrary", "/dev/tape_T10D6116", "manual");
  cta::common::dataStructures::DriveInfo driveInfo;
  driveInfo.driveName=driveConfig.unitName;
  driveInfo.logicalLibrary=driveConfig.rawLibrarySlot;
  // We need to create the drive in the registry before being able to put it up.
1115
  scheduler.reportDriveStatus(driveInfo, cta::common::dataStructures::MountType::NoMount, cta::common::dataStructures::DriveStatus::Down, logContext);
1116
1117
1118
1119
  cta::common::dataStructures::DesiredDriveState driveState;
  driveState.up = true;
  driveState.forceDown = false;
  scheduler.setDesiredDriveState(s_adminOnAdminHost, driveConfig.unitName, driveState, logContext);
1120
1121
1122
1123
1124
1125
1126
1127
1128

  // 7) Create the data transfer session
  DataTransferConfig castorConf;
  castorConf.bufsz = 1024*1024; // 1 MB memory buffers
  castorConf.nbBufs = 10;
  castorConf.bulkRequestRecallMaxBytes = UINT64_C(100)*1000*1000*1000;
  castorConf.bulkRequestRecallMaxFiles = MAX_BULK_RECALLS - 1;
  castorConf.nbDiskThreads = 1;
  castorConf.useRAO = true;
1129
  castorConf.raoLtoAlgorithm = "linear";
1130
  castorConf.tapeLoadTimeout = 300;
1131
  cta::log::DummyLogger dummyLog("dummy", "dummy");
1132
1133
1134
1135
  cta::mediachanger::MediaChangerFacade mc(dummyLog);
  cta::server::ProcessCap capUtils;
  castor::messages::TapeserverProxyDummy initialProcess;
  castor::tape::tapeserver::daemon::DataTransferSession sess("tapeHost", logger, mockSys,
1136
    driveConfig, mc, initialProcess, capUtils, castorConf, scheduler);
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155