db_stress_test_base.cc 79.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  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).
//
// 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.
//

#ifdef GFLAGS
#include "db_stress_tool/db_stress_common.h"
#include "db_stress_tool/db_stress_driver.h"
14
#include "rocksdb/convenience.h"
15
#include "rocksdb/sst_file_manager.h"
16

17
namespace ROCKSDB_NAMESPACE {
18 19 20 21 22 23 24 25 26 27 28 29 30 31
StressTest::StressTest()
    : cache_(NewCache(FLAGS_cache_size)),
      compressed_cache_(NewLRUCache(FLAGS_compressed_cache_size)),
      filter_policy_(FLAGS_bloom_bits >= 0
                         ? FLAGS_use_block_based_filter
                               ? NewBloomFilterPolicy(FLAGS_bloom_bits, true)
                               : NewBloomFilterPolicy(FLAGS_bloom_bits, false)
                         : nullptr),
      db_(nullptr),
#ifndef ROCKSDB_LITE
      txn_db_(nullptr),
#endif
      new_column_family_name_(1),
      num_times_reopened_(0),
32 33
      db_preload_finished_(false),
      cmp_db_(nullptr) {
34 35
  if (FLAGS_destroy_db_initially) {
    std::vector<std::string> files;
36
    db_stress_env->GetChildren(FLAGS_db, &files);
37 38
    for (unsigned int i = 0; i < files.size(); i++) {
      if (Slice(files[i]).starts_with("heap-")) {
39
        db_stress_env->DeleteFile(FLAGS_db + "/" + files[i]);
40 41
      }
    }
L
Levi Tamasi 已提交
42

43
    Options options;
44
    options.env = db_stress_env;
45
    // Remove files without preserving manfiest files
L
Levi Tamasi 已提交
46 47 48 49 50 51 52 53 54
#ifndef ROCKSDB_LITE
    const Status s = !FLAGS_use_blob_db
                         ? DestroyDB(FLAGS_db, options)
                         : blob_db::DestroyBlobDB(FLAGS_db, options,
                                                  blob_db::BlobDBOptions());
#else
    const Status s = DestroyDB(FLAGS_db, options);
#endif  // !ROCKSDB_LITE

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    if (!s.ok()) {
      fprintf(stderr, "Cannot destroy original db: %s\n", s.ToString().c_str());
      exit(1);
    }
  }
}

StressTest::~StressTest() {
  for (auto cf : column_families_) {
    delete cf;
  }
  column_families_.clear();
  delete db_;

  assert(secondaries_.size() == secondary_cfh_lists_.size());
  size_t n = secondaries_.size();
  for (size_t i = 0; i != n; ++i) {
    for (auto* cf : secondary_cfh_lists_[i]) {
      delete cf;
    }
    secondary_cfh_lists_[i].clear();
    delete secondaries_[i];
  }
  secondaries_.clear();
79 80 81 82 83 84

  for (auto* cf : cmp_cfhs_) {
    delete cf;
  }
  cmp_cfhs_.clear();
  delete cmp_db_;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

std::shared_ptr<Cache> StressTest::NewCache(size_t capacity) {
  if (capacity <= 0) {
    return nullptr;
  }
  if (FLAGS_use_clock_cache) {
    auto cache = NewClockCache((size_t)capacity);
    if (!cache) {
      fprintf(stderr, "Clock cache not supported.");
      exit(1);
    }
    return cache;
  } else {
    return NewLRUCache((size_t)capacity);
  }
}

bool StressTest::BuildOptionsTable() {
  if (FLAGS_set_options_one_in <= 0) {
    return true;
  }

  std::unordered_map<std::string, std::vector<std::string>> options_tbl = {
      {"write_buffer_size",
       {ToString(options_.write_buffer_size),
        ToString(options_.write_buffer_size * 2),
        ToString(options_.write_buffer_size * 4)}},
      {"max_write_buffer_number",
       {ToString(options_.max_write_buffer_number),
        ToString(options_.max_write_buffer_number * 2),
        ToString(options_.max_write_buffer_number * 4)}},
      {"arena_block_size",
       {
           ToString(options_.arena_block_size),
           ToString(options_.write_buffer_size / 4),
           ToString(options_.write_buffer_size / 8),
       }},
      {"memtable_huge_page_size", {"0", ToString(2 * 1024 * 1024)}},
      {"max_successive_merges", {"0", "2", "4"}},
      {"inplace_update_num_locks", {"100", "200", "300"}},
      // TODO(ljin): enable test for this option
      // {"disable_auto_compactions", {"100", "200", "300"}},
      {"soft_rate_limit", {"0", "0.5", "0.9"}},
      {"hard_rate_limit", {"0", "1.1", "2.0"}},
      {"level0_file_num_compaction_trigger",
       {
           ToString(options_.level0_file_num_compaction_trigger),
           ToString(options_.level0_file_num_compaction_trigger + 2),
           ToString(options_.level0_file_num_compaction_trigger + 4),
       }},
      {"level0_slowdown_writes_trigger",
       {
           ToString(options_.level0_slowdown_writes_trigger),
           ToString(options_.level0_slowdown_writes_trigger + 2),
           ToString(options_.level0_slowdown_writes_trigger + 4),
       }},
      {"level0_stop_writes_trigger",
       {
           ToString(options_.level0_stop_writes_trigger),
           ToString(options_.level0_stop_writes_trigger + 2),
           ToString(options_.level0_stop_writes_trigger + 4),
       }},
      {"max_compaction_bytes",
       {
           ToString(options_.target_file_size_base * 5),
           ToString(options_.target_file_size_base * 15),
           ToString(options_.target_file_size_base * 100),
       }},
      {"target_file_size_base",
       {
           ToString(options_.target_file_size_base),
           ToString(options_.target_file_size_base * 2),
           ToString(options_.target_file_size_base * 4),
       }},
      {"target_file_size_multiplier",
       {
           ToString(options_.target_file_size_multiplier),
           "1",
           "2",
       }},
      {"max_bytes_for_level_base",
       {
           ToString(options_.max_bytes_for_level_base / 2),
           ToString(options_.max_bytes_for_level_base),
           ToString(options_.max_bytes_for_level_base * 2),
       }},
      {"max_bytes_for_level_multiplier",
       {
           ToString(options_.max_bytes_for_level_multiplier),
           "1",
           "2",
       }},
      {"max_sequential_skip_in_iterations", {"4", "8", "12"}},
  };

  options_table_ = std::move(options_tbl);

  for (const auto& iter : options_table_) {
    options_index_.push_back(iter.first);
  }
  return true;
}

void StressTest::InitDb() {
190
  uint64_t now = db_stress_env->NowMicros();
191
  fprintf(stdout, "%s Initializing db_stress\n",
192
          db_stress_env->TimeToString(now / 1000000).c_str());
193 194 195 196 197 198
  PrintEnv();
  Open();
  BuildOptionsTable();
}

void StressTest::InitReadonlyDb(SharedState* shared) {
199
  uint64_t now = db_stress_env->NowMicros();
200
  fprintf(stdout, "%s Preloading db with %" PRIu64 " KVs\n",
201
          db_stress_env->TimeToString(now / 1000000).c_str(), FLAGS_max_key);
202 203 204 205 206
  PreloadDbAndReopenAsReadOnly(FLAGS_max_key, shared);
}

bool StressTest::VerifySecondaries() {
#ifndef ROCKSDB_LITE
207
  if (FLAGS_test_secondary) {
208
    uint64_t now = db_stress_env->NowMicros();
209 210
    fprintf(
        stdout, "%s Start to verify secondaries against primary\n",
211
        db_stress_env->TimeToString(static_cast<uint64_t>(now) / 1000000).c_str());
212 213 214 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
  }
  for (size_t k = 0; k != secondaries_.size(); ++k) {
    Status s = secondaries_[k]->TryCatchUpWithPrimary();
    if (!s.ok()) {
      fprintf(stderr, "Secondary failed to catch up with primary\n");
      return false;
    }
    ReadOptions ropts;
    ropts.total_order_seek = true;
    // Verify only the default column family since the primary may have
    // dropped other column families after most recent reopen.
    std::unique_ptr<Iterator> iter1(db_->NewIterator(ropts));
    std::unique_ptr<Iterator> iter2(secondaries_[k]->NewIterator(ropts));
    for (iter1->SeekToFirst(), iter2->SeekToFirst();
         iter1->Valid() && iter2->Valid(); iter1->Next(), iter2->Next()) {
      if (iter1->key().compare(iter2->key()) != 0 ||
          iter1->value().compare(iter2->value())) {
        fprintf(stderr,
                "Secondary %d contains different data from "
                "primary.\nPrimary: %s : %s\nSecondary: %s : %s\n",
                static_cast<int>(k),
                iter1->key().ToString(/*hex=*/true).c_str(),
                iter1->value().ToString(/*hex=*/true).c_str(),
                iter2->key().ToString(/*hex=*/true).c_str(),
                iter2->value().ToString(/*hex=*/true).c_str());
        return false;
      }
    }
    if (iter1->Valid() && !iter2->Valid()) {
      fprintf(stderr,
              "Secondary %d record count is smaller than that of primary\n",
              static_cast<int>(k));
      return false;
    } else if (!iter1->Valid() && iter2->Valid()) {
      fprintf(stderr,
              "Secondary %d record count is larger than that of primary\n",
              static_cast<int>(k));
      return false;
    }
  }
252
  if (FLAGS_test_secondary) {
253
    uint64_t now = db_stress_env->NowMicros();
254 255
    fprintf(
        stdout, "%s Verification of secondaries succeeded\n",
256
        db_stress_env->TimeToString(static_cast<uint64_t>(now) / 1000000).c_str());
257 258 259 260 261 262 263 264 265 266 267 268 269 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 311 312 313
  }
#endif  // ROCKSDB_LITE
  return true;
}

Status StressTest::AssertSame(DB* db, ColumnFamilyHandle* cf,
                              ThreadState::SnapshotState& snap_state) {
  Status s;
  if (cf->GetName() != snap_state.cf_at_name) {
    return s;
  }
  ReadOptions ropt;
  ropt.snapshot = snap_state.snapshot;
  PinnableSlice exp_v(&snap_state.value);
  exp_v.PinSelf();
  PinnableSlice v;
  s = db->Get(ropt, cf, snap_state.key, &v);
  if (!s.ok() && !s.IsNotFound()) {
    return s;
  }
  if (snap_state.status != s) {
    return Status::Corruption(
        "The snapshot gave inconsistent results for key " +
        ToString(Hash(snap_state.key.c_str(), snap_state.key.size(), 0)) +
        " in cf " + cf->GetName() + ": (" + snap_state.status.ToString() +
        ") vs. (" + s.ToString() + ")");
  }
  if (s.ok()) {
    if (exp_v != v) {
      return Status::Corruption("The snapshot gave inconsistent values: (" +
                                exp_v.ToString() + ") vs. (" + v.ToString() +
                                ")");
    }
  }
  if (snap_state.key_vec != nullptr) {
    // When `prefix_extractor` is set, seeking to beginning and scanning
    // across prefixes are only supported with `total_order_seek` set.
    ropt.total_order_seek = true;
    std::unique_ptr<Iterator> iterator(db->NewIterator(ropt));
    std::unique_ptr<std::vector<bool>> tmp_bitvec(
        new std::vector<bool>(FLAGS_max_key));
    for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) {
      uint64_t key_val;
      if (GetIntVal(iterator->key().ToString(), &key_val)) {
        (*tmp_bitvec.get())[key_val] = true;
      }
    }
    if (!std::equal(snap_state.key_vec->begin(), snap_state.key_vec->end(),
                    tmp_bitvec.get()->begin())) {
      return Status::Corruption("Found inconsistent keys at this snapshot");
    }
  }
  return Status::OK();
}

void StressTest::VerificationAbort(SharedState* shared, std::string msg,
                                   Status s) const {
314 315
  fprintf(stderr, "Verification failed: %s. Status is %s\n", msg.c_str(),
          s.ToString().c_str());
316 317 318 319 320
  shared->SetVerificationFailure();
}

void StressTest::VerificationAbort(SharedState* shared, std::string msg, int cf,
                                   int64_t key) const {
321 322 323
  fprintf(stderr,
          "Verification failed for column family %d key %" PRIi64 ": %s\n", cf,
          key, msg.c_str());
324 325 326 327 328 329 330 331 332 333 334 335 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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  shared->SetVerificationFailure();
}

void StressTest::PrintStatistics() {
  if (dbstats) {
    fprintf(stdout, "STATISTICS:\n%s\n", dbstats->ToString().c_str());
  }
  if (dbstats_secondaries) {
    fprintf(stdout, "Secondary instances STATISTICS:\n%s\n",
            dbstats_secondaries->ToString().c_str());
  }
}

// Currently PreloadDb has to be single-threaded.
void StressTest::PreloadDbAndReopenAsReadOnly(int64_t number_of_keys,
                                              SharedState* shared) {
  WriteOptions write_opts;
  write_opts.disableWAL = FLAGS_disable_wal;
  if (FLAGS_sync) {
    write_opts.sync = true;
  }
  char value[100];
  int cf_idx = 0;
  Status s;
  for (auto cfh : column_families_) {
    for (int64_t k = 0; k != number_of_keys; ++k) {
      std::string key_str = Key(k);
      Slice key = key_str;
      size_t sz = GenerateValue(0 /*value_base*/, value, sizeof(value));
      Slice v(value, sz);
      shared->Put(cf_idx, k, 0, true /* pending */);

      if (FLAGS_use_merge) {
        if (!FLAGS_use_txn) {
          s = db_->Merge(write_opts, cfh, key, v);
        } else {
#ifndef ROCKSDB_LITE
          Transaction* txn;
          s = NewTxn(write_opts, &txn);
          if (s.ok()) {
            s = txn->Merge(cfh, key, v);
            if (s.ok()) {
              s = CommitTxn(txn);
            }
          }
#endif
        }
      } else {
        if (!FLAGS_use_txn) {
          s = db_->Put(write_opts, cfh, key, v);
        } else {
#ifndef ROCKSDB_LITE
          Transaction* txn;
          s = NewTxn(write_opts, &txn);
          if (s.ok()) {
            s = txn->Put(cfh, key, v);
            if (s.ok()) {
              s = CommitTxn(txn);
            }
          }
#endif
        }
      }

      shared->Put(cf_idx, k, 0, false /* pending */);
      if (!s.ok()) {
        break;
      }
    }
    if (!s.ok()) {
      break;
    }
    ++cf_idx;
  }
  if (s.ok()) {
    s = db_->Flush(FlushOptions(), column_families_);
  }
  if (s.ok()) {
    for (auto cf : column_families_) {
      delete cf;
    }
    column_families_.clear();
    delete db_;
    db_ = nullptr;
#ifndef ROCKSDB_LITE
    txn_db_ = nullptr;
#endif

    db_preload_finished_.store(true);
413
    auto now = db_stress_env->NowMicros();
414
    fprintf(stdout, "%s Reopening database in read-only\n",
415
            db_stress_env->TimeToString(now / 1000000).c_str());
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    // Reopen as read-only, can ignore all options related to updates
    Open();
  } else {
    fprintf(stderr, "Failed to preload db");
    exit(1);
  }
}

Status StressTest::SetOptions(ThreadState* thread) {
  assert(FLAGS_set_options_one_in > 0);
  std::unordered_map<std::string, std::string> opts;
  std::string name =
      options_index_[thread->rand.Next() % options_index_.size()];
  int value_idx = thread->rand.Next() % options_table_[name].size();
  if (name == "soft_rate_limit" || name == "hard_rate_limit") {
    opts["soft_rate_limit"] = options_table_["soft_rate_limit"][value_idx];
    opts["hard_rate_limit"] = options_table_["hard_rate_limit"][value_idx];
  } else if (name == "level0_file_num_compaction_trigger" ||
             name == "level0_slowdown_writes_trigger" ||
             name == "level0_stop_writes_trigger") {
    opts["level0_file_num_compaction_trigger"] =
        options_table_["level0_file_num_compaction_trigger"][value_idx];
    opts["level0_slowdown_writes_trigger"] =
        options_table_["level0_slowdown_writes_trigger"][value_idx];
    opts["level0_stop_writes_trigger"] =
        options_table_["level0_stop_writes_trigger"][value_idx];
  } else {
    opts[name] = options_table_[name][value_idx];
  }

  int rand_cf_idx = thread->rand.Next() % FLAGS_column_families;
  auto cfh = column_families_[rand_cf_idx];
  return db_->SetOptions(cfh, opts);
}

#ifndef ROCKSDB_LITE
Status StressTest::NewTxn(WriteOptions& write_opts, Transaction** txn) {
  if (!FLAGS_use_txn) {
    return Status::InvalidArgument("NewTxn when FLAGS_use_txn is not set");
  }
  static std::atomic<uint64_t> txn_id = {0};
  TransactionOptions txn_options;
  *txn = txn_db_->BeginTransaction(write_opts, txn_options);
  auto istr = std::to_string(txn_id.fetch_add(1));
  Status s = (*txn)->SetName("xid" + istr);
  return s;
}

Status StressTest::CommitTxn(Transaction* txn) {
  if (!FLAGS_use_txn) {
    return Status::InvalidArgument("CommitTxn when FLAGS_use_txn is not set");
  }
  Status s = txn->Prepare();
  if (s.ok()) {
    s = txn->Commit();
  }
  delete txn;
  return s;
}
475 476 477 478 479 480 481 482 483 484 485

Status StressTest::RollbackTxn(Transaction* txn) {
  if (!FLAGS_use_txn) {
    return Status::InvalidArgument(
        "RollbackTxn when FLAGS_use_txn is not"
        " set");
  }
  Status s = txn->Rollback();
  delete txn;
  return s;
}
486 487 488 489 490 491 492 493 494 495 496 497
#endif

void StressTest::OperateDb(ThreadState* thread) {
  ReadOptions read_opts(FLAGS_verify_checksum, true);
  WriteOptions write_opts;
  auto shared = thread->shared;
  char value[100];
  std::string from_db;
  if (FLAGS_sync) {
    write_opts.sync = true;
  }
  write_opts.disableWAL = FLAGS_disable_wal;
498 499 500 501 502
  const int prefixBound = static_cast<int>(FLAGS_readpercent) +
                          static_cast<int>(FLAGS_prefixpercent);
  const int writeBound = prefixBound + static_cast<int>(FLAGS_writepercent);
  const int delBound = writeBound + static_cast<int>(FLAGS_delpercent);
  const int delRangeBound = delBound + static_cast<int>(FLAGS_delrangepercent);
503 504
  const uint64_t ops_per_open = FLAGS_ops_per_thread / (FLAGS_reopen + 1);

A
anand76 已提交
505 506 507 508 509 510
#ifndef NDEBUG
  if (FLAGS_read_fault_one_in) {
    fault_fs_guard->SetThreadLocalReadErrorContext(thread->shared->GetSeed(),
                                            FLAGS_read_fault_one_in);
  }
#endif // NDEBUG
511 512
  thread->stats.Start();
  for (int open_cnt = 0; open_cnt <= FLAGS_reopen; ++open_cnt) {
513 514
    if (thread->shared->HasVerificationFailedYet() ||
        thread->shared->ShouldStopTest()) {
515 516 517 518 519 520 521 522 523 524 525 526
      break;
    }
    if (open_cnt != 0) {
      thread->stats.FinishedSingleOp();
      MutexLock l(thread->shared->GetMutex());
      while (!thread->snapshot_queue.empty()) {
        db_->ReleaseSnapshot(thread->snapshot_queue.front().second.snapshot);
        delete thread->snapshot_queue.front().second.key_vec;
        thread->snapshot_queue.pop();
      }
      thread->shared->IncVotedReopen();
      if (thread->shared->AllVotedReopen()) {
527
        thread->shared->GetStressTest()->Reopen(thread);
528 529 530 531 532 533 534 535 536 537 538 539 540 541
        thread->shared->GetCondVar()->SignalAll();
      } else {
        thread->shared->GetCondVar()->Wait();
      }
      // Commenting this out as we don't want to reset stats on each open.
      // thread->stats.Start();
    }

    for (uint64_t i = 0; i < ops_per_open; i++) {
      if (thread->shared->HasVerificationFailedYet()) {
        break;
      }

      // Change Options
542
      if (thread->rand.OneInOpt(FLAGS_set_options_one_in)) {
543 544 545
        SetOptions(thread);
      }

546
      if (thread->rand.OneInOpt(FLAGS_set_in_place_one_in)) {
547 548 549
        options_.inplace_update_support ^= options_.inplace_update_support;
      }

550 551 552 553 554 555 556 557
      if (thread->tid == 0 && FLAGS_verify_db_one_in > 0 &&
          thread->rand.OneIn(FLAGS_verify_db_one_in)) {
        ContinuouslyVerifyDb(thread);
        if (thread->shared->ShouldStopTest()) {
          break;
        }
      }

558 559
      MaybeClearOneColumnFamily(thread);

560
      if (thread->rand.OneInOpt(FLAGS_sync_wal_one_in)) {
Y
Yanqin Jin 已提交
561 562
        Status s = db_->SyncWAL();
        if (!s.ok() && !s.IsNotSupported()) {
563
          fprintf(stderr, "SyncWAL() failed: %s\n", s.ToString().c_str());
Y
Yanqin Jin 已提交
564 565 566
        }
      }

567 568
      int rand_column_family = thread->rand.Next() % FLAGS_column_families;
      ColumnFamilyHandle* column_family = column_families_[rand_column_family];
569

570 571
      if (thread->rand.OneInOpt(FLAGS_compact_files_one_in)) {
        TestCompactFiles(thread, column_family);
572
      }
573

574 575 576 577 578 579 580 581 582
      int64_t rand_key = GenerateOneKey(thread, i);
      std::string keystr = Key(rand_key);
      Slice key = keystr;
      std::unique_ptr<MutexLock> lock;
      if (ShouldAcquireMutexOnKey()) {
        lock.reset(new MutexLock(
            shared->GetMutexForKey(rand_column_family, rand_key)));
      }

583
      if (thread->rand.OneInOpt(FLAGS_compact_range_one_in)) {
584 585 586
        TestCompactRange(thread, rand_key, key, column_family);
        if (thread->shared->HasVerificationFailedYet()) {
          break;
587 588 589 590 591 592
        }
      }

      std::vector<int> rand_column_families =
          GenerateColumnFamilies(FLAGS_column_families, rand_column_family);

593
      if (thread->rand.OneInOpt(FLAGS_flush_one_in)) {
594
        Status status = TestFlush(rand_column_families);
595 596 597 598 599 600
        if (!status.ok()) {
          fprintf(stdout, "Unable to perform Flush(): %s\n",
                  status.ToString().c_str());
        }
      }

601
#ifndef ROCKSDB_LITE
602 603 604
      // Verify GetLiveFiles with a 1 in N chance.
      if (thread->rand.OneInOpt(FLAGS_get_live_files_one_in)) {
        Status status = VerifyGetLiveFiles();
605
        if (!status.ok()) {
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
          VerificationAbort(shared, "VerifyGetLiveFiles status not OK", status);
        }
      }

      // Verify GetSortedWalFiles with a 1 in N chance.
      if (thread->rand.OneInOpt(FLAGS_get_sorted_wal_files_one_in)) {
        Status status = VerifyGetSortedWalFiles();
        if (!status.ok()) {
          VerificationAbort(shared, "VerifyGetSortedWalFiles status not OK",
                            status);
        }
      }

      // Verify GetCurrentWalFile with a 1 in N chance.
      if (thread->rand.OneInOpt(FLAGS_get_current_wal_file_one_in)) {
        Status status = VerifyGetCurrentWalFile();
        if (!status.ok()) {
          VerificationAbort(shared, "VerifyGetCurrentWalFile status not OK",
624 625 626 627 628
                            status);
        }
      }
#endif  // !ROCKSDB_LITE

629
      if (thread->rand.OneInOpt(FLAGS_pause_background_one_in)) {
630
        Status status = TestPauseBackground(thread);
631
        if (!status.ok()) {
632 633
          VerificationAbort(
              shared, "Pause/ContinueBackgroundWork status not OK", status);
634 635 636
        }
      }

637 638 639 640 641 642 643 644 645
#ifndef ROCKSDB_LITE
      if (thread->rand.OneInOpt(FLAGS_verify_checksum_one_in)) {
        Status status = db_->VerifyChecksum();
        if (!status.ok()) {
          VerificationAbort(shared, "VerifyChecksum status not OK", status);
        }
      }
#endif

646 647
      std::vector<int64_t> rand_keys = GenerateKeys(rand_key);

648
      if (thread->rand.OneInOpt(FLAGS_ingest_external_file_one_in)) {
649 650 651
        TestIngestExternalFile(thread, rand_column_families, rand_keys, lock);
      }

652
      if (thread->rand.OneInOpt(FLAGS_backup_one_in)) {
653 654 655 656 657 658 659
        Status s = TestBackupRestore(thread, rand_column_families, rand_keys);
        if (!s.ok()) {
          VerificationAbort(shared, "Backup/restore gave inconsistent state",
                            s);
        }
      }

660
      if (thread->rand.OneInOpt(FLAGS_checkpoint_one_in)) {
661 662 663 664 665 666
        Status s = TestCheckpoint(thread, rand_column_families, rand_keys);
        if (!s.ok()) {
          VerificationAbort(shared, "Checkpoint gave inconsistent state", s);
        }
      }

S
sdong 已提交
667 668 669 670 671 672 673 674 675
#ifndef ROCKSDB_LITE
      if (thread->rand.OneInOpt(FLAGS_approximate_size_one_in)) {
        Status s =
            TestApproximateSize(thread, i, rand_column_families, rand_keys);
        if (!s.ok()) {
          VerificationAbort(shared, "ApproximateSize Failed", s);
        }
      }
#endif  // !ROCKSDB_LITE
676
      if (thread->rand.OneInOpt(FLAGS_acquire_snapshot_one_in)) {
677
        TestAcquireSnapshot(thread, rand_column_family, keystr, i);
678
      }
679 680 681

      /*always*/ {
        Status s = MaybeReleaseSnapshots(thread, i);
682 683 684 685 686 687 688 689 690
        if (!s.ok()) {
          VerificationAbort(shared, "Snapshot gave inconsistent state", s);
        }
      }

      int prob_op = thread->rand.Uniform(100);
      // Reset this in case we pick something other than a read op. We don't
      // want to use a stale value when deciding at the beginning of the loop
      // whether to vote to reopen
691
      if (prob_op >= 0 && prob_op < static_cast<int>(FLAGS_readpercent)) {
692
        assert(0 <= prob_op);
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        // OPERATION read
        if (FLAGS_use_multiget) {
          // Leave room for one more iteration of the loop with a single key
          // batch. This is to ensure that each thread does exactly the same
          // number of ops
          int multiget_batch_size = static_cast<int>(
              std::min(static_cast<uint64_t>(thread->rand.Uniform(64)),
                       FLAGS_ops_per_thread - i - 1));
          // If its the last iteration, ensure that multiget_batch_size is 1
          multiget_batch_size = std::max(multiget_batch_size, 1);
          rand_keys = GenerateNKeys(thread, multiget_batch_size, i);
          TestMultiGet(thread, read_opts, rand_column_families, rand_keys);
          i += multiget_batch_size - 1;
        } else {
          TestGet(thread, read_opts, rand_column_families, rand_keys);
        }
709
      } else if (prob_op < prefixBound) {
710
        assert(static_cast<int>(FLAGS_readpercent) <= prob_op);
711 712 713 714 715 716
        // OPERATION prefix scan
        // keys are 8 bytes long, prefix size is FLAGS_prefix_size. There are
        // (8 - FLAGS_prefix_size) bytes besides the prefix. So there will
        // be 2 ^ ((8 - FLAGS_prefix_size) * 8) possible keys with the same
        // prefix
        TestPrefixScan(thread, read_opts, rand_column_families, rand_keys);
717 718
      } else if (prob_op < writeBound) {
        assert(prefixBound <= prob_op);
719 720 721
        // OPERATION write
        TestPut(thread, write_opts, read_opts, rand_column_families, rand_keys,
                value, lock);
722 723
      } else if (prob_op < delBound) {
        assert(writeBound <= prob_op);
724 725
        // OPERATION delete
        TestDelete(thread, write_opts, rand_column_families, rand_keys, lock);
726 727
      } else if (prob_op < delRangeBound) {
        assert(delBound <= prob_op);
728 729 730 731
        // OPERATION delete range
        TestDeleteRange(thread, write_opts, rand_column_families, rand_keys,
                        lock);
      } else {
732
        assert(delRangeBound <= prob_op);
733 734 735 736 737 738 739 740 741 742 743 744 745
        // OPERATION iterate
        int num_seeks = static_cast<int>(
            std::min(static_cast<uint64_t>(thread->rand.Uniform(4)),
                     FLAGS_ops_per_thread - i - 1));
        rand_keys = GenerateNKeys(thread, num_seeks, i);
        i += num_seeks - 1;
        TestIterate(thread, read_opts, rand_column_families, rand_keys);
      }
      thread->stats.FinishedSingleOp();
#ifndef ROCKSDB_LITE
      uint32_t tid = thread->tid;
      assert(secondaries_.empty() ||
             static_cast<size_t>(tid) < secondaries_.size());
746
      if (thread->rand.OneInOpt(FLAGS_secondary_catch_up_one_in)) {
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
        Status s = secondaries_[tid]->TryCatchUpWithPrimary();
        if (!s.ok()) {
          VerificationAbort(shared, "Secondary instance failed to catch up", s);
          break;
        }
      }
#endif
    }
  }
  while (!thread->snapshot_queue.empty()) {
    db_->ReleaseSnapshot(thread->snapshot_queue.front().second.snapshot);
    delete thread->snapshot_queue.front().second.key_vec;
    thread->snapshot_queue.pop();
  }

  thread->stats.Stop();
}

#ifndef ROCKSDB_LITE
// Generated a list of keys that close to boundaries of SST keys.
// If there isn't any SST file in the DB, return empty list.
std::vector<std::string> StressTest::GetWhiteBoxKeys(ThreadState* thread,
                                                     DB* db,
                                                     ColumnFamilyHandle* cfh,
                                                     size_t num_keys) {
  ColumnFamilyMetaData cfmd;
  db->GetColumnFamilyMetaData(cfh, &cfmd);
  std::vector<std::string> boundaries;
  for (const LevelMetaData& lmd : cfmd.levels) {
    for (const SstFileMetaData& sfmd : lmd.files) {
      boundaries.push_back(sfmd.smallestkey);
      boundaries.push_back(sfmd.largestkey);
    }
  }
  if (boundaries.empty()) {
    return {};
  }

  std::vector<std::string> ret;
  for (size_t j = 0; j < num_keys; j++) {
    std::string k =
        boundaries[thread->rand.Uniform(static_cast<int>(boundaries.size()))];
    if (thread->rand.OneIn(3)) {
      // Reduce one byte from the string
      for (int i = static_cast<int>(k.length()) - 1; i >= 0; i--) {
        uint8_t cur = k[i];
        if (cur > 0) {
          k[i] = static_cast<char>(cur - 1);
          break;
        } else if (i > 0) {
B
Burton Li 已提交
797
          k[i] = 0xFFu;
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
        }
      }
    } else if (thread->rand.OneIn(2)) {
      // Add one byte to the string
      for (int i = static_cast<int>(k.length()) - 1; i >= 0; i--) {
        uint8_t cur = k[i];
        if (cur < 255) {
          k[i] = static_cast<char>(cur + 1);
          break;
        } else if (i > 0) {
          k[i] = 0x00;
        }
      }
    }
    ret.push_back(k);
  }
  return ret;
}
#endif  // !ROCKSDB_LITE

// Given a key K, this creates an iterator which scans to K and then
// does a random sequence of Next/Prev operations.
Status StressTest::TestIterate(ThreadState* thread,
                               const ReadOptions& read_opts,
                               const std::vector<int>& rand_column_families,
                               const std::vector<int64_t>& rand_keys) {
  Status s;
  const Snapshot* snapshot = db_->GetSnapshot();
  ReadOptions readoptionscopy = read_opts;
  readoptionscopy.snapshot = snapshot;

S
sdong 已提交
829
  bool expect_total_order = false;
830 831 832
  if (thread->rand.OneIn(16)) {
    // When prefix extractor is used, it's useful to cover total order seek.
    readoptionscopy.total_order_seek = true;
S
sdong 已提交
833 834 835 836 837 838 839
    expect_total_order = true;
  } else if (thread->rand.OneIn(4)) {
    readoptionscopy.total_order_seek = false;
    readoptionscopy.auto_prefix_mode = true;
    expect_total_order = true;
  } else if (options_.prefix_extractor.get() == nullptr) {
    expect_total_order = true;
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
  }

  std::string upper_bound_str;
  Slice upper_bound;
  if (thread->rand.OneIn(16)) {
    // in 1/16 chance, set a iterator upper bound
    int64_t rand_upper_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
    upper_bound_str = Key(rand_upper_key);
    upper_bound = Slice(upper_bound_str);
    // uppder_bound can be smaller than seek key, but the query itself
    // should not crash either.
    readoptionscopy.iterate_upper_bound = &upper_bound;
  }
  std::string lower_bound_str;
  Slice lower_bound;
  if (thread->rand.OneIn(16)) {
    // in 1/16 chance, enable iterator lower bound
    int64_t rand_lower_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
    lower_bound_str = Key(rand_lower_key);
    lower_bound = Slice(lower_bound_str);
    // uppder_bound can be smaller than seek key, but the query itself
    // should not crash either.
    readoptionscopy.iterate_lower_bound = &lower_bound;
  }

  auto cfh = column_families_[rand_column_families[0]];
  std::unique_ptr<Iterator> iter(db_->NewIterator(readoptionscopy, cfh));

  std::vector<std::string> key_str;
  if (thread->rand.OneIn(16)) {
    // Generate keys close to lower or upper bound of SST files.
    key_str = GetWhiteBoxKeys(thread, db_, cfh, rand_keys.size());
  }
  if (key_str.empty()) {
    // If key string is not geneerated using white block keys,
    // Use randomized key passe in.
    for (int64_t rkey : rand_keys) {
      key_str.push_back(Key(rkey));
    }
  }

881 882 883
  std::string op_logs;
  const size_t kOpLogsLimit = 10000;

884
  for (const std::string& skey : key_str) {
885 886 887 888 889
    if (op_logs.size() > kOpLogsLimit) {
      // Shouldn't take too much memory for the history log. Clear it.
      op_logs = "(cleared...)\n";
    }

890 891 892 893 894 895 896 897 898 899
    Slice key = skey;

    if (readoptionscopy.iterate_upper_bound != nullptr &&
        thread->rand.OneIn(2)) {
      // 1/2 chance, change the upper bound.
      // It is possible that it is changed without first use, but there is no
      // problem with that.
      int64_t rand_upper_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
      upper_bound_str = Key(rand_upper_key);
      upper_bound = Slice(upper_bound_str);
900 901 902 903 904 905 906 907 908 909 910 911 912
    } else if (readoptionscopy.iterate_lower_bound != nullptr &&
               thread->rand.OneIn(4)) {
      // 1/4 chance, change the lower bound.
      // It is possible that it is changed without first use, but there is no
      // problem with that.
      int64_t rand_lower_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
      lower_bound_str = Key(rand_lower_key);
      lower_bound = Slice(lower_bound_str);
    }

    // Record some options to op_logs;
    op_logs += "total_order_seek: ";
    op_logs += (readoptionscopy.total_order_seek ? "1 " : "0 ");
S
sdong 已提交
913 914
    op_logs += "auto_prefix_mode: ";
    op_logs += (readoptionscopy.auto_prefix_mode ? "1 " : "0 ");
915 916 917 918 919
    if (readoptionscopy.iterate_upper_bound != nullptr) {
      op_logs += "ub: " + upper_bound.ToString(true) + " ";
    }
    if (readoptionscopy.iterate_lower_bound != nullptr) {
      op_logs += "lb: " + lower_bound.ToString(true) + " ";
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    }

    // Set up an iterator and does the same without bounds and with total
    // order seek and compare the results. This is to identify bugs related
    // to bounds, prefix extractor or reseeking. Sometimes we are comparing
    // iterators with the same set-up, and it doesn't hurt to check them
    // to be equal.
    ReadOptions cmp_ro;
    cmp_ro.snapshot = snapshot;
    cmp_ro.total_order_seek = true;
    ColumnFamilyHandle* cmp_cfh =
        GetControlCfh(thread, rand_column_families[0]);
    std::unique_ptr<Iterator> cmp_iter(db_->NewIterator(cmp_ro, cmp_cfh));
    bool diverged = false;

S
sdong 已提交
935
    bool support_seek_first_or_last = expect_total_order;
936

937
    LastIterateOp last_op;
938 939 940 941 942 943 944 945 946 947 948
    if (support_seek_first_or_last && thread->rand.OneIn(100)) {
      iter->SeekToFirst();
      cmp_iter->SeekToFirst();
      last_op = kLastOpSeekToFirst;
      op_logs += "STF ";
    } else if (support_seek_first_or_last && thread->rand.OneIn(100)) {
      iter->SeekToLast();
      cmp_iter->SeekToLast();
      last_op = kLastOpSeekToLast;
      op_logs += "STL ";
    } else if (thread->rand.OneIn(8)) {
949 950 951
      iter->SeekForPrev(key);
      cmp_iter->SeekForPrev(key);
      last_op = kLastOpSeekForPrev;
952
      op_logs += "SFP " + key.ToString(true) + " ";
953 954 955 956
    } else {
      iter->Seek(key);
      cmp_iter->Seek(key);
      last_op = kLastOpSeek;
957
      op_logs += "S " + key.ToString(true) + " ";
958 959
    }
    VerifyIterator(thread, cmp_cfh, readoptionscopy, iter.get(), cmp_iter.get(),
960
                   last_op, key, op_logs, &diverged);
961 962

    bool no_reverse =
S
sdong 已提交
963
        (FLAGS_memtablerep == "prefix_hash" && !expect_total_order);
964 965 966 967 968 969 970
    for (uint64_t i = 0; i < FLAGS_num_iterations && iter->Valid(); i++) {
      if (no_reverse || thread->rand.OneIn(2)) {
        iter->Next();
        if (!diverged) {
          assert(cmp_iter->Valid());
          cmp_iter->Next();
        }
971
        op_logs += "N";
972 973 974 975 976 977
      } else {
        iter->Prev();
        if (!diverged) {
          assert(cmp_iter->Valid());
          cmp_iter->Prev();
        }
978
        op_logs += "P";
979 980 981
      }
      last_op = kLastOpNextOrPrev;
      VerifyIterator(thread, cmp_cfh, readoptionscopy, iter.get(),
982
                     cmp_iter.get(), last_op, key, op_logs, &diverged);
983 984 985 986 987
    }

    if (s.ok()) {
      thread->stats.AddIterations(1);
    } else {
988
      fprintf(stderr, "TestIterate error: %s\n", s.ToString().c_str());
989 990 991
      thread->stats.AddErrors(1);
      break;
    }
992 993

    op_logs += "; ";
994 995 996 997 998 999 1000
  }

  db_->ReleaseSnapshot(snapshot);

  return s;
}

1001
#ifndef ROCKSDB_LITE
1002 1003 1004 1005 1006 1007
// Test the return status of GetLiveFiles.
Status StressTest::VerifyGetLiveFiles() const {
  std::vector<std::string> live_file;
  uint64_t manifest_size = 0;
  return db_->GetLiveFiles(live_file, &manifest_size);
}
1008

1009 1010 1011 1012 1013
// Test the return status of GetSortedWalFiles.
Status StressTest::VerifyGetSortedWalFiles() const {
  VectorLogPtr log_ptr;
  return db_->GetSortedWalFiles(log_ptr);
}
1014

1015 1016 1017 1018
// Test the return status of GetCurrentWalFile.
Status StressTest::VerifyGetCurrentWalFile() const {
  std::unique_ptr<LogFile> cur_wal_file;
  return db_->GetCurrentWalFile(&cur_wal_file);
1019 1020 1021
}
#endif  // !ROCKSDB_LITE

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
// Compare the two iterator, iter and cmp_iter are in the same position,
// unless iter might be made invalidate or undefined because of
// upper or lower bounds, or prefix extractor.
// Will flag failure if the verification fails.
// diverged = true if the two iterator is already diverged.
// True if verification passed, false if not.
void StressTest::VerifyIterator(ThreadState* thread,
                                ColumnFamilyHandle* cmp_cfh,
                                const ReadOptions& ro, Iterator* iter,
                                Iterator* cmp_iter, LastIterateOp op,
1032 1033
                                const Slice& seek_key,
                                const std::string& op_logs, bool* diverged) {
1034 1035 1036 1037
  if (*diverged) {
    return;
  }

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  if (op == kLastOpSeekToFirst && ro.iterate_lower_bound != nullptr) {
    // SeekToFirst() with lower bound is not well defined.
    *diverged = true;
    return;
  } else if (op == kLastOpSeekToLast && ro.iterate_upper_bound != nullptr) {
    // SeekToLast() with higher bound is not well defined.
    *diverged = true;
    return;
  } else if (op == kLastOpSeek && ro.iterate_lower_bound != nullptr &&
             (options_.comparator->Compare(*ro.iterate_lower_bound, seek_key) >=
                  0 ||
              (ro.iterate_upper_bound != nullptr &&
               options_.comparator->Compare(*ro.iterate_lower_bound,
                                            *ro.iterate_upper_bound) >= 0))) {
1052 1053 1054 1055
    // Lower bound behavior is not well defined if it is larger than
    // seek key or upper bound. Disable the check for now.
    *diverged = true;
    return;
1056 1057 1058 1059 1060 1061
  } else if (op == kLastOpSeekForPrev && ro.iterate_upper_bound != nullptr &&
             (options_.comparator->Compare(*ro.iterate_upper_bound, seek_key) <=
                  0 ||
              (ro.iterate_lower_bound != nullptr &&
               options_.comparator->Compare(*ro.iterate_lower_bound,
                                            *ro.iterate_upper_bound) >= 0))) {
1062 1063 1064 1065 1066 1067
    // Uppder bound behavior is not well defined if it is smaller than
    // seek key or lower bound. Disable the check for now.
    *diverged = true;
    return;
  }

S
sdong 已提交
1068 1069 1070
  const SliceTransform* pe = (ro.total_order_seek || ro.auto_prefix_mode)
                                 ? nullptr
                                 : options_.prefix_extractor.get();
1071 1072
  const Comparator* cmp = options_.comparator;

1073
  if (iter->Valid() && !cmp_iter->Valid()) {
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    if (pe != nullptr) {
      if (!pe->InDomain(seek_key)) {
        // Prefix seek a non-in-domain key is undefined. Skip checking for
        // this scenario.
        *diverged = true;
        return;
      } else if (!pe->InDomain(iter->key())) {
        // out of range is iterator key is not in domain anymore.
        *diverged = true;
        return;
      } else if (pe->Transform(iter->key()) != pe->Transform(seek_key)) {
        *diverged = true;
        return;
      }
    }
1089
    fprintf(stderr,
1090
            "Control interator is invalid but iterator has key %s "
1091
            "%s\n",
1092
            iter->key().ToString(true).c_str(), op_logs.c_str());
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

    *diverged = true;
  } else if (cmp_iter->Valid()) {
    // Iterator is not valid. It can be legimate if it has already been
    // out of upper or lower bound, or filtered out by prefix iterator.
    const Slice& total_order_key = cmp_iter->key();

    if (pe != nullptr) {
      if (!pe->InDomain(seek_key)) {
        // Prefix seek a non-in-domain key is undefined. Skip checking for
        // this scenario.
        *diverged = true;
        return;
      }

      if (!pe->InDomain(total_order_key) ||
          pe->Transform(total_order_key) != pe->Transform(seek_key)) {
        // If the prefix is exhausted, the only thing needs to check
        // is the iterator isn't return a position in prefix.
        // Either way, checking can stop from here.
        *diverged = true;
        if (!iter->Valid() || !pe->InDomain(iter->key()) ||
            pe->Transform(iter->key()) != pe->Transform(seek_key)) {
          return;
        }
        fprintf(stderr,
1119 1120
                "Iterator stays in prefix but contol doesn't"
                " iterator key %s control iterator key %s %s\n",
1121
                iter->key().ToString(true).c_str(),
1122
                cmp_iter->key().ToString(true).c_str(), op_logs.c_str());
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
      }
    }
    // Check upper or lower bounds.
    if (!*diverged) {
      if ((iter->Valid() && iter->key() != cmp_iter->key()) ||
          (!iter->Valid() &&
           (ro.iterate_upper_bound == nullptr ||
            cmp->Compare(total_order_key, *ro.iterate_upper_bound) < 0) &&
           (ro.iterate_lower_bound == nullptr ||
            cmp->Compare(total_order_key, *ro.iterate_lower_bound) > 0))) {
        fprintf(stderr,
                "Iterator diverged from control iterator which"
1135 1136
                " has value %s %s\n",
                total_order_key.ToString(true).c_str(), op_logs.c_str());
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
        if (iter->Valid()) {
          fprintf(stderr, "iterator has value %s\n",
                  iter->key().ToString(true).c_str());
        } else {
          fprintf(stderr, "iterator is not valid\n");
        }
        *diverged = true;
      }
    }
  }
  if (*diverged) {
    fprintf(stderr, "Control CF %s\n", cmp_cfh->GetName().c_str());
    thread->stats.AddErrors(1);
    // Fail fast to preserve the DB state.
    thread->shared->SetVerificationFailure();
  }
}

#ifdef ROCKSDB_LITE
Status StressTest::TestBackupRestore(
    ThreadState* /* thread */,
    const std::vector<int>& /* rand_column_families */,
    const std::vector<int64_t>& /* rand_keys */) {
  assert(false);
  fprintf(stderr,
          "RocksDB lite does not support "
          "TestBackupRestore\n");
  std::terminate();
}

Status StressTest::TestCheckpoint(
    ThreadState* /* thread */,
    const std::vector<int>& /* rand_column_families */,
    const std::vector<int64_t>& /* rand_keys */) {
  assert(false);
  fprintf(stderr,
          "RocksDB lite does not support "
          "TestCheckpoint\n");
  std::terminate();
}
1177 1178 1179 1180 1181 1182 1183 1184 1185

void StressTest::TestCompactFiles(ThreadState* /* thread */,
                                  ColumnFamilyHandle* /* column_family */) {
  assert(false);
  fprintf(stderr,
          "RocksDB lite does not support "
          "CompactFiles\n");
  std::terminate();
}
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
#else   // ROCKSDB_LITE
Status StressTest::TestBackupRestore(
    ThreadState* thread, const std::vector<int>& rand_column_families,
    const std::vector<int64_t>& rand_keys) {
  // Note the column families chosen by `rand_column_families` cannot be
  // dropped while the locks for `rand_keys` are held. So we should not have
  // to worry about accessing those column families throughout this function.
  assert(rand_column_families.size() == rand_keys.size());
  std::string backup_dir = FLAGS_db + "/.backup" + ToString(thread->tid);
  std::string restore_dir = FLAGS_db + "/.restore" + ToString(thread->tid);
  BackupableDBOptions backup_opts(backup_dir);
  BackupEngine* backup_engine = nullptr;
1198
  Status s = BackupEngine::Open(db_stress_env, backup_opts, &backup_engine);
1199 1200 1201 1202 1203 1204
  if (s.ok()) {
    s = backup_engine->CreateNewBackup(db_);
  }
  if (s.ok()) {
    delete backup_engine;
    backup_engine = nullptr;
1205
    s = BackupEngine::Open(db_stress_env, backup_opts, &backup_engine);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 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
  }
  if (s.ok()) {
    s = backup_engine->RestoreDBFromLatestBackup(restore_dir /* db_dir */,
                                                 restore_dir /* wal_dir */);
  }
  if (s.ok()) {
    s = backup_engine->PurgeOldBackups(0 /* num_backups_to_keep */);
  }
  DB* restored_db = nullptr;
  std::vector<ColumnFamilyHandle*> restored_cf_handles;
  if (s.ok()) {
    Options restore_options(options_);
    restore_options.listeners.clear();
    std::vector<ColumnFamilyDescriptor> cf_descriptors;
    // TODO(ajkr): `column_family_names_` is not safe to access here when
    // `clear_column_family_one_in != 0`. But we can't easily switch to
    // `ListColumnFamilies` to get names because it won't necessarily give
    // the same order as `column_family_names_`.
    assert(FLAGS_clear_column_family_one_in == 0);
    for (auto name : column_family_names_) {
      cf_descriptors.emplace_back(name, ColumnFamilyOptions(restore_options));
    }
    s = DB::Open(DBOptions(restore_options), restore_dir, cf_descriptors,
                 &restored_cf_handles, &restored_db);
  }
  // for simplicity, currently only verifies existence/non-existence of a few
  // keys
  for (size_t i = 0; s.ok() && i < rand_column_families.size(); ++i) {
    std::string key_str = Key(rand_keys[i]);
    Slice key = key_str;
    std::string restored_value;
    Status get_status = restored_db->Get(
        ReadOptions(), restored_cf_handles[rand_column_families[i]], key,
        &restored_value);
    bool exists = thread->shared->Exists(rand_column_families[i], rand_keys[i]);
    if (get_status.ok()) {
      if (!exists) {
        s = Status::Corruption("key exists in restore but not in original db");
      }
    } else if (get_status.IsNotFound()) {
      if (exists) {
        s = Status::Corruption("key exists in original db but not in restore");
      }
    } else {
      s = get_status;
    }
  }
  if (backup_engine != nullptr) {
    delete backup_engine;
    backup_engine = nullptr;
  }
  if (restored_db != nullptr) {
    for (auto* cf_handle : restored_cf_handles) {
      restored_db->DestroyColumnFamilyHandle(cf_handle);
    }
    delete restored_db;
    restored_db = nullptr;
  }
  if (!s.ok()) {
1265 1266
    fprintf(stderr, "A backup/restore operation failed with: %s\n",
            s.ToString().c_str());
1267 1268 1269 1270
  }
  return s;
}

S
sdong 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
#ifndef ROCKSDB_LITE
Status StressTest::TestApproximateSize(
    ThreadState* thread, uint64_t iteration,
    const std::vector<int>& rand_column_families,
    const std::vector<int64_t>& rand_keys) {
  // rand_keys likely only has one key. Just use the first one.
  assert(!rand_keys.empty());
  assert(!rand_column_families.empty());
  int64_t key1 = rand_keys[0];
  int64_t key2;
  if (thread->rand.OneIn(2)) {
    // Two totally random keys. This tends to cover large ranges.
    key2 = GenerateOneKey(thread, iteration);
    if (key2 < key1) {
      std::swap(key1, key2);
    }
  } else {
    // Unless users pass a very large FLAGS_max_key, it we should not worry
    // about overflow. It is for testing, so we skip the overflow checking
    // for simplicity.
    key2 = key1 + static_cast<int64_t>(thread->rand.Uniform(1000));
  }
  std::string key1_str = Key(key1);
  std::string key2_str = Key(key2);
  Range range{Slice(key1_str), Slice(key2_str)};
  SizeApproximationOptions sao;
  sao.include_memtabtles = thread->rand.OneIn(2);
  if (sao.include_memtabtles) {
    sao.include_files = thread->rand.OneIn(2);
  }
  if (thread->rand.OneIn(2)) {
    if (thread->rand.OneIn(2)) {
      sao.files_size_error_margin = 0.0;
    } else {
      sao.files_size_error_margin =
          static_cast<double>(thread->rand.Uniform(3));
    }
  }
  uint64_t result;
  return db_->GetApproximateSizes(
      sao, column_families_[rand_column_families[0]], &range, 1, &result);
}
#endif  // ROCKSDB_LITE

1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
Status StressTest::TestCheckpoint(ThreadState* thread,
                                  const std::vector<int>& rand_column_families,
                                  const std::vector<int64_t>& rand_keys) {
  // Note the column families chosen by `rand_column_families` cannot be
  // dropped while the locks for `rand_keys` are held. So we should not have
  // to worry about accessing those column families throughout this function.
  assert(rand_column_families.size() == rand_keys.size());
  std::string checkpoint_dir =
      FLAGS_db + "/.checkpoint" + ToString(thread->tid);
  Options tmp_opts(options_);
  tmp_opts.listeners.clear();
1326
  tmp_opts.env = db_stress_env->target();
1327

1328
  DestroyDB(checkpoint_dir, tmp_opts);
1329

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
  Checkpoint* checkpoint = nullptr;
  Status s = Checkpoint::Create(db_, &checkpoint);
  if (s.ok()) {
    s = checkpoint->CreateCheckpoint(checkpoint_dir);
  }
  std::vector<ColumnFamilyHandle*> cf_handles;
  DB* checkpoint_db = nullptr;
  if (s.ok()) {
    delete checkpoint;
    checkpoint = nullptr;
    Options options(options_);
    options.listeners.clear();
    std::vector<ColumnFamilyDescriptor> cf_descs;
    // TODO(ajkr): `column_family_names_` is not safe to access here when
    // `clear_column_family_one_in != 0`. But we can't easily switch to
    // `ListColumnFamilies` to get names because it won't necessarily give
    // the same order as `column_family_names_`.
    if (FLAGS_clear_column_family_one_in == 0) {
      for (const auto& name : column_family_names_) {
        cf_descs.emplace_back(name, ColumnFamilyOptions(options));
      }
      s = DB::OpenForReadOnly(DBOptions(options), checkpoint_dir, cf_descs,
                              &cf_handles, &checkpoint_db);
    }
  }
  if (checkpoint_db != nullptr) {
    for (size_t i = 0; s.ok() && i < rand_column_families.size(); ++i) {
      std::string key_str = Key(rand_keys[i]);
      Slice key = key_str;
      std::string value;
      Status get_status = checkpoint_db->Get(
          ReadOptions(), cf_handles[rand_column_families[i]], key, &value);
      bool exists =
          thread->shared->Exists(rand_column_families[i], rand_keys[i]);
      if (get_status.ok()) {
        if (!exists) {
          s = Status::Corruption(
              "key exists in checkpoint but not in original db");
        }
      } else if (get_status.IsNotFound()) {
        if (exists) {
          s = Status::Corruption(
              "key exists in original db but not in checkpoint");
        }
      } else {
        s = get_status;
      }
    }
    for (auto cfh : cf_handles) {
      delete cfh;
    }
    cf_handles.clear();
    delete checkpoint_db;
    checkpoint_db = nullptr;
  }
1385

1386
  DestroyDB(checkpoint_dir, tmp_opts);
1387

1388 1389 1390 1391 1392 1393
  if (!s.ok()) {
    fprintf(stderr, "A checkpoint operation failed with: %s\n",
            s.ToString().c_str());
  }
  return s;
}
1394 1395 1396

void StressTest::TestCompactFiles(ThreadState* thread,
                                  ColumnFamilyHandle* column_family) {
1397
  ROCKSDB_NAMESPACE::ColumnFamilyMetaData cf_meta_data;
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
  db_->GetColumnFamilyMetaData(column_family, &cf_meta_data);

  // Randomly compact up to three consecutive files from a level
  const int kMaxRetry = 3;
  for (int attempt = 0; attempt < kMaxRetry; ++attempt) {
    size_t random_level =
        thread->rand.Uniform(static_cast<int>(cf_meta_data.levels.size()));

    const auto& files = cf_meta_data.levels[random_level].files;
    if (files.size() > 0) {
      size_t random_file_index =
          thread->rand.Uniform(static_cast<int>(files.size()));
      if (files[random_file_index].being_compacted) {
        // Retry as the selected file is currently being compacted
        continue;
      }

      std::vector<std::string> input_files;
      input_files.push_back(files[random_file_index].name);
      if (random_file_index > 0 &&
          !files[random_file_index - 1].being_compacted) {
        input_files.push_back(files[random_file_index - 1].name);
      }
      if (random_file_index + 1 < files.size() &&
          !files[random_file_index + 1].being_compacted) {
        input_files.push_back(files[random_file_index + 1].name);
      }

      size_t output_level =
          std::min(random_level + 1, cf_meta_data.levels.size() - 1);
      auto s = db_->CompactFiles(CompactionOptions(), column_family,
                                 input_files, static_cast<int>(output_level));
      if (!s.ok()) {
        fprintf(stdout, "Unable to perform CompactFiles(): %s\n",
                s.ToString().c_str());
        thread->stats.AddNumCompactFilesFailed(1);
      } else {
        thread->stats.AddNumCompactFilesSucceed(1);
      }
      break;
    }
  }
}
1441 1442
#endif  // ROCKSDB_LITE

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
Status StressTest::TestFlush(const std::vector<int>& rand_column_families) {
  FlushOptions flush_opts;
  std::vector<ColumnFamilyHandle*> cfhs;
  std::for_each(rand_column_families.begin(), rand_column_families.end(),
                [this, &cfhs](int k) { cfhs.push_back(column_families_[k]); });
  return db_->Flush(flush_opts, cfhs);
}

Status StressTest::TestPauseBackground(ThreadState* thread) {
  Status status = db_->PauseBackgroundWork();
  if (!status.ok()) {
    return status;
  }
  // To avoid stalling/deadlocking ourself in this thread, just
  // sleep here during pause and let other threads do db operations.
  // Sleep up to ~16 seconds (2**24 microseconds), but very skewed
  // toward short pause. (1 chance in 25 of pausing >= 1s;
  // 1 chance in 625 of pausing full 16s.)
  int pwr2_micros =
      std::min(thread->rand.Uniform(25), thread->rand.Uniform(25));
1463
  db_stress_env->SleepForMicroseconds(1 << pwr2_micros);
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
  return db_->ContinueBackgroundWork();
}

void StressTest::TestAcquireSnapshot(ThreadState* thread,
                                     int rand_column_family,
                                     const std::string& keystr, uint64_t i) {
  Slice key = keystr;
  ColumnFamilyHandle* column_family = column_families_[rand_column_family];
#ifndef ROCKSDB_LITE
  auto db_impl = reinterpret_cast<DBImpl*>(db_->GetRootDB());
  const bool ww_snapshot = thread->rand.OneIn(10);
  const Snapshot* snapshot =
      ww_snapshot ? db_impl->GetSnapshotForWriteConflictBoundary()
                  : db_->GetSnapshot();
#else
  const Snapshot* snapshot = db_->GetSnapshot();
#endif  // !ROCKSDB_LITE
  ReadOptions ropt;
  ropt.snapshot = snapshot;
  std::string value_at;
  // When taking a snapshot, we also read a key from that snapshot. We
  // will later read the same key before releasing the snapshot and
  // verify that the results are the same.
  auto status_at = db_->Get(ropt, column_family, key, &value_at);
  std::vector<bool>* key_vec = nullptr;

  if (FLAGS_compare_full_db_state_snapshot && (thread->tid == 0)) {
    key_vec = new std::vector<bool>(FLAGS_max_key);
    // When `prefix_extractor` is set, seeking to beginning and scanning
    // across prefixes are only supported with `total_order_seek` set.
    ropt.total_order_seek = true;
    std::unique_ptr<Iterator> iterator(db_->NewIterator(ropt));
    for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) {
      uint64_t key_val;
      if (GetIntVal(iterator->key().ToString(), &key_val)) {
        (*key_vec)[key_val] = true;
      }
    }
  }

  ThreadState::SnapshotState snap_state = {
      snapshot, rand_column_family, column_family->GetName(),
      keystr,   status_at,          value_at,
      key_vec};
  uint64_t hold_for = FLAGS_snapshot_hold_ops;
  if (FLAGS_long_running_snapshots) {
    // Hold 10% of snapshots for 10x more
    if (thread->rand.OneIn(10)) {
      assert(hold_for < port::kMaxInt64 / 10);
      hold_for *= 10;
      // Hold 1% of snapshots for 100x more
      if (thread->rand.OneIn(10)) {
        assert(hold_for < port::kMaxInt64 / 10);
        hold_for *= 10;
      }
    }
  }
  uint64_t release_at = std::min(FLAGS_ops_per_thread - 1, i + hold_for);
  thread->snapshot_queue.emplace(release_at, snap_state);
}

Status StressTest::MaybeReleaseSnapshots(ThreadState* thread, uint64_t i) {
  while (!thread->snapshot_queue.empty() &&
         i >= thread->snapshot_queue.front().first) {
    auto snap_state = thread->snapshot_queue.front().second;
    assert(snap_state.snapshot);
    // Note: this is unsafe as the cf might be dropped concurrently. But
    // it is ok since unclean cf drop is cunnrently not supported by write
    // prepared transactions.
    Status s = AssertSame(db_, column_families_[snap_state.cf_at], snap_state);
    db_->ReleaseSnapshot(snap_state.snapshot);
    delete snap_state.key_vec;
    thread->snapshot_queue.pop();
    if (!s.ok()) {
      return s;
    }
  }
  return Status::OK();
}

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
void StressTest::TestCompactRange(ThreadState* thread, int64_t rand_key,
                                  const Slice& start_key,
                                  ColumnFamilyHandle* column_family) {
  int64_t end_key_num;
  if (port::kMaxInt64 - rand_key < FLAGS_compact_range_width) {
    end_key_num = port::kMaxInt64;
  } else {
    end_key_num = FLAGS_compact_range_width + rand_key;
  }
  std::string end_key_buf = Key(end_key_num);
  Slice end_key(end_key_buf);

  CompactRangeOptions cro;
  cro.exclusive_manual_compaction = static_cast<bool>(thread->rand.Next() % 2);
  cro.change_level = static_cast<bool>(thread->rand.Next() % 2);
  std::vector<BottommostLevelCompaction> bottom_level_styles = {
      BottommostLevelCompaction::kSkip,
      BottommostLevelCompaction::kIfHaveCompactionFilter,
      BottommostLevelCompaction::kForce,
      BottommostLevelCompaction::kForceOptimized};
  cro.bottommost_level_compaction =
      bottom_level_styles[thread->rand.Next() %
                          static_cast<uint32_t>(bottom_level_styles.size())];
  cro.allow_write_stall = static_cast<bool>(thread->rand.Next() % 2);
  cro.max_subcompactions = static_cast<uint32_t>(thread->rand.Next() % 4);

  const Snapshot* pre_snapshot = nullptr;
B
Burton Li 已提交
1571
  uint32_t pre_hash = 0;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
  if (thread->rand.OneIn(2)) {
    // Do some validation by declaring a snapshot and compare the data before
    // and after the compaction
    pre_snapshot = db_->GetSnapshot();
    pre_hash =
        GetRangeHash(thread, pre_snapshot, column_family, start_key, end_key);
  }

  Status status = db_->CompactRange(cro, column_family, &start_key, &end_key);

  if (!status.ok()) {
1583 1584
    fprintf(stdout, "Unable to perform CompactRange(): %s\n",
            status.ToString().c_str());
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
  }

  if (pre_snapshot != nullptr) {
    uint32_t post_hash =
        GetRangeHash(thread, pre_snapshot, column_family, start_key, end_key);
    if (pre_hash != post_hash) {
      fprintf(stderr,
              "Data hash different before and after compact range "
              "start_key %s end_key %s\n",
              start_key.ToString(true).c_str(), end_key.ToString(true).c_str());
      thread->stats.AddErrors(1);
      // Fail fast to preserve the DB state.
      thread->shared->SetVerificationFailure();
    }
    db_->ReleaseSnapshot(pre_snapshot);
  }
}

uint32_t StressTest::GetRangeHash(ThreadState* thread, const Snapshot* snapshot,
                                  ColumnFamilyHandle* column_family,
                                  const Slice& start_key,
                                  const Slice& end_key) {
  const std::string kCrcCalculatorSepearator = ";";
  uint32_t crc = 0;
  ReadOptions ro;
  ro.snapshot = snapshot;
  ro.total_order_seek = true;
  std::unique_ptr<Iterator> it(db_->NewIterator(ro, column_family));
  for (it->Seek(start_key);
       it->Valid() && options_.comparator->Compare(it->key(), end_key) <= 0;
       it->Next()) {
    crc = crc32c::Extend(crc, it->key().data(), it->key().size());
    crc = crc32c::Extend(crc, kCrcCalculatorSepearator.data(), 1);
    crc = crc32c::Extend(crc, it->value().data(), it->value().size());
    crc = crc32c::Extend(crc, kCrcCalculatorSepearator.data(), 1);
  }
  if (!it->status().ok()) {
    fprintf(stderr, "Iterator non-OK when calculating range CRC: %s\n",
            it->status().ToString().c_str());
    thread->stats.AddErrors(1);
    // Fail fast to preserve the DB state.
    thread->shared->SetVerificationFailure();
  }
  return crc;
}

1631 1632 1633 1634 1635 1636
void StressTest::PrintEnv() const {
  fprintf(stdout, "RocksDB version           : %d.%d\n", kMajorVersion,
          kMinorVersion);
  fprintf(stdout, "Format version            : %d\n", FLAGS_format_version);
  fprintf(stdout, "TransactionDB             : %s\n",
          FLAGS_use_txn ? "true" : "false");
L
Levi Tamasi 已提交
1637 1638 1639 1640
#ifndef ROCKSDB_LITE
  fprintf(stdout, "BlobDB                    : %s\n",
          FLAGS_use_blob_db ? "true" : "false");
#endif  // !ROCKSDB_LITE
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
  fprintf(stdout, "Read only mode            : %s\n",
          FLAGS_read_only ? "true" : "false");
  fprintf(stdout, "Atomic flush              : %s\n",
          FLAGS_atomic_flush ? "true" : "false");
  fprintf(stdout, "Column families           : %d\n", FLAGS_column_families);
  if (!FLAGS_test_batches_snapshots) {
    fprintf(stdout, "Clear CFs one in          : %d\n",
            FLAGS_clear_column_family_one_in);
  }
  fprintf(stdout, "Number of threads         : %d\n", FLAGS_threads);
  fprintf(stdout, "Ops per thread            : %lu\n",
          (unsigned long)FLAGS_ops_per_thread);
  std::string ttl_state("unused");
  if (FLAGS_ttl > 0) {
    ttl_state = NumberToString(FLAGS_ttl);
  }
  fprintf(stdout, "Time to live(sec)         : %s\n", ttl_state.c_str());
  fprintf(stdout, "Read percentage           : %d%%\n", FLAGS_readpercent);
  fprintf(stdout, "Prefix percentage         : %d%%\n", FLAGS_prefixpercent);
  fprintf(stdout, "Write percentage          : %d%%\n", FLAGS_writepercent);
  fprintf(stdout, "Delete percentage         : %d%%\n", FLAGS_delpercent);
  fprintf(stdout, "Delete range percentage   : %d%%\n", FLAGS_delrangepercent);
  fprintf(stdout, "No overwrite percentage   : %d%%\n",
          FLAGS_nooverwritepercent);
  fprintf(stdout, "Iterate percentage        : %d%%\n", FLAGS_iterpercent);
  fprintf(stdout, "DB-write-buffer-size      : %" PRIu64 "\n",
          FLAGS_db_write_buffer_size);
  fprintf(stdout, "Write-buffer-size         : %d\n", FLAGS_write_buffer_size);
  fprintf(stdout, "Iterations                : %lu\n",
          (unsigned long)FLAGS_num_iterations);
  fprintf(stdout, "Max key                   : %lu\n",
          (unsigned long)FLAGS_max_key);
  fprintf(stdout, "Ratio #ops/#keys          : %f\n",
          (1.0 * FLAGS_ops_per_thread * FLAGS_threads) / FLAGS_max_key);
  fprintf(stdout, "Num times DB reopens      : %d\n", FLAGS_reopen);
  fprintf(stdout, "Batches/snapshots         : %d\n",
          FLAGS_test_batches_snapshots);
  fprintf(stdout, "Do update in place        : %d\n", FLAGS_in_place_update);
  fprintf(stdout, "Num keys per lock         : %d\n",
          1 << FLAGS_log2_keys_per_lock);
1681
  std::string compression = CompressionTypeToString(compression_type_e);
1682
  fprintf(stdout, "Compression               : %s\n", compression.c_str());
1683 1684 1685 1686 1687
  std::string bottommost_compression =
      CompressionTypeToString(bottommost_compression_type_e);
  fprintf(stdout, "Bottommost Compression    : %s\n",
          bottommost_compression.c_str());
  std::string checksum = ChecksumTypeToString(checksum_type_e);
1688
  fprintf(stdout, "Checksum type             : %s\n", checksum.c_str());
1689 1690
  fprintf(stdout, "Bloom bits / key          : %s\n",
          FormatDoubleParam(FLAGS_bloom_bits).c_str());
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  fprintf(stdout, "Max subcompactions        : %" PRIu64 "\n",
          FLAGS_subcompactions);
  fprintf(stdout, "Use MultiGet              : %s\n",
          FLAGS_use_multiget ? "true" : "false");

  const char* memtablerep = "";
  switch (FLAGS_rep_factory) {
    case kSkipList:
      memtablerep = "skip_list";
      break;
    case kHashSkipList:
      memtablerep = "prefix_hash";
      break;
    case kVectorRep:
      memtablerep = "vector";
      break;
  }

  fprintf(stdout, "Memtablerep               : %s\n", memtablerep);

  fprintf(stdout, "Test kill odd             : %d\n", rocksdb_kill_odds);
  if (!rocksdb_kill_prefix_blacklist.empty()) {
    fprintf(stdout, "Skipping kill points prefixes:\n");
    for (auto& p : rocksdb_kill_prefix_blacklist) {
      fprintf(stdout, "  %s\n", p.c_str());
    }
  }
  fprintf(stdout, "Periodic Compaction Secs  : %" PRIu64 "\n",
          FLAGS_periodic_compaction_seconds);
  fprintf(stdout, "Compaction TTL            : %" PRIu64 "\n",
          FLAGS_compaction_ttl);
S
sdong 已提交
1722 1723 1724 1725 1726 1727 1728 1729
  fprintf(stdout, "Background Purge          : %d\n",
          static_cast<int>(FLAGS_avoid_unnecessary_blocking_io));
  fprintf(stdout, "Write DB ID to manifest   : %d\n",
          static_cast<int>(FLAGS_write_dbid_to_manifest));
  fprintf(stdout, "Max Write Batch Group Size: %" PRIu64 "\n",
          FLAGS_max_write_batch_group_size_bytes);
  fprintf(stdout, "Use dynamic level         : %d\n",
          static_cast<int>(FLAGS_level_compaction_dynamic_level_bytes));
A
anand76 已提交
1730
  fprintf(stdout, "Read fault one in         : %d\n", FLAGS_read_fault_one_in);
1731
  fprintf(stdout, "Sync fault injection      : %d\n", FLAGS_sync_fault_injection);
1732 1733
  fprintf(stdout, "Best efforts recovery     : %d\n",
          static_cast<int>(FLAGS_best_efforts_recovery));
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

  fprintf(stdout, "------------------------------------------------\n");
}

void StressTest::Open() {
  assert(db_ == nullptr);
#ifndef ROCKSDB_LITE
  assert(txn_db_ == nullptr);
#endif
  if (FLAGS_options_file.empty()) {
    BlockBasedTableOptions block_based_options;
    block_based_options.block_cache = cache_;
    block_based_options.cache_index_and_filter_blocks =
        FLAGS_cache_index_and_filter_blocks;
    block_based_options.block_cache_compressed = compressed_cache_;
1749
    block_based_options.checksum = checksum_type_e;
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    block_based_options.block_size = FLAGS_block_size;
    block_based_options.format_version =
        static_cast<uint32_t>(FLAGS_format_version);
    block_based_options.index_block_restart_interval =
        static_cast<int32_t>(FLAGS_index_block_restart_interval);
    block_based_options.filter_policy = filter_policy_;
    block_based_options.partition_filters = FLAGS_partition_filters;
    block_based_options.index_type =
        static_cast<BlockBasedTableOptions::IndexType>(FLAGS_index_type);
    options_.table_factory.reset(
        NewBlockBasedTableFactory(block_based_options));
    options_.db_write_buffer_size = FLAGS_db_write_buffer_size;
    options_.write_buffer_size = FLAGS_write_buffer_size;
    options_.max_write_buffer_number = FLAGS_max_write_buffer_number;
    options_.min_write_buffer_number_to_merge =
        FLAGS_min_write_buffer_number_to_merge;
    options_.max_write_buffer_number_to_maintain =
        FLAGS_max_write_buffer_number_to_maintain;
    options_.max_write_buffer_size_to_maintain =
        FLAGS_max_write_buffer_size_to_maintain;
    options_.memtable_prefix_bloom_size_ratio =
        FLAGS_memtable_prefix_bloom_size_ratio;
    options_.memtable_whole_key_filtering = FLAGS_memtable_whole_key_filtering;
    options_.max_background_compactions = FLAGS_max_background_compactions;
    options_.max_background_flushes = FLAGS_max_background_flushes;
    options_.compaction_style =
1776
        static_cast<ROCKSDB_NAMESPACE::CompactionStyle>(FLAGS_compaction_style);
1777 1778 1779 1780 1781 1782
    if (FLAGS_prefix_size >= 0) {
      options_.prefix_extractor.reset(
          NewFixedPrefixTransform(FLAGS_prefix_size));
    }
    options_.max_open_files = FLAGS_open_files;
    options_.statistics = dbstats;
1783
    options_.env = db_stress_env;
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    options_.use_fsync = FLAGS_use_fsync;
    options_.compaction_readahead_size = FLAGS_compaction_readahead_size;
    options_.allow_mmap_reads = FLAGS_mmap_read;
    options_.allow_mmap_writes = FLAGS_mmap_write;
    options_.use_direct_reads = FLAGS_use_direct_reads;
    options_.use_direct_io_for_flush_and_compaction =
        FLAGS_use_direct_io_for_flush_and_compaction;
    options_.recycle_log_file_num =
        static_cast<size_t>(FLAGS_recycle_log_file_num);
    options_.target_file_size_base = FLAGS_target_file_size_base;
    options_.target_file_size_multiplier = FLAGS_target_file_size_multiplier;
    options_.max_bytes_for_level_base = FLAGS_max_bytes_for_level_base;
    options_.max_bytes_for_level_multiplier =
        FLAGS_max_bytes_for_level_multiplier;
    options_.level0_stop_writes_trigger = FLAGS_level0_stop_writes_trigger;
    options_.level0_slowdown_writes_trigger =
        FLAGS_level0_slowdown_writes_trigger;
    options_.level0_file_num_compaction_trigger =
        FLAGS_level0_file_num_compaction_trigger;
1803 1804
    options_.compression = compression_type_e;
    options_.bottommost_compression = bottommost_compression_type_e;
1805 1806 1807
    options_.compression_opts.max_dict_bytes = FLAGS_compression_max_dict_bytes;
    options_.compression_opts.zstd_max_train_bytes =
        FLAGS_compression_zstd_max_train_bytes;
1808 1809
    options_.compression_opts.parallel_threads =
        FLAGS_compression_parallel_threads;
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
    options_.create_if_missing = true;
    options_.max_manifest_file_size = FLAGS_max_manifest_file_size;
    options_.inplace_update_support = FLAGS_in_place_update;
    options_.max_subcompactions = static_cast<uint32_t>(FLAGS_subcompactions);
    options_.allow_concurrent_memtable_write =
        FLAGS_allow_concurrent_memtable_write;
    options_.periodic_compaction_seconds = FLAGS_periodic_compaction_seconds;
    options_.ttl = FLAGS_compaction_ttl;
    options_.enable_pipelined_write = FLAGS_enable_pipelined_write;
    options_.enable_write_thread_adaptive_yield =
        FLAGS_enable_write_thread_adaptive_yield;
    options_.compaction_options_universal.size_ratio =
        FLAGS_universal_size_ratio;
    options_.compaction_options_universal.min_merge_width =
        FLAGS_universal_min_merge_width;
    options_.compaction_options_universal.max_merge_width =
        FLAGS_universal_max_merge_width;
    options_.compaction_options_universal.max_size_amplification_percent =
        FLAGS_universal_max_size_amplification_percent;
    options_.atomic_flush = FLAGS_atomic_flush;
S
sdong 已提交
1830 1831 1832
    options_.avoid_unnecessary_blocking_io =
        FLAGS_avoid_unnecessary_blocking_io;
    options_.write_dbid_to_manifest = FLAGS_write_dbid_to_manifest;
1833
    options_.avoid_flush_during_recovery = FLAGS_avoid_flush_during_recovery;
S
sdong 已提交
1834 1835 1836 1837
    options_.max_write_batch_group_size_bytes =
        FLAGS_max_write_batch_group_size_bytes;
    options_.level_compaction_dynamic_level_bytes =
        FLAGS_level_compaction_dynamic_level_bytes;
1838 1839 1840 1841 1842 1843 1844
  } else {
#ifdef ROCKSDB_LITE
    fprintf(stderr, "--options_file not supported in lite mode\n");
    exit(1);
#else
    DBOptions db_options;
    std::vector<ColumnFamilyDescriptor> cf_descriptors;
1845 1846 1847
    Status s = LoadOptionsFromFile(FLAGS_options_file, db_stress_env,
                                   &db_options, &cf_descriptors);
    db_options.env = new DbStressEnvWrapper(db_stress_env);
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
    if (!s.ok()) {
      fprintf(stderr, "Unable to load options file %s --- %s\n",
              FLAGS_options_file.c_str(), s.ToString().c_str());
      exit(1);
    }
    options_ = Options(db_options, cf_descriptors[0].options);
#endif  // ROCKSDB_LITE
  }

  if (FLAGS_rate_limiter_bytes_per_sec > 0) {
    options_.rate_limiter.reset(NewGenericRateLimiter(
        FLAGS_rate_limiter_bytes_per_sec, 1000 /* refill_period_us */,
        10 /* fairness */,
        FLAGS_rate_limit_bg_reads ? RateLimiter::Mode::kReadsOnly
                                  : RateLimiter::Mode::kWritesOnly));
    if (FLAGS_rate_limit_bg_reads) {
      options_.new_table_reader_for_compaction_inputs = true;
    }
  }
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  if (FLAGS_sst_file_manager_bytes_per_sec > 0 ||
      FLAGS_sst_file_manager_bytes_per_truncate > 0) {
    Status status;
    options_.sst_file_manager.reset(NewSstFileManager(
        db_stress_env, options_.info_log, "" /* trash_dir */,
        static_cast<int64_t>(FLAGS_sst_file_manager_bytes_per_sec),
        true /* delete_existing_trash */, &status,
        0.25 /* max_trash_db_ratio */,
        FLAGS_sst_file_manager_bytes_per_truncate));
    if (!status.ok()) {
      fprintf(stderr, "SstFileManager creation failed: %s\n",
              status.ToString().c_str());
      exit(1);
    }
  }
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917

  if (FLAGS_prefix_size == 0 && FLAGS_rep_factory == kHashSkipList) {
    fprintf(stderr,
            "prefeix_size cannot be zero if memtablerep == prefix_hash\n");
    exit(1);
  }
  if (FLAGS_prefix_size != 0 && FLAGS_rep_factory != kHashSkipList) {
    fprintf(stderr,
            "WARNING: prefix_size is non-zero but "
            "memtablerep != prefix_hash\n");
  }
  switch (FLAGS_rep_factory) {
    case kSkipList:
      // no need to do anything
      break;
#ifndef ROCKSDB_LITE
    case kHashSkipList:
      options_.memtable_factory.reset(NewHashSkipListRepFactory(10000));
      break;
    case kVectorRep:
      options_.memtable_factory.reset(new VectorRepFactory());
      break;
#else
    default:
      fprintf(stderr,
              "RocksdbLite only supports skip list mem table. Skip "
              "--rep_factory\n");
#endif  // ROCKSDB_LITE
  }

  if (FLAGS_use_full_merge_v1) {
    options_.merge_operator = MergeOperators::CreateDeprecatedPutOperator();
  } else {
    options_.merge_operator = MergeOperators::CreatePutOperator();
  }

1918 1919
  options_.best_efforts_recovery = FLAGS_best_efforts_recovery;

1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
  fprintf(stdout, "DB path: [%s]\n", FLAGS_db.c_str());

  Status s;
  if (FLAGS_ttl == -1) {
    std::vector<std::string> existing_column_families;
    s = DB::ListColumnFamilies(DBOptions(options_), FLAGS_db,
                               &existing_column_families);  // ignore errors
    if (!s.ok()) {
      // DB doesn't exist
      assert(existing_column_families.empty());
      assert(column_family_names_.empty());
      column_family_names_.push_back(kDefaultColumnFamilyName);
    } else if (column_family_names_.empty()) {
      // this is the first call to the function Open()
      column_family_names_ = existing_column_families;
    } else {
      // this is a reopen. just assert that existing column_family_names are
      // equivalent to what we remember
      auto sorted_cfn = column_family_names_;
      std::sort(sorted_cfn.begin(), sorted_cfn.end());
      std::sort(existing_column_families.begin(),
                existing_column_families.end());
      if (sorted_cfn != existing_column_families) {
        fprintf(stderr, "Expected column families differ from the existing:\n");
1944
        fprintf(stderr, "Expected: {");
1945
        for (auto cf : sorted_cfn) {
1946
          fprintf(stderr, "%s ", cf.c_str());
1947
        }
1948 1949
        fprintf(stderr, "}\n");
        fprintf(stderr, "Existing: {");
1950
        for (auto cf : existing_column_families) {
1951
          fprintf(stderr, "%s ", cf.c_str());
1952
        }
1953
        fprintf(stderr, "}\n");
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
      }
      assert(sorted_cfn == existing_column_families);
    }
    std::vector<ColumnFamilyDescriptor> cf_descriptors;
    for (auto name : column_family_names_) {
      if (name != kDefaultColumnFamilyName) {
        new_column_family_name_ =
            std::max(new_column_family_name_.load(), std::stoi(name) + 1);
      }
      cf_descriptors.emplace_back(name, ColumnFamilyOptions(options_));
    }
    while (cf_descriptors.size() < (size_t)FLAGS_column_families) {
      std::string name = ToString(new_column_family_name_.load());
      new_column_family_name_++;
      cf_descriptors.emplace_back(name, ColumnFamilyOptions(options_));
      column_family_names_.push_back(name);
    }
    options_.listeners.clear();
    options_.listeners.emplace_back(
        new DbStressListener(FLAGS_db, options_.db_paths, cf_descriptors));
    options_.create_missing_column_families = true;
    if (!FLAGS_use_txn) {
L
Levi Tamasi 已提交
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
#ifndef ROCKSDB_LITE
      if (FLAGS_use_blob_db) {
        blob_db::BlobDBOptions blob_db_options;
        blob_db_options.min_blob_size = FLAGS_blob_db_min_blob_size;
        blob_db_options.bytes_per_sync = FLAGS_blob_db_bytes_per_sync;
        blob_db_options.blob_file_size = FLAGS_blob_db_file_size;
        blob_db_options.enable_garbage_collection = FLAGS_blob_db_enable_gc;
        blob_db_options.garbage_collection_cutoff = FLAGS_blob_db_gc_cutoff;

        blob_db::BlobDB* blob_db = nullptr;
        s = blob_db::BlobDB::Open(options_, blob_db_options, FLAGS_db,
                                  cf_descriptors, &column_families_, &blob_db);
        if (s.ok()) {
          db_ = blob_db;
        }
      } else
#endif  // !ROCKSDB_LITE
      {
        if (db_preload_finished_.load() && FLAGS_read_only) {
          s = DB::OpenForReadOnly(DBOptions(options_), FLAGS_db, cf_descriptors,
                                  &column_families_, &db_);
        } else {
          s = DB::Open(DBOptions(options_), FLAGS_db, cf_descriptors,
                       &column_families_, &db_);
        }
2001 2002 2003 2004
      }
    } else {
#ifndef ROCKSDB_LITE
      TransactionDBOptions txn_db_options;
2005 2006 2007
      assert(FLAGS_txn_write_policy <= TxnDBWritePolicy::WRITE_UNPREPARED);
      txn_db_options.write_policy =
          static_cast<TxnDBWritePolicy>(FLAGS_txn_write_policy);
2008 2009 2010 2011 2012 2013
      if (FLAGS_unordered_write) {
        assert(txn_db_options.write_policy == TxnDBWritePolicy::WRITE_PREPARED);
        options_.unordered_write = true;
        options_.two_write_queues = true;
        txn_db_options.skip_concurrency_control = true;
      }
2014 2015
      s = TransactionDB::Open(options_, txn_db_options, FLAGS_db,
                              cf_descriptors, &column_families_, &txn_db_);
2016 2017 2018 2019 2020
      if (!s.ok()) {
        fprintf(stderr, "Error in opening the TransactionDB [%s]\n",
                s.ToString().c_str());
        fflush(stderr);
      }
2021
      assert(s.ok());
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
      db_ = txn_db_;
      // after a crash, rollback to commit recovered transactions
      std::vector<Transaction*> trans;
      txn_db_->GetAllPreparedTransactions(&trans);
      Random rand(static_cast<uint32_t>(FLAGS_seed));
      for (auto txn : trans) {
        if (rand.OneIn(2)) {
          s = txn->Commit();
          assert(s.ok());
        } else {
          s = txn->Rollback();
          assert(s.ok());
        }
        delete txn;
      }
      trans.clear();
      txn_db_->GetAllPreparedTransactions(&trans);
      assert(trans.size() == 0);
#endif
    }
    assert(!s.ok() || column_families_.size() ==
                          static_cast<size_t>(FLAGS_column_families));

2045
    if (FLAGS_test_secondary) {
2046 2047 2048 2049 2050 2051
#ifndef ROCKSDB_LITE
      secondaries_.resize(FLAGS_threads);
      std::fill(secondaries_.begin(), secondaries_.end(), nullptr);
      secondary_cfh_lists_.clear();
      secondary_cfh_lists_.resize(FLAGS_threads);
      Options tmp_opts;
2052 2053
      // TODO(yanqin) support max_open_files != -1 for secondary instance.
      tmp_opts.max_open_files = -1;
2054
      tmp_opts.statistics = dbstats_secondaries;
2055
      tmp_opts.env = db_stress_env;
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
      for (size_t i = 0; i != static_cast<size_t>(FLAGS_threads); ++i) {
        const std::string secondary_path =
            FLAGS_secondaries_base + "/" + std::to_string(i);
        s = DB::OpenAsSecondary(tmp_opts, FLAGS_db, secondary_path,
                                cf_descriptors, &secondary_cfh_lists_[i],
                                &secondaries_[i]);
        if (!s.ok()) {
          break;
        }
      }
2066
      assert(s.ok());
2067 2068 2069 2070 2071
#else
      fprintf(stderr, "Secondary is not supported in RocksDBLite\n");
      exit(1);
#endif
    }
2072 2073 2074 2075
    if (FLAGS_continuous_verification_interval > 0 && !cmp_db_) {
      Options tmp_opts;
      // TODO(yanqin) support max_open_files != -1 for secondary instance.
      tmp_opts.max_open_files = -1;
2076
      tmp_opts.env = db_stress_env;
2077 2078 2079 2080 2081 2082
      std::string secondary_path = FLAGS_secondaries_base + "/cmp_database";
      s = DB::OpenAsSecondary(tmp_opts, FLAGS_db, secondary_path,
                              cf_descriptors, &cmp_cfhs_, &cmp_db_);
      assert(!s.ok() ||
             cmp_cfhs_.size() == static_cast<size_t>(FLAGS_column_families));
    }
2083 2084 2085 2086 2087
  } else {
#ifndef ROCKSDB_LITE
    DBWithTTL* db_with_ttl;
    s = DBWithTTL::Open(options_, FLAGS_db, &db_with_ttl, FLAGS_ttl);
    db_ = db_with_ttl;
2088
    if (FLAGS_test_secondary) {
2089 2090 2091 2092
      secondaries_.resize(FLAGS_threads);
      std::fill(secondaries_.begin(), secondaries_.end(), nullptr);
      Options tmp_opts;
      tmp_opts.env = options_.env;
2093 2094
      // TODO(yanqin) support max_open_files != -1 for secondary instance.
      tmp_opts.max_open_files = -1;
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
      for (size_t i = 0; i != static_cast<size_t>(FLAGS_threads); ++i) {
        const std::string secondary_path =
            FLAGS_secondaries_base + "/" + std::to_string(i);
        s = DB::OpenAsSecondary(tmp_opts, FLAGS_db, secondary_path,
                                &secondaries_[i]);
        if (!s.ok()) {
          break;
        }
      }
    }
#else
    fprintf(stderr, "TTL is not supported in RocksDBLite\n");
    exit(1);
#endif
  }
  if (!s.ok()) {
    fprintf(stderr, "open error: %s\n", s.ToString().c_str());
    exit(1);
  }
}

2116 2117
void StressTest::Reopen(ThreadState* thread) {
#ifndef ROCKSDB_LITE
2118 2119 2120 2121
  // BG jobs in WritePrepared must be canceled first because i) they can access
  // the db via a callbac ii) they hold on to a snapshot and the upcoming
  // ::Close would complain about it.
  const bool write_prepared = FLAGS_use_txn && FLAGS_txn_write_policy != 0;
2122
  bool bg_canceled = false;
2123 2124 2125
  if (write_prepared || thread->rand.OneIn(2)) {
    const bool wait =
        write_prepared || static_cast<bool>(thread->rand.OneIn(2));
2126 2127
    CancelAllBackgroundWork(db_, wait);
    bg_canceled = wait;
2128
  }
2129
  assert(!write_prepared || bg_canceled);
2130
  (void) bg_canceled;
2131 2132 2133 2134
#else
  (void) thread;
#endif

2135 2136 2137 2138
  for (auto cf : column_families_) {
    delete cf;
  }
  column_families_.clear();
2139 2140

#ifndef ROCKSDB_LITE
2141
  if (thread->rand.OneIn(2)) {
2142
    Status s = db_->Close();
2143 2144 2145 2146
    if (!s.ok()) {
      fprintf(stderr, "Non-ok close status: %s\n", s.ToString().c_str());
      fflush(stderr);
    }
2147 2148 2149
    assert(s.ok());
  }
#endif
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
  delete db_;
  db_ = nullptr;
#ifndef ROCKSDB_LITE
  txn_db_ = nullptr;
#endif

  assert(secondaries_.size() == secondary_cfh_lists_.size());
  size_t n = secondaries_.size();
  for (size_t i = 0; i != n; ++i) {
    for (auto* cf : secondary_cfh_lists_[i]) {
      delete cf;
    }
    secondary_cfh_lists_[i].clear();
    delete secondaries_[i];
  }
  secondaries_.clear();

  num_times_reopened_++;
2168
  auto now = db_stress_env->NowMicros();
2169
  fprintf(stdout, "%s Reopening database for the %dth time\n",
2170 2171
          db_stress_env->TimeToString(now / 1000000).c_str(),
          num_times_reopened_);
2172 2173
  Open();
}
2174
}  // namespace ROCKSDB_NAMESPACE
2175
#endif  // GFLAGS