MysqlCatalogue.cpp 29.4 KB
Newer Older
Tao Lin's avatar
Tao Lin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * The CERN Tape Archive(CTA) project
 * Copyright(C) 2015  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 3 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, see <http://www.gnu.org/licenses/>.
 */

#include "catalogue/ArchiveFileRow.hpp"
20
#include "catalogue/ArchiveFileRowWithoutTimestamps.hpp"
Tao Lin's avatar
Tao Lin committed
21
22
23
24
25
26
27
28
29
#include "catalogue/MysqlCatalogueSchema.hpp"
#include "catalogue/MysqlCatalogue.hpp"
#include "common/exception/Exception.hpp"
#include "common/exception/UserError.hpp"
#include "common/make_unique.hpp"
#include "common/threading/MutexLocker.hpp"
#include "common/Timer.hpp"
#include "common/utils/utils.hpp"
#include "rdbms/AutoRollback.hpp"
30
31
#include "rdbms/ConstraintError.hpp"
#include "rdbms/PrimaryKeyError.hpp"
32
#include "common/log/TimingList.hpp"
Tao Lin's avatar
Tao Lin committed
33
34
35
36
37
38
39
40
41
42
43

namespace cta {
namespace catalogue {

//------------------------------------------------------------------------------
// constructor
//------------------------------------------------------------------------------
MysqlCatalogue::MysqlCatalogue(
  log::Logger &log,
  const rdbms::Login &login,
  const uint64_t nbConns,
44
  const uint64_t nbArchiveFileListingConns):
Tao Lin's avatar
Tao Lin committed
45
46
47
48
49
50
  RdbmsCatalogue(
    log,
    rdbms::Login(rdbms::Login::DBTYPE_MYSQL, 
                 login.username, login.password, login.database,
                 login.hostname, login.port),
    nbConns,
51
    nbArchiveFileListingConns) {
Tao Lin's avatar
Tao Lin committed
52
53
54
55
56
57
58
59
}

//------------------------------------------------------------------------------
// destructor
//------------------------------------------------------------------------------
MysqlCatalogue::~MysqlCatalogue() {
}

60
61
62
63
//------------------------------------------------------------------------------
// createAndPopulateTempTableFxid
//------------------------------------------------------------------------------
std::string MysqlCatalogue::createAndPopulateTempTableFxid(rdbms::Conn &conn, const TapeFileSearchCriteria &tapeFileSearchCriteria) const {
64
  const std::string tempTableName = "TEMP_DISK_FXIDS";
65

66
67
68
69
70
71
72
73
74
75
76
77
  if(tapeFileSearchCriteria.diskFileIds) {
    try {
      std::string sql = "CREATE TEMPORARY TABLE " + tempTableName + "(DISK_FILE_ID VARCHAR(100))";
      try {
        conn.executeNonQuery(sql);
      } catch(exception::Exception &ex) {
        // MySQL does not drop temporary tables until the end of the session; trying to create another
        // temporary table in the same unit test will fail. If this happens, truncate the table and carry on.
        sql = "TRUNCATE TABLE " + tempTableName;
        conn.executeNonQuery(sql);
      }

78
79
80
81
82
83
      sql = "INSERT INTO " + tempTableName + " VALUES(:DISK_FILE_ID)";
      auto stmt = conn.createStmt(sql);
      for(auto &diskFileId : tapeFileSearchCriteria.diskFileIds.value()) {
        stmt.bindString(":DISK_FILE_ID", diskFileId);
        stmt.executeNonQuery();
      }
84
85
86
    } catch(exception::Exception &ex) {
      ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
      throw;
87
88
    }
  }
89
  return tempTableName;
90
91
}

Tao Lin's avatar
Tao Lin committed
92
93
94
95
96
97
//------------------------------------------------------------------------------
// getNextArchiveFileId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextArchiveFileId(rdbms::Conn &conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);
98
99
100

    conn.executeNonQuery("START TRANSACTION");

Tao Lin's avatar
Tao Lin committed
101
102
103
104
    {
      const char *const sql =
        "UPDATE ARCHIVE_FILE_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
105
      stmt.executeNonQuery();
Tao Lin's avatar
Tao Lin committed
106
107
108
109
110
111
112
    }

    uint64_t archiveFileId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
113
      auto rset = stmt.executeQuery();
Tao Lin's avatar
Tao Lin committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
      if(!rset.next()) {
        throw exception::Exception("ARCHIVE_FILE_ID table is empty");
      }
      archiveFileId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the ARCHIVE_FILE_ID table");
      }
    }
    conn.commit();

    return archiveFileId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//------------------------------------------------------------------------------
// getNextLogicalLibraryId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextLogicalLibraryId(rdbms::Conn &conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);

    conn.executeNonQuery("START TRANSACTION");

    {
      const char *const sql =
        "UPDATE LOGICAL_LIBRARY_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
      stmt.executeNonQuery();
    }

    uint64_t logicalLibraryId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
      auto rset = stmt.executeQuery();
      if(!rset.next()) {
        throw exception::Exception("LOGICAL_LIBRARY_ID table is empty");
      }
      logicalLibraryId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the LOGICAL_LIBRARY_ID table");
      }
    }
    conn.commit();

    return logicalLibraryId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//------------------------------------------------------------------------------
// getNextVirtualOrganizationId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextVirtualOrganizationId(rdbms::Conn& conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);

    conn.executeNonQuery("START TRANSACTION");

    {
      const char *const sql =
        "UPDATE VIRTUAL_ORGANIZATION_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
      stmt.executeNonQuery();
    }

    uint64_t virtualOrganizationId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
      auto rset = stmt.executeQuery();
      if(!rset.next()) {
        throw exception::Exception("VIRTUAL_ORGANIZATION_ID table is empty");
      }
      virtualOrganizationId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the VIRTUAL_ORGANIZATION_ID table");
      }
    }
    conn.commit();

    return virtualOrganizationId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//------------------------------------------------------------------------------
// getNextMediaTypeId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextMediaTypeId(rdbms::Conn &conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);

    conn.executeNonQuery("START TRANSACTION");

    {
      const char *const sql = "UPDATE MEDIA_TYPE_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
      stmt.executeNonQuery();
    }

    uint64_t id = 0;
    {
      const char *const sql = "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
      auto rset = stmt.executeQuery();
      if(!rset.next()) {
        throw exception::Exception("MEDIA_TYPE_ID table is empty");
      }
      id = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the MEDIA_TYPE_ID table");
      }
    }
    conn.commit();

    return id;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}
253

Tao Lin's avatar
Tao Lin committed
254
255
256
257
258
259
//------------------------------------------------------------------------------
// getNextStorageClassId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextStorageClassId(rdbms::Conn &conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);
260
261
262

    conn.executeNonQuery("START TRANSACTION");

Tao Lin's avatar
Tao Lin committed
263
264
265
266
    {
      const char *const sql =
        "UPDATE STORAGE_CLASS_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
267
      stmt.executeNonQuery();
Tao Lin's avatar
Tao Lin committed
268
269
270
271
272
273
274
    }

    uint64_t storageClassId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
275
      auto rset = stmt.executeQuery();
Tao Lin's avatar
Tao Lin committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
      if(!rset.next()) {
        throw exception::Exception("STORAGE_CLASS_ID table is empty");
      }
      storageClassId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the STORAGE_CLASS_ID table");
      }
    }
    conn.commit();

    return storageClassId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

//------------------------------------------------------------------------------
296
// getNextTapePoolId
Tao Lin's avatar
Tao Lin committed
297
//------------------------------------------------------------------------------
298
uint64_t MysqlCatalogue::getNextTapePoolId(rdbms::Conn &conn) {
Tao Lin's avatar
Tao Lin committed
299
  try {
300
    rdbms::AutoRollback autoRollback(conn);
Tao Lin's avatar
Tao Lin committed
301

302
    conn.executeNonQuery("START TRANSACTION");
Tao Lin's avatar
Tao Lin committed
303

304
305
306
307
308
309
    {
      const char *const sql =
        "UPDATE TAPE_POOL_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
      stmt.executeNonQuery();
    }
Tao Lin's avatar
Tao Lin committed
310

311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    uint64_t tapePoolId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
      auto rset = stmt.executeQuery();
      if(!rset.next()) {
        throw exception::Exception("TAPE_POOL_ID table is empty");
      }
      tapePoolId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the TAPE_POOL_ID table");
      }
    }
    conn.commit();
Tao Lin's avatar
Tao Lin committed
326

327
328
329
330
331
332
333
334
    return tapePoolId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}
Tao Lin's avatar
Tao Lin committed
335

Cedric Caffy's avatar
Cedric Caffy committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//------------------------------------------------------------------------------
// getNextFileRecyleLogId
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::getNextFileRecyleLogId(rdbms::Conn& conn) {
  try {
    rdbms::AutoRollback autoRollback(conn);

    conn.executeNonQuery("START TRANSACTION");

    {
      const char *const sql =
        "UPDATE FILE_RECYCLE_LOG_ID SET ID = LAST_INSERT_ID(ID + 1)";
      auto stmt = conn.createStmt(sql);
      stmt.executeNonQuery();
    }

    uint64_t fileRecycleLogId = 0;
    {
      const char *const sql =
        "SELECT LAST_INSERT_ID() AS ID ";
      auto stmt = conn.createStmt(sql);
      auto rset = stmt.executeQuery();
      if(!rset.next()) {
        throw exception::Exception("FILE_RECYCLE_LOG_ID table is empty");
      }
      fileRecycleLogId = rset.columnUint64("ID");
      if(rset.next()) {
        throw exception::Exception("Found more than one ID counter in the FILE_RECYCLE_LOG_ID table");
      }
    }
    conn.commit();

    return fileRecycleLogId;
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

377
378
379
380
381
382
383
384
//------------------------------------------------------------------------------
// selectTapeForUpdateAndGetLastFSeq
//------------------------------------------------------------------------------
uint64_t MysqlCatalogue::selectTapeForUpdateAndGetLastFSeq(rdbms::Conn &conn, const std::string &vid) {
  try {
    const char *const sql =
      "SELECT "
        "LAST_FSEQ AS LAST_FSEQ "
Tao Lin's avatar
Tao Lin committed
385
      "FROM "
386
        "TAPE "
Tao Lin's avatar
Tao Lin committed
387
      "WHERE "
388
        "VID = :VID "
Tao Lin's avatar
Tao Lin committed
389
390
391
      "FOR UPDATE";
    auto stmt = conn.createStmt(sql);
    stmt.bindString(":VID", vid);
392
    auto rset = stmt.executeQuery();
Tao Lin's avatar
Tao Lin committed
393
394
395
396
    if (!rset.next()) {
      throw exception::Exception(std::string("The tape with VID " + vid + " does not exist"));
    }

397
    return rset.columnUint64("LAST_FSEQ");
Tao Lin's avatar
Tao Lin committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

//------------------------------------------------------------------------------
// filesWrittenToTape
//------------------------------------------------------------------------------
void MysqlCatalogue::filesWrittenToTape(const std::set<TapeItemWrittenPointer> &events) {
  try {
    if(events.empty()) {
      return;
    }

    auto firstEventItor = events.cbegin();
    const auto &firstEvent = **firstEventItor;;
    checkTapeItemWrittenFieldsAreSet(__FUNCTION__, firstEvent);

    auto conn = m_connPool.getConn();
    rdbms::AutoRollback autoRollback(conn);

422
423
    conn.executeNonQuery("START TRANSACTION");

424
425
    const uint64_t lastFSeq = selectTapeForUpdateAndGetLastFSeq(conn, firstEvent.vid);
    uint64_t expectedFSeq = lastFSeq + 1;
426
    uint64_t totalLogicalBytesWritten = 0;
Tao Lin's avatar
Tao Lin committed
427
428
429
430
431
432
433
434
435
436

    for(const auto &eventP: events) {
      const auto & event = *eventP;
      checkTapeItemWrittenFieldsAreSet(__FUNCTION__, event);

      if(event.vid != firstEvent.vid) {
        throw exception::Exception(std::string("VID mismatch: expected=") + firstEvent.vid + " actual=" + event.vid);
      }

      if(expectedFSeq != event.fSeq) {
437
        exception::TapeFseqMismatch ex;
Tao Lin's avatar
Tao Lin committed
438
439
440
441
442
443
444
445
446
447
        ex.getMessage() << "FSeq mismatch for tape " << firstEvent.vid << ": expected=" << expectedFSeq << " actual=" <<
          firstEvent.fSeq;
        throw ex;
      }
      expectedFSeq++;
      
      
      try {
        // If this is a file (as opposed to a placeholder), do the full processing.
        const auto &fileEvent=dynamic_cast<const TapeFileWritten &>(event); 
448
        totalLogicalBytesWritten += fileEvent.size;
Tao Lin's avatar
Tao Lin committed
449
450
451
452
453
454
      } catch (std::bad_cast&) {}
    }

    auto lastEventItor = events.cend();
    lastEventItor--;
    const TapeItemWritten &lastEvent = **lastEventItor;
455
    updateTape(conn, lastEvent.vid, lastEvent.fSeq, totalLogicalBytesWritten, lastEvent.tapeDrive);
Tao Lin's avatar
Tao Lin committed
456
457
458
459
460

    for(const auto &event : events) {
      try {
        // If this is a file (as opposed to a placeholder), do the full processing.
        const auto &fileEvent=dynamic_cast<const TapeFileWritten &>(*event); 
461
        fileWrittenToTape(conn, fileEvent);
Tao Lin's avatar
Tao Lin committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
      } catch (std::bad_cast&) {}
    }
    conn.commit();
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

//------------------------------------------------------------------------------
// fileWrittenToTape
//------------------------------------------------------------------------------
476
void MysqlCatalogue::fileWrittenToTape(rdbms::Conn &conn, const TapeFileWritten &event) {
Tao Lin's avatar
Tao Lin committed
477
478
479
480
481
482
  try {
    checkTapeFileWrittenFieldsAreSet(__FUNCTION__, event);

    // Try to insert a row into the ARCHIVE_FILE table - it is normal this will
    // fail if another tape copy has already been written to tape
    try {
483
      ArchiveFileRowWithoutTimestamps row;
Tao Lin's avatar
Tao Lin committed
484
485
486
487
      row.archiveFileId = event.archiveFileId;
      row.diskFileId = event.diskFileId;
      row.diskInstance = event.diskInstance;
      row.size = event.size;
488
      row.checksumBlob = event.checksumBlob;
Tao Lin's avatar
Tao Lin committed
489
      row.storageClassName = event.storageClassName;
490
491
      row.diskFileOwnerUid = event.diskFileOwnerUid;
      row.diskFileGid = event.diskFileGid;
492
      insertArchiveFile(conn, row);
493
    } catch(rdbms::PrimaryKeyError &) {
Tao Lin's avatar
Tao Lin committed
494
495
496
497
      // Ignore this error
    }

    const time_t now = time(nullptr);
498
    const auto archiveFileRow = getArchiveFileRowById(conn, event.archiveFileId);
Tao Lin's avatar
Tao Lin committed
499

500
    if(nullptr == archiveFileRow) {
Tao Lin's avatar
Tao Lin committed
501
502
503
504
505
506
507
508
      // This should never happen
      exception::Exception ex;
      ex.getMessage() << "Failed to find archive file: archiveFileId=" << event.archiveFileId;
      throw ex;
    }

    std::ostringstream fileContext;
    fileContext << "archiveFileId=" << event.archiveFileId << ", diskInstanceName=" << event.diskInstance <<
509
      ", diskFileId=" << event.diskFileId;
Tao Lin's avatar
Tao Lin committed
510

511
    if(archiveFileRow->size != event.size) {
Tao Lin's avatar
Tao Lin committed
512
      catalogue::FileSizeMismatch ex;
513
      ex.getMessage() << "File size mismatch: expected=" << archiveFileRow->size << ", actual=" << event.size << ": "
Tao Lin's avatar
Tao Lin committed
514
515
516
517
        << fileContext.str();
      throw ex;
    }

518
    archiveFileRow->checksumBlob.validate(event.checksumBlob);
Tao Lin's avatar
Tao Lin committed
519
520
521
522
523
524

    // Insert the tape file
    common::dataStructures::TapeFile tapeFile;
    tapeFile.vid            = event.vid;
    tapeFile.fSeq           = event.fSeq;
    tapeFile.blockId        = event.blockId;
525
    tapeFile.fileSize       = event.size;
Tao Lin's avatar
Tao Lin committed
526
527
    tapeFile.copyNb         = event.copyNb;
    tapeFile.creationTime   = now;
528
    insertTapeFile(conn, tapeFile, event.archiveFileId);
Tao Lin's avatar
Tao Lin committed
529
530
531
532
533
534
535
536
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

537
538
539
//------------------------------------------------------------------------------
// deleteArchiveFile
//------------------------------------------------------------------------------
540
void MysqlCatalogue::DO_NOT_USE_deleteArchiveFile_DO_NOT_USE(const std::string &diskInstanceName, const uint64_t archiveFileId,
541
542
543
544
545
546
547
  log::LogContext &lc) {
  try {
    const char *selectSql =
      "SELECT "
        "ARCHIVE_FILE.ARCHIVE_FILE_ID AS ARCHIVE_FILE_ID,"
        "ARCHIVE_FILE.DISK_INSTANCE_NAME AS DISK_INSTANCE_NAME,"
        "ARCHIVE_FILE.DISK_FILE_ID AS DISK_FILE_ID,"
548
549
        "ARCHIVE_FILE.DISK_FILE_UID AS DISK_FILE_UID,"
        "ARCHIVE_FILE.DISK_FILE_GID AS DISK_FILE_GID,"
550
        "ARCHIVE_FILE.SIZE_IN_BYTES AS SIZE_IN_BYTES,"
551
        "ARCHIVE_FILE.CHECKSUM_BLOB AS CHECKSUM_BLOB,"
552
        "ARCHIVE_FILE.CHECKSUM_ADLER32 AS CHECKSUM_ADLER32,"
553
554
555
556
557
558
        "STORAGE_CLASS.STORAGE_CLASS_NAME AS STORAGE_CLASS_NAME,"
        "ARCHIVE_FILE.CREATION_TIME AS ARCHIVE_FILE_CREATION_TIME,"
        "ARCHIVE_FILE.RECONCILIATION_TIME AS RECONCILIATION_TIME,"
        "TAPE_FILE.VID AS VID,"
        "TAPE_FILE.FSEQ AS FSEQ,"
        "TAPE_FILE.BLOCK_ID AS BLOCK_ID,"
559
        "TAPE_FILE.LOGICAL_SIZE_IN_BYTES AS LOGICAL_SIZE_IN_BYTES,"
560
        "TAPE_FILE.COPY_NB AS COPY_NB,"
Cedric Caffy's avatar
Cedric Caffy committed
561
        "TAPE_FILE.CREATION_TIME AS TAPE_FILE_CREATION_TIME "
562
563
564
565
      "FROM "
        "ARCHIVE_FILE "
      "INNER JOIN STORAGE_CLASS ON "
        "ARCHIVE_FILE.STORAGE_CLASS_ID = STORAGE_CLASS.STORAGE_CLASS_ID "
566
      "INNER JOIN TAPE_FILE ON "
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        "ARCHIVE_FILE.ARCHIVE_FILE_ID = TAPE_FILE.ARCHIVE_FILE_ID "
      "WHERE "
        "ARCHIVE_FILE.ARCHIVE_FILE_ID = :ARCHIVE_FILE_ID "
      "FOR UPDATE";
    utils::Timer t;
    auto conn = m_connPool.getConn();
    rdbms::AutoRollback autoRollback(conn);
    const auto getConnTime = t.secs(utils::Timer::resetCounter);
    auto selectStmt = conn.createStmt(selectSql);
    const auto createStmtTime = t.secs();
    selectStmt.bindUint64(":ARCHIVE_FILE_ID", archiveFileId);
    t.reset();
    rdbms::Rset selectRset = selectStmt.executeQuery();
    const auto selectFromArchiveFileTime = t.secs();
    std::unique_ptr<common::dataStructures::ArchiveFile> archiveFile;
582
    std::set<std::string> vidsToSetDirty;
583
584
585
586
587
588
589
    while(selectRset.next()) {
      if(nullptr == archiveFile.get()) {
        archiveFile = cta::make_unique<common::dataStructures::ArchiveFile>();

        archiveFile->archiveFileID = selectRset.columnUint64("ARCHIVE_FILE_ID");
        archiveFile->diskInstance = selectRset.columnString("DISK_INSTANCE_NAME");
        archiveFile->diskFileId = selectRset.columnString("DISK_FILE_ID");
590
591
        archiveFile->diskFileInfo.owner_uid = selectRset.columnUint64("DISK_FILE_UID");
        archiveFile->diskFileInfo.gid = selectRset.columnUint64("DISK_FILE_GID");
592
        archiveFile->fileSize = selectRset.columnUint64("SIZE_IN_BYTES");
593
        archiveFile->checksumBlob.deserializeOrSetAdler32(selectRset.columnBlob("CHECKSUM_BLOB"), selectRset.columnUint64("CHECKSUM_ADLER32"));
594
595
596
597
598
599
600
601
602
603
        archiveFile->storageClass = selectRset.columnString("STORAGE_CLASS_NAME");
        archiveFile->creationTime = selectRset.columnUint64("ARCHIVE_FILE_CREATION_TIME");
        archiveFile->reconciliationTime = selectRset.columnUint64("RECONCILIATION_TIME");
      }

      // If there is a tape file
      if(!selectRset.columnIsNull("VID")) {
        // Add the tape file to the archive file's in-memory structure
        common::dataStructures::TapeFile tapeFile;
        tapeFile.vid = selectRset.columnString("VID");
604
        vidsToSetDirty.insert(tapeFile.vid);
605
606
        tapeFile.fSeq = selectRset.columnUint64("FSEQ");
        tapeFile.blockId = selectRset.columnUint64("BLOCK_ID");
607
        tapeFile.fileSize = selectRset.columnUint64("LOGICAL_SIZE_IN_BYTES");
608
609
        tapeFile.copyNb = selectRset.columnUint64("COPY_NB");
        tapeFile.creationTime = selectRset.columnUint64("TAPE_FILE_CREATION_TIME");
610
        tapeFile.checksumBlob = archiveFile->checksumBlob; // Duplicated for convenience
611

612
        archiveFile->tapeFiles.push_back(tapeFile);
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
      }
    }

    if(nullptr == archiveFile.get()) {
      log::ScopedParamContainer spc(lc);
      spc.add("fileId", archiveFileId);
      lc.log(log::WARNING, "Ignoring request to delete archive file because it does not exist in the catalogue");
      return;
    }

    if(diskInstanceName != archiveFile->diskInstance) {
      log::ScopedParamContainer spc(lc);
      spc.add("fileId", std::to_string(archiveFile->archiveFileID))
         .add("diskInstance", archiveFile->diskInstance)
         .add("requestDiskInstance", diskInstanceName)
         .add("diskFileId", archiveFile->diskFileId)
629
630
         .add("diskFileInfo.owner_uid", archiveFile->diskFileInfo.owner_uid)
         .add("diskFileInfo.gid", archiveFile->diskFileInfo.gid)
631
         .add("fileSize", std::to_string(archiveFile->fileSize))
632
         .add("checksumBlob", archiveFile->checksumBlob)
633
634
635
636
637
638
639
640
         .add("creationTime", std::to_string(archiveFile->creationTime))
         .add("reconciliationTime", std::to_string(archiveFile->reconciliationTime))
         .add("storageClass", archiveFile->storageClass)
         .add("getConnTime", getConnTime)
         .add("createStmtTime", createStmtTime)
         .add("selectFromArchiveFileTime", selectFromArchiveFileTime);
      for(auto it=archiveFile->tapeFiles.begin(); it!=archiveFile->tapeFiles.end(); it++) {
        std::stringstream tapeCopyLogStream;
641
642
643
644
645
        tapeCopyLogStream << "copy number: " << it->copyNb
          << " vid: " << it->vid
          << " fSeq: " << it->fSeq
          << " blockId: " << it->blockId
          << " creationTime: " << it->creationTime
646
          << " fileSize: " << it->fileSize
647
          << " checksumBlob: " << it->checksumBlob //this shouldn't be here: repeated field
Cedric Caffy's avatar
Cedric Caffy committed
648
          << " copyNb: " << it->copyNb;
649
650
651
652
653
654
655
        spc.add("TAPE FILE", tapeCopyLogStream.str());
      }
      lc.log(log::WARNING, "Failed to delete archive file because the disk instance of the request does not match that "
        "of the archived file");

      exception::UserError ue;
      ue.getMessage() << "Failed to delete archive file with ID " << archiveFileId << " because the disk instance of "
656
        "the request does not match that of the archived file: archiveFileId=" << archiveFileId << " requestDiskInstance=" << diskInstanceName << " archiveFileDiskInstance=" <<     archiveFile->diskInstance;
657
658
659
660
661
662
663
664
665
666
667
668
669
      throw ue;
    }

    t.reset();

    conn.executeNonQuery("START TRANSACTION");

    {
      const char *const sql = "DELETE FROM TAPE_FILE WHERE ARCHIVE_FILE_ID = :ARCHIVE_FILE_ID";
      auto stmt = conn.createStmt(sql);
      stmt.bindUint64(":ARCHIVE_FILE_ID", archiveFileId);
      stmt.executeNonQuery();
    }
670
671
    
    const auto deleteFromTapeFileTime = t.secs(utils::Timer::resetCounter);
672

673
    for(auto &vidToSetDirty: vidsToSetDirty){
674
      //We deleted the TAPE_FILE so the tapes containing them should be set as dirty
675
      setTapeDirty(conn,vidToSetDirty);
676
677
    }
    
678
    const auto setTapeDirtyTime = t.secs(utils::Timer::resetCounter);
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

    {
      const char *const sql = "DELETE FROM ARCHIVE_FILE WHERE ARCHIVE_FILE_ID = :ARCHIVE_FILE_ID";
      auto stmt = conn.createStmt(sql);
      stmt.bindUint64(":ARCHIVE_FILE_ID", archiveFileId);
      stmt.executeNonQuery();
    }
    const auto deleteFromArchiveFileTime = t.secs(utils::Timer::resetCounter);
    conn.commit();
    const auto commitTime = t.secs();

    log::ScopedParamContainer spc(lc);
    spc.add("fileId", std::to_string(archiveFile->archiveFileID))
       .add("diskInstance", archiveFile->diskInstance)
       .add("diskFileId", archiveFile->diskFileId)
694
695
       .add("diskFileInfo.owner_uid", archiveFile->diskFileInfo.owner_uid)
       .add("diskFileInfo.gid", archiveFile->diskFileInfo.gid)
696
       .add("fileSize", std::to_string(archiveFile->fileSize))
697
       .add("checksumBlob", archiveFile->checksumBlob)
698
699
700
701
702
703
704
705
       .add("creationTime", std::to_string(archiveFile->creationTime))
       .add("reconciliationTime", std::to_string(archiveFile->reconciliationTime))
       .add("storageClass", archiveFile->storageClass)
       .add("getConnTime", getConnTime)
       .add("createStmtTime", createStmtTime)
       .add("selectFromArchiveFileTime", selectFromArchiveFileTime)
       .add("deleteFromTapeFileTime", deleteFromTapeFileTime)
       .add("deleteFromArchiveFileTime", deleteFromArchiveFileTime)
706
       .add("setTapeDirtyTime",setTapeDirtyTime)
707
708
709
       .add("commitTime", commitTime);
    for(auto it=archiveFile->tapeFiles.begin(); it!=archiveFile->tapeFiles.end(); it++) {
      std::stringstream tapeCopyLogStream;
710
711
712
713
714
      tapeCopyLogStream << "copy number: " << it->copyNb
        << " vid: " << it->vid
        << " fSeq: " << it->fSeq
        << " blockId: " << it->blockId
        << " creationTime: " << it->creationTime
715
        << " fileSize: " << it->fileSize
716
        << " checksumBlob: " << it->checksumBlob //this shouldn't be here: repeated field
Cedric Caffy's avatar
Cedric Caffy committed
717
        << " copyNb: " << static_cast<int>(it->copyNb); //this shouldn't be here: repeated field
718
719
720
721
722
723
724
725
726
727
728
      spc.add("TAPE FILE", tapeCopyLogStream.str());
    }
    lc.log(log::INFO, "Archive file deleted from CTA catalogue");
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

729
730
731
//------------------------------------------------------------------------------
// copyArchiveFileToRecycleBinAndDelete
//------------------------------------------------------------------------------
732
void MysqlCatalogue::copyArchiveFileToFileRecyleLogAndDelete(rdbms::Conn & conn, const common::dataStructures::DeleteArchiveRequest &request, log::LogContext & lc){
733
734
735
736
737
738
  try {
    utils::Timer t;
    log::TimingList tl;
    //We currently do an INSERT INTO and a DELETE FROM
    //in a single transaction
    conn.executeNonQuery("START TRANSACTION");
739
    copyArchiveFileToFileRecycleLog(conn,request);
740
    tl.insertAndReset("insertToRecycleBinTime",t);
741
742
743
744
745
746
    setTapeDirty(conn,request.archiveFileID);
    tl.insertAndReset("setTapeDirtyTime",t);
    deleteTapeFiles(conn,request);
    tl.insertAndReset("deleteTapeFilesTime",t);
    RdbmsCatalogue::deleteArchiveFile(conn,request);
    tl.insertAndReset("deleteArchiveFileTime",t);
747
748
749
750
751
752
753
754
    conn.commit();
    tl.insertAndReset("commitTime",t);
    log::ScopedParamContainer spc(lc);
    spc.add("archiveFileId",request.archiveFileID);
    spc.add("diskFileId",request.diskFileId);
    spc.add("diskFilePath",request.diskFilePath);
    spc.add("diskInstance",request.diskInstance);
    tl.addToLog(spc);
755
    lc.log(log::INFO,"In MysqlCatalogue::copyArchiveFileToRecycleBinAndDelete: ArchiveFile moved to the recycle-bin.");
756
757
758
759
760
761
762
763
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

764
765
766
//------------------------------------------------------------------------------
// deleteTapeFilesAndArchiveFileFromRecycleBin
//------------------------------------------------------------------------------
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
void MysqlCatalogue::deleteTapeFilesAndArchiveFileFromRecycleBin(rdbms::Conn & conn, const uint64_t archiveFileId, log::LogContext &lc) {
  try {
    utils::Timer t;
    log::TimingList tl;
    //We currently do two delete in one transaction
    conn.executeNonQuery("START TRANSACTION");
    deleteTapeFilesFromRecycleBin(conn,archiveFileId);
    tl.insertAndReset("deleteTapeFilesTime",t);
    deleteArchiveFileFromRecycleBin(conn,archiveFileId);
    tl.insertAndReset("deleteArchiveFileTime",t);
    conn.commit();
    tl.insertAndReset("commitTime",t);
    log::ScopedParamContainer spc(lc);
    spc.add("archiveFileId",archiveFileId);
    tl.addToLog(spc);
    lc.log(log::INFO,"In MysqlCatalogue::deleteTapeFilesAndArchiveFileFromRecycleBin: tape files and archiveFiles deleted from the recycle-bin.");
  } catch(exception::UserError &) {
    throw;
  } catch(exception::Exception &ex) {
    ex.getMessage().str(std::string(__FUNCTION__) + ": " + ex.getMessage().str());
    throw;
  }
}

Tao Lin's avatar
Tao Lin committed
791
792
} // namespace catalogue
} // namespace cta