db_stress_test_base.cc 128.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
//  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.
//

11
#include <ios>
12
#include <thread>
13

14
#include "util/compression.h"
15 16
#ifdef GFLAGS
#include "db_stress_tool/db_stress_common.h"
17
#include "db_stress_tool/db_stress_compaction_filter.h"
18
#include "db_stress_tool/db_stress_driver.h"
19
#include "db_stress_tool/db_stress_table_properties_collector.h"
20
#include "rocksdb/convenience.h"
21
#include "rocksdb/filter_policy.h"
22
#include "rocksdb/secondary_cache.h"
23
#include "rocksdb/sst_file_manager.h"
24
#include "rocksdb/types.h"
25
#include "rocksdb/utilities/object_registry.h"
26
#include "rocksdb/utilities/write_batch_with_index.h"
27
#include "test_util/testutil.h"
28
#include "util/cast_util.h"
29
#include "utilities/backup/backup_engine_impl.h"
M
mrambacher 已提交
30
#include "utilities/fault_injection_fs.h"
A
anand76 已提交
31
#include "utilities/fault_injection_secondary_cache.h"
32

33
namespace ROCKSDB_NAMESPACE {
34 35 36 37 38 39 40 41

namespace {

std::shared_ptr<const FilterPolicy> CreateFilterPolicy() {
  if (FLAGS_bloom_bits < 0) {
    return BlockBasedTableOptions().filter_policy;
  }
  const FilterPolicy* new_policy;
42
  if (FLAGS_ribbon_starting_level >= 999) {
43 44 45 46 47
    // Use Bloom API
    new_policy = NewBloomFilterPolicy(FLAGS_bloom_bits, false);
  } else {
    new_policy = NewRibbonFilterPolicy(
        FLAGS_bloom_bits, /* bloom_before_level */ FLAGS_ribbon_starting_level);
48 49 50 51 52 53
  }
  return std::shared_ptr<const FilterPolicy>(new_policy);
}

}  // namespace

54
StressTest::StressTest()
55
    : cache_(NewCache(FLAGS_cache_size, FLAGS_cache_numshardbits)),
56
      filter_policy_(CreateFilterPolicy()),
57 58
      db_(nullptr),
      txn_db_(nullptr),
59
      optimistic_txn_db_(nullptr),
60
      db_aptr_(nullptr),
61
      clock_(db_stress_env->GetSystemClock().get()),
62 63
      new_column_family_name_(1),
      num_times_reopened_(0),
64
      db_preload_finished_(false),
65 66
      cmp_db_(nullptr),
      is_db_stopped_(false) {
67 68
  if (FLAGS_destroy_db_initially) {
    std::vector<std::string> files;
69
    db_stress_env->GetChildren(FLAGS_db, &files);
70 71
    for (unsigned int i = 0; i < files.size(); i++) {
      if (Slice(files[i]).starts_with("heap-")) {
72
        db_stress_env->DeleteFile(FLAGS_db + "/" + files[i]);
73 74
      }
    }
L
Levi Tamasi 已提交
75

76
    Options options;
77
    options.env = db_stress_env;
78
    // Remove files without preserving manfiest files
L
Levi Tamasi 已提交
79 80 81 82 83
    const Status s = !FLAGS_use_blob_db
                         ? DestroyDB(FLAGS_db, options)
                         : blob_db::DestroyBlobDB(FLAGS_db, options,
                                                  blob_db::BlobDBOptions());

84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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_;

98 99 100 101 102
  for (auto* cf : cmp_cfhs_) {
    delete cf;
  }
  cmp_cfhs_.clear();
  delete cmp_db_;
103 104
}

105 106
std::shared_ptr<Cache> StressTest::NewCache(size_t capacity,
                                            int32_t num_shard_bits) {
107
  ConfigOptions config_options;
108 109 110
  if (capacity <= 0) {
    return nullptr;
  }
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  std::shared_ptr<SecondaryCache> secondary_cache;
  if (!FLAGS_secondary_cache_uri.empty()) {
    Status s = SecondaryCache::CreateFromString(
        config_options, FLAGS_secondary_cache_uri, &secondary_cache);
    if (secondary_cache == nullptr) {
      fprintf(stderr,
              "No secondary cache registered matching string: %s status=%s\n",
              FLAGS_secondary_cache_uri.c_str(), s.ToString().c_str());
      exit(1);
    }
    if (FLAGS_secondary_cache_fault_one_in > 0) {
      secondary_cache = std::make_shared<FaultInjectionSecondaryCache>(
          secondary_cache, static_cast<uint32_t>(FLAGS_seed),
          FLAGS_secondary_cache_fault_one_in);
    }
  }

129
  if (FLAGS_cache_type == "clock_cache") {
130 131
    fprintf(stderr, "Old clock cache implementation has been removed.\n");
    exit(1);
132 133 134 135 136 137 138 139 140 141 142 143
  } else if (EndsWith(FLAGS_cache_type, "hyper_clock_cache")) {
    size_t estimated_entry_charge;
    if (FLAGS_cache_type == "fixed_hyper_clock_cache" ||
        FLAGS_cache_type == "hyper_clock_cache") {
      estimated_entry_charge = FLAGS_block_size;
    } else if (FLAGS_cache_type == "auto_hyper_clock_cache") {
      estimated_entry_charge = 0;
    } else {
      fprintf(stderr, "Cache type not supported.");
      exit(1);
    }
    HyperClockCacheOptions opts(FLAGS_cache_size, estimated_entry_charge,
144
                                num_shard_bits);
145
    opts.hash_seed = BitwiseAnd(FLAGS_seed, INT32_MAX);
146
    return opts.MakeSharedCache();
147
  } else if (FLAGS_cache_type == "lru_cache") {
148 149 150
    LRUCacheOptions opts;
    opts.capacity = capacity;
    opts.num_shard_bits = num_shard_bits;
151
    opts.secondary_cache = std::move(secondary_cache);
152
    return NewLRUCache(opts);
153 154 155
  } else {
    fprintf(stderr, "Cache type not supported.");
    exit(1);
156 157 158
  }
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
std::vector<std::string> StressTest::GetBlobCompressionTags() {
  std::vector<std::string> compression_tags{"kNoCompression"};

  if (Snappy_Supported()) {
    compression_tags.emplace_back("kSnappyCompression");
  }
  if (LZ4_Supported()) {
    compression_tags.emplace_back("kLZ4Compression");
  }
  if (ZSTD_Supported()) {
    compression_tags.emplace_back("kZSTD");
  }

  return compression_tags;
}

175 176 177 178 179 180 181
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",
S
sdong 已提交
182 183 184
       {std::to_string(options_.write_buffer_size),
        std::to_string(options_.write_buffer_size * 2),
        std::to_string(options_.write_buffer_size * 4)}},
185
      {"max_write_buffer_number",
S
sdong 已提交
186 187 188
       {std::to_string(options_.max_write_buffer_number),
        std::to_string(options_.max_write_buffer_number * 2),
        std::to_string(options_.max_write_buffer_number * 4)}},
189 190
      {"arena_block_size",
       {
S
sdong 已提交
191 192 193
           std::to_string(options_.arena_block_size),
           std::to_string(options_.write_buffer_size / 4),
           std::to_string(options_.write_buffer_size / 8),
194
       }},
S
sdong 已提交
195
      {"memtable_huge_page_size", {"0", std::to_string(2 * 1024 * 1024)}},
196 197
      {"max_successive_merges", {"0", "2", "4"}},
      {"inplace_update_num_locks", {"100", "200", "300"}},
198 199
      // TODO: re-enable once internal task T124324915 is fixed.
      // {"experimental_mempurge_threshold", {"0.0", "1.0"}},
200 201 202 203
      // TODO(ljin): enable test for this option
      // {"disable_auto_compactions", {"100", "200", "300"}},
      {"level0_file_num_compaction_trigger",
       {
S
sdong 已提交
204 205 206
           std::to_string(options_.level0_file_num_compaction_trigger),
           std::to_string(options_.level0_file_num_compaction_trigger + 2),
           std::to_string(options_.level0_file_num_compaction_trigger + 4),
207 208 209
       }},
      {"level0_slowdown_writes_trigger",
       {
S
sdong 已提交
210 211 212
           std::to_string(options_.level0_slowdown_writes_trigger),
           std::to_string(options_.level0_slowdown_writes_trigger + 2),
           std::to_string(options_.level0_slowdown_writes_trigger + 4),
213 214 215
       }},
      {"level0_stop_writes_trigger",
       {
S
sdong 已提交
216 217 218
           std::to_string(options_.level0_stop_writes_trigger),
           std::to_string(options_.level0_stop_writes_trigger + 2),
           std::to_string(options_.level0_stop_writes_trigger + 4),
219 220 221
       }},
      {"max_compaction_bytes",
       {
S
sdong 已提交
222 223 224
           std::to_string(options_.target_file_size_base * 5),
           std::to_string(options_.target_file_size_base * 15),
           std::to_string(options_.target_file_size_base * 100),
225 226 227
       }},
      {"target_file_size_base",
       {
S
sdong 已提交
228 229 230
           std::to_string(options_.target_file_size_base),
           std::to_string(options_.target_file_size_base * 2),
           std::to_string(options_.target_file_size_base * 4),
231 232 233
       }},
      {"target_file_size_multiplier",
       {
S
sdong 已提交
234
           std::to_string(options_.target_file_size_multiplier),
235 236 237 238 239
           "1",
           "2",
       }},
      {"max_bytes_for_level_base",
       {
S
sdong 已提交
240 241 242
           std::to_string(options_.max_bytes_for_level_base / 2),
           std::to_string(options_.max_bytes_for_level_base),
           std::to_string(options_.max_bytes_for_level_base * 2),
243 244 245
       }},
      {"max_bytes_for_level_multiplier",
       {
S
sdong 已提交
246
           std::to_string(options_.max_bytes_for_level_multiplier),
247 248 249 250 251 252
           "1",
           "2",
       }},
      {"max_sequential_skip_in_iterations", {"4", "8", "12"}},
  };

253 254 255 256
  if (FLAGS_allow_setting_blob_options_dynamically) {
    options_tbl.emplace("enable_blob_files",
                        std::vector<std::string>{"false", "true"});
    options_tbl.emplace("min_blob_size",
257
                        std::vector<std::string>{"0", "8", "16"});
258 259 260 261 262 263 264 265
    options_tbl.emplace("blob_file_size",
                        std::vector<std::string>{"1M", "16M", "256M", "1G"});
    options_tbl.emplace("blob_compression_type", GetBlobCompressionTags());
    options_tbl.emplace("enable_blob_garbage_collection",
                        std::vector<std::string>{"false", "true"});
    options_tbl.emplace(
        "blob_garbage_collection_age_cutoff",
        std::vector<std::string>{"0.0", "0.25", "0.5", "0.75", "1.0"});
266 267
    options_tbl.emplace("blob_garbage_collection_force_threshold",
                        std::vector<std::string>{"0.5", "0.75", "1.0"});
268 269
    options_tbl.emplace("blob_compaction_readahead_size",
                        std::vector<std::string>{"0", "1M", "4M"});
270 271
    options_tbl.emplace("blob_file_starting_level",
                        std::vector<std::string>{"0", "1", "2"});
272 273
    options_tbl.emplace("prepopulate_blob_cache",
                        std::vector<std::string>{"kDisable", "kFlushOnly"});
274 275
  }

276 277 278 279 280 281 282 283
  options_table_ = std::move(options_tbl);

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

284
void StressTest::InitDb(SharedState* shared) {
285
  uint64_t now = clock_->NowMicros();
286
  fprintf(stdout, "%s Initializing db_stress\n",
287
          clock_->TimeToString(now / 1000000).c_str());
288
  PrintEnv();
289
  Open(shared);
290 291 292
  BuildOptionsTable();
}

293 294
void StressTest::FinishInitDb(SharedState* shared) {
  if (FLAGS_read_only) {
295
    uint64_t now = clock_->NowMicros();
296
    fprintf(stdout, "%s Preloading db with %" PRIu64 " KVs\n",
297
            clock_->TimeToString(now / 1000000).c_str(), FLAGS_max_key);
298 299
    PreloadDbAndReopenAsReadOnly(FLAGS_max_key, shared);
  }
300

301
  if (shared->HasHistory()) {
302 303 304 305 306 307 308 309 310 311 312
    // The way it works right now is, if there's any history, that means the
    // previous run mutating the DB had all its operations traced, in which case
    // we should always be able to `Restore()` the expected values to match the
    // `db_`'s current seqno.
    Status s = shared->Restore(db_);
    if (!s.ok()) {
      fprintf(stderr, "Error restoring historical expected values: %s\n",
              s.ToString().c_str());
      exit(1);
    }
  }
313
  if (FLAGS_use_txn && !FLAGS_use_optimistic_txn) {
314 315 316 317 318 319
    // It's OK here without sync because unsynced data cannot be lost at this
    // point
    // - even with sync_fault_injection=1 as the
    // file is still directly writable until after FinishInitDb()
    ProcessRecoveredPreparedTxns(shared);
  }
S
sdong 已提交
320

321 322 323 324 325 326 327 328 329 330 331
  if (FLAGS_enable_compaction_filter) {
    auto* compaction_filter_factory =
        reinterpret_cast<DbStressCompactionFilterFactory*>(
            options_.compaction_filter_factory.get());
    assert(compaction_filter_factory);
    // This must be called only after any potential `SharedState::Restore()` has
    // completed in order for the `compaction_filter_factory` to operate on the
    // correct latest values file.
    compaction_filter_factory->SetSharedState(shared);
    fprintf(stdout, "Compaction filter factory: %s\n",
            compaction_filter_factory->Name());
332 333 334 335
  }
}

void StressTest::TrackExpectedState(SharedState* shared) {
336 337 338 339 340 341 342 343
  // For `FLAGS_manual_wal_flush_one_inWAL`
  // data can be lost when `manual_wal_flush_one_in > 0` and `FlushWAL()` is not
  // explictly called by users of RocksDB (in our case, db stress).
  // Therefore recovery from such potential WAL data loss is a prefix recovery
  // that requires tracing
  if ((FLAGS_sync_fault_injection || FLAGS_disable_wal ||
       FLAGS_manual_wal_flush_one_in > 0) &&
      IsStateTracked()) {
344 345 346 347 348 349
    Status s = shared->SaveAtAndAfter(db_);
    if (!s.ok()) {
      fprintf(stderr, "Error enabling history tracing: %s\n",
              s.ToString().c_str());
      exit(1);
    }
350
  }
351 352 353 354 355 356 357 358
}

Status StressTest::AssertSame(DB* db, ColumnFamilyHandle* cf,
                              ThreadState::SnapshotState& snap_state) {
  Status s;
  if (cf->GetName() != snap_state.cf_at_name) {
    return s;
  }
359 360
  // This `ReadOptions` is for validation purposes. Ignore
  // `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
361 362
  ReadOptions ropt;
  ropt.snapshot = snap_state.snapshot;
363 364 365 366 367
  Slice ts;
  if (!snap_state.timestamp.empty()) {
    ts = snap_state.timestamp;
    ropt.timestamp = &ts;
  }
368 369 370 371 372 373 374 375 376 377
  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 " +
S
sdong 已提交
378
        std::to_string(Hash(snap_state.key.c_str(), snap_state.key.size(), 0)) +
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
        " 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 {
412 413
  fprintf(stderr, "Verification failed: %s. Status is %s\n", msg.c_str(),
          s.ToString().c_str());
414 415 416 417 418
  shared->SetVerificationFailure();
}

void StressTest::VerificationAbort(SharedState* shared, std::string msg, int cf,
                                   int64_t key) const {
J
Jay Zhuang 已提交
419 420
  auto key_str = Key(key);
  Slice key_slice = key_str;
421
  fprintf(stderr,
J
Jay Zhuang 已提交
422 423
          "Verification failed for column family %d key %s (%" PRIi64 "): %s\n",
          cf, key_slice.ToString(true).c_str(), key, msg.c_str());
424 425 426
  shared->SetVerificationFailure();
}

427 428 429 430 431 432 433 434 435 436 437 438 439
void StressTest::VerificationAbort(SharedState* shared, std::string msg, int cf,
                                   int64_t key, Slice value_from_db,
                                   Slice value_from_expected) const {
  auto key_str = Key(key);
  fprintf(stderr,
          "Verification failed for column family %d key %s (%" PRIi64
          "): value_from_db: %s, value_from_expected: %s, msg: %s\n",
          cf, Slice(key_str).ToString(true).c_str(), key,
          value_from_db.ToString(true).c_str(),
          value_from_expected.ToString(true).c_str(), msg.c_str());
  shared->SetVerificationFailure();
}

440 441
void StressTest::VerificationAbort(SharedState* shared, int cf, int64_t key,
                                   const Slice& value,
442
                                   const WideColumns& columns) const {
443 444 445 446 447 448
  assert(shared);

  auto key_str = Key(key);

  fprintf(stderr,
          "Verification failed for column family %d key %s (%" PRIi64
449
          "): Value and columns inconsistent: value: %s, columns: %s\n",
450
          cf, Slice(key_str).ToString(/* hex */ true).c_str(), key,
451 452
          value.ToString(/* hex */ true).c_str(),
          WideColumnsToHex(columns).c_str());
453 454 455 456 457

  shared->SetVerificationFailure();
}

std::string StressTest::DebugString(const Slice& value,
458
                                    const WideColumns& columns) {
459 460
  std::ostringstream oss;

461 462
  oss << "value: " << value.ToString(/* hex */ true)
      << ", columns: " << WideColumnsToHex(columns);
463 464 465 466

  return oss.str();
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
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;
  }
485 486 487
  if (FLAGS_rate_limit_auto_wal_flush) {
    write_opts.rate_limiter_priority = Env::IO_USER;
  }
488 489 490 491 492
  char value[100];
  int cf_idx = 0;
  Status s;
  for (auto cfh : column_families_) {
    for (int64_t k = 0; k != number_of_keys; ++k) {
493 494
      const std::string key = Key(k);

495 496 497
      PendingExpectedValue pending_expected_value =
          shared->PreparePut(cf_idx, k);
      const uint32_t value_base = pending_expected_value.GetFinalValueBase();
498 499 500 501
      const size_t sz = GenerateValue(value_base, value, sizeof(value));

      const Slice v(value, sz);

502 503 504 505 506
      std::string ts;
      if (FLAGS_user_timestamp_size > 0) {
        ts = GetNowNanos();
      }

507 508
      if (FLAGS_use_merge) {
        if (!FLAGS_use_txn) {
509 510 511 512 513
          if (FLAGS_user_timestamp_size > 0) {
            s = db_->Merge(write_opts, cfh, key, ts, v);
          } else {
            s = db_->Merge(write_opts, cfh, key, v);
          }
514
        } else {
515 516 517
          s = ExecuteTransaction(
              write_opts, /*thread=*/nullptr,
              [&](Transaction& txn) { return txn.Merge(cfh, key, v); });
518
        }
519 520 521
      } else if (FLAGS_use_put_entity_one_in > 0) {
        s = db_->PutEntity(write_opts, cfh, key,
                           GenerateWideColumns(value_base, v));
522 523
      } else {
        if (!FLAGS_use_txn) {
524
          if (FLAGS_user_timestamp_size > 0) {
525 526 527
            s = db_->Put(write_opts, cfh, key, ts, v);
          } else {
            s = db_->Put(write_opts, cfh, key, v);
528
          }
529
        } else {
530 531 532
          s = ExecuteTransaction(
              write_opts, /*thread=*/nullptr,
              [&](Transaction& txn) { return txn.Put(cfh, key, v); });
533 534 535
        }
      }

536
      pending_expected_value.Commit();
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
      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;
    txn_db_ = nullptr;
557
    optimistic_txn_db_ = nullptr;
558 559

    db_preload_finished_.store(true);
560
    auto now = clock_->NowMicros();
561
    fprintf(stdout, "%s Reopening database in read-only\n",
562
            clock_->TimeToString(now / 1000000).c_str());
563
    // Reopen as read-only, can ignore all options related to updates
564
    Open(shared);
565 566 567 568 569 570 571 572 573 574 575 576
  } 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();
577 578 579
  if (name == "level0_file_num_compaction_trigger" ||
      name == "level0_slowdown_writes_trigger" ||
      name == "level0_stop_writes_trigger") {
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    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);
}

595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
void StressTest::ProcessRecoveredPreparedTxns(SharedState* shared) {
  assert(txn_db_);
  std::vector<Transaction*> recovered_prepared_trans;
  txn_db_->GetAllPreparedTransactions(&recovered_prepared_trans);
  for (Transaction* txn : recovered_prepared_trans) {
    ProcessRecoveredPreparedTxnsHelper(txn, shared);
    delete txn;
  }
  recovered_prepared_trans.clear();
  txn_db_->GetAllPreparedTransactions(&recovered_prepared_trans);
  assert(recovered_prepared_trans.size() == 0);
}

void StressTest::ProcessRecoveredPreparedTxnsHelper(Transaction* txn,
                                                    SharedState* shared) {
  thread_local Random rand(static_cast<uint32_t>(FLAGS_seed));
  for (size_t i = 0; i < column_families_.size(); ++i) {
    std::unique_ptr<WBWIIterator> wbwi_iter(
        txn->GetWriteBatch()->NewIterator(column_families_[i]));
    for (wbwi_iter->SeekToFirst(); wbwi_iter->Valid(); wbwi_iter->Next()) {
      uint64_t key_val;
      if (GetIntVal(wbwi_iter->Entry().key.ToString(), &key_val)) {
617
        shared->SyncPendingPut(static_cast<int>(i) /* cf_idx */, key_val);
618 619 620 621 622 623 624 625 626 627 628 629
      }
    }
  }
  if (rand.OneIn(2)) {
    Status s = txn->Commit();
    assert(s.ok());
  } else {
    Status s = txn->Rollback();
    assert(s.ok());
  }
}

630 631
Status StressTest::NewTxn(WriteOptions& write_opts,
                          std::unique_ptr<Transaction>* out_txn) {
632 633 634
  if (!FLAGS_use_txn) {
    return Status::InvalidArgument("NewTxn when FLAGS_use_txn is not set");
  }
635
  write_opts.disableWAL = FLAGS_disable_wal;
636
  static std::atomic<uint64_t> txn_id = {0};
637
  if (FLAGS_use_optimistic_txn) {
638
    out_txn->reset(optimistic_txn_db_->BeginTransaction(write_opts));
639 640 641 642 643 644 645
    return Status::OK();
  } else {
    TransactionOptions txn_options;
    txn_options.use_only_the_last_commit_time_batch_for_recovery =
        FLAGS_use_only_the_last_commit_time_batch_for_recovery;
    txn_options.lock_timeout = 600000;  // 10 min
    txn_options.deadlock_detect = true;
646
    out_txn->reset(txn_db_->BeginTransaction(write_opts, txn_options));
647
    auto istr = std::to_string(txn_id.fetch_add(1));
648
    Status s = (*out_txn)->SetName("xid" + istr);
649 650
    return s;
  }
651 652
}

653
Status StressTest::CommitTxn(Transaction& txn, ThreadState* thread) {
654 655 656
  if (!FLAGS_use_txn) {
    return Status::InvalidArgument("CommitTxn when FLAGS_use_txn is not set");
  }
657 658 659
  Status s = Status::OK();
  if (FLAGS_use_optimistic_txn) {
    assert(optimistic_txn_db_);
660
    s = txn.Commit();
661 662
  } else {
    assert(txn_db_);
663
    s = txn.Prepare();
664 665 666 667 668
    std::shared_ptr<const Snapshot> timestamped_snapshot;
    if (s.ok()) {
      if (thread && FLAGS_create_timestamped_snapshot_one_in &&
          thread->rand.OneIn(FLAGS_create_timestamped_snapshot_one_in)) {
        uint64_t ts = db_stress_env->NowNanos();
669 670
        s = txn.CommitAndTryCreateSnapshot(/*notifier=*/nullptr, ts,
                                           &timestamped_snapshot);
671 672 673 674 675 676 677 678 679 680 681 682 683 684

        std::pair<Status, std::shared_ptr<const Snapshot>> res;
        if (thread->tid == 0) {
          uint64_t now = db_stress_env->NowNanos();
          res = txn_db_->CreateTimestampedSnapshot(now);
          if (res.first.ok()) {
            assert(res.second);
            assert(res.second->GetTimestamp() == now);
            if (timestamped_snapshot) {
              assert(res.second->GetTimestamp() >
                     timestamped_snapshot->GetTimestamp());
            }
          } else {
            assert(!res.second);
685 686
          }
        }
687
      } else {
688
        s = txn.Commit();
689
      }
690
    }
691 692 693 694 695 696
    if (thread && FLAGS_create_timestamped_snapshot_one_in > 0 &&
        thread->rand.OneInOpt(50000)) {
      uint64_t now = db_stress_env->NowNanos();
      constexpr uint64_t time_diff = static_cast<uint64_t>(1000) * 1000 * 1000;
      txn_db_->ReleaseTimestampedSnapshotsOlderThan(now - time_diff);
    }
697
  }
698 699
  return s;
}
700

701 702 703 704 705
Status StressTest::ExecuteTransaction(
    WriteOptions& write_opts, ThreadState* thread,
    std::function<Status(Transaction&)>&& ops) {
  std::unique_ptr<Transaction> txn;
  Status s = NewTxn(write_opts, &txn);
706
  std::string try_again_messages;
707 708 709 710 711 712 713 714 715 716
  if (s.ok()) {
    for (int tries = 1;; ++tries) {
      s = ops(*txn);
      if (s.ok()) {
        s = CommitTxn(*txn, thread);
        if (s.ok()) {
          break;
        }
      }
      // Optimistic txn might return TryAgain, in which case rollback
717
      // and try again.
718 719 720
      if (!s.IsTryAgain() || !FLAGS_use_optimistic_txn) {
        break;
      }
721 722 723 724 725 726 727 728 729 730 731
      // Record and report historical TryAgain messages for debugging
      try_again_messages +=
          std::to_string(SystemClock::Default()->NowMicros() / 1000);
      try_again_messages += "ms ";
      try_again_messages += s.getState();
      try_again_messages += "\n";
      // In theory, each Rollback after TryAgain should have an independent
      // chance of success, so too many retries could indicate something is
      // not working properly.
      if (tries >= 10) {
        s = Status::TryAgain(try_again_messages);
732 733 734 735 736 737 738
        break;
      }
      s = txn->Rollback();
      if (!s.ok()) {
        break;
      }
    }
739 740 741
  }
  return s;
}
742 743 744

void StressTest::OperateDb(ThreadState* thread) {
  ReadOptions read_opts(FLAGS_verify_checksum, true);
745 746
  read_opts.rate_limiter_priority =
      FLAGS_rate_limit_user_ops ? Env::IO_USER : Env::IO_TOTAL;
747 748
  read_opts.async_io = FLAGS_async_io;
  read_opts.adaptive_readahead = FLAGS_adaptive_readahead;
749
  read_opts.readahead_size = FLAGS_readahead_size;
750
  read_opts.auto_readahead_size = FLAGS_auto_readahead_size;
751
  WriteOptions write_opts;
752 753 754
  if (FLAGS_rate_limit_auto_wal_flush) {
    write_opts.rate_limiter_priority = Env::IO_USER;
  }
755 756 757 758 759 760 761
  auto shared = thread->shared;
  char value[100];
  std::string from_db;
  if (FLAGS_sync) {
    write_opts.sync = true;
  }
  write_opts.disableWAL = FLAGS_disable_wal;
762
  write_opts.protection_bytes_per_key = FLAGS_batch_protection_bytes_per_key;
763 764 765 766 767 768 769 770 771
  const int prefix_bound = static_cast<int>(FLAGS_readpercent) +
                           static_cast<int>(FLAGS_prefixpercent);
  const int write_bound = prefix_bound + static_cast<int>(FLAGS_writepercent);
  const int del_bound = write_bound + static_cast<int>(FLAGS_delpercent);
  const int delrange_bound =
      del_bound + static_cast<int>(FLAGS_delrangepercent);
  const int iterate_bound =
      delrange_bound + static_cast<int>(FLAGS_iterpercent);

772 773
  const uint64_t ops_per_open = FLAGS_ops_per_thread / (FLAGS_reopen + 1);

A
anand76 已提交
774 775
#ifndef NDEBUG
  if (FLAGS_read_fault_one_in) {
776 777 778
    fault_fs_guard->SetThreadLocalReadErrorContext(
        thread->shared->GetSeed(), FLAGS_read_fault_one_in,
        FLAGS_inject_error_severity == 1 /* retryable */);
A
anand76 已提交
779
  }
780
#endif  // NDEBUG
781
  if (FLAGS_write_fault_one_in) {
782
    IOStatus error_msg;
783
    if (FLAGS_inject_error_severity <= 1 || FLAGS_inject_error_severity > 2) {
784 785
      error_msg = IOStatus::IOError("Retryable IO Error");
      error_msg.SetRetryable(true);
786 787
    } else if (FLAGS_inject_error_severity == 2) {
      // Inject a fatal error
788 789 790
      error_msg = IOStatus::IOError("Fatal IO Error");
      error_msg.SetDataLoss(true);
    }
791 792 793
    std::vector<FileType> types = {FileType::kTableFile,
                                   FileType::kDescriptorFile,
                                   FileType::kCurrentFile};
794
    fault_fs_guard->SetRandomWriteError(
795 796
        thread->shared->GetSeed(), FLAGS_write_fault_one_in, error_msg,
        /*inject_for_all_file_types=*/false, types);
797
  }
798 799
  thread->stats.Start();
  for (int open_cnt = 0; open_cnt <= FLAGS_reopen; ++open_cnt) {
800 801
    if (thread->shared->HasVerificationFailedYet() ||
        thread->shared->ShouldStopTest()) {
802 803 804 805 806 807 808 809 810 811 812 813
      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()) {
814
        thread->shared->GetStressTest()->Reopen(thread);
815 816 817 818 819 820 821 822 823 824 825 826 827 828
        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
829
      if (thread->rand.OneInOpt(FLAGS_set_options_one_in)) {
830 831 832
        SetOptions(thread);
      }

833
      if (thread->rand.OneInOpt(FLAGS_set_in_place_one_in)) {
834 835 836
        options_.inplace_update_support ^= options_.inplace_update_support;
      }

837 838 839 840 841 842 843 844
      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;
        }
      }

845 846
      MaybeClearOneColumnFamily(thread);

847 848 849
      if (thread->rand.OneInOpt(FLAGS_manual_wal_flush_one_in)) {
        bool sync = thread->rand.OneIn(2) ? true : false;
        Status s = db_->FlushWAL(sync);
850
        if (!s.ok() && !(sync && s.IsNotSupported())) {
851 852 853 854 855
          fprintf(stderr, "FlushWAL(sync=%s) failed: %s\n",
                  (sync ? "true" : "false"), s.ToString().c_str());
        }
      }

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
      if (thread->rand.OneInOpt(FLAGS_lock_wal_one_in)) {
        Status s = db_->LockWAL();
        if (!s.ok()) {
          fprintf(stderr, "LockWAL() failed: %s\n", s.ToString().c_str());
        } else {
          auto old_seqno = db_->GetLatestSequenceNumber();
          // Yield for a while
          do {
            std::this_thread::yield();
          } while (thread->rand.OneIn(2));
          // Latest seqno should not have changed
          auto new_seqno = db_->GetLatestSequenceNumber();
          if (old_seqno != new_seqno) {
            fprintf(
                stderr,
                "Failure: latest seqno changed from %u to %u with WAL locked\n",
                (unsigned)old_seqno, (unsigned)new_seqno);
          }
          s = db_->UnlockWAL();
          if (!s.ok()) {
            fprintf(stderr, "UnlockWAL() failed: %s\n", s.ToString().c_str());
          }
        }
      }

881
      if (thread->rand.OneInOpt(FLAGS_sync_wal_one_in)) {
Y
Yanqin Jin 已提交
882 883
        Status s = db_->SyncWAL();
        if (!s.ok() && !s.IsNotSupported()) {
884
          fprintf(stderr, "SyncWAL() failed: %s\n", s.ToString().c_str());
Y
Yanqin Jin 已提交
885 886 887
        }
      }

888 889
      int rand_column_family = thread->rand.Next() % FLAGS_column_families;
      ColumnFamilyHandle* column_family = column_families_[rand_column_family];
890

891 892
      if (thread->rand.OneInOpt(FLAGS_compact_files_one_in)) {
        TestCompactFiles(thread, column_family);
893
      }
894

895 896 897 898
      int64_t rand_key = GenerateOneKey(thread, i);
      std::string keystr = Key(rand_key);
      Slice key = keystr;

899
      if (thread->rand.OneInOpt(FLAGS_compact_range_one_in)) {
900 901 902
        TestCompactRange(thread, rand_key, key, column_family);
        if (thread->shared->HasVerificationFailedYet()) {
          break;
903 904 905 906 907 908
        }
      }

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

909
      if (thread->rand.OneInOpt(FLAGS_flush_one_in)) {
910
        Status status = TestFlush(rand_column_families);
911 912 913 914 915 916
        if (!status.ok()) {
          fprintf(stdout, "Unable to perform Flush(): %s\n",
                  status.ToString().c_str());
        }
      }

917
      // Verify GetLiveFiles with a 1 in N chance.
918 919
      if (thread->rand.OneInOpt(FLAGS_get_live_files_one_in) &&
          !FLAGS_write_fault_one_in) {
920
        Status status = VerifyGetLiveFiles();
921
        if (!status.ok()) {
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
          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",
940 941 942 943
                            status);
        }
      }

944
      if (thread->rand.OneInOpt(FLAGS_pause_background_one_in)) {
945
        Status status = TestPauseBackground(thread);
946
        if (!status.ok()) {
947 948
          VerificationAbort(
              shared, "Pause/ContinueBackgroundWork status not OK", status);
949 950 951
        }
      }

952
      if (thread->rand.OneInOpt(FLAGS_verify_checksum_one_in)) {
953 954 955
        ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
        ThreadStatusUtil::SetThreadOperation(
            ThreadStatus::OperationType::OP_VERIFY_DB_CHECKSUM);
956
        Status status = db_->VerifyChecksum();
957
        ThreadStatusUtil::ResetThreadStatus();
958 959 960 961
        if (!status.ok()) {
          VerificationAbort(shared, "VerifyChecksum status not OK", status);
        }
      }
962

963 964 965 966 967 968 969 970 971 972 973 974
      if (thread->rand.OneInOpt(FLAGS_verify_file_checksums_one_in)) {
        ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
        ThreadStatusUtil::SetThreadOperation(
            ThreadStatus::OperationType::OP_VERIFY_FILE_CHECKSUMS);
        Status status = db_->VerifyFileChecksums(read_opts);
        ThreadStatusUtil::ResetThreadStatus();
        if (!status.ok()) {
          VerificationAbort(shared, "VerifyFileChecksums status not OK",
                            status);
        }
      }

975 976 977
      if (thread->rand.OneInOpt(FLAGS_get_property_one_in)) {
        TestGetProperty(thread);
      }
978

979 980
      std::vector<int64_t> rand_keys = GenerateKeys(rand_key);

981
      if (thread->rand.OneInOpt(FLAGS_ingest_external_file_one_in)) {
982
        TestIngestExternalFile(thread, rand_column_families, rand_keys);
983 984
      }

985
      if (thread->rand.OneInOpt(FLAGS_backup_one_in)) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        // Beyond a certain DB size threshold, this test becomes heavier than
        // it's worth.
        uint64_t total_size = 0;
        if (FLAGS_backup_max_size > 0) {
          std::vector<FileAttributes> files;
          db_stress_env->GetChildrenFileAttributes(FLAGS_db, &files);
          for (auto& file : files) {
            total_size += file.size_bytes;
          }
        }

        if (total_size <= FLAGS_backup_max_size) {
          Status s = TestBackupRestore(thread, rand_column_families, rand_keys);
          if (!s.ok()) {
            VerificationAbort(shared, "Backup/restore gave inconsistent state",
                              s);
          }
1003 1004 1005
        }
      }

1006
      if (thread->rand.OneInOpt(FLAGS_checkpoint_one_in)) {
1007 1008 1009 1010 1011 1012
        Status s = TestCheckpoint(thread, rand_column_families, rand_keys);
        if (!s.ok()) {
          VerificationAbort(shared, "Checkpoint gave inconsistent state", s);
        }
      }

S
sdong 已提交
1013 1014 1015 1016 1017 1018 1019
      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);
        }
      }
1020
      if (thread->rand.OneInOpt(FLAGS_acquire_snapshot_one_in)) {
1021
        TestAcquireSnapshot(thread, rand_column_family, keystr, i);
1022
      }
1023 1024 1025

      /*always*/ {
        Status s = MaybeReleaseSnapshots(thread, i);
1026 1027 1028 1029 1030
        if (!s.ok()) {
          VerificationAbort(shared, "Snapshot gave inconsistent state", s);
        }
      }

1031 1032 1033
      // Assign timestamps if necessary.
      std::string read_ts_str;
      Slice read_ts;
1034
      if (FLAGS_user_timestamp_size > 0) {
1035
        read_ts_str = GetNowNanos();
1036 1037 1038 1039
        read_ts = read_ts_str;
        read_opts.timestamp = &read_ts;
      }

1040 1041 1042 1043
      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
1044
      if (prob_op >= 0 && prob_op < static_cast<int>(FLAGS_readpercent)) {
1045
        assert(0 <= prob_op);
1046
        // OPERATION read
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        if (FLAGS_use_multi_get_entity) {
          constexpr uint64_t max_batch_size = 64;
          const uint64_t batch_size = std::min(
              static_cast<uint64_t>(thread->rand.Uniform(max_batch_size)) + 1,
              ops_per_open - i);
          assert(batch_size >= 1);
          assert(batch_size <= max_batch_size);
          assert(i + batch_size <= ops_per_open);

          rand_keys = GenerateNKeys(thread, static_cast<int>(batch_size), i);

          TestMultiGetEntity(thread, read_opts, rand_column_families,
                             rand_keys);

          i += batch_size - 1;
        } else if (FLAGS_use_get_entity) {
1063 1064
          TestGetEntity(thread, read_opts, rand_column_families, rand_keys);
        } else if (FLAGS_use_multiget) {
1065 1066 1067 1068 1069 1070 1071 1072 1073
          // 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);
1074 1075 1076
          ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
          ThreadStatusUtil::SetThreadOperation(
              ThreadStatus::OperationType::OP_MULTIGET);
1077
          TestMultiGet(thread, read_opts, rand_column_families, rand_keys);
1078
          ThreadStatusUtil::ResetThreadStatus();
1079 1080
          i += multiget_batch_size - 1;
        } else {
1081 1082 1083
          ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
          ThreadStatusUtil::SetThreadOperation(
              ThreadStatus::OperationType::OP_GET);
1084
          TestGet(thread, read_opts, rand_column_families, rand_keys);
1085
          ThreadStatusUtil::ResetThreadStatus();
1086
        }
1087
      } else if (prob_op < prefix_bound) {
1088
        assert(static_cast<int>(FLAGS_readpercent) <= prob_op);
1089 1090 1091 1092 1093 1094
        // 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);
1095 1096
      } else if (prob_op < write_bound) {
        assert(prefix_bound <= prob_op);
1097 1098
        // OPERATION write
        TestPut(thread, write_opts, read_opts, rand_column_families, rand_keys,
1099
                value);
1100 1101
      } else if (prob_op < del_bound) {
        assert(write_bound <= prob_op);
1102
        // OPERATION delete
1103
        TestDelete(thread, write_opts, rand_column_families, rand_keys);
1104 1105
      } else if (prob_op < delrange_bound) {
        assert(del_bound <= prob_op);
1106
        // OPERATION delete range
1107
        TestDeleteRange(thread, write_opts, rand_column_families, rand_keys);
1108 1109
      } else if (prob_op < iterate_bound) {
        assert(delrange_bound <= prob_op);
1110
        // OPERATION iterate
1111 1112 1113
        if (!FLAGS_skip_verifydb &&
            thread->rand.OneInOpt(
                FLAGS_verify_iterator_with_expected_state_one_in)) {
1114 1115 1116
          ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
          ThreadStatusUtil::SetThreadOperation(
              ThreadStatus::OperationType::OP_DBITERATOR);
1117
          TestIterateAgainstExpected(thread, read_opts, rand_column_families,
1118
                                     rand_keys);
1119
          ThreadStatusUtil::ResetThreadStatus();
1120
        } else {
1121 1122 1123 1124 1125
          int num_seeks = static_cast<int>(std::min(
              std::max(static_cast<uint64_t>(thread->rand.Uniform(4)),
                       static_cast<uint64_t>(1)),
              std::max(static_cast<uint64_t>(FLAGS_ops_per_thread - i - 1),
                       static_cast<uint64_t>(1))));
1126 1127
          rand_keys = GenerateNKeys(thread, num_seeks, i);
          i += num_seeks - 1;
1128 1129 1130
          ThreadStatusUtil::SetEnableTracking(FLAGS_enable_thread_tracking);
          ThreadStatusUtil::SetThreadOperation(
              ThreadStatus::OperationType::OP_DBITERATOR);
1131
          TestIterate(thread, read_opts, rand_column_families, rand_keys);
1132
          ThreadStatusUtil::ResetThreadStatus();
1133
        }
1134 1135 1136
      } else {
        assert(iterate_bound <= prob_op);
        TestCustomOperations(thread, rand_column_families);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
      }
      thread->stats.FinishedSingleOp();
    }
  }
  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();
}

// 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) {
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
      // If FLAGS_user_timestamp_size > 0, then both smallestkey and largestkey
      // have timestamps.
      const auto& skey = sfmd.smallestkey;
      const auto& lkey = sfmd.largestkey;
      assert(skey.size() >= FLAGS_user_timestamp_size);
      assert(lkey.size() >= FLAGS_user_timestamp_size);
      boundaries.push_back(
          skey.substr(0, skey.size() - FLAGS_user_timestamp_size));
      boundaries.push_back(
          lkey.substr(0, lkey.size() - FLAGS_user_timestamp_size));
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    }
  }
  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 已提交
1189
          k[i] = 0xFFu;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
        }
      }
    } 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;
}

// 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) {
1215 1216 1217 1218 1219 1220 1221
  assert(!rand_column_families.empty());
  assert(!rand_keys.empty());

  ManagedSnapshot snapshot_guard(db_);

  ReadOptions ro = read_opts;
  ro.snapshot = snapshot_guard.snapshot();
1222

1223 1224
  std::string read_ts_str;
  Slice read_ts_slice;
1225
  MaybeUseOlderTimestampForRangeScan(thread, read_ts_str, read_ts_slice, ro);
1226

S
sdong 已提交
1227
  bool expect_total_order = false;
1228 1229
  if (thread->rand.OneIn(16)) {
    // When prefix extractor is used, it's useful to cover total order seek.
1230
    ro.total_order_seek = true;
S
sdong 已提交
1231 1232
    expect_total_order = true;
  } else if (thread->rand.OneIn(4)) {
1233 1234
    ro.total_order_seek = false;
    ro.auto_prefix_mode = true;
S
sdong 已提交
1235 1236 1237
    expect_total_order = true;
  } else if (options_.prefix_extractor.get() == nullptr) {
    expect_total_order = true;
1238 1239 1240 1241 1242
  }

  std::string upper_bound_str;
  Slice upper_bound;
  if (thread->rand.OneIn(16)) {
1243 1244 1245
    // With a 1/16 chance, set an iterator upper bound.
    // Note: upper_bound can be smaller than the seek key.
    const int64_t rand_upper_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
1246 1247
    upper_bound_str = Key(rand_upper_key);
    upper_bound = Slice(upper_bound_str);
1248
    ro.iterate_upper_bound = &upper_bound;
1249 1250 1251 1252
  }
  std::string lower_bound_str;
  Slice lower_bound;
  if (thread->rand.OneIn(16)) {
1253 1254 1255
    // With a 1/16 chance, enable iterator lower bound.
    // Note: lower_bound can be greater than the seek key.
    const int64_t rand_lower_key = GenerateOneKey(thread, FLAGS_ops_per_thread);
1256 1257
    lower_bound_str = Key(rand_lower_key);
    lower_bound = Slice(lower_bound_str);
1258
    ro.iterate_lower_bound = &lower_bound;
1259 1260
  }

1261 1262 1263 1264
  ColumnFamilyHandle* const cfh = column_families_[rand_column_families[0]];
  assert(cfh);

  std::unique_ptr<Iterator> iter(db_->NewIterator(ro, cfh));
1265

1266
  std::vector<std::string> key_strs;
1267 1268
  if (thread->rand.OneIn(16)) {
    // Generate keys close to lower or upper bound of SST files.
1269
    key_strs = GetWhiteBoxKeys(thread, db_, cfh, rand_keys.size());
1270
  }
1271 1272
  if (key_strs.empty()) {
    // Use the random keys passed in.
1273
    for (int64_t rkey : rand_keys) {
1274
      key_strs.push_back(Key(rkey));
1275 1276 1277
    }
  }

1278
  std::string op_logs;
1279
  constexpr size_t kOpLogsLimit = 10000;
1280

1281
  for (const std::string& key_str : key_strs) {
1282 1283 1284 1285 1286
    if (op_logs.size() > kOpLogsLimit) {
      // Shouldn't take too much memory for the history log. Clear it.
      op_logs = "(cleared...)\n";
    }

1287 1288 1289
    if (ro.iterate_upper_bound != nullptr && thread->rand.OneIn(2)) {
      // With a 1/2 chance, change the upper bound.
      // It is possible that it is changed before first use, but there is no
1290
      // problem with that.
1291 1292
      const int64_t rand_upper_key =
          GenerateOneKey(thread, FLAGS_ops_per_thread);
1293 1294
      upper_bound_str = Key(rand_upper_key);
      upper_bound = Slice(upper_bound_str);
1295 1296 1297 1298
    }
    if (ro.iterate_lower_bound != nullptr && thread->rand.OneIn(4)) {
      // With a 1/4 chance, change the lower bound.
      // It is possible that it is changed before first use, but there is no
1299
      // problem with that.
1300 1301
      const int64_t rand_lower_key =
          GenerateOneKey(thread, FLAGS_ops_per_thread);
1302 1303 1304 1305
      lower_bound_str = Key(rand_lower_key);
      lower_bound = Slice(lower_bound_str);
    }

1306
    // Record some options to op_logs
1307
    op_logs += "total_order_seek: ";
1308
    op_logs += (ro.total_order_seek ? "1 " : "0 ");
S
sdong 已提交
1309
    op_logs += "auto_prefix_mode: ";
1310 1311
    op_logs += (ro.auto_prefix_mode ? "1 " : "0 ");
    if (ro.iterate_upper_bound != nullptr) {
1312 1313
      op_logs += "ub: " + upper_bound.ToString(true) + " ";
    }
1314
    if (ro.iterate_lower_bound != nullptr) {
1315
      op_logs += "lb: " + lower_bound.ToString(true) + " ";
1316 1317
    }

1318 1319 1320 1321 1322 1323
    // Set up an iterator, perform the same operations 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.
    //
1324 1325
    // This `ReadOptions` is for validation purposes. Ignore
    // `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
1326
    ReadOptions cmp_ro;
1327 1328 1329
    cmp_ro.timestamp = ro.timestamp;
    cmp_ro.iter_start_ts = ro.iter_start_ts;
    cmp_ro.snapshot = snapshot_guard.snapshot();
1330
    cmp_ro.total_order_seek = true;
1331 1332

    ColumnFamilyHandle* const cmp_cfh =
1333
        GetControlCfh(thread, rand_column_families[0]);
1334 1335
    assert(cmp_cfh);

1336
    std::unique_ptr<Iterator> cmp_iter(db_->NewIterator(cmp_ro, cmp_cfh));
1337

1338 1339
    bool diverged = false;

1340 1341 1342
    Slice key(key_str);

    const bool support_seek_first_or_last = expect_total_order;
1343

1344
    LastIterateOp last_op;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    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)) {
1356 1357 1358
      iter->SeekForPrev(key);
      cmp_iter->SeekForPrev(key);
      last_op = kLastOpSeekForPrev;
1359
      op_logs += "SFP " + key.ToString(true) + " ";
1360 1361 1362 1363
    } else {
      iter->Seek(key);
      cmp_iter->Seek(key);
      last_op = kLastOpSeek;
1364
      op_logs += "S " + key.ToString(true) + " ";
1365 1366
    }

1367 1368 1369 1370
    VerifyIterator(thread, cmp_cfh, ro, iter.get(), cmp_iter.get(), last_op,
                   key, op_logs, &diverged);

    const bool no_reverse =
S
sdong 已提交
1371
        (FLAGS_memtablerep == "prefix_hash" && !expect_total_order);
1372
    for (uint64_t i = 0; i < FLAGS_num_iterations && iter->Valid(); ++i) {
1373 1374 1375 1376 1377 1378
      if (no_reverse || thread->rand.OneIn(2)) {
        iter->Next();
        if (!diverged) {
          assert(cmp_iter->Valid());
          cmp_iter->Next();
        }
1379
        op_logs += "N";
1380 1381 1382 1383 1384 1385
      } else {
        iter->Prev();
        if (!diverged) {
          assert(cmp_iter->Valid());
          cmp_iter->Prev();
        }
1386
        op_logs += "P";
1387
      }
1388

1389 1390
      last_op = kLastOpNextOrPrev;

1391 1392
      VerifyIterator(thread, cmp_cfh, ro, iter.get(), cmp_iter.get(), last_op,
                     key, op_logs, &diverged);
1393
    }
1394

1395 1396
    thread->stats.AddIterations(1);

1397
    op_logs += "; ";
1398 1399
  }

1400
  return Status::OK();
1401 1402
}

1403 1404 1405 1406 1407 1408
// 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);
}
1409

1410 1411 1412 1413 1414
// Test the return status of GetSortedWalFiles.
Status StressTest::VerifyGetSortedWalFiles() const {
  VectorLogPtr log_ptr;
  return db_->GetSortedWalFiles(log_ptr);
}
1415

1416 1417 1418 1419
// Test the return status of GetCurrentWalFile.
Status StressTest::VerifyGetCurrentWalFile() const {
  std::unique_ptr<LogFile> cur_wal_file;
  return db_->GetCurrentWalFile(&cur_wal_file);
1420 1421
}

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
// 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,
1432 1433
                                const Slice& seek_key,
                                const std::string& op_logs, bool* diverged) {
1434 1435
  assert(diverged);

1436 1437 1438 1439
  if (*diverged) {
    return;
  }

1440 1441 1442 1443 1444 1445 1446 1447
  if (ro.iter_start_ts != nullptr) {
    assert(FLAGS_user_timestamp_size > 0);
    // We currently do not verify iterator when dumping history of internal
    // keys.
    *diverged = true;
    return;
  }

1448 1449 1450 1451 1452 1453 1454 1455 1456
  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 &&
1457 1458 1459
             (options_.comparator->CompareWithoutTimestamp(
                  *ro.iterate_lower_bound, /*a_has_ts=*/false, seek_key,
                  /*b_has_ts=*/false) >= 0 ||
1460
              (ro.iterate_upper_bound != nullptr &&
1461 1462 1463
               options_.comparator->CompareWithoutTimestamp(
                   *ro.iterate_lower_bound, /*a_has_ts=*/false,
                   *ro.iterate_upper_bound, /*b_has_ts*/ false) >= 0))) {
1464 1465 1466 1467
    // 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;
1468
  } else if (op == kLastOpSeekForPrev && ro.iterate_upper_bound != nullptr &&
1469 1470 1471
             (options_.comparator->CompareWithoutTimestamp(
                  *ro.iterate_upper_bound, /*a_has_ts=*/false, seek_key,
                  /*b_has_ts=*/false) <= 0 ||
1472
              (ro.iterate_lower_bound != nullptr &&
1473 1474 1475
               options_.comparator->CompareWithoutTimestamp(
                   *ro.iterate_lower_bound, /*a_has_ts=*/false,
                   *ro.iterate_upper_bound, /*b_has_ts=*/false) >= 0))) {
1476 1477 1478 1479 1480 1481
    // 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 已提交
1482 1483 1484
  const SliceTransform* pe = (ro.total_order_seek || ro.auto_prefix_mode)
                                 ? nullptr
                                 : options_.prefix_extractor.get();
1485 1486
  const Comparator* cmp = options_.comparator;

1487
  if (iter->Valid() && !cmp_iter->Valid()) {
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    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;
      }
    }
1503
    fprintf(stderr,
1504
            "Control interator is invalid but iterator has key %s "
1505
            "%s\n",
1506
            iter->key().ToString(true).c_str(), op_logs.c_str());
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

    *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,
1533 1534
                "Iterator stays in prefix but contol doesn't"
                " iterator key %s control iterator key %s %s\n",
1535
                iter->key().ToString(true).c_str(),
1536
                cmp_iter->key().ToString(true).c_str(), op_logs.c_str());
1537 1538 1539 1540 1541 1542 1543
      }
    }
    // Check upper or lower bounds.
    if (!*diverged) {
      if ((iter->Valid() && iter->key() != cmp_iter->key()) ||
          (!iter->Valid() &&
           (ro.iterate_upper_bound == nullptr ||
1544 1545 1546
            cmp->CompareWithoutTimestamp(total_order_key, /*a_has_ts=*/false,
                                         *ro.iterate_upper_bound,
                                         /*b_has_ts=*/false) < 0) &&
1547
           (ro.iterate_lower_bound == nullptr ||
1548 1549 1550
            cmp->CompareWithoutTimestamp(total_order_key, /*a_has_ts=*/false,
                                         *ro.iterate_lower_bound,
                                         /*b_has_ts=*/false) > 0))) {
1551 1552
        fprintf(stderr,
                "Iterator diverged from control iterator which"
1553 1554
                " has value %s %s\n",
                total_order_key.ToString(true).c_str(), op_logs.c_str());
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
        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;
      }
    }
  }
1565 1566

  if (!*diverged && iter->Valid()) {
1567 1568 1569 1570 1571 1572
    if (!VerifyWideColumns(iter->value(), iter->columns())) {
      fprintf(stderr,
              "Value and columns inconsistent for iterator: value: %s, "
              "columns: %s\n",
              iter->value().ToString(/* hex */ true).c_str(),
              WideColumnsToHex(iter->columns()).c_str());
1573 1574 1575 1576 1577

      *diverged = true;
    }
  }

1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
  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();
  }
}

Status StressTest::TestBackupRestore(
    ThreadState* thread, const std::vector<int>& rand_column_families,
    const std::vector<int64_t>& rand_keys) {
1589 1590 1591 1592 1593 1594 1595 1596 1597
  std::vector<std::unique_ptr<MutexLock>> locks;
  if (ShouldAcquireMutexOnKey()) {
    for (int rand_column_family : rand_column_families) {
      // `rand_keys[0]` on each chosen CF will be verified.
      locks.emplace_back(new MutexLock(
          thread->shared->GetMutexForKey(rand_column_family, rand_keys[0])));
    }
  }

1598 1599 1600
  const std::string backup_dir =
      FLAGS_db + "/.backup" + std::to_string(thread->tid);
  const std::string restore_dir =
S
sdong 已提交
1601
      FLAGS_db + "/.restore" + std::to_string(thread->tid);
1602
  BackupEngineOptions backup_opts(backup_dir);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
  // For debugging, get info_log from live options
  backup_opts.info_log = db_->GetDBOptions().info_log.get();
  if (thread->rand.OneIn(10)) {
    backup_opts.share_table_files = false;
  } else {
    backup_opts.share_table_files = true;
    if (thread->rand.OneIn(5)) {
      backup_opts.share_files_with_checksum = false;
    } else {
      backup_opts.share_files_with_checksum = true;
      if (thread->rand.OneIn(2)) {
        // old
1615
        backup_opts.share_files_with_checksum_naming =
1616
            BackupEngineOptions::kLegacyCrc32cAndFileSize;
1617 1618 1619
      } else {
        // new
        backup_opts.share_files_with_checksum_naming =
1620
            BackupEngineOptions::kUseDbSessionId;
1621 1622 1623 1624
      }
      if (thread->rand.OneIn(2)) {
        backup_opts.share_files_with_checksum_naming =
            backup_opts.share_files_with_checksum_naming |
1625
            BackupEngineOptions::kFlagIncludeFileSize;
1626
      }
1627 1628
    }
  }
1629 1630 1631 1632 1633
  if (thread->rand.OneIn(2)) {
    backup_opts.schema_version = 1;
  } else {
    backup_opts.schema_version = 2;
  }
1634
  BackupEngine* backup_engine = nullptr;
1635
  std::string from = "a backup/restore operation";
1636
  Status s = BackupEngine::Open(db_stress_env, backup_opts, &backup_engine);
1637 1638 1639
  if (!s.ok()) {
    from = "BackupEngine::Open";
  }
1640
  if (s.ok()) {
1641 1642
    if (backup_opts.schema_version >= 2 && thread->rand.OneIn(2)) {
      TEST_BackupMetaSchemaOptions test_opts;
1643 1644
      test_opts.crc32c_checksums = thread->rand.OneIn(2) == 0;
      test_opts.file_sizes = thread->rand.OneIn(2) == 0;
1645
      TEST_SetBackupMetaSchemaOptions(backup_engine, test_opts);
1646
    }
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
    CreateBackupOptions create_opts;
    if (FLAGS_disable_wal) {
      // The verification can only work when latest value of `key` is backed up,
      // which requires flushing in case of WAL disabled.
      //
      // Note this triggers a flush with a key lock held. Meanwhile, operations
      // like flush/compaction may attempt to grab key locks like in
      // `DbStressCompactionFilter`. The philosophy around preventing deadlock
      // is the background operation key lock acquisition only tries but does
      // not wait for the lock. So here in the foreground it is OK to hold the
      // lock and wait on a background operation (flush).
      create_opts.flush_before_backup = true;
    }
    s = backup_engine->CreateNewBackup(create_opts, db_);
1661 1662 1663
    if (!s.ok()) {
      from = "BackupEngine::CreateNewBackup";
    }
1664 1665 1666 1667
  }
  if (s.ok()) {
    delete backup_engine;
    backup_engine = nullptr;
1668
    s = BackupEngine::Open(db_stress_env, backup_opts, &backup_engine);
1669 1670 1671
    if (!s.ok()) {
      from = "BackupEngine::Open (again)";
    }
1672
  }
1673
  std::vector<BackupInfo> backup_info;
1674 1675 1676 1677
  // If inplace_not_restore, we verify the backup by opening it as a
  // read-only DB. If !inplace_not_restore, we restore it to a temporary
  // directory for verification.
  bool inplace_not_restore = thread->rand.OneIn(3);
1678
  if (s.ok()) {
1679 1680
    backup_engine->GetBackupInfo(&backup_info,
                                 /*include_file_details*/ inplace_not_restore);
1681 1682
    if (backup_info.empty()) {
      s = Status::NotFound("no backups found");
1683
      from = "BackupEngine::GetBackupInfo";
1684 1685 1686 1687 1688 1689
    }
  }
  if (s.ok() && thread->rand.OneIn(2)) {
    s = backup_engine->VerifyBackup(
        backup_info.front().backup_id,
        thread->rand.OneIn(2) /* verify_with_checksum */);
1690 1691 1692
    if (!s.ok()) {
      from = "BackupEngine::VerifyBackup";
    }
1693
  }
1694
  const bool allow_persistent = thread->tid == 0;  // not too many
1695
  bool from_latest = false;
1696 1697
  int count = static_cast<int>(backup_info.size());
  if (s.ok() && !inplace_not_restore) {
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
    if (count > 1) {
      s = backup_engine->RestoreDBFromBackup(
          RestoreOptions(), backup_info[thread->rand.Uniform(count)].backup_id,
          restore_dir /* db_dir */, restore_dir /* wal_dir */);
      if (!s.ok()) {
        from = "BackupEngine::RestoreDBFromBackup";
      }
    } else {
      from_latest = true;
      s = backup_engine->RestoreDBFromLatestBackup(RestoreOptions(),
                                                   restore_dir /* db_dir */,
                                                   restore_dir /* wal_dir */);
      if (!s.ok()) {
        from = "BackupEngine::RestoreDBFromLatestBackup";
      }
    }
1714
  }
1715 1716 1717
  if (s.ok() && !inplace_not_restore) {
    // Purge early if restoring, to ensure the restored directory doesn't
    // have some secret dependency on the backup directory.
1718
    uint32_t to_keep = 0;
1719
    if (allow_persistent) {
1720 1721 1722 1723
      // allow one thread to keep up to 2 backups
      to_keep = thread->rand.Uniform(3);
    }
    s = backup_engine->PurgeOldBackups(to_keep);
1724 1725 1726
    if (!s.ok()) {
      from = "BackupEngine::PurgeOldBackups";
    }
1727 1728 1729
  }
  DB* restored_db = nullptr;
  std::vector<ColumnFamilyHandle*> restored_cf_handles;
1730 1731
  // Not yet implemented: opening restored BlobDB or TransactionDB
  if (s.ok() && !FLAGS_use_txn && !FLAGS_use_blob_db) {
1732
    Options restore_options(options_);
1733
    restore_options.best_efforts_recovery = false;
1734
    restore_options.listeners.clear();
1735 1736
    // Avoid dangling/shared file descriptors, for reliable destroy
    restore_options.sst_file_manager = nullptr;
1737 1738 1739 1740 1741 1742 1743 1744 1745
    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));
    }
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
    if (inplace_not_restore) {
      BackupInfo& info = backup_info[thread->rand.Uniform(count)];
      restore_options.env = info.env_for_open.get();
      s = DB::OpenForReadOnly(DBOptions(restore_options), info.name_for_open,
                              cf_descriptors, &restored_cf_handles,
                              &restored_db);
      if (!s.ok()) {
        from = "DB::OpenForReadOnly in backup/restore";
      }
    } else {
      s = DB::Open(DBOptions(restore_options), restore_dir, cf_descriptors,
                   &restored_cf_handles, &restored_db);
      if (!s.ok()) {
        from = "DB::Open in backup/restore";
      }
1761
    }
1762
  }
1763 1764 1765 1766 1767 1768
  // 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.
  //
  // For simplicity, currently only verifies existence/non-existence of a
  // single key
1769
  for (size_t i = 0; restored_db && s.ok() && i < rand_column_families.size();
1770 1771
       ++i) {
    std::string key_str = Key(rand_keys[0]);
1772 1773
    Slice key = key_str;
    std::string restored_value;
1774 1775
    // This `ReadOptions` is for validation purposes. Ignore
    // `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
1776 1777 1778 1779
    ReadOptions read_opts;
    std::string ts_str;
    Slice ts;
    if (FLAGS_user_timestamp_size > 0) {
1780
      ts_str = GetNowNanos();
1781 1782 1783
      ts = ts_str;
      read_opts.timestamp = &ts;
    }
1784
    Status get_status = restored_db->Get(
1785
        read_opts, restored_cf_handles[rand_column_families[i]], key,
1786
        &restored_value);
1787
    bool exists = thread->shared->Exists(rand_column_families[i], rand_keys[0]);
1788
    if (get_status.ok()) {
1789
      if (!exists && from_latest && ShouldAcquireMutexOnKey()) {
1790 1791 1792 1793
        std::ostringstream oss;
        oss << "0x" << key.ToString(true)
            << " exists in restore but not in original db";
        s = Status::Corruption(oss.str());
1794 1795
      }
    } else if (get_status.IsNotFound()) {
1796
      if (exists && from_latest && ShouldAcquireMutexOnKey()) {
1797 1798 1799 1800
        std::ostringstream oss;
        oss << "0x" << key.ToString(true)
            << " exists in original db but not in restore";
        s = Status::Corruption(oss.str());
1801 1802 1803
      }
    } else {
      s = get_status;
1804 1805 1806
      if (!s.ok()) {
        from = "DB::Get in backup/restore";
      }
1807 1808 1809 1810 1811 1812 1813 1814 1815
    }
  }
  if (restored_db != nullptr) {
    for (auto* cf_handle : restored_cf_handles) {
      restored_db->DestroyColumnFamilyHandle(cf_handle);
    }
    delete restored_db;
    restored_db = nullptr;
  }
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
  if (s.ok() && inplace_not_restore) {
    // Purge late if inplace open read-only
    uint32_t to_keep = 0;
    if (allow_persistent) {
      // allow one thread to keep up to 2 backups
      to_keep = thread->rand.Uniform(3);
    }
    s = backup_engine->PurgeOldBackups(to_keep);
    if (!s.ok()) {
      from = "BackupEngine::PurgeOldBackups";
    }
  }
  if (backup_engine != nullptr) {
    delete backup_engine;
    backup_engine = nullptr;
  }
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
  if (s.ok()) {
    // Preserve directories on failure, or allowed persistent backup
    if (!allow_persistent) {
      s = DestroyDir(db_stress_env, backup_dir);
      if (!s.ok()) {
        from = "Destroy backup dir";
      }
    }
  }
  if (s.ok()) {
    s = DestroyDir(db_stress_env, restore_dir);
    if (!s.ok()) {
      from = "Destroy restore dir";
    }
  }
1847
  if (!s.ok()) {
1848
    fprintf(stderr, "Failure in %s with: %s\n", from.c_str(),
1849
            s.ToString().c_str());
1850 1851 1852 1853
  }
  return s;
}

S
sdong 已提交
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
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;
Y
Yanqin Jin 已提交
1879 1880
  sao.include_memtables = thread->rand.OneIn(2);
  if (sao.include_memtables) {
S
sdong 已提交
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
    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);
}

1896 1897 1898
Status StressTest::TestCheckpoint(ThreadState* thread,
                                  const std::vector<int>& rand_column_families,
                                  const std::vector<int64_t>& rand_keys) {
1899 1900 1901 1902 1903 1904 1905 1906 1907
  std::vector<std::unique_ptr<MutexLock>> locks;
  if (ShouldAcquireMutexOnKey()) {
    for (int rand_column_family : rand_column_families) {
      // `rand_keys[0]` on each chosen CF will be verified.
      locks.emplace_back(new MutexLock(
          thread->shared->GetMutexForKey(rand_column_family, rand_keys[0])));
    }
  }

1908
  std::string checkpoint_dir =
S
sdong 已提交
1909
      FLAGS_db + "/.checkpoint" + std::to_string(thread->tid);
1910 1911
  Options tmp_opts(options_);
  tmp_opts.listeners.clear();
1912
  tmp_opts.env = db_stress_env;
1913 1914
  // Avoid delayed deletion so whole directory can be deleted
  tmp_opts.sst_file_manager.reset();
1915

1916
  DestroyDB(checkpoint_dir, tmp_opts);
1917

1918 1919 1920 1921
  Checkpoint* checkpoint = nullptr;
  Status s = Checkpoint::Create(db_, &checkpoint);
  if (s.ok()) {
    s = checkpoint->CreateCheckpoint(checkpoint_dir);
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
    if (!s.ok()) {
      fprintf(stderr, "Fail to create checkpoint to %s\n",
              checkpoint_dir.c_str());
      std::vector<std::string> files;
      Status my_s = db_stress_env->GetChildren(checkpoint_dir, &files);
      if (my_s.ok()) {
        for (const auto& f : files) {
          fprintf(stderr, " %s\n", f.c_str());
        }
      } else {
        fprintf(stderr, "Fail to get files under the directory to %s\n",
                my_s.ToString().c_str());
      }
    }
1936
  }
1937 1938
  delete checkpoint;
  checkpoint = nullptr;
1939 1940 1941 1942
  std::vector<ColumnFamilyHandle*> cf_handles;
  DB* checkpoint_db = nullptr;
  if (s.ok()) {
    Options options(options_);
1943
    options.best_efforts_recovery = false;
1944
    options.listeners.clear();
1945 1946
    // Avoid race condition in trash handling after delete checkpoint_db
    options.sst_file_manager.reset();
1947 1948 1949 1950 1951
    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_`.
1952
    assert(FLAGS_clear_column_family_one_in == 0);
1953 1954 1955 1956 1957 1958 1959 1960 1961
    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) {
1962 1963 1964
    // 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.
1965
    for (size_t i = 0; s.ok() && i < rand_column_families.size(); ++i) {
1966
      std::string key_str = Key(rand_keys[0]);
1967
      Slice key = key_str;
1968 1969 1970 1971
      std::string ts_str;
      Slice ts;
      ReadOptions read_opts;
      if (FLAGS_user_timestamp_size > 0) {
1972
        ts_str = GetNowNanos();
1973 1974 1975
        ts = ts_str;
        read_opts.timestamp = &ts;
      }
1976 1977
      std::string value;
      Status get_status = checkpoint_db->Get(
1978
          read_opts, cf_handles[rand_column_families[i]], key, &value);
1979
      bool exists =
1980
          thread->shared->Exists(rand_column_families[i], rand_keys[0]);
1981
      if (get_status.ok()) {
1982
        if (!exists && ShouldAcquireMutexOnKey()) {
1983 1984 1985 1986
          std::ostringstream oss;
          oss << "0x" << key.ToString(true) << " exists in checkpoint "
              << checkpoint_dir << " but not in original db";
          s = Status::Corruption(oss.str());
1987 1988
        }
      } else if (get_status.IsNotFound()) {
1989
        if (exists && ShouldAcquireMutexOnKey()) {
1990 1991 1992 1993 1994
          std::ostringstream oss;
          oss << "0x" << key.ToString(true)
              << " exists in original db but not in checkpoint "
              << checkpoint_dir;
          s = Status::Corruption(oss.str());
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
        }
      } else {
        s = get_status;
      }
    }
    for (auto cfh : cf_handles) {
      delete cfh;
    }
    cf_handles.clear();
    delete checkpoint_db;
    checkpoint_db = nullptr;
  }
2007

2008 2009 2010
  if (!s.ok()) {
    fprintf(stderr, "A checkpoint operation failed with: %s\n",
            s.ToString().c_str());
2011 2012
  } else {
    DestroyDB(checkpoint_dir, tmp_opts);
2013 2014 2015
  }
  return s;
}
2016

2017 2018 2019 2020 2021 2022 2023 2024 2025
void StressTest::TestGetProperty(ThreadState* thread) const {
  std::unordered_set<std::string> levelPropertyNames = {
      DB::Properties::kAggregatedTablePropertiesAtLevel,
      DB::Properties::kCompressionRatioAtLevelPrefix,
      DB::Properties::kNumFilesAtLevelPrefix,
  };
  std::unordered_set<std::string> unknownPropertyNames = {
      DB::Properties::kEstimateOldestKeyTime,
      DB::Properties::kOptionsStatistics,
2026 2027 2028
      DB::Properties::
          kLiveSstFilesSizeAtTemperature,  // similar to levelPropertyNames, it
                                           // requires a number suffix
2029 2030 2031 2032
  };
  unknownPropertyNames.insert(levelPropertyNames.begin(),
                              levelPropertyNames.end());

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
  std::unordered_set<std::string> blobCachePropertyNames = {
      DB::Properties::kBlobCacheCapacity,
      DB::Properties::kBlobCacheUsage,
      DB::Properties::kBlobCachePinnedUsage,
  };
  if (db_->GetOptions().blob_cache == nullptr) {
    unknownPropertyNames.insert(blobCachePropertyNames.begin(),
                                blobCachePropertyNames.end());
  }

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
  std::string prop;
  for (const auto& ppt_name_and_info : InternalStats::ppt_name_to_info) {
    bool res = db_->GetProperty(ppt_name_and_info.first, &prop);
    if (unknownPropertyNames.find(ppt_name_and_info.first) ==
        unknownPropertyNames.end()) {
      if (!res) {
        fprintf(stderr, "Failed to get DB property: %s\n",
                ppt_name_and_info.first.c_str());
        thread->shared->SetVerificationFailure();
      }
      if (ppt_name_and_info.second.handle_int != nullptr) {
        uint64_t prop_int;
        if (!db_->GetIntProperty(ppt_name_and_info.first, &prop_int)) {
          fprintf(stderr, "Failed to get Int property: %s\n",
                  ppt_name_and_info.first.c_str());
          thread->shared->SetVerificationFailure();
        }
      }
2061 2062 2063 2064 2065 2066 2067 2068
      if (ppt_name_and_info.second.handle_map != nullptr) {
        std::map<std::string, std::string> prop_map;
        if (!db_->GetMapProperty(ppt_name_and_info.first, &prop_map)) {
          fprintf(stderr, "Failed to get Map property: %s\n",
                  ppt_name_and_info.first.c_str());
          thread->shared->SetVerificationFailure();
        }
      }
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
    }
  }

  ROCKSDB_NAMESPACE::ColumnFamilyMetaData cf_meta_data;
  db_->GetColumnFamilyMetaData(&cf_meta_data);
  int level_size = static_cast<int>(cf_meta_data.levels.size());
  for (int level = 0; level < level_size; level++) {
    for (const auto& ppt_name : levelPropertyNames) {
      bool res = db_->GetProperty(ppt_name + std::to_string(level), &prop);
      if (!res) {
        fprintf(stderr, "Failed to get DB property: %s\n",
                (ppt_name + std::to_string(level)).c_str());
        thread->shared->SetVerificationFailure();
      }
    }
  }

  // Test for an invalid property name
  if (thread->rand.OneIn(100)) {
    if (db_->GetProperty("rocksdb.invalid_property_name", &prop)) {
      fprintf(stderr, "Failed to return false for invalid property name\n");
      thread->shared->SetVerificationFailure();
    }
  }
}

2095 2096
void StressTest::TestCompactFiles(ThreadState* thread,
                                  ColumnFamilyHandle* column_family) {
2097
  ROCKSDB_NAMESPACE::ColumnFamilyMetaData cf_meta_data;
2098 2099
  db_->GetColumnFamilyMetaData(column_family, &cf_meta_data);

2100 2101 2102 2103
  if (cf_meta_data.levels.empty()) {
    return;
  }

2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
  // 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;
    }
  }
}
2145

2146 2147
Status StressTest::TestFlush(const std::vector<int>& rand_column_families) {
  FlushOptions flush_opts;
2148 2149 2150
  if (FLAGS_atomic_flush) {
    return db_->Flush(flush_opts, column_families_);
  }
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
  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));
2169
  clock_->SleepForMicroseconds(1 << pwr2_micros);
2170 2171 2172 2173 2174 2175 2176 2177
  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];
2178 2179
  // This `ReadOptions` is for validation purposes. Ignore
  // `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
2180
  ReadOptions ropt;
2181
  auto db_impl = static_cast_with_check<DBImpl>(db_->GetRootDB());
2182 2183 2184 2185 2186
  const bool ww_snapshot = thread->rand.OneIn(10);
  const Snapshot* snapshot =
      ww_snapshot ? db_impl->GetSnapshotForWriteConflictBoundary()
                  : db_->GetSnapshot();
  ropt.snapshot = snapshot;
2187 2188 2189 2190 2191 2192 2193

  // Ideally, we want snapshot taking and timestamp generation to be atomic
  // here, so that the snapshot corresponds to the timestamp. However, it is
  // not possible with current GetSnapshot() API.
  std::string ts_str;
  Slice ts;
  if (FLAGS_user_timestamp_size > 0) {
2194
    ts_str = GetNowNanos();
2195 2196 2197 2198
    ts = ts_str;
    ropt.timestamp = &ts;
  }

2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
  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;
      }
    }
  }

2220 2221 2222 2223 2224 2225 2226 2227
  ThreadState::SnapshotState snap_state = {snapshot,
                                           rand_column_family,
                                           column_family->GetName(),
                                           keystr,
                                           status_at,
                                           value_at,
                                           key_vec,
                                           ts_str};
2228 2229 2230 2231
  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)) {
S
sdong 已提交
2232
      assert(hold_for < std::numeric_limits<uint64_t>::max() / 10);
2233 2234 2235
      hold_for *= 10;
      // Hold 1% of snapshots for 100x more
      if (thread->rand.OneIn(10)) {
S
sdong 已提交
2236
        assert(hold_for < std::numeric_limits<uint64_t>::max() / 10);
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
        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();
}

2264 2265 2266 2267
void StressTest::TestCompactRange(ThreadState* thread, int64_t rand_key,
                                  const Slice& start_key,
                                  ColumnFamilyHandle* column_family) {
  int64_t end_key_num;
S
sdong 已提交
2268 2269 2270
  if (std::numeric_limits<int64_t>::max() - rand_key <
      FLAGS_compact_range_width) {
    end_key_num = std::numeric_limits<int64_t>::max();
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
  } 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);
2290 2291 2292 2293 2294 2295 2296 2297 2298
  std::vector<BlobGarbageCollectionPolicy> blob_gc_policies = {
      BlobGarbageCollectionPolicy::kForce,
      BlobGarbageCollectionPolicy::kDisable,
      BlobGarbageCollectionPolicy::kUseDefault};
  cro.blob_garbage_collection_policy =
      blob_gc_policies[thread->rand.Next() %
                       static_cast<uint32_t>(blob_gc_policies.size())];
  cro.blob_garbage_collection_age_cutoff =
      static_cast<double>(thread->rand.Next() % 100) / 100.0;
2299 2300

  const Snapshot* pre_snapshot = nullptr;
B
Burton Li 已提交
2301
  uint32_t pre_hash = 0;
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
  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()) {
2313 2314
    fprintf(stdout, "Unable to perform CompactRange(): %s\n",
            status.ToString().c_str());
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
  }

  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) {
2337 2338
  // This `ReadOptions` is for validation purposes. Ignore
  // `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
2339 2340 2341
  ReadOptions ro;
  ro.snapshot = snapshot;
  ro.total_order_seek = true;
2342 2343 2344
  std::string ts_str;
  Slice ts;
  if (FLAGS_user_timestamp_size > 0) {
2345
    ts_str = GetNowNanos();
2346 2347 2348
    ts = ts_str;
    ro.timestamp = &ts;
  }
2349

2350
  std::unique_ptr<Iterator> it(db_->NewIterator(ro, column_family));
2351 2352 2353 2354 2355

  constexpr char kCrcCalculatorSepearator = ';';

  uint32_t crc = 0;

2356 2357 2358 2359
  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());
2360
    crc = crc32c::Extend(crc, &kCrcCalculatorSepearator, sizeof(char));
2361
    crc = crc32c::Extend(crc, it->value().data(), it->value().size());
2362 2363 2364 2365 2366 2367 2368 2369
    crc = crc32c::Extend(crc, &kCrcCalculatorSepearator, sizeof(char));

    for (const auto& column : it->columns()) {
      crc = crc32c::Extend(crc, column.name().data(), column.name().size());
      crc = crc32c::Extend(crc, &kCrcCalculatorSepearator, sizeof(char));
      crc = crc32c::Extend(crc, column.value().data(), column.value().size());
      crc = crc32c::Extend(crc, &kCrcCalculatorSepearator, sizeof(char));
    }
2370
  }
2371

2372 2373 2374 2375 2376 2377 2378
  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();
  }
2379

2380 2381 2382
  return crc;
}

2383 2384 2385 2386 2387 2388
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");
2389
  if (FLAGS_use_txn) {
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    fprintf(stdout, "TransactionDB Type        : %s\n",
            FLAGS_use_optimistic_txn ? "Optimistic" : "Pessimistic");
    if (FLAGS_use_optimistic_txn) {
      fprintf(stdout, "OCC Validation Type       : %d\n",
              static_cast<int>(FLAGS_occ_validation_policy));
      if (static_cast<uint64_t>(OccValidationPolicy::kValidateParallel) ==
          FLAGS_occ_validation_policy) {
        fprintf(stdout, "Share Lock Buckets        : %s\n",
                FLAGS_share_occ_lock_buckets ? "true" : "false");
        if (FLAGS_share_occ_lock_buckets) {
          fprintf(stdout, "Lock Bucket Count         : %d\n",
                  static_cast<int>(FLAGS_occ_lock_bucket_count));
        }
      }
    } else {
      fprintf(stdout, "Two write queues:         : %s\n",
              FLAGS_two_write_queues ? "true" : "false");
      fprintf(stdout, "Write policy              : %d\n",
              static_cast<int>(FLAGS_txn_write_policy));
      if (static_cast<uint64_t>(TxnDBWritePolicy::WRITE_PREPARED) ==
              FLAGS_txn_write_policy ||
          static_cast<uint64_t>(TxnDBWritePolicy::WRITE_UNPREPARED) ==
              FLAGS_txn_write_policy) {
        fprintf(stdout, "Snapshot cache bits       : %d\n",
                static_cast<int>(FLAGS_wp_snapshot_cache_bits));
        fprintf(stdout, "Commit cache bits         : %d\n",
                static_cast<int>(FLAGS_wp_commit_cache_bits));
      }
      fprintf(stdout, "last cwb for recovery    : %s\n",
              FLAGS_use_only_the_last_commit_time_batch_for_recovery ? "true"
                                                                     : "false");
    }
2422 2423
  }

2424
  fprintf(stdout, "Stacked BlobDB            : %s\n",
L
Levi Tamasi 已提交
2425
          FLAGS_use_blob_db ? "true" : "false");
2426 2427 2428 2429
  fprintf(stdout, "Read only mode            : %s\n",
          FLAGS_read_only ? "true" : "false");
  fprintf(stdout, "Atomic flush              : %s\n",
          FLAGS_atomic_flush ? "true" : "false");
2430 2431
  fprintf(stdout, "Manual WAL flush          : %s\n",
          FLAGS_manual_wal_flush_one_in > 0 ? "true" : "false");
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
  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) {
S
sdong 已提交
2442
    ttl_state = std::to_string(FLAGS_ttl);
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
  }
  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);
2453
  fprintf(stdout, "Custom ops percentage     : %d%%\n", FLAGS_customopspercent);
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
  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);
2469
  std::string compression = CompressionTypeToString(compression_type_e);
2470
  fprintf(stdout, "Compression               : %s\n", compression.c_str());
2471 2472 2473 2474 2475
  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);
2476
  fprintf(stdout, "Checksum type             : %s\n", checksum.c_str());
2477 2478
  fprintf(stdout, "File checksum impl        : %s\n",
          FLAGS_file_checksum_impl.c_str());
2479 2480
  fprintf(stdout, "Bloom bits / key          : %s\n",
          FormatDoubleParam(FLAGS_bloom_bits).c_str());
2481 2482 2483 2484
  fprintf(stdout, "Max subcompactions        : %" PRIu64 "\n",
          FLAGS_subcompactions);
  fprintf(stdout, "Use MultiGet              : %s\n",
          FLAGS_use_multiget ? "true" : "false");
2485 2486
  fprintf(stdout, "Use GetEntity             : %s\n",
          FLAGS_use_get_entity ? "true" : "false");
2487 2488
  fprintf(stdout, "Use MultiGetEntity        : %s\n",
          FLAGS_use_multi_get_entity ? "true" : "false");
2489 2490
  fprintf(stdout, "Verification only         : %s\n",
          FLAGS_verification_only ? "true" : "false");
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

  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);

S
sdong 已提交
2507 2508 2509 2510
#ifndef NDEBUG
  KillPoint* kp = KillPoint::GetInstance();
  fprintf(stdout, "Test kill odd             : %d\n", kp->rocksdb_kill_odds);
  if (!kp->rocksdb_kill_exclude_prefixes.empty()) {
2511
    fprintf(stdout, "Skipping kill points prefixes:\n");
S
sdong 已提交
2512
    for (auto& p : kp->rocksdb_kill_exclude_prefixes) {
2513 2514 2515
      fprintf(stdout, "  %s\n", p.c_str());
    }
  }
S
sdong 已提交
2516
#endif
2517 2518 2519 2520
  fprintf(stdout, "Periodic Compaction Secs  : %" PRIu64 "\n",
          FLAGS_periodic_compaction_seconds);
  fprintf(stdout, "Compaction TTL            : %" PRIu64 "\n",
          FLAGS_compaction_ttl);
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
  const char* compaction_pri = "";
  switch (FLAGS_compaction_pri) {
    case kByCompensatedSize:
      compaction_pri = "kByCompensatedSize";
      break;
    case kOldestLargestSeqFirst:
      compaction_pri = "kOldestLargestSeqFirst";
      break;
    case kOldestSmallestSeqFirst:
      compaction_pri = "kOldestSmallestSeqFirst";
      break;
    case kMinOverlappingRatio:
      compaction_pri = "kMinOverlappingRatio";
      break;
    case kRoundRobin:
      compaction_pri = "kRoundRobin";
      break;
  }
  fprintf(stdout, "Compaction Pri            : %s\n", compaction_pri);
S
sdong 已提交
2540 2541 2542 2543 2544 2545 2546 2547
  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 已提交
2548
  fprintf(stdout, "Read fault one in         : %d\n", FLAGS_read_fault_one_in);
2549
  fprintf(stdout, "Write fault one in        : %d\n", FLAGS_write_fault_one_in);
2550 2551 2552
  fprintf(stdout, "Open metadata write fault one in:\n");
  fprintf(stdout, "                            %d\n",
          FLAGS_open_metadata_write_fault_one_in);
2553 2554
  fprintf(stdout, "Sync fault injection      : %d\n",
          FLAGS_sync_fault_injection);
2555 2556
  fprintf(stdout, "Best efforts recovery     : %d\n",
          static_cast<int>(FLAGS_best_efforts_recovery));
2557 2558
  fprintf(stdout, "Fail if OPTIONS file error: %d\n",
          static_cast<int>(FLAGS_fail_if_options_file_error));
2559 2560
  fprintf(stdout, "User timestamp size bytes : %d\n",
          static_cast<int>(FLAGS_user_timestamp_size));
2561 2562
  fprintf(stdout, "WAL compression           : %s\n",
          FLAGS_wal_compression.c_str());
2563 2564
  fprintf(stdout, "Try verify sst unique id  : %d\n",
          static_cast<int>(FLAGS_verify_sst_unique_id_in_manifest));
2565 2566 2567 2568

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

2569
void StressTest::Open(SharedState* shared, bool reopen) {
2570 2571
  assert(db_ == nullptr);
  assert(txn_db_ == nullptr);
2572
  assert(optimistic_txn_db_ == nullptr);
2573
  if (!InitializeOptionsFromFile(options_)) {
S
sdong 已提交
2574
    InitializeOptionsFromFlags(cache_, filter_policy_, options_);
2575
  }
S
sdong 已提交
2576
  InitializeOptionsGeneral(cache_, filter_policy_, options_);
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587

  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");
  }
2588

2589 2590
  if ((options_.enable_blob_files || options_.enable_blob_garbage_collection ||
       FLAGS_allow_setting_blob_options_dynamically) &&
2591
      FLAGS_best_efforts_recovery) {
2592
    fprintf(stderr,
2593 2594
            "Integrated BlobDB is currently incompatible with best-effort "
            "recovery\n");
2595 2596 2597
    exit(1);
  }

2598 2599 2600 2601
  fprintf(stdout,
          "Integrated BlobDB: blob files enabled %d, min blob size %" PRIu64
          ", blob file size %" PRIu64
          ", blob compression type %s, blob GC enabled %d, cutoff %f, force "
2602 2603
          "threshold %f, blob compaction readahead size %" PRIu64
          ", blob file starting level %d\n",
2604 2605 2606 2607 2608 2609
          options_.enable_blob_files, options_.min_blob_size,
          options_.blob_file_size,
          CompressionTypeToString(options_.blob_compression_type).c_str(),
          options_.enable_blob_garbage_collection,
          options_.blob_garbage_collection_age_cutoff,
          options_.blob_garbage_collection_force_threshold,
2610 2611
          options_.blob_compaction_readahead_size,
          options_.blob_file_starting_level);
2612

2613 2614
  if (FLAGS_use_blob_cache) {
    fprintf(stdout,
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
            "Integrated BlobDB: blob cache enabled"
            ", block and blob caches shared: %d",
            FLAGS_use_shared_block_and_blob_cache);
    if (!FLAGS_use_shared_block_and_blob_cache) {
      fprintf(stdout,
              ", blob cache size %" PRIu64 ", blob cache num shard bits: %d",
              FLAGS_blob_cache_size, FLAGS_blob_cache_numshardbits);
    }
    fprintf(stdout, ", blob cache prepopulated: %d\n",
            FLAGS_prepopulate_blob_cache);
2625 2626 2627 2628
  } else {
    fprintf(stdout, "Integrated BlobDB: blob cache disabled\n");
  }

2629 2630 2631
  fprintf(stdout, "DB path: [%s]\n", FLAGS_db.c_str());

  Status s;
2632

2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
  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");
2654
        fprintf(stderr, "Expected: {");
2655
        for (auto cf : sorted_cfn) {
2656
          fprintf(stderr, "%s ", cf.c_str());
2657
        }
2658 2659
        fprintf(stderr, "}\n");
        fprintf(stderr, "Existing: {");
2660
        for (auto cf : existing_column_families) {
2661
          fprintf(stderr, "%s ", cf.c_str());
2662
        }
2663
        fprintf(stderr, "}\n");
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
      }
      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) {
S
sdong 已提交
2676
      std::string name = std::to_string(new_column_family_name_.load());
2677 2678 2679 2680
      new_column_family_name_++;
      cf_descriptors.emplace_back(name, ColumnFamilyOptions(options_));
      column_family_names_.push_back(name);
    }
2681

2682
    options_.listeners.clear();
2683 2684
    options_.listeners.emplace_back(new DbStressListener(
        FLAGS_db, options_.db_paths, cf_descriptors, db_stress_listener_env));
2685
    RegisterAdditionalListeners();
2686

2687
    if (!FLAGS_use_txn) {
2688
      // Determine whether we need to inject file metadata write failures
2689
      // during DB reopen. If it does, enable it.
2690
      // Only inject metadata error if it is reopening, as initial open
2691 2692
      // failure doesn't need to be handled.
      // TODO cover transaction DB is not covered in this fault test too.
2693 2694 2695
      bool inject_meta_error = false;
      bool inject_write_error = false;
      bool inject_read_error = false;
2696
      if ((FLAGS_open_metadata_write_fault_one_in ||
2697
           FLAGS_open_write_fault_one_in || FLAGS_open_read_fault_one_in) &&
2698 2699
          fault_fs_guard
              ->FileExists(FLAGS_db + "/CURRENT", IOOptions(), nullptr)
2700
              .ok()) {
2701 2702 2703 2704 2705 2706 2707
        if (!FLAGS_sync) {
          // When DB Stress is not sync mode, we expect all WAL writes to
          // WAL is durable. Buffering unsynced writes will cause false
          // positive in crash tests. Before we figure out a way to
          // solve it, skip WAL from failure injection.
          fault_fs_guard->SetSkipDirectWritableTypes({kWalFile});
        }
2708 2709 2710 2711
        inject_meta_error = FLAGS_open_metadata_write_fault_one_in;
        inject_write_error = FLAGS_open_write_fault_one_in;
        inject_read_error = FLAGS_open_read_fault_one_in;
        if (inject_meta_error) {
2712 2713 2714 2715
          fault_fs_guard->EnableMetadataWriteErrorInjection();
          fault_fs_guard->SetRandomMetadataWriteError(
              FLAGS_open_metadata_write_fault_one_in);
        }
2716
        if (inject_write_error) {
2717 2718 2719 2720 2721 2722 2723
          fault_fs_guard->SetFilesystemDirectWritable(false);
          fault_fs_guard->EnableWriteErrorInjection();
          fault_fs_guard->SetRandomWriteError(
              static_cast<uint32_t>(FLAGS_seed), FLAGS_open_write_fault_one_in,
              IOStatus::IOError("Injected Open Error"),
              /*inject_for_all_file_types=*/true, /*types=*/{});
        }
2724
        if (inject_read_error) {
2725 2726
          fault_fs_guard->SetRandomReadError(FLAGS_open_read_fault_one_in);
        }
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
      }
      while (true) {
        // StackableDB-based BlobDB
        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
        {
          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_);
          }
        }

2756
        if (inject_meta_error || inject_write_error || inject_read_error) {
2757
          fault_fs_guard->SetFilesystemDirectWritable(true);
2758
          fault_fs_guard->DisableMetadataWriteErrorInjection();
2759
          fault_fs_guard->DisableWriteErrorInjection();
2760
          fault_fs_guard->SetSkipDirectWritableTypes({});
2761
          fault_fs_guard->SetRandomReadError(0);
2762
          if (s.ok()) {
2763
            // Injected errors might happen in background compactions. We
2764 2765
            // wait for all compactions to finish to make sure DB is in
            // clean state before executing queries.
2766
            s = db_->GetRootDB()->WaitForCompact(WaitForCompactOptions());
2767
            if (!s.ok()) {
2768 2769 2770 2771
              for (auto cf : column_families_) {
                delete cf;
              }
              column_families_.clear();
2772
              delete db_;
2773
              db_ = nullptr;
2774 2775
            }
          }
2776 2777 2778 2779
          if (!s.ok()) {
            // After failure to opening a DB due to IO error, retry should
            // successfully open the DB with correct data if no IO error shows
            // up.
2780 2781 2782
            inject_meta_error = false;
            inject_write_error = false;
            inject_read_error = false;
2783

2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
            // TODO: Unsynced data loss during DB reopen is not supported yet in
            //  stress test. Will need to recreate expected state if we decide
            //  to support unsynced data loss during DB reopen.
            if (!reopen) {
              Random rand(static_cast<uint32_t>(FLAGS_seed));
              if (rand.OneIn(2)) {
                fault_fs_guard->DeleteFilesCreatedAfterLastDirSync(IOOptions(),
                                                                   nullptr);
              }
              if (rand.OneIn(3)) {
                fault_fs_guard->DropUnsyncedFileData();
              } else if (rand.OneIn(2)) {
                fault_fs_guard->DropRandomUnsyncedFileData(&rand);
              }
2798 2799 2800
            }
            continue;
          }
L
Levi Tamasi 已提交
2801
        }
2802
        break;
2803 2804
      }
    } else {
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
      if (FLAGS_use_optimistic_txn) {
        OptimisticTransactionDBOptions optimistic_txn_db_options;
        optimistic_txn_db_options.validate_policy =
            static_cast<OccValidationPolicy>(FLAGS_occ_validation_policy);

        if (FLAGS_share_occ_lock_buckets) {
          optimistic_txn_db_options.shared_lock_buckets =
              MakeSharedOccLockBuckets(FLAGS_occ_lock_bucket_count);
        } else {
          optimistic_txn_db_options.occ_lock_buckets =
              FLAGS_occ_lock_bucket_count;
          optimistic_txn_db_options.shared_lock_buckets = nullptr;
        }
        s = OptimisticTransactionDB::Open(
            options_, optimistic_txn_db_options, FLAGS_db, cf_descriptors,
            &column_families_, &optimistic_txn_db_);
        if (!s.ok()) {
          fprintf(stderr, "Error in opening the OptimisticTransactionDB [%s]\n",
                  s.ToString().c_str());
          fflush(stderr);
        }
        assert(s.ok());
        {
          db_ = optimistic_txn_db_;
          db_aptr_.store(optimistic_txn_db_, std::memory_order_release);
        }
2831
      } else {
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
        TransactionDBOptions txn_db_options;
        assert(FLAGS_txn_write_policy <= TxnDBWritePolicy::WRITE_UNPREPARED);
        txn_db_options.write_policy =
            static_cast<TxnDBWritePolicy>(FLAGS_txn_write_policy);
        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;
        } else {
          options_.two_write_queues = FLAGS_two_write_queues;
        }
        txn_db_options.wp_snapshot_cache_bits =
            static_cast<size_t>(FLAGS_wp_snapshot_cache_bits);
        txn_db_options.wp_commit_cache_bits =
            static_cast<size_t>(FLAGS_wp_commit_cache_bits);
        PrepareTxnDbOptions(shared, txn_db_options);
        s = TransactionDB::Open(options_, txn_db_options, FLAGS_db,
                                cf_descriptors, &column_families_, &txn_db_);
        if (!s.ok()) {
          fprintf(stderr, "Error in opening the TransactionDB [%s]\n",
                  s.ToString().c_str());
          fflush(stderr);
        }
        assert(s.ok());
2858

2859 2860 2861 2862 2863
        // Do not swap the order of the following.
        {
          db_ = txn_db_;
          db_aptr_.store(txn_db_, std::memory_order_release);
        }
2864
      }
2865
    }
2866 2867 2868 2869
    if (!s.ok()) {
      fprintf(stderr, "Error in opening the DB [%s]\n", s.ToString().c_str());
      fflush(stderr);
    }
2870 2871 2872
    assert(s.ok());
    assert(column_families_.size() ==
           static_cast<size_t>(FLAGS_column_families));
2873

2874 2875 2876
    // Secondary instance does not support write-prepared/write-unprepared
    // transactions, thus just disable secondary instance if we use
    // transaction.
2877
    if (s.ok() && FLAGS_test_secondary && !FLAGS_use_txn) {
2878 2879 2880
      Options tmp_opts;
      // TODO(yanqin) support max_open_files != -1 for secondary instance.
      tmp_opts.max_open_files = -1;
2881
      tmp_opts.env = db_stress_env;
2882
      const std::string& secondary_path = FLAGS_secondaries_base;
2883 2884
      s = DB::OpenAsSecondary(tmp_opts, FLAGS_db, secondary_path,
                              cf_descriptors, &cmp_cfhs_, &cmp_db_);
2885 2886
      assert(s.ok());
      assert(cmp_cfhs_.size() == static_cast<size_t>(FLAGS_column_families));
2887
    }
2888 2889 2890 2891 2892
  } else {
    DBWithTTL* db_with_ttl;
    s = DBWithTTL::Open(options_, FLAGS_db, &db_with_ttl, FLAGS_ttl);
    db_ = db_with_ttl;
  }
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907

  if (FLAGS_preserve_unverified_changes) {
    // Up until now, no live file should have become obsolete due to these
    // options. After `DisableFileDeletions()` we can reenable auto compactions
    // since, even if live files become obsolete, they won't be deleted.
    assert(options_.avoid_flush_during_recovery);
    assert(options_.disable_auto_compactions);
    if (s.ok()) {
      s = db_->DisableFileDeletions();
    }
    if (s.ok()) {
      s = db_->EnableAutoCompaction(column_families_);
    }
  }

2908 2909 2910 2911 2912 2913
  if (!s.ok()) {
    fprintf(stderr, "open error: %s\n", s.ToString().c_str());
    exit(1);
  }
}

2914
void StressTest::Reopen(ThreadState* thread) {
2915 2916 2917 2918
  // 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;
2919
  bool bg_canceled __attribute__((unused)) = false;
2920 2921 2922
  if (write_prepared || thread->rand.OneIn(2)) {
    const bool wait =
        write_prepared || static_cast<bool>(thread->rand.OneIn(2));
2923 2924
    CancelAllBackgroundWork(db_, wait);
    bg_canceled = wait;
2925
  }
2926
  assert(!write_prepared || bg_canceled);
2927

2928 2929 2930 2931
  for (auto cf : column_families_) {
    delete cf;
  }
  column_families_.clear();
2932

2933
  if (thread->rand.OneIn(2)) {
2934
    Status s = db_->Close();
2935 2936 2937 2938
    if (!s.ok()) {
      fprintf(stderr, "Non-ok close status: %s\n", s.ToString().c_str());
      fflush(stderr);
    }
2939 2940
    assert(s.ok());
  }
2941 2942
  assert((txn_db_ == nullptr && optimistic_txn_db_ == nullptr) ||
         (db_ == txn_db_ || db_ == optimistic_txn_db_));
2943 2944
  delete db_;
  db_ = nullptr;
2945
  txn_db_ = nullptr;
2946
  optimistic_txn_db_ = nullptr;
2947 2948

  num_times_reopened_++;
2949
  auto now = clock_->NowMicros();
2950
  fprintf(stdout, "%s Reopening database for the %dth time\n",
2951
          clock_->TimeToString(now / 1000000).c_str(), num_times_reopened_);
2952
  Open(thread->shared, /*reopen=*/true);
2953

2954 2955 2956
  if ((FLAGS_sync_fault_injection || FLAGS_disable_wal ||
       FLAGS_manual_wal_flush_one_in > 0) &&
      IsStateTracked()) {
2957 2958 2959 2960 2961 2962 2963
    Status s = thread->shared->SaveAtAndAfter(db_);
    if (!s.ok()) {
      fprintf(stderr, "Error enabling history tracing: %s\n",
              s.ToString().c_str());
      exit(1);
    }
  }
2964
}
2965

2966
bool StressTest::MaybeUseOlderTimestampForPointLookup(ThreadState* thread,
2967 2968 2969 2970
                                                      std::string& ts_str,
                                                      Slice& ts_slice,
                                                      ReadOptions& read_opts) {
  if (FLAGS_user_timestamp_size == 0) {
2971
    return false;
2972 2973 2974 2975
  }

  assert(thread);
  if (!thread->rand.OneInOpt(3)) {
2976
    return false;
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
  }

  const SharedState* const shared = thread->shared;
  assert(shared);
  const uint64_t start_ts = shared->GetStartTimestamp();

  uint64_t now = db_stress_env->NowNanos();

  assert(now > start_ts);
  uint64_t time_diff = now - start_ts;
  uint64_t ts = start_ts + (thread->rand.Next64() % time_diff);
  ts_str.clear();
  PutFixed64(&ts_str, ts);
  ts_slice = ts_str;
  read_opts.timestamp = &ts_slice;
2992
  return true;
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
}

void StressTest::MaybeUseOlderTimestampForRangeScan(ThreadState* thread,
                                                    std::string& ts_str,
                                                    Slice& ts_slice,
                                                    ReadOptions& read_opts) {
  if (FLAGS_user_timestamp_size == 0) {
    return;
  }

  assert(thread);
  if (!thread->rand.OneInOpt(3)) {
    return;
  }

  const Slice* const saved_ts = read_opts.timestamp;
  assert(saved_ts != nullptr);

  const SharedState* const shared = thread->shared;
  assert(shared);
  const uint64_t start_ts = shared->GetStartTimestamp();

  uint64_t now = db_stress_env->NowNanos();

  assert(now > start_ts);
  uint64_t time_diff = now - start_ts;
  uint64_t ts = start_ts + (thread->rand.Next64() % time_diff);
  ts_str.clear();
  PutFixed64(&ts_str, ts);
  ts_slice = ts_str;
  read_opts.timestamp = &ts_slice;

3025
  // TODO (yanqin): support Merge with iter_start_ts
3026
  if (!thread->rand.OneInOpt(3) || FLAGS_use_merge || FLAGS_use_full_merge_v1) {
3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
    return;
  }

  ts_str.clear();
  PutFixed64(&ts_str, start_ts);
  ts_slice = ts_str;
  read_opts.iter_start_ts = &ts_slice;
  read_opts.timestamp = saved_ts;
}

3037
void CheckAndSetOptionsForUserTimestamp(Options& options) {
3038
  assert(FLAGS_user_timestamp_size > 0);
3039
  const Comparator* const cmp = test::BytewiseComparatorWithU64TsWrapper();
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
  assert(cmp);
  if (FLAGS_user_timestamp_size != cmp->timestamp_size()) {
    fprintf(stderr,
            "Only -user_timestamp_size=%d is supported in stress test.\n",
            static_cast<int>(cmp->timestamp_size()));
    exit(1);
  }
  if (FLAGS_use_txn) {
    fprintf(stderr, "TransactionDB does not support timestamp yet.\n");
    exit(1);
  }
  if (FLAGS_test_cf_consistency || FLAGS_test_batches_snapshots) {
    fprintf(stderr,
            "Due to per-key ts-seq ordering constraint, only the (default) "
            "non-batched test is supported with timestamp.\n");
    exit(1);
  }
  if (FLAGS_ingest_external_file_one_in > 0) {
    fprintf(stderr, "Bulk loading may not support timestamp yet.\n");
    exit(1);
  }
3061
  options.comparator = cmp;
3062
}
3063 3064 3065

bool InitializeOptionsFromFile(Options& options) {
  DBOptions db_options;
3066 3067 3068 3069
  ConfigOptions config_options;
  config_options.ignore_unknown_options = false;
  config_options.input_strings_escaped = true;
  config_options.env = db_stress_env;
3070 3071
  std::vector<ColumnFamilyDescriptor> cf_descriptors;
  if (!FLAGS_options_file.empty()) {
3072
    Status s = LoadOptionsFromFile(config_options, FLAGS_options_file,
3073 3074 3075 3076 3077 3078
                                   &db_options, &cf_descriptors);
    if (!s.ok()) {
      fprintf(stderr, "Unable to load options file %s --- %s\n",
              FLAGS_options_file.c_str(), s.ToString().c_str());
      exit(1);
    }
3079
    db_options.env = new CompositeEnvWrapper(db_stress_env);
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
    options = Options(db_options, cf_descriptors[0].options);
    return true;
  }
  return false;
}

void InitializeOptionsFromFlags(
    const std::shared_ptr<Cache>& cache,
    const std::shared_ptr<const FilterPolicy>& filter_policy,
    Options& options) {
  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.metadata_cache_options.top_level_index_pinning =
      static_cast<PinningTier>(FLAGS_top_level_index_pinning);
  block_based_options.metadata_cache_options.partition_pinning =
      static_cast<PinningTier>(FLAGS_partition_pinning);
  block_based_options.metadata_cache_options.unpartitioned_pinning =
      static_cast<PinningTier>(FLAGS_unpartitioned_pinning);
  block_based_options.checksum = checksum_type_e;
  block_based_options.block_size = FLAGS_block_size;
  block_based_options.cache_usage_options.options_overrides.insert(
      {CacheEntryRole::kCompressionDictionaryBuildingBuffer,
       {/*.charged = */ FLAGS_charge_compression_dictionary_building_buffer
            ? CacheEntryRoleOptions::Decision::kEnabled
            : CacheEntryRoleOptions::Decision::kDisabled}});
  block_based_options.cache_usage_options.options_overrides.insert(
      {CacheEntryRole::kFilterConstruction,
       {/*.charged = */ FLAGS_charge_filter_construction
            ? CacheEntryRoleOptions::Decision::kEnabled
            : CacheEntryRoleOptions::Decision::kDisabled}});
  block_based_options.cache_usage_options.options_overrides.insert(
      {CacheEntryRole::kBlockBasedTableReader,
       {/*.charged = */ FLAGS_charge_table_reader
            ? CacheEntryRoleOptions::Decision::kEnabled
            : CacheEntryRoleOptions::Decision::kDisabled}});
3117 3118 3119 3120 3121
  block_based_options.cache_usage_options.options_overrides.insert(
      {CacheEntryRole::kFileMetadata,
       {/*.charged = */ FLAGS_charge_file_metadata
            ? CacheEntryRoleOptions::Decision::kEnabled
            : CacheEntryRoleOptions::Decision::kDisabled}});
3122 3123 3124 3125 3126
  block_based_options.cache_usage_options.options_overrides.insert(
      {CacheEntryRole::kBlobCache,
       {/*.charged = */ FLAGS_charge_blob_cache
            ? CacheEntryRoleOptions::Decision::kEnabled
            : CacheEntryRoleOptions::Decision::kDisabled}});
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
  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.optimize_filters_for_memory =
      FLAGS_optimize_filters_for_memory;
  block_based_options.detect_filter_construct_corruption =
      FLAGS_detect_filter_construct_corruption;
  block_based_options.index_type =
      static_cast<BlockBasedTableOptions::IndexType>(FLAGS_index_type);
3139 3140 3141
  block_based_options.data_block_index_type =
      static_cast<BlockBasedTableOptions::DataBlockIndexType>(
          FLAGS_data_block_index_type);
3142 3143 3144
  block_based_options.prepopulate_block_cache =
      static_cast<BlockBasedTableOptions::PrepopulateBlockCache>(
          FLAGS_prepopulate_block_cache);
3145 3146 3147 3148 3149
  block_based_options.initial_auto_readahead_size =
      FLAGS_initial_auto_readahead_size;
  block_based_options.max_auto_readahead_size = FLAGS_max_auto_readahead_size;
  block_based_options.num_file_reads_for_auto_readahead =
      FLAGS_num_file_reads_for_auto_readahead;
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167
  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.disable_auto_compactions = FLAGS_disable_auto_compactions;
  options.max_background_compactions = FLAGS_max_background_compactions;
  options.max_background_flushes = FLAGS_max_background_flushes;
  options.compaction_style =
      static_cast<ROCKSDB_NAMESPACE::CompactionStyle>(FLAGS_compaction_style);
3168 3169 3170 3171 3172
  if (options.compaction_style ==
      ROCKSDB_NAMESPACE::CompactionStyle::kCompactionStyleFIFO) {
    options.compaction_options_fifo.allow_compaction =
        FLAGS_fifo_allow_compaction;
  }
3173 3174
  options.compaction_pri =
      static_cast<ROCKSDB_NAMESPACE::CompactionPri>(FLAGS_compaction_pri);
3175
  options.num_levels = FLAGS_num_levels;
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
  if (FLAGS_prefix_size >= 0) {
    options.prefix_extractor.reset(NewFixedPrefixTransform(FLAGS_prefix_size));
  }
  options.max_open_files = FLAGS_open_files;
  options.statistics = dbstats;
  options.env = db_stress_env;
  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;
  options.compression = compression_type_e;
  options.bottommost_compression = bottommost_compression_type_e;
  options.compression_opts.max_dict_bytes = FLAGS_compression_max_dict_bytes;
  options.compression_opts.zstd_max_train_bytes =
      FLAGS_compression_zstd_max_train_bytes;
  options.compression_opts.parallel_threads =
      FLAGS_compression_parallel_threads;
  options.compression_opts.max_dict_buffer_bytes =
      FLAGS_compression_max_dict_buffer_bytes;
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
  if (ZSTD_FinalizeDictionarySupported()) {
    options.compression_opts.use_zstd_dict_trainer =
        FLAGS_compression_use_zstd_dict_trainer;
  } else if (!FLAGS_compression_use_zstd_dict_trainer) {
    fprintf(
        stderr,
        "WARNING: use_zstd_dict_trainer is false but zstd finalizeDictionary "
        "cannot be used because ZSTD 1.4.5+ is not linked with the binary."
        " zstd dictionary trainer will be used.\n");
  }
3218 3219 3220
  if (FLAGS_compression_checksum) {
    options.compression_opts.checksum = true;
  }
3221 3222 3223 3224 3225 3226 3227 3228
  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.experimental_mempurge_threshold =
      FLAGS_experimental_mempurge_threshold;
  options.periodic_compaction_seconds = FLAGS_periodic_compaction_seconds;
3229 3230
  options.stats_dump_period_sec =
      static_cast<unsigned int>(FLAGS_stats_dump_period_sec);
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
  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;
3243
  options.manual_wal_flush = FLAGS_manual_wal_flush_one_in > 0 ? true : false;
3244 3245 3246 3247 3248 3249 3250 3251
  options.avoid_unnecessary_blocking_io = FLAGS_avoid_unnecessary_blocking_io;
  options.write_dbid_to_manifest = FLAGS_write_dbid_to_manifest;
  options.avoid_flush_during_recovery = FLAGS_avoid_flush_during_recovery;
  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;
  options.track_and_verify_wals_in_manifest = true;
3252 3253
  options.verify_sst_unique_id_in_manifest =
      FLAGS_verify_sst_unique_id_in_manifest;
3254 3255
  options.memtable_protection_bytes_per_key =
      FLAGS_memtable_protection_bytes_per_key;
3256
  options.block_protection_bytes_per_key = FLAGS_block_protection_bytes_per_key;
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269

  // Integrated BlobDB
  options.enable_blob_files = FLAGS_enable_blob_files;
  options.min_blob_size = FLAGS_min_blob_size;
  options.blob_file_size = FLAGS_blob_file_size;
  options.blob_compression_type =
      StringToCompressionType(FLAGS_blob_compression_type.c_str());
  options.enable_blob_garbage_collection = FLAGS_enable_blob_garbage_collection;
  options.blob_garbage_collection_age_cutoff =
      FLAGS_blob_garbage_collection_age_cutoff;
  options.blob_garbage_collection_force_threshold =
      FLAGS_blob_garbage_collection_force_threshold;
  options.blob_compaction_readahead_size = FLAGS_blob_compaction_readahead_size;
3270
  options.blob_file_starting_level = FLAGS_blob_file_starting_level;
3271

3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
  if (FLAGS_use_blob_cache) {
    if (FLAGS_use_shared_block_and_blob_cache) {
      options.blob_cache = cache;
    } else {
      if (FLAGS_blob_cache_size > 0) {
        LRUCacheOptions co;
        co.capacity = FLAGS_blob_cache_size;
        co.num_shard_bits = FLAGS_blob_cache_numshardbits;
        options.blob_cache = NewLRUCache(co);
      } else {
        fprintf(stderr,
                "Unable to create a standalone blob cache if blob_cache_size "
                "<= 0.\n");
        exit(1);
      }
    }
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    switch (FLAGS_prepopulate_blob_cache) {
      case 0:
        options.prepopulate_blob_cache = PrepopulateBlobCache::kDisable;
        break;
      case 1:
        options.prepopulate_blob_cache = PrepopulateBlobCache::kFlushOnly;
        break;
      default:
        fprintf(stderr, "Unknown prepopulate blob cache mode\n");
        exit(1);
    }
3299 3300
  }

3301 3302 3303
  options.wal_compression =
      StringToCompressionType(FLAGS_wal_compression.c_str());

J
Jay Zhuang 已提交
3304 3305 3306 3307 3308
  if (FLAGS_enable_tiered_storage) {
    options.bottommost_temperature = Temperature::kCold;
  }
  options.preclude_last_level_data_seconds =
      FLAGS_preclude_last_level_data_seconds;
3309
  options.preserve_internal_time_seconds = FLAGS_preserve_internal_time_seconds;
J
Jay Zhuang 已提交
3310

3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
  switch (FLAGS_rep_factory) {
    case kSkipList:
      // no need to do anything
      break;
    case kHashSkipList:
      options.memtable_factory.reset(NewHashSkipListRepFactory(10000));
      break;
    case kVectorRep:
      options.memtable_factory.reset(new VectorRepFactory());
      break;
  }
  if (FLAGS_use_full_merge_v1) {
    options.merge_operator = MergeOperators::CreateDeprecatedPutOperator();
  } else {
    options.merge_operator = MergeOperators::CreatePutOperator();
  }

  if (FLAGS_enable_compaction_filter) {
    options.compaction_filter_factory =
        std::make_shared<DbStressCompactionFilterFactory>();
  }

  options.best_efforts_recovery = FLAGS_best_efforts_recovery;
  options.paranoid_file_checks = FLAGS_paranoid_file_checks;
  options.fail_if_options_file_error = FLAGS_fail_if_options_file_error;

  if (FLAGS_user_timestamp_size > 0) {
    CheckAndSetOptionsForUserTimestamp(options);
  }
3340 3341

  options.allow_data_in_errors = FLAGS_allow_data_in_errors;
3342 3343

  options.enable_thread_tracking = FLAGS_enable_thread_tracking;
3344 3345

  options.memtable_max_range_deletions = FLAGS_memtable_max_range_deletions;
3346 3347 3348

  options.bottommost_file_compaction_delay =
      FLAGS_bottommost_file_compaction_delay;
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
}

void InitializeOptionsGeneral(
    const std::shared_ptr<Cache>& cache,
    const std::shared_ptr<const FilterPolicy>& filter_policy,
    Options& options) {
  options.create_missing_column_families = true;
  options.create_if_missing = true;

  if (!options.statistics) {
    options.statistics = dbstats;
  }

  if (options.env == Options().env) {
    options.env = db_stress_env;
  }

  assert(options.table_factory);
  auto table_options =
      options.table_factory->GetOptions<BlockBasedTableOptions>();
  if (table_options) {
    if (FLAGS_cache_size > 0) {
      table_options->block_cache = cache;
    }
    if (!table_options->filter_policy) {
      table_options->filter_policy = filter_policy;
    }
  }

  // TODO: row_cache, thread-pool IO priority, CPU priority.

  if (!options.rate_limiter) {
    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 (!options.file_checksum_gen_factory) {
    options.file_checksum_gen_factory =
        GetFileChecksumImpl(FLAGS_file_checksum_impl);
  }

  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);
    }
  }

3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
  if (FLAGS_preserve_unverified_changes) {
    if (!options.avoid_flush_during_recovery) {
      fprintf(stderr,
              "WARNING: flipping `avoid_flush_during_recovery` to true for "
              "`preserve_unverified_changes` to keep all files\n");
      options.avoid_flush_during_recovery = true;
    }
    // Together with `avoid_flush_during_recovery == true`, this will prevent
    // live files from becoming obsolete and deleted between `DB::Open()` and
    // `DisableFileDeletions()` due to flush or compaction. We do not need to
    // warn the user since we will reenable compaction soon.
    options.disable_auto_compactions = true;
  }

3425 3426 3427 3428
  options.table_properties_collector_factories.emplace_back(
      std::make_shared<DbStressTablePropertiesCollectorFactory>());
}

3429
}  // namespace ROCKSDB_NAMESPACE
3430
#endif  // GFLAGS