db_test_util.cc 49.6 KB
Newer Older
1
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5 6 7 8 9
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

10
#include "db/db_test_util.h"
11
#include "db/forward_iterator.h"
E
Ewout Prangsma 已提交
12
#include "rocksdb/env_encryption.h"
13
#include "rocksdb/utilities/object_registry.h"
14 15 16 17 18 19 20 21 22 23

namespace rocksdb {

// Special Env used to delay background operations

SpecialEnv::SpecialEnv(Env* base)
    : EnvWrapper(base),
      rnd_(301),
      sleep_counter_(this),
      addon_time_(0),
24
      time_elapse_only_sleep_(false),
M
Maysam Yabandeh 已提交
25
      no_slowdown_(false) {
26 27 28 29 30 31 32 33 34
  delay_sstable_sync_.store(false, std::memory_order_release);
  drop_writes_.store(false, std::memory_order_release);
  no_space_.store(false, std::memory_order_release);
  non_writable_.store(false, std::memory_order_release);
  count_random_reads_ = false;
  count_sequential_reads_ = false;
  manifest_sync_error_.store(false, std::memory_order_release);
  manifest_write_error_.store(false, std::memory_order_release);
  log_write_error_.store(false, std::memory_order_release);
35
  random_file_open_counter_.store(0, std::memory_order_relaxed);
36 37
  delete_count_.store(0, std::memory_order_relaxed);
  num_open_wal_file_.store(0);
38 39 40 41 42 43 44 45
  log_write_slowdown_ = 0;
  bytes_written_ = 0;
  sync_counter_ = 0;
  non_writeable_rate_ = 0;
  new_writable_count_ = 0;
  non_writable_count_ = 0;
  table_write_callback_ = nullptr;
}
S
Siying Dong 已提交
46
#ifndef ROCKSDB_LITE
E
Ewout Prangsma 已提交
47
ROT13BlockCipher rot13Cipher_(16);
S
Siying Dong 已提交
48
#endif  // ROCKSDB_LITE
E
Ewout Prangsma 已提交
49

S
sdong 已提交
50
DBTestBase::DBTestBase(const std::string path)
51
    : mem_env_(nullptr), encrypted_env_(nullptr), option_config_(kDefault) {
52
  Env* base_env = Env::Default();
53 54
#ifndef ROCKSDB_LITE
  const char* test_env_uri = getenv("TEST_ENV_URI");
55
  if (test_env_uri) {
56 57 58
    Env* test_env = nullptr;
    Status s = Env::LoadEnv(test_env_uri, &test_env, &env_guard_);
    base_env = test_env;
59 60 61
    EXPECT_OK(s);
    EXPECT_NE(Env::Default(), base_env);
  }
62
#endif  // !ROCKSDB_LITE
63 64 65 66 67 68 69 70 71 72 73 74
  EXPECT_NE(nullptr, base_env);
  if (getenv("MEM_ENV")) {
    mem_env_ = new MockEnv(base_env);
  }
#ifndef ROCKSDB_LITE
  if (getenv("ENCRYPTED_ENV")) {
    encrypted_env_ = NewEncryptedEnv(mem_env_ ? mem_env_ : base_env,
                                     new CTREncryptionProvider(rot13Cipher_));
  }
#endif  // !ROCKSDB_LITE
  env_ = new SpecialEnv(encrypted_env_ ? encrypted_env_
                                       : (mem_env_ ? mem_env_ : base_env));
75 76
  env_->SetBackgroundThreads(1, Env::LOW);
  env_->SetBackgroundThreads(1, Env::HIGH);
77
  dbname_ = test::PerThreadDBPath(env_, path);
78
  alternative_wal_dir_ = dbname_ + "/wal";
S
sdong 已提交
79
  alternative_db_log_dir_ = dbname_ + "/db_log_dir";
80
  auto options = CurrentOptions();
M
Maysam Yabandeh 已提交
81
  options.env = env_;
82 83 84 85 86 87 88
  auto delete_options = options;
  delete_options.wal_dir = alternative_wal_dir_;
  EXPECT_OK(DestroyDB(dbname_, delete_options));
  // Destroy it for not alternative WAL dir is used.
  EXPECT_OK(DestroyDB(dbname_, options));
  db_ = nullptr;
  Reopen(options);
89
  Random::GetTLSInstance()->Reset(0xdeadbeef);
90 91 92 93 94 95 96 97 98 99 100 101
}

DBTestBase::~DBTestBase() {
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  rocksdb::SyncPoint::GetInstance()->LoadDependency({});
  rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();
  Close();
  Options options;
  options.db_paths.emplace_back(dbname_, 0);
  options.db_paths.emplace_back(dbname_ + "_2", 0);
  options.db_paths.emplace_back(dbname_ + "_3", 0);
  options.db_paths.emplace_back(dbname_ + "_4", 0);
M
Maysam Yabandeh 已提交
102
  options.env = env_;
I
Islam AbdelRahman 已提交
103 104 105 106 107 108

  if (getenv("KEEP_DB")) {
    printf("DB is still at %s\n", dbname_.c_str());
  } else {
    EXPECT_OK(DestroyDB(dbname_, options));
  }
109 110 111
  delete env_;
}

S
sdong 已提交
112
bool DBTestBase::ShouldSkipOptions(int option_config, int skip_mask) {
113 114
#ifdef ROCKSDB_LITE
    // These options are not supported in ROCKSDB_LITE
115 116 117 118 119 120 121 122 123 124 125 126
    if (option_config == kHashSkipList ||
        option_config == kPlainTableFirstBytePrefix ||
        option_config == kPlainTableCappedPrefix ||
        option_config == kPlainTableCappedPrefixNonMmap ||
        option_config == kPlainTableAllBytesPrefix ||
        option_config == kVectorRep || option_config == kHashLinkList ||
        option_config == kUniversalCompaction ||
        option_config == kUniversalCompactionMultiLevel ||
        option_config == kUniversalSubcompactions ||
        option_config == kFIFOCompaction ||
        option_config == kConcurrentSkipList) {
      return true;
127 128 129
    }
#endif

130
    if ((skip_mask & kSkipUniversalCompaction) &&
S
sdong 已提交
131
        (option_config == kUniversalCompaction ||
132 133
         option_config == kUniversalCompactionMultiLevel ||
         option_config == kUniversalSubcompactions)) {
S
sdong 已提交
134
      return true;
135
    }
S
sdong 已提交
136 137
    if ((skip_mask & kSkipMergePut) && option_config == kMergePut) {
      return true;
138 139
    }
    if ((skip_mask & kSkipNoSeekToLast) &&
S
sdong 已提交
140 141
        (option_config == kHashLinkList || option_config == kHashSkipList)) {
      return true;
142 143
    }
    if ((skip_mask & kSkipPlainTable) &&
S
sdong 已提交
144 145 146 147 148
        (option_config == kPlainTableAllBytesPrefix ||
         option_config == kPlainTableFirstBytePrefix ||
         option_config == kPlainTableCappedPrefix ||
         option_config == kPlainTableCappedPrefixNonMmap)) {
      return true;
149 150
    }
    if ((skip_mask & kSkipHashIndex) &&
S
sdong 已提交
151 152 153
        (option_config == kBlockBasedTableWithPrefixHashIndex ||
         option_config == kBlockBasedTableWithWholeKeyHashIndex)) {
      return true;
154
    }
S
sdong 已提交
155 156
    if ((skip_mask & kSkipFIFOCompaction) && option_config == kFIFOCompaction) {
      return true;
157
    }
S
sdong 已提交
158 159 160 161 162 163 164 165 166 167 168
    if ((skip_mask & kSkipMmapReads) && option_config == kWalDirAndMmapReads) {
      return true;
    }
    return false;
}

// Switch to a fresh database with the next option configuration to
// test.  Return false if there are no more configurations to test.
bool DBTestBase::ChangeOptions(int skip_mask) {
  for (option_config_++; option_config_ < kEnd; option_config_++) {
    if (ShouldSkipOptions(option_config_, skip_mask)) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
      continue;
    }
    break;
  }

  if (option_config_ >= kEnd) {
    Destroy(last_options_);
    return false;
  } else {
    auto options = CurrentOptions();
    options.create_if_missing = true;
    DestroyAndReopen(options);
    return true;
  }
}

185
// Switch between different compaction styles.
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
bool DBTestBase::ChangeCompactOptions() {
  if (option_config_ == kDefault) {
    option_config_ = kUniversalCompaction;
    Destroy(last_options_);
    auto options = CurrentOptions();
    options.create_if_missing = true;
    TryReopen(options);
    return true;
  } else if (option_config_ == kUniversalCompaction) {
    option_config_ = kUniversalCompactionMultiLevel;
    Destroy(last_options_);
    auto options = CurrentOptions();
    options.create_if_missing = true;
    TryReopen(options);
    return true;
201 202 203 204
  } else if (option_config_ == kUniversalCompactionMultiLevel) {
    option_config_ = kLevelSubcompactions;
    Destroy(last_options_);
    auto options = CurrentOptions();
205 206 207 208 209 210 211 212
    assert(options.max_subcompactions > 1);
    TryReopen(options);
    return true;
  } else if (option_config_ == kLevelSubcompactions) {
    option_config_ = kUniversalSubcompactions;
    Destroy(last_options_);
    auto options = CurrentOptions();
    assert(options.max_subcompactions > 1);
213 214
    TryReopen(options);
    return true;
215 216 217 218 219
  } else {
    return false;
  }
}

S
Siying Dong 已提交
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
// Switch between different WAL settings
bool DBTestBase::ChangeWalOptions() {
  if (option_config_ == kDefault) {
    option_config_ = kDBLogDir;
    Destroy(last_options_);
    auto options = CurrentOptions();
    Destroy(options);
    options.create_if_missing = true;
    TryReopen(options);
    return true;
  } else if (option_config_ == kDBLogDir) {
    option_config_ = kWalDirAndMmapReads;
    Destroy(last_options_);
    auto options = CurrentOptions();
    Destroy(options);
    options.create_if_missing = true;
    TryReopen(options);
    return true;
  } else if (option_config_ == kWalDirAndMmapReads) {
    option_config_ = kRecycleLogFiles;
    Destroy(last_options_);
    auto options = CurrentOptions();
    Destroy(options);
    TryReopen(options);
    return true;
  } else {
    return false;
  }
}

250 251 252 253 254 255
// Switch between different filter policy
// Jump from kDefault to kFilter to kFullFilter
bool DBTestBase::ChangeFilterOptions() {
  if (option_config_ == kDefault) {
    option_config_ = kFilter;
  } else if (option_config_ == kFilter) {
256
    option_config_ = kFullFilterWithNewTableReaderForCompactions;
M
Maysam Yabandeh 已提交
257 258
  } else if (option_config_ == kFullFilterWithNewTableReaderForCompactions) {
    option_config_ = kPartitionedFilterWithNewTableReaderForCompactions;
259 260 261 262 263 264 265 266 267 268 269
  } else {
    return false;
  }
  Destroy(last_options_);

  auto options = CurrentOptions();
  options.create_if_missing = true;
  TryReopen(options);
  return true;
}

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
// Switch between different DB options for file ingestion tests.
bool DBTestBase::ChangeOptionsForFileIngestionTest() {
  if (option_config_ == kDefault) {
    option_config_ = kUniversalCompaction;
    Destroy(last_options_);
    auto options = CurrentOptions();
    options.create_if_missing = true;
    TryReopen(options);
    return true;
  } else if (option_config_ == kUniversalCompaction) {
    option_config_ = kUniversalCompactionMultiLevel;
    Destroy(last_options_);
    auto options = CurrentOptions();
    options.create_if_missing = true;
    TryReopen(options);
    return true;
  } else if (option_config_ == kUniversalCompactionMultiLevel) {
    option_config_ = kLevelSubcompactions;
    Destroy(last_options_);
    auto options = CurrentOptions();
    assert(options.max_subcompactions > 1);
    TryReopen(options);
    return true;
  } else if (option_config_ == kLevelSubcompactions) {
    option_config_ = kUniversalSubcompactions;
    Destroy(last_options_);
    auto options = CurrentOptions();
    assert(options.max_subcompactions > 1);
    TryReopen(options);
    return true;
  } else if (option_config_ == kUniversalSubcompactions) {
    option_config_ = kDirectIO;
    Destroy(last_options_);
    auto options = CurrentOptions();
    TryReopen(options);
    return true;
  } else {
    return false;
  }
}

311 312
// Return the current option configuration.
Options DBTestBase::CurrentOptions(
Y
Yi Wu 已提交
313 314 315 316 317 318 319 320 321 322 323
    const anon::OptionsOverride& options_override) const {
  return GetOptions(option_config_, GetDefaultOptions(), options_override);
}

Options DBTestBase::CurrentOptions(
    const Options& default_options,
    const anon::OptionsOverride& options_override) const {
  return GetOptions(option_config_, default_options, options_override);
}

Options DBTestBase::GetDefaultOptions() {
324
  Options options;
325
  options.write_buffer_size = 4090 * 4096;
S
sdong 已提交
326 327
  options.target_file_size_base = 2 * 1024 * 1024;
  options.max_bytes_for_level_base = 10 * 1024 * 1024;
S
sdong 已提交
328 329 330
  options.max_open_files = 5000;
  options.wal_recovery_mode = WALRecoveryMode::kTolerateCorruptedTailRecords;
  options.compaction_pri = CompactionPri::kByCompensatedSize;
Y
Yi Wu 已提交
331
  return options;
332 333
}

Y
Yi Wu 已提交
334 335 336
Options DBTestBase::GetOptions(
    int option_config, const Options& default_options,
    const anon::OptionsOverride& options_override) const {
A
Andres Notzli 已提交
337
  // this redundant copy is to minimize code change w/o having lint error.
Y
Yi Wu 已提交
338
  Options options = default_options;
339 340
  BlockBasedTableOptions table_options;
  bool set_block_based_table_factory = true;
341 342
#if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && \
    !defined(OS_AIX)
343 344
  rocksdb::SyncPoint::GetInstance()->ClearCallBack(
      "NewRandomAccessFile:O_DIRECT");
345
  rocksdb::SyncPoint::GetInstance()->ClearCallBack("NewWritableFile:O_DIRECT");
346 347
#endif

E
Ewout Prangsma 已提交
348
  bool can_allow_mmap = IsMemoryMappedAccessSupported();
Y
Yi Wu 已提交
349
  switch (option_config) {
350
#ifndef ROCKSDB_LITE
351 352
    case kHashSkipList:
      options.prefix_extractor.reset(NewFixedPrefixTransform(1));
S
sdong 已提交
353
      options.memtable_factory.reset(NewHashSkipListRepFactory(16));
354
      options.allow_concurrent_memtable_write = false;
M
Maysam Yabandeh 已提交
355
      options.unordered_write = false;
356 357 358 359
      break;
    case kPlainTableFirstBytePrefix:
      options.table_factory.reset(new PlainTableFactory());
      options.prefix_extractor.reset(NewFixedPrefixTransform(1));
E
Ewout Prangsma 已提交
360
      options.allow_mmap_reads = can_allow_mmap;
361 362 363 364 365 366
      options.max_sequential_skip_in_iterations = 999999;
      set_block_based_table_factory = false;
      break;
    case kPlainTableCappedPrefix:
      options.table_factory.reset(new PlainTableFactory());
      options.prefix_extractor.reset(NewCappedPrefixTransform(8));
E
Ewout Prangsma 已提交
367
      options.allow_mmap_reads = can_allow_mmap;
368 369 370
      options.max_sequential_skip_in_iterations = 999999;
      set_block_based_table_factory = false;
      break;
371 372 373 374 375 376 377
    case kPlainTableCappedPrefixNonMmap:
      options.table_factory.reset(new PlainTableFactory());
      options.prefix_extractor.reset(NewCappedPrefixTransform(8));
      options.allow_mmap_reads = false;
      options.max_sequential_skip_in_iterations = 999999;
      set_block_based_table_factory = false;
      break;
378 379 380
    case kPlainTableAllBytesPrefix:
      options.table_factory.reset(new PlainTableFactory());
      options.prefix_extractor.reset(NewNoopTransform());
E
Ewout Prangsma 已提交
381
      options.allow_mmap_reads = can_allow_mmap;
382 383 384
      options.max_sequential_skip_in_iterations = 999999;
      set_block_based_table_factory = false;
      break;
385 386
    case kVectorRep:
      options.memtable_factory.reset(new VectorRepFactory(100));
387
      options.allow_concurrent_memtable_write = false;
M
Maysam Yabandeh 已提交
388
      options.unordered_write = false;
389 390 391 392 393
      break;
    case kHashLinkList:
      options.prefix_extractor.reset(NewFixedPrefixTransform(1));
      options.memtable_factory.reset(
          NewHashLinkListRepFactory(4, 0, 3, true, 4));
394
      options.allow_concurrent_memtable_write = false;
M
Maysam Yabandeh 已提交
395
      options.unordered_write = false;
396
      break;
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
      case kDirectIO: {
        options.use_direct_reads = true;
        options.use_direct_io_for_flush_and_compaction = true;
        options.compaction_readahead_size = 2 * 1024 * 1024;
  #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && \
      !defined(OS_AIX) && !defined(OS_OPENBSD)
        rocksdb::SyncPoint::GetInstance()->SetCallBack(
            "NewWritableFile:O_DIRECT", [&](void* arg) {
              int* val = static_cast<int*>(arg);
              *val &= ~O_DIRECT;
            });
        rocksdb::SyncPoint::GetInstance()->SetCallBack(
            "NewRandomAccessFile:O_DIRECT", [&](void* arg) {
              int* val = static_cast<int*>(arg);
              *val &= ~O_DIRECT;
            });
        rocksdb::SyncPoint::GetInstance()->EnableProcessing();
  #endif
        break;
      }
417
#endif  // ROCKSDB_LITE
418 419 420 421 422 423
    case kMergePut:
      options.merge_operator = MergeOperators::CreatePutOperator();
      break;
    case kFilter:
      table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
      break;
424
    case kFullFilterWithNewTableReaderForCompactions:
425
      table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
426
      options.new_table_reader_for_compaction_inputs = true;
427
      options.compaction_readahead_size = 10 * 1024 * 1024;
428
      break;
M
Maysam Yabandeh 已提交
429 430 431 432 433 434 435 436
    case kPartitionedFilterWithNewTableReaderForCompactions:
      table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
      table_options.partition_filters = true;
      table_options.index_type =
          BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
      options.new_table_reader_for_compaction_inputs = true;
      options.compaction_readahead_size = 10 * 1024 * 1024;
      break;
437 438 439 440 441 442 443
    case kUncompressed:
      options.compression = kNoCompression;
      break;
    case kNumLevel_3:
      options.num_levels = 3;
      break;
    case kDBLogDir:
S
sdong 已提交
444
      options.db_log_dir = alternative_db_log_dir_;
445 446 447 448 449
      break;
    case kWalDirAndMmapReads:
      options.wal_dir = alternative_wal_dir_;
      // mmap reads should be orthogonal to WalDir setting, so we piggyback to
      // this option config to test mmap reads as well
E
Ewout Prangsma 已提交
450
      options.allow_mmap_reads = can_allow_mmap;
451 452 453
      break;
    case kManifestFileSize:
      options.max_manifest_file_size = 50;  // 50 bytes
454
      break;
455
    case kPerfOptions:
456 457
      options.soft_rate_limit = 2.0;
      options.delayed_write_rate = 8 * 1024 * 1024;
458
      options.report_bg_io_stats = true;
459 460 461 462 463 464 465 466 467 468 469
      // TODO(3.13) -- test more options
      break;
    case kUniversalCompaction:
      options.compaction_style = kCompactionStyleUniversal;
      options.num_levels = 1;
      break;
    case kUniversalCompactionMultiLevel:
      options.compaction_style = kCompactionStyleUniversal;
      options.num_levels = 8;
      break;
    case kCompressedBlockCache:
E
Ewout Prangsma 已提交
470
      options.allow_mmap_writes = can_allow_mmap;
S
sdong 已提交
471
      table_options.block_cache_compressed = NewLRUCache(8 * 1024 * 1024);
472 473 474 475 476 477 478 479
      break;
    case kInfiniteMaxOpenFiles:
      options.max_open_files = -1;
      break;
    case kxxHashChecksum: {
      table_options.checksum = kxxHash;
      break;
    }
B
Bo Hou 已提交
480 481 482 483
    case kxxHash64Checksum: {
      table_options.checksum = kxxHash64;
      break;
    }
484 485 486 487 488 489 490 491 492 493 494 495 496 497
    case kFIFOCompaction: {
      options.compaction_style = kCompactionStyleFIFO;
      break;
    }
    case kBlockBasedTableWithPrefixHashIndex: {
      table_options.index_type = BlockBasedTableOptions::kHashSearch;
      options.prefix_extractor.reset(NewFixedPrefixTransform(1));
      break;
    }
    case kBlockBasedTableWithWholeKeyHashIndex: {
      table_options.index_type = BlockBasedTableOptions::kHashSearch;
      options.prefix_extractor.reset(NewNoopTransform());
      break;
    }
M
Maysam Yabandeh 已提交
498 499 500 501 502
    case kBlockBasedTableWithPartitionedIndex: {
      table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
      options.prefix_extractor.reset(NewNoopTransform());
      break;
    }
503 504
    case kBlockBasedTableWithPartitionedIndexFormat4: {
      table_options.format_version = 4;
505
      // Format 4 changes the binary index format. Since partitioned index is a
506 507
      // super-set of simple indexes, we are also using kTwoLevelIndexSearch to
      // test this format.
508
      table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
509
      // The top-level index in partition filters are also affected by format 4.
510 511
      table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
      table_options.partition_filters = true;
512
      table_options.index_block_restart_interval = 8;
513 514
      break;
    }
515 516 517 518
    case kBlockBasedTableWithIndexRestartInterval: {
      table_options.index_block_restart_interval = 8;
      break;
    }
519 520 521 522 523 524 525 526 527
    case kOptimizeFiltersForHits: {
      options.optimize_filters_for_hits = true;
      set_block_based_table_factory = true;
      break;
    }
    case kRowCache: {
      options.row_cache = NewLRUCache(1024 * 1024);
      break;
    }
528 529 530 531
    case kRecycleLogFiles: {
      options.recycle_log_file_num = 2;
      break;
    }
532
    case kLevelSubcompactions: {
533 534 535 536 537 538 539
      options.max_subcompactions = 4;
      break;
    }
    case kUniversalSubcompactions: {
      options.compaction_style = kCompactionStyleUniversal;
      options.num_levels = 8;
      options.max_subcompactions = 4;
540 541
      break;
    }
542 543 544 545 546
    case kConcurrentSkipList: {
      options.allow_concurrent_memtable_write = true;
      options.enable_write_thread_adaptive_yield = true;
      break;
    }
Y
Yi Wu 已提交
547 548 549 550
    case kPipelinedWrite: {
      options.enable_pipelined_write = true;
      break;
    }
551 552
    case kConcurrentWALWrites: {
      // This options optimize 2PC commit path
553
      options.two_write_queues = true;
554 555 556
      options.manual_wal_flush = true;
      break;
    }
M
Maysam Yabandeh 已提交
557 558 559 560 561
    case kUnorderedWrite: {
      options.allow_concurrent_memtable_write = false;
      options.unordered_write = false;
      break;
    }
562 563 564 565 566 567 568

    default:
      break;
  }

  if (options_override.filter_policy) {
    table_options.filter_policy = options_override.filter_policy;
M
Maysam Yabandeh 已提交
569
    table_options.partition_filters = options_override.partition_filters;
M
Maysam Yabandeh 已提交
570
    table_options.metadata_block_size = options_override.metadata_block_size;
571 572 573 574 575 576
  }
  if (set_block_based_table_factory) {
    options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  }
  options.env = env_;
  options.create_if_missing = true;
577
  options.fail_if_options_file_error = true;
578 579 580 581
  return options;
}

void DBTestBase::CreateColumnFamilies(const std::vector<std::string>& cfs,
S
sdong 已提交
582
                                      const Options& options) {
583 584 585 586
  ColumnFamilyOptions cf_opts(options);
  size_t cfi = handles_.size();
  handles_.resize(cfi + cfs.size());
  for (auto cf : cfs) {
Y
Yanqin Jin 已提交
587 588
    Status s = db_->CreateColumnFamily(cf_opts, cf, &handles_[cfi++]);
    ASSERT_OK(s);
589 590 591 592
  }
}

void DBTestBase::CreateAndReopenWithCF(const std::vector<std::string>& cfs,
S
sdong 已提交
593
                                       const Options& options) {
594 595 596 597 598 599 600
  CreateColumnFamilies(cfs, options);
  std::vector<std::string> cfs_plus_default = cfs;
  cfs_plus_default.insert(cfs_plus_default.begin(), kDefaultColumnFamilyName);
  ReopenWithColumnFamilies(cfs_plus_default, options);
}

void DBTestBase::ReopenWithColumnFamilies(const std::vector<std::string>& cfs,
S
sdong 已提交
601
                                          const std::vector<Options>& options) {
602 603 604 605
  ASSERT_OK(TryReopenWithColumnFamilies(cfs, options));
}

void DBTestBase::ReopenWithColumnFamilies(const std::vector<std::string>& cfs,
S
sdong 已提交
606
                                          const Options& options) {
607 608 609 610
  ASSERT_OK(TryReopenWithColumnFamilies(cfs, options));
}

Status DBTestBase::TryReopenWithColumnFamilies(
S
sdong 已提交
611
    const std::vector<std::string>& cfs, const std::vector<Options>& options) {
612 613 614 615 616 617 618
  Close();
  EXPECT_EQ(cfs.size(), options.size());
  std::vector<ColumnFamilyDescriptor> column_families;
  for (size_t i = 0; i < cfs.size(); ++i) {
    column_families.push_back(ColumnFamilyDescriptor(cfs[i], options[i]));
  }
  DBOptions db_opts = DBOptions(options[0]);
619
  last_options_ = options[0];
620 621 622 623
  return DB::Open(db_opts, dbname_, column_families, &handles_, &db_);
}

Status DBTestBase::TryReopenWithColumnFamilies(
S
sdong 已提交
624
    const std::vector<std::string>& cfs, const Options& options) {
625 626 627 628 629 630 631 632 633 634 635
  Close();
  std::vector<Options> v_opts(cfs.size(), options);
  return TryReopenWithColumnFamilies(cfs, v_opts);
}

void DBTestBase::Reopen(const Options& options) {
  ASSERT_OK(TryReopen(options));
}

void DBTestBase::Close() {
  for (auto h : handles_) {
636
    db_->DestroyColumnFamilyHandle(h);
637 638 639 640 641 642 643 644 645 646 647 648
  }
  handles_.clear();
  delete db_;
  db_ = nullptr;
}

void DBTestBase::DestroyAndReopen(const Options& options) {
  // Destroy using last options
  Destroy(last_options_);
  ASSERT_OK(TryReopen(options));
}

649 650 651 652 653 654 655 656 657
void DBTestBase::Destroy(const Options& options, bool delete_cf_paths) {
  std::vector<ColumnFamilyDescriptor> column_families;
  if (delete_cf_paths) {
    for (size_t i = 0; i < handles_.size(); ++i) {
      ColumnFamilyDescriptor cfdescriptor;
      handles_[i]->GetDescriptor(&cfdescriptor);
      column_families.push_back(cfdescriptor);
    }
  }
658
  Close();
659
  ASSERT_OK(DestroyDB(dbname_, options, column_families));
660 661 662 663 664 665 666 667
}

Status DBTestBase::ReadOnlyReopen(const Options& options) {
  return DB::OpenForReadOnly(options, dbname_, &db_);
}

Status DBTestBase::TryReopen(const Options& options) {
  Close();
668
  last_options_.table_factory.reset();
669 670 671 672 673 674 675
  // Note: operator= is an unsafe approach here since it destructs
  // std::shared_ptr in the same order of their creation, in contrast to
  // destructors which destructs them in the opposite order of creation. One
  // particular problme is that the cache destructor might invoke callback
  // functions that use Option members such as statistics. To work around this
  // problem, we manually call destructor of table_facotry which eventually
  // clears the block cache.
676 677 678 679
  last_options_ = options;
  return DB::Open(options, dbname_, &db_);
}

A
Aaron Gao 已提交
680
bool DBTestBase::IsDirectIOSupported() {
681
  return test::IsDirectIOSupported(env_, dbname_);
A
Aaron Gao 已提交
682 683
}

E
Ewout Prangsma 已提交
684 685 686 687
bool DBTestBase::IsMemoryMappedAccessSupported() const {
  return (!encrypted_env_);
}

688 689 690 691 692 693 694 695
Status DBTestBase::Flush(int cf) {
  if (cf == 0) {
    return db_->Flush(FlushOptions());
  } else {
    return db_->Flush(FlushOptions(), handles_[cf]);
  }
}

Y
Yanqin Jin 已提交
696 697 698 699 700 701 702
Status DBTestBase::Flush(const std::vector<int>& cf_ids) {
  std::vector<ColumnFamilyHandle*> cfhs;
  std::for_each(cf_ids.begin(), cf_ids.end(),
                [&cfhs, this](int id) { cfhs.emplace_back(handles_[id]); });
  return db_->Flush(FlushOptions(), cfhs);
}

703 704 705 706 707 708 709 710 711
Status DBTestBase::Put(const Slice& k, const Slice& v, WriteOptions wo) {
  if (kMergePut == option_config_) {
    return db_->Merge(wo, k, v);
  } else {
    return db_->Put(wo, k, v);
  }
}

Status DBTestBase::Put(int cf, const Slice& k, const Slice& v,
S
sdong 已提交
712
                       WriteOptions wo) {
713 714 715 716 717 718 719
  if (kMergePut == option_config_) {
    return db_->Merge(wo, handles_[cf], k, v);
  } else {
    return db_->Put(wo, handles_[cf], k, v);
  }
}

720 721 722 723 724 725 726 727 728
Status DBTestBase::Merge(const Slice& k, const Slice& v, WriteOptions wo) {
  return db_->Merge(wo, k, v);
}

Status DBTestBase::Merge(int cf, const Slice& k, const Slice& v,
                         WriteOptions wo) {
  return db_->Merge(wo, handles_[cf], k, v);
}

729 730 731 732 733 734 735 736
Status DBTestBase::Delete(const std::string& k) {
  return db_->Delete(WriteOptions(), k);
}

Status DBTestBase::Delete(int cf, const std::string& k) {
  return db_->Delete(WriteOptions(), handles_[cf], k);
}

A
Andres Noetzli 已提交
737 738 739 740 741 742 743 744
Status DBTestBase::SingleDelete(const std::string& k) {
  return db_->SingleDelete(WriteOptions(), k);
}

Status DBTestBase::SingleDelete(int cf, const std::string& k) {
  return db_->SingleDelete(WriteOptions(), handles_[cf], k);
}

745 746 747 748
bool DBTestBase::SetPreserveDeletesSequenceNumber(SequenceNumber sn) {
  return db_->SetPreserveDeletesSequenceNumber(sn);
}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
std::string DBTestBase::Get(const std::string& k, const Snapshot* snapshot) {
  ReadOptions options;
  options.verify_checksums = true;
  options.snapshot = snapshot;
  std::string result;
  Status s = db_->Get(options, k, &result);
  if (s.IsNotFound()) {
    result = "NOT_FOUND";
  } else if (!s.ok()) {
    result = s.ToString();
  }
  return result;
}

std::string DBTestBase::Get(int cf, const std::string& k,
S
sdong 已提交
764
                            const Snapshot* snapshot) {
765 766 767 768 769 770 771 772 773 774 775 776 777
  ReadOptions options;
  options.verify_checksums = true;
  options.snapshot = snapshot;
  std::string result;
  Status s = db_->Get(options, handles_[cf], k, &result);
  if (s.IsNotFound()) {
    result = "NOT_FOUND";
  } else if (!s.ok()) {
    result = s.ToString();
  }
  return result;
}

A
Anand Ananthabhotla 已提交
778 779
std::vector<std::string> DBTestBase::MultiGet(std::vector<int> cfs,
                                              const std::vector<std::string>& k,
780 781
                                              const Snapshot* snapshot,
                                              const bool batched) {
A
Anand Ananthabhotla 已提交
782 783 784 785 786 787 788 789 790 791 792
  ReadOptions options;
  options.verify_checksums = true;
  options.snapshot = snapshot;
  std::vector<ColumnFamilyHandle*> handles;
  std::vector<Slice> keys;
  std::vector<std::string> result;

  for (unsigned int i = 0; i < cfs.size(); ++i) {
    handles.push_back(handles_[cfs[i]]);
    keys.push_back(k[i]);
  }
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  std::vector<Status> s;
  if (!batched) {
    s = db_->MultiGet(options, handles, keys, &result);
    for (unsigned int i = 0; i < s.size(); ++i) {
      if (s[i].IsNotFound()) {
        result[i] = "NOT_FOUND";
      } else if (!s[i].ok()) {
        result[i] = s[i].ToString();
      }
    }
  } else {
    std::vector<PinnableSlice> pin_values(cfs.size());
    result.resize(cfs.size());
    s.resize(cfs.size());
    db_->MultiGet(options, cfs.size(), handles.data(), keys.data(),
                  pin_values.data(), s.data());
    for (unsigned int i = 0; i < s.size(); ++i) {
      if (s[i].IsNotFound()) {
        result[i] = "NOT_FOUND";
      } else if (!s[i].ok()) {
        result[i] = s[i].ToString();
      } else {
        result[i].assign(pin_values[i].data(), pin_values[i].size());
      }
A
Anand Ananthabhotla 已提交
817 818 819 820 821
    }
  }
  return result;
}

822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
std::vector<std::string> DBTestBase::MultiGet(const std::vector<std::string>& k,
                                              const Snapshot* snapshot) {
  ReadOptions options;
  options.verify_checksums = true;
  options.snapshot = snapshot;
  std::vector<Slice> keys;
  std::vector<std::string> result;
  std::vector<Status> statuses(k.size());
  std::vector<PinnableSlice> pin_values(k.size());

  for (unsigned int i = 0; i < k.size(); ++i) {
    keys.push_back(k[i]);
  }
  db_->MultiGet(options, dbfull()->DefaultColumnFamily(), keys.size(),
                keys.data(), pin_values.data(), statuses.data());
  result.resize(k.size());
  for (auto iter = result.begin(); iter != result.end(); ++iter) {
    iter->assign(pin_values[iter - result.begin()].data(),
                 pin_values[iter - result.begin()].size());
  }
  for (unsigned int i = 0; i < statuses.size(); ++i) {
    if (statuses[i].IsNotFound()) {
      result[i] = "NOT_FOUND";
    }
  }
  return result;
}

850 851 852 853 854 855 856
Status DBTestBase::Get(const std::string& k, PinnableSlice* v) {
  ReadOptions options;
  options.verify_checksums = true;
  Status s = dbfull()->Get(options, dbfull()->DefaultColumnFamily(), k, v);
  return s;
}

857 858 859 860 861 862 863 864 865 866 867 868 869
uint64_t DBTestBase::GetNumSnapshots() {
  uint64_t int_num;
  EXPECT_TRUE(dbfull()->GetIntProperty("rocksdb.num-snapshots", &int_num));
  return int_num;
}

uint64_t DBTestBase::GetTimeOldestSnapshots() {
  uint64_t int_num;
  EXPECT_TRUE(
      dbfull()->GetIntProperty("rocksdb.oldest-snapshot-time", &int_num));
  return int_num;
}

870 871 872 873 874 875 876
uint64_t DBTestBase::GetSequenceOldestSnapshots() {
  uint64_t int_num;
  EXPECT_TRUE(
      dbfull()->GetIntProperty("rocksdb.oldest-snapshot-sequence", &int_num));
  return int_num;
}

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
// Return a string that contains all key,value pairs in order,
// formatted like "(k1->v1)(k2->v2)".
std::string DBTestBase::Contents(int cf) {
  std::vector<std::string> forward;
  std::string result;
  Iterator* iter = (cf == 0) ? db_->NewIterator(ReadOptions())
                             : db_->NewIterator(ReadOptions(), handles_[cf]);
  for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
    std::string s = IterStatus(iter);
    result.push_back('(');
    result.append(s);
    result.push_back(')');
    forward.push_back(s);
  }

  // Check reverse iteration results are the reverse of forward results
  unsigned int matched = 0;
  for (iter->SeekToLast(); iter->Valid(); iter->Prev()) {
    EXPECT_LT(matched, forward.size());
    EXPECT_EQ(IterStatus(iter), forward[forward.size() - matched - 1]);
    matched++;
  }
  EXPECT_EQ(matched, forward.size());

  delete iter;
  return result;
}

std::string DBTestBase::AllEntriesFor(const Slice& user_key, int cf) {
  Arena arena;
A
Andrew Kryczka 已提交
907
  auto options = CurrentOptions();
A
Andrew Kryczka 已提交
908
  InternalKeyComparator icmp(options.comparator);
909 910
  ReadRangeDelAggregator range_del_agg(&icmp,
                                       kMaxSequenceNumber /* upper_bound */);
911 912
  ScopedArenaIterator iter;
  if (cf == 0) {
913 914
    iter.set(dbfull()->NewInternalIterator(&arena, &range_del_agg,
                                           kMaxSequenceNumber));
915
  } else {
916 917
    iter.set(dbfull()->NewInternalIterator(&arena, &range_del_agg,
                                           kMaxSequenceNumber, handles_[cf]));
918 919 920 921 922 923 924 925 926 927 928 929 930 931
  }
  InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  iter->Seek(target.Encode());
  std::string result;
  if (!iter->status().ok()) {
    result = iter->status().ToString();
  } else {
    result = "[ ";
    bool first = true;
    while (iter->Valid()) {
      ParsedInternalKey ikey(Slice(), 0, kTypeValue);
      if (!ParseInternalKey(iter->key(), &ikey)) {
        result += "CORRUPTED";
      } else {
932
        if (!last_options_.comparator->Equal(ikey.user_key, user_key)) {
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
          break;
        }
        if (!first) {
          result += ", ";
        }
        first = false;
        switch (ikey.type) {
          case kTypeValue:
            result += iter->value().ToString();
            break;
          case kTypeMerge:
            // keep it the same as kTypeValue for testing kMergePut
            result += iter->value().ToString();
            break;
          case kTypeDeletion:
            result += "DEL";
            break;
A
Andres Noetzli 已提交
950 951 952
          case kTypeSingleDeletion:
            result += "SDEL";
            break;
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
          default:
            assert(false);
            break;
        }
      }
      iter->Next();
    }
    if (!first) {
      result += " ";
    }
    result += "]";
  }
  return result;
}

968
#ifndef ROCKSDB_LITE
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
int DBTestBase::NumSortedRuns(int cf) {
  ColumnFamilyMetaData cf_meta;
  if (cf == 0) {
    db_->GetColumnFamilyMetaData(&cf_meta);
  } else {
    db_->GetColumnFamilyMetaData(handles_[cf], &cf_meta);
  }
  int num_sr = static_cast<int>(cf_meta.levels[0].files.size());
  for (size_t i = 1U; i < cf_meta.levels.size(); i++) {
    if (cf_meta.levels[i].files.size() > 0) {
      num_sr++;
    }
  }
  return num_sr;
}

uint64_t DBTestBase::TotalSize(int cf) {
  ColumnFamilyMetaData cf_meta;
  if (cf == 0) {
    db_->GetColumnFamilyMetaData(&cf_meta);
  } else {
    db_->GetColumnFamilyMetaData(handles_[cf], &cf_meta);
  }
  return cf_meta.size;
}

uint64_t DBTestBase::SizeAtLevel(int level) {
  std::vector<LiveFileMetaData> metadata;
  db_->GetLiveFilesMetaData(&metadata);
  uint64_t sum = 0;
  for (const auto& m : metadata) {
    if (m.level == level) {
      sum += m.size;
    }
  }
  return sum;
}

V
Vasili Svirski 已提交
1007
size_t DBTestBase::TotalLiveFiles(int cf) {
1008 1009 1010 1011 1012 1013
  ColumnFamilyMetaData cf_meta;
  if (cf == 0) {
    db_->GetColumnFamilyMetaData(&cf_meta);
  } else {
    db_->GetColumnFamilyMetaData(handles_[cf], &cf_meta);
  }
V
Vasili Svirski 已提交
1014
  size_t num_files = 0;
1015 1016 1017 1018 1019 1020
  for (auto& level : cf_meta.levels) {
    num_files += level.files.size();
  }
  return num_files;
}

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
size_t DBTestBase::CountLiveFiles() {
  std::vector<LiveFileMetaData> metadata;
  db_->GetLiveFilesMetaData(&metadata);
  return metadata.size();
}

int DBTestBase::NumTableFilesAtLevel(int level, int cf) {
  std::string property;
  if (cf == 0) {
    // default cfd
    EXPECT_TRUE(db_->GetProperty(
        "rocksdb.num-files-at-level" + NumberToString(level), &property));
  } else {
    EXPECT_TRUE(db_->GetProperty(
        handles_[cf], "rocksdb.num-files-at-level" + NumberToString(level),
        &property));
  }
  return atoi(property.c_str());
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
double DBTestBase::CompressionRatioAtLevel(int level, int cf) {
  std::string property;
  if (cf == 0) {
    // default cfd
    EXPECT_TRUE(db_->GetProperty(
        "rocksdb.compression-ratio-at-level" + NumberToString(level),
        &property));
  } else {
    EXPECT_TRUE(db_->GetProperty(
        handles_[cf],
        "rocksdb.compression-ratio-at-level" + NumberToString(level),
        &property));
  }
  return std::stod(property);
}

1057 1058
int DBTestBase::TotalTableFiles(int cf, int levels) {
  if (levels == -1) {
1059
    levels = (cf == 0) ? db_->NumberLevels() : db_->NumberLevels(handles_[1]);
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
  }
  int result = 0;
  for (int level = 0; level < levels; level++) {
    result += NumTableFilesAtLevel(level, cf);
  }
  return result;
}

// Return spread of files per level
std::string DBTestBase::FilesPerLevel(int cf) {
  int num_levels =
      (cf == 0) ? db_->NumberLevels() : db_->NumberLevels(handles_[1]);
  std::string result;
  size_t last_non_zero_offset = 0;
  for (int level = 0; level < num_levels; level++) {
    int f = NumTableFilesAtLevel(level, cf);
    char buf[100];
    snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
    result += buf;
    if (f > 0) {
      last_non_zero_offset = result.size();
    }
  }
  result.resize(last_non_zero_offset);
  return result;
}
Y
Yi Wu 已提交
1086
#endif  // !ROCKSDB_LITE
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

size_t DBTestBase::CountFiles() {
  std::vector<std::string> files;
  env_->GetChildren(dbname_, &files);

  std::vector<std::string> logfiles;
  if (dbname_ != last_options_.wal_dir) {
    env_->GetChildren(last_options_.wal_dir, &logfiles);
  }

  return files.size() + logfiles.size();
}

uint64_t DBTestBase::Size(const Slice& start, const Slice& limit, int cf) {
  Range r(start, limit);
  uint64_t size;
  if (cf == 0) {
    db_->GetApproximateSizes(&r, 1, &size);
  } else {
    db_->GetApproximateSizes(handles_[1], &r, 1, &size);
  }
  return size;
}

void DBTestBase::Compact(int cf, const Slice& start, const Slice& limit,
S
sdong 已提交
1112
                         uint32_t target_path_id) {
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
  CompactRangeOptions compact_options;
  compact_options.target_path_id = target_path_id;
  ASSERT_OK(db_->CompactRange(compact_options, handles_[cf], &start, &limit));
}

void DBTestBase::Compact(int cf, const Slice& start, const Slice& limit) {
  ASSERT_OK(
      db_->CompactRange(CompactRangeOptions(), handles_[cf], &start, &limit));
}

void DBTestBase::Compact(const Slice& start, const Slice& limit) {
  ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &limit));
}

// Do n memtable compactions, each of which produces an sstable
// covering the range [small,large].
S
sdong 已提交
1129 1130
void DBTestBase::MakeTables(int n, const std::string& small,
                            const std::string& large, int cf) {
1131 1132 1133 1134
  for (int i = 0; i < n; i++) {
    ASSERT_OK(Put(cf, small, "begin"));
    ASSERT_OK(Put(cf, large, "end"));
    ASSERT_OK(Flush(cf));
1135
    MoveFilesToLevel(n - i - 1, cf);
1136 1137 1138 1139 1140
  }
}

// Prevent pushing of new sstables into deeper levels by adding
// tables that cover a specified range to all levels.
S
sdong 已提交
1141 1142
void DBTestBase::FillLevels(const std::string& smallest,
                            const std::string& largest, int cf) {
1143 1144 1145
  MakeTables(db_->NumberLevels(handles_[cf]), smallest, largest, cf);
}

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
void DBTestBase::MoveFilesToLevel(int level, int cf) {
  for (int l = 0; l < level; ++l) {
    if (cf > 0) {
      dbfull()->TEST_CompactRange(l, nullptr, nullptr, handles_[cf]);
    } else {
      dbfull()->TEST_CompactRange(l, nullptr, nullptr);
    }
  }
}

Y
Yi Wu 已提交
1156
#ifndef ROCKSDB_LITE
1157 1158 1159
void DBTestBase::DumpFileCounts(const char* label) {
  fprintf(stderr, "---\n%s:\n", label);
  fprintf(stderr, "maxoverlap: %" PRIu64 "\n",
S
sdong 已提交
1160
          dbfull()->TEST_MaxNextLevelOverlappingBytes());
1161 1162 1163 1164 1165 1166 1167
  for (int level = 0; level < db_->NumberLevels(); level++) {
    int num = NumTableFilesAtLevel(level);
    if (num > 0) {
      fprintf(stderr, "  level %3d : %d files\n", level, num);
    }
  }
}
Y
Yi Wu 已提交
1168
#endif  // !ROCKSDB_LITE
1169 1170 1171 1172 1173 1174 1175

std::string DBTestBase::DumpSSTableList() {
  std::string property;
  db_->GetProperty("rocksdb.sstables", &property);
  return property;
}

1176
void DBTestBase::GetSstFiles(Env* env, std::string path,
D
dyniusz 已提交
1177
                             std::vector<std::string>* files) {
1178
  env->GetChildren(path, files);
D
dyniusz 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187

  files->erase(
      std::remove_if(files->begin(), files->end(), [](std::string name) {
        uint64_t number;
        FileType type;
        return !(ParseFileName(name, &number, &type) && type == kTableFile);
      }), files->end());
}

1188 1189
int DBTestBase::GetSstFileCount(std::string path) {
  std::vector<std::string> files;
1190
  DBTestBase::GetSstFiles(env_, path, &files);
D
dyniusz 已提交
1191
  return static_cast<int>(files.size());
1192 1193
}

1194 1195 1196
// this will generate non-overlapping files since it keeps increasing key_idx
void DBTestBase::GenerateNewFile(int cf, Random* rnd, int* key_idx,
                                 bool nowait) {
K
krad 已提交
1197
  for (int i = 0; i < KNumKeysByGenerateNewFile; i++) {
1198 1199 1200 1201 1202 1203 1204 1205 1206
    ASSERT_OK(Put(cf, Key(*key_idx), RandomString(rnd, (i == 99) ? 1 : 990)));
    (*key_idx)++;
  }
  if (!nowait) {
    dbfull()->TEST_WaitForFlushMemTable();
    dbfull()->TEST_WaitForCompact();
  }
}

1207 1208
// this will generate non-overlapping files since it keeps increasing key_idx
void DBTestBase::GenerateNewFile(Random* rnd, int* key_idx, bool nowait) {
K
krad 已提交
1209
  for (int i = 0; i < KNumKeysByGenerateNewFile; i++) {
1210
    ASSERT_OK(Put(Key(*key_idx), RandomString(rnd, (i == 99) ? 1 : 990)));
1211 1212 1213 1214 1215 1216 1217 1218
    (*key_idx)++;
  }
  if (!nowait) {
    dbfull()->TEST_WaitForFlushMemTable();
    dbfull()->TEST_WaitForCompact();
  }
}

1219 1220
const int DBTestBase::kNumKeysByGenerateNewRandomFile = 51;

1221
void DBTestBase::GenerateNewRandomFile(Random* rnd, bool nowait) {
1222
  for (int i = 0; i < kNumKeysByGenerateNewRandomFile; i++) {
1223
    ASSERT_OK(Put("key" + RandomString(rnd, 7), RandomString(rnd, 2000)));
1224
  }
1225
  ASSERT_OK(Put("key" + RandomString(rnd, 7), RandomString(rnd, 200)));
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  if (!nowait) {
    dbfull()->TEST_WaitForFlushMemTable();
    dbfull()->TEST_WaitForCompact();
  }
}

std::string DBTestBase::IterStatus(Iterator* iter) {
  std::string result;
  if (iter->Valid()) {
    result = iter->key().ToString() + "->" + iter->value().ToString();
  } else {
    result = "(invalid)";
  }
  return result;
}

Options DBTestBase::OptionsForLogIterTest() {
  Options options = CurrentOptions();
  options.create_if_missing = true;
  options.WAL_ttl_seconds = 1000;
  return options;
}

std::string DBTestBase::DummyString(size_t len, char c) {
  return std::string(len, c);
}

void DBTestBase::VerifyIterLast(std::string expected_key, int cf) {
  Iterator* iter;
  ReadOptions ro;
  if (cf == 0) {
    iter = db_->NewIterator(ro);
  } else {
    iter = db_->NewIterator(ro, handles_[cf]);
  }
  iter->SeekToLast();
  ASSERT_EQ(IterStatus(iter), expected_key);
  delete iter;
}

// Used to test InplaceUpdate

// If previous value is nullptr or delta is > than previous value,
//   sets newValue with delta
// If previous value is not empty,
//   updates previous value with 'b' string of previous value size - 1.
S
sdong 已提交
1272 1273 1274 1275
UpdateStatus DBTestBase::updateInPlaceSmallerSize(char* prevValue,
                                                  uint32_t* prevSize,
                                                  Slice delta,
                                                  std::string* newValue) {
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  if (prevValue == nullptr) {
    *newValue = std::string(delta.size(), 'c');
    return UpdateStatus::UPDATED;
  } else {
    *prevSize = *prevSize - 1;
    std::string str_b = std::string(*prevSize, 'b');
    memcpy(prevValue, str_b.c_str(), str_b.size());
    return UpdateStatus::UPDATED_INPLACE;
  }
}

S
sdong 已提交
1287 1288 1289 1290
UpdateStatus DBTestBase::updateInPlaceSmallerVarintSize(char* prevValue,
                                                        uint32_t* prevSize,
                                                        Slice delta,
                                                        std::string* newValue) {
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
  if (prevValue == nullptr) {
    *newValue = std::string(delta.size(), 'c');
    return UpdateStatus::UPDATED;
  } else {
    *prevSize = 1;
    std::string str_b = std::string(*prevSize, 'b');
    memcpy(prevValue, str_b.c_str(), str_b.size());
    return UpdateStatus::UPDATED_INPLACE;
  }
}

A
Andrew Kryczka 已提交
1302 1303
UpdateStatus DBTestBase::updateInPlaceLargerSize(char* /*prevValue*/,
                                                 uint32_t* /*prevSize*/,
S
sdong 已提交
1304 1305
                                                 Slice delta,
                                                 std::string* newValue) {
1306 1307 1308 1309
  *newValue = std::string(delta.size(), 'c');
  return UpdateStatus::UPDATED;
}

A
Andrew Kryczka 已提交
1310 1311 1312 1313
UpdateStatus DBTestBase::updateInPlaceNoAction(char* /*prevValue*/,
                                               uint32_t* /*prevSize*/,
                                               Slice /*delta*/,
                                               std::string* /*newValue*/) {
1314 1315 1316 1317 1318 1319
  return UpdateStatus::UPDATE_FAILED;
}

// Utility method to test InplaceUpdate
void DBTestBase::validateNumberOfEntries(int numValues, int cf) {
  Arena arena;
A
Andrew Kryczka 已提交
1320
  auto options = CurrentOptions();
A
Andrew Kryczka 已提交
1321
  InternalKeyComparator icmp(options.comparator);
1322 1323
  ReadRangeDelAggregator range_del_agg(&icmp,
                                       kMaxSequenceNumber /* upper_bound */);
1324 1325 1326
  // This should be defined after range_del_agg so that it destructs the
  // assigned iterator before it range_del_agg is already destructed.
  ScopedArenaIterator iter;
1327
  if (cf != 0) {
1328 1329
    iter.set(dbfull()->NewInternalIterator(&arena, &range_del_agg,
                                           kMaxSequenceNumber, handles_[cf]));
1330
  } else {
1331 1332
    iter.set(dbfull()->NewInternalIterator(&arena, &range_del_agg,
                                           kMaxSequenceNumber));
1333 1334 1335 1336 1337 1338
  }
  iter->SeekToFirst();
  ASSERT_EQ(iter->status().ok(), true);
  int seq = numValues;
  while (iter->Valid()) {
    ParsedInternalKey ikey;
1339
    ikey.clear();
1340 1341 1342 1343 1344 1345 1346 1347 1348
    ASSERT_EQ(ParseInternalKey(iter->key(), &ikey), true);

    // checks sequence number for updates
    ASSERT_EQ(ikey.sequence, (unsigned)seq--);
    iter->Next();
  }
  ASSERT_EQ(0, seq);
}

S
sdong 已提交
1349 1350
void DBTestBase::CopyFile(const std::string& source,
                          const std::string& destination, uint64_t size) {
1351
  const EnvOptions soptions;
1352
  std::unique_ptr<SequentialFile> srcfile;
1353
  ASSERT_OK(env_->NewSequentialFile(source, &srcfile, soptions));
1354
  std::unique_ptr<WritableFile> destfile;
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
  ASSERT_OK(env_->NewWritableFile(destination, &destfile, soptions));

  if (size == 0) {
    // default argument means copy everything
    ASSERT_OK(env_->GetFileSize(source, &size));
  }

  char buffer[4096];
  Slice slice;
  while (size > 0) {
    uint64_t one = std::min(uint64_t(sizeof(buffer)), size);
    ASSERT_OK(srcfile->Read(one, &slice, buffer));
    ASSERT_OK(destfile->Append(slice));
    size -= slice.size();
  }
  ASSERT_OK(destfile->Close());
}

1373 1374
std::unordered_map<std::string, uint64_t> DBTestBase::GetAllSSTFiles(
    uint64_t* total_size) {
1375 1376
  std::unordered_map<std::string, uint64_t> res;

1377 1378 1379
  if (total_size) {
    *total_size = 0;
  }
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  std::vector<std::string> files;
  env_->GetChildren(dbname_, &files);
  for (auto& file_name : files) {
    uint64_t number;
    FileType type;
    std::string file_path = dbname_ + "/" + file_name;
    if (ParseFileName(file_name, &number, &type) && type == kTableFile) {
      uint64_t file_size = 0;
      env_->GetFileSize(file_path, &file_size);
      res[file_path] = file_size;
1390 1391 1392
      if (total_size) {
        *total_size += file_size;
      }
1393 1394 1395 1396 1397
    }
  }
  return res;
}

Y
Yi Wu 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
std::vector<std::uint64_t> DBTestBase::ListTableFiles(Env* env,
                                                      const std::string& path) {
  std::vector<std::string> files;
  std::vector<uint64_t> file_numbers;
  env->GetChildren(path, &files);
  uint64_t number;
  FileType type;
  for (size_t i = 0; i < files.size(); ++i) {
    if (ParseFileName(files[i], &number, &type)) {
      if (type == kTableFile) {
        file_numbers.push_back(number);
      }
    }
  }
  return file_numbers;
}

1415
void DBTestBase::VerifyDBFromMap(std::map<std::string, std::string> true_data,
1416 1417
                                 size_t* total_reads_res, bool tailing_iter,
                                 std::map<std::string, Status> status) {
1418 1419
  size_t total_reads = 0;

1420
  for (auto& kv : true_data) {
1421 1422 1423 1424 1425 1426 1427
    Status s = status[kv.first];
    if (s.ok()) {
      ASSERT_EQ(Get(kv.first), kv.second);
    } else {
      std::string value;
      ASSERT_EQ(s, db_->Get(ReadOptions(), kv.first, &value));
    }
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    total_reads++;
  }

  // Normal Iterator
  {
    int iter_cnt = 0;
    ReadOptions ro;
    ro.total_order_seek = true;
    Iterator* iter = db_->NewIterator(ro);
    // Verify Iterator::Next()
    iter_cnt = 0;
    auto data_iter = true_data.begin();
1440
    Status s;
1441 1442
    for (iter->SeekToFirst(); iter->Valid(); iter->Next(), data_iter++) {
      ASSERT_EQ(iter->key().ToString(), data_iter->first);
1443 1444 1445 1446 1447 1448 1449 1450
      Status current_status = status[data_iter->first];
      if (!current_status.ok()) {
        s = current_status;
      }
      ASSERT_EQ(iter->status(), s);
      if (current_status.ok()) {
        ASSERT_EQ(iter->value().ToString(), data_iter->second);
      }
1451 1452 1453 1454 1455
      iter_cnt++;
      total_reads++;
    }
    ASSERT_EQ(data_iter, true_data.end()) << iter_cnt << " / "
                                          << true_data.size();
1456
    delete iter;
1457 1458

    // Verify Iterator::Prev()
1459 1460
    // Use a new iterator to make sure its status is clean.
    iter = db_->NewIterator(ro);
1461
    iter_cnt = 0;
1462
    s = Status::OK();
1463 1464 1465
    auto data_rev = true_data.rbegin();
    for (iter->SeekToLast(); iter->Valid(); iter->Prev(), data_rev++) {
      ASSERT_EQ(iter->key().ToString(), data_rev->first);
1466 1467 1468 1469 1470 1471 1472 1473
      Status current_status = status[data_rev->first];
      if (!current_status.ok()) {
        s = current_status;
      }
      ASSERT_EQ(iter->status(), s);
      if (current_status.ok()) {
        ASSERT_EQ(iter->value().ToString(), data_rev->second);
      }
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
      iter_cnt++;
      total_reads++;
    }
    ASSERT_EQ(data_rev, true_data.rend()) << iter_cnt << " / "
                                          << true_data.size();

    // Verify Iterator::Seek()
    for (auto kv : true_data) {
      iter->Seek(kv.first);
      ASSERT_EQ(kv.first, iter->key().ToString());
      ASSERT_EQ(kv.second, iter->value().ToString());
      total_reads++;
    }
    delete iter;
1488 1489
  }

1490
  if (tailing_iter) {
1491
#ifndef ROCKSDB_LITE
1492 1493 1494 1495 1496 1497
    // Tailing iterator
    int iter_cnt = 0;
    ReadOptions ro;
    ro.tailing = true;
    ro.total_order_seek = true;
    Iterator* iter = db_->NewIterator(ro);
1498

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    // Verify ForwardIterator::Next()
    iter_cnt = 0;
    auto data_iter = true_data.begin();
    for (iter->SeekToFirst(); iter->Valid(); iter->Next(), data_iter++) {
      ASSERT_EQ(iter->key().ToString(), data_iter->first);
      ASSERT_EQ(iter->value().ToString(), data_iter->second);
      iter_cnt++;
      total_reads++;
    }
    ASSERT_EQ(data_iter, true_data.end()) << iter_cnt << " / "
                                          << true_data.size();

    // Verify ForwardIterator::Seek()
    for (auto kv : true_data) {
      iter->Seek(kv.first);
      ASSERT_EQ(kv.first, iter->key().ToString());
      ASSERT_EQ(kv.second, iter->value().ToString());
      total_reads++;
    }

    delete iter;
1520
#endif  // ROCKSDB_LITE
1521
  }
1522 1523 1524 1525

  if (total_reads_res) {
    *total_reads_res = total_reads;
  }
1526 1527
}

1528 1529 1530 1531
void DBTestBase::VerifyDBInternal(
    std::vector<std::pair<std::string, std::string>> true_data) {
  Arena arena;
  InternalKeyComparator icmp(last_options_.comparator);
1532 1533
  ReadRangeDelAggregator range_del_agg(&icmp,
                                       kMaxSequenceNumber /* upper_bound */);
1534 1535
  auto iter =
      dbfull()->NewInternalIterator(&arena, &range_del_agg, kMaxSequenceNumber);
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
  iter->SeekToFirst();
  for (auto p : true_data) {
    ASSERT_TRUE(iter->Valid());
    ParsedInternalKey ikey;
    ASSERT_TRUE(ParseInternalKey(iter->key(), &ikey));
    ASSERT_EQ(p.first, ikey.user_key);
    ASSERT_EQ(p.second, iter->value());
    iter->Next();
  };
  ASSERT_FALSE(iter->Valid());
  iter->~InternalIterator();
}

Y
Yi Wu 已提交
1549
#ifndef ROCKSDB_LITE
1550

Y
Yi Wu 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
uint64_t DBTestBase::GetNumberOfSstFilesForColumnFamily(
    DB* db, std::string column_family_name) {
  std::vector<LiveFileMetaData> metadata;
  db->GetLiveFilesMetaData(&metadata);
  uint64_t result = 0;
  for (auto& fileMetadata : metadata) {
    result += (fileMetadata.column_family_name == column_family_name);
  }
  return result;
}
#endif  // ROCKSDB_LITE

1563
}  // namespace rocksdb