db_test_util.h 45.0 KB
Newer Older
1
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5 6 7 8 9 10
//
// 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.

#pragma once
11

12 13 14
#include <fcntl.h>

#include <algorithm>
15
#include <cinttypes>
16
#include <map>
17
#include <memory>
18 19 20 21 22 23 24
#include <set>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>

25
#include "db/db_impl/db_impl.h"
26
#include "file/filename.h"
27
#include "rocksdb/advanced_options.h"
28 29
#include "rocksdb/cache.h"
#include "rocksdb/compaction_filter.h"
A
agiardullo 已提交
30
#include "rocksdb/convenience.h"
31 32
#include "rocksdb/db.h"
#include "rocksdb/env.h"
33
#include "rocksdb/file_system.h"
34
#include "rocksdb/filter_policy.h"
35
#include "rocksdb/io_status.h"
36 37
#include "rocksdb/options.h"
#include "rocksdb/slice.h"
38
#include "rocksdb/sst_file_writer.h"
Y
Yi Wu 已提交
39
#include "rocksdb/statistics.h"
40 41 42
#include "rocksdb/table.h"
#include "rocksdb/utilities/checkpoint.h"
#include "table/mock_table.h"
S
sdong 已提交
43
#include "table/scoped_arena_iterator.h"
44 45
#include "test_util/sync_point.h"
#include "test_util/testharness.h"
46 47 48
#include "util/cast_util.h"
#include "util/compression.h"
#include "util/mutexlock.h"
49
#include "util/string_util.h"
50 51
#include "utilities/merge_operators.h"

52
namespace ROCKSDB_NAMESPACE {
53
class MockEnv;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

namespace anon {
class AtomicCounter {
 public:
  explicit AtomicCounter(Env* env = NULL)
      : env_(env), cond_count_(&mu_), count_(0) {}

  void Increment() {
    MutexLock l(&mu_);
    count_++;
    cond_count_.SignalAll();
  }

  int Read() {
    MutexLock l(&mu_);
    return count_;
  }

  bool WaitFor(int count) {
    MutexLock l(&mu_);

    uint64_t start = env_->NowMicros();
    while (count_ < count) {
      uint64_t now = env_->NowMicros();
78 79
      cond_count_.TimedWait(now + /*1s*/ 1 * 1000 * 1000);
      if (env_->NowMicros() - start > /*10s*/ 10 * 1000 * 1000) {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        return false;
      }
      if (count_ < count) {
        GTEST_LOG_(WARNING) << "WaitFor is taking more time than usual";
      }
    }

    return true;
  }

  void Reset() {
    MutexLock l(&mu_);
    count_ = 0;
    cond_count_.SignalAll();
  }

 private:
  Env* env_;
  port::Mutex mu_;
  port::CondVar cond_count_;
  int count_;
};

struct OptionsOverride {
  std::shared_ptr<const FilterPolicy> filter_policy = nullptr;
M
Maysam Yabandeh 已提交
105 106
  // These will be used only if filter_policy is set
  bool partition_filters = false;
107 108 109
  // Force using a default block cache. (Setting to false allows ASAN build
  // use a trivially small block cache for better UAF error detection.)
  bool full_block_cache = false;
M
Maysam Yabandeh 已提交
110
  uint64_t metadata_block_size = 1024;
111 112 113 114 115 116 117

  // Used as a bit mask of individual enums in which to skip an XF test point
  int skip_policy = 0;
};

}  // namespace anon

S
Siying Dong 已提交
118 119
enum SkipPolicy { kSkipNone = 0, kSkipNoSnapshot = 1, kSkipNoPrefix = 2 };

120 121 122
// Special Env used to delay background operations
class SpecialEnv : public EnvWrapper {
 public:
123
  explicit SpecialEnv(Env* base, bool time_elapse_only_sleep = false);
124

125 126 127
  static const char* kClassName() { return "SpecialEnv"; }
  const char* Name() const override { return kClassName(); }

128
  Status NewWritableFile(const std::string& f, std::unique_ptr<WritableFile>* r,
129 130 131 132
                         const EnvOptions& soptions) override {
    class SSTableFile : public WritableFile {
     private:
      SpecialEnv* env_;
133
      std::unique_ptr<WritableFile> base_;
134 135

     public:
136
      SSTableFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& base)
S
sdong 已提交
137
          : env_(env), base_(std::move(base)) {}
138 139 140 141 142 143 144 145
      Status Append(const Slice& data) override {
        if (env_->table_write_callback_) {
          (*env_->table_write_callback_)();
        }
        if (env_->drop_writes_.load(std::memory_order_acquire)) {
          // Drop writes on the floor
          return Status::OK();
        } else if (env_->no_space_.load(std::memory_order_acquire)) {
146
          return Status::NoSpace("No space left on device");
147 148 149 150 151
        } else {
          env_->bytes_written_ += data.size();
          return base_->Append(data);
        }
      }
152 153 154 155 156
      Status Append(
          const Slice& data,
          const DataVerificationInfo& /* verification_info */) override {
        return Append(data);
      }
A
Aaron Gao 已提交
157
      Status PositionedAppend(const Slice& data, uint64_t offset) override {
A
Aaron Gao 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170
        if (env_->table_write_callback_) {
          (*env_->table_write_callback_)();
        }
        if (env_->drop_writes_.load(std::memory_order_acquire)) {
          // Drop writes on the floor
          return Status::OK();
        } else if (env_->no_space_.load(std::memory_order_acquire)) {
          return Status::NoSpace("No space left on device");
        } else {
          env_->bytes_written_ += data.size();
          return base_->PositionedAppend(data, offset);
        }
      }
171 172 173 174 175
      Status PositionedAppend(
          const Slice& data, uint64_t offset,
          const DataVerificationInfo& /* verification_info */) override {
        return PositionedAppend(data, offset);
      }
S
sdong 已提交
176
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
177 178 179 180 181 182 183
      Status RangeSync(uint64_t offset, uint64_t nbytes) override {
        Status s = base_->RangeSync(offset, nbytes);
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT_CALLBACK("SpecialEnv::SStableFile::RangeSync", &s);
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
        return s;
      }
184
      Status Close() override {
185 186
// SyncPoint is not supported in Released Windows Mode.
#if !(defined NDEBUG) || !defined(OS_WIN)
187 188 189 190 191
        // Check preallocation size
        // preallocation size is never passed to base file.
        size_t preallocation_size = preallocation_block_size();
        TEST_SYNC_POINT_CALLBACK("DBTestWritableFile.GetPreallocationStatus",
                                 &preallocation_size);
192
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
193 194 195 196 197
        Status s = base_->Close();
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT_CALLBACK("SpecialEnv::SStableFile::Close", &s);
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
        return s;
198 199 200 201 202 203 204
      }
      Status Flush() override { return base_->Flush(); }
      Status Sync() override {
        ++env_->sync_counter_;
        while (env_->delay_sstable_sync_.load(std::memory_order_acquire)) {
          env_->SleepForMicroseconds(100000);
        }
205 206 207 208
        Status s;
        if (!env_->skip_fsync_) {
          s = base_->Sync();
        }
209 210 211 212
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT_CALLBACK("SpecialEnv::SStableFile::Sync", &s);
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
        return s;
213 214 215 216
      }
      void SetIOPriority(Env::IOPriority pri) override {
        base_->SetIOPriority(pri);
      }
217 218 219
      Env::IOPriority GetIOPriority() override {
        return base_->GetIOPriority();
      }
A
Aaron Gao 已提交
220 221 222
      bool use_direct_io() const override {
        return base_->use_direct_io();
      }
223 224 225
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
226 227 228
      size_t GetUniqueId(char* id, size_t max_size) const override {
        return base_->GetUniqueId(id, max_size);
      }
229 230 231
    };
    class ManifestFile : public WritableFile {
     public:
232
      ManifestFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& b)
S
sdong 已提交
233
          : env_(env), base_(std::move(b)) {}
234 235 236 237 238 239 240
      Status Append(const Slice& data) override {
        if (env_->manifest_write_error_.load(std::memory_order_acquire)) {
          return Status::IOError("simulated writer error");
        } else {
          return base_->Append(data);
        }
      }
241 242 243 244 245 246
      Status Append(
          const Slice& data,
          const DataVerificationInfo& /*verification_info*/) override {
        return Append(data);
      }

247
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
248 249 250 251 252 253 254
      Status Close() override { return base_->Close(); }
      Status Flush() override { return base_->Flush(); }
      Status Sync() override {
        ++env_->sync_counter_;
        if (env_->manifest_sync_error_.load(std::memory_order_acquire)) {
          return Status::IOError("simulated sync error");
        } else {
255 256 257 258 259
          if (env_->skip_fsync_) {
            return Status::OK();
          } else {
            return base_->Sync();
          }
260 261 262
        }
      }
      uint64_t GetFileSize() override { return base_->GetFileSize(); }
263 264 265
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
266 267 268

     private:
      SpecialEnv* env_;
269
      std::unique_ptr<WritableFile> base_;
270 271 272
    };
    class WalFile : public WritableFile {
     public:
273
      WalFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& b)
274 275 276 277
          : env_(env), base_(std::move(b)) {
        env_->num_open_wal_file_.fetch_add(1);
      }
      virtual ~WalFile() { env_->num_open_wal_file_.fetch_add(-1); }
278
      Status Append(const Slice& data) override {
S
sdong 已提交
279 280 281 282
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT("SpecialEnv::WalFile::Append:1");
#endif
        Status s;
283
        if (env_->log_write_error_.load(std::memory_order_acquire)) {
S
sdong 已提交
284
          s = Status::IOError("simulated writer error");
285 286 287 288 289 290
        } else {
          int slowdown =
              env_->log_write_slowdown_.load(std::memory_order_acquire);
          if (slowdown > 0) {
            env_->SleepForMicroseconds(slowdown);
          }
S
sdong 已提交
291
          s = base_->Append(data);
292
        }
S
sdong 已提交
293 294 295 296
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT("SpecialEnv::WalFile::Append:2");
#endif
        return s;
297
      }
298 299 300 301 302
      Status Append(
          const Slice& data,
          const DataVerificationInfo& /* verification_info */) override {
        return Append(data);
      }
303
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
J
Jay Zhuang 已提交
304 305 306 307 308 309
      void PrepareWrite(size_t offset, size_t len) override {
        base_->PrepareWrite(offset, len);
      }
      void SetPreallocationBlockSize(size_t size) override {
        base_->SetPreallocationBlockSize(size);
      }
310 311 312 313
      Status Close() override {
// SyncPoint is not supported in Released Windows Mode.
#if !(defined NDEBUG) || !defined(OS_WIN)
        // Check preallocation size
J
Jay Zhuang 已提交
314 315
        size_t block_size, last_allocated_block;
        base_->GetPreallocationStatus(&block_size, &last_allocated_block);
316
        TEST_SYNC_POINT_CALLBACK("DBTestWalFile.GetPreallocationStatus",
J
Jay Zhuang 已提交
317
                                 &block_size);
318 319 320 321
#endif  // !(defined NDEBUG) || !defined(OS_WIN)

        return base_->Close();
      }
322 323 324
      Status Flush() override { return base_->Flush(); }
      Status Sync() override {
        ++env_->sync_counter_;
325
        if (env_->corrupt_in_sync_) {
326
          EXPECT_OK(Append(std::string(33000, ' ')));
327 328
          return Status::IOError("Ingested Sync Failure");
        }
329 330 331 332 333
        if (env_->skip_fsync_) {
          return Status::OK();
        } else {
          return base_->Sync();
        }
334
      }
335 336 337
      bool IsSyncThreadSafe() const override {
        return env_->is_wal_sync_thread_safe_.load();
      }
338 339 340
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
341 342 343

     private:
      SpecialEnv* env_;
344
      std::unique_ptr<WritableFile> base_;
345
    };
346 347 348 349 350
    class OtherFile : public WritableFile {
     public:
      OtherFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& b)
          : env_(env), base_(std::move(b)) {}
      Status Append(const Slice& data) override { return base_->Append(data); }
351 352 353 354 355
      Status Append(
          const Slice& data,
          const DataVerificationInfo& /*verification_info*/) override {
        return Append(data);
      }
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
      Status Close() override { return base_->Close(); }
      Status Flush() override { return base_->Flush(); }
      Status Sync() override {
        if (env_->skip_fsync_) {
          return Status::OK();
        } else {
          return base_->Sync();
        }
      }
      uint64_t GetFileSize() override { return base_->GetFileSize(); }
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }

     private:
      SpecialEnv* env_;
      std::unique_ptr<WritableFile> base_;
    };
375

376 377 378 379 380
    if (no_file_overwrite_.load(std::memory_order_acquire) &&
        target()->FileExists(f).ok()) {
      return Status::NotSupported("SpecialEnv::no_file_overwrite_ is true.");
    }

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    if (non_writeable_rate_.load(std::memory_order_acquire) > 0) {
      uint32_t random_number;
      {
        MutexLock l(&rnd_mutex_);
        random_number = rnd_.Uniform(100);
      }
      if (random_number < non_writeable_rate_.load()) {
        return Status::IOError("simulated random write error");
      }
    }

    new_writable_count_++;

    if (non_writable_count_.load() > 0) {
      non_writable_count_--;
      return Status::IOError("simulated write error");
    }

A
Aaron Gao 已提交
399 400 401 402 403 404 405 406
    EnvOptions optimized = soptions;
    if (strstr(f.c_str(), "MANIFEST") != nullptr ||
        strstr(f.c_str(), "log") != nullptr) {
      optimized.use_mmap_writes = false;
      optimized.use_direct_writes = false;
    }

    Status s = target()->NewWritableFile(f, r, optimized);
407 408 409 410 411 412 413
    if (s.ok()) {
      if (strstr(f.c_str(), ".sst") != nullptr) {
        r->reset(new SSTableFile(this, std::move(*r)));
      } else if (strstr(f.c_str(), "MANIFEST") != nullptr) {
        r->reset(new ManifestFile(this, std::move(*r)));
      } else if (strstr(f.c_str(), "log") != nullptr) {
        r->reset(new WalFile(this, std::move(*r)));
414 415
      } else {
        r->reset(new OtherFile(this, std::move(*r)));
416 417 418 419 420 421
      }
    }
    return s;
  }

  Status NewRandomAccessFile(const std::string& f,
422
                             std::unique_ptr<RandomAccessFile>* r,
423 424 425
                             const EnvOptions& soptions) override {
    class CountingFile : public RandomAccessFile {
     public:
426
      CountingFile(std::unique_ptr<RandomAccessFile>&& target,
427
                   anon::AtomicCounter* counter,
Y
Yi Wu 已提交
428
                   std::atomic<size_t>* bytes_read)
429 430 431
          : target_(std::move(target)),
            counter_(counter),
            bytes_read_(bytes_read) {}
432 433 434
      virtual Status Read(uint64_t offset, size_t n, Slice* result,
                          char* scratch) const override {
        counter_->Increment();
435 436 437
        Status s = target_->Read(offset, n, result, scratch);
        *bytes_read_ += result->size();
        return s;
438 439
      }

440 441 442 443 444 445
      virtual Status Prefetch(uint64_t offset, size_t n) override {
        Status s = target_->Prefetch(offset, n);
        *bytes_read_ += n;
        return s;
      }

446
     private:
447
      std::unique_ptr<RandomAccessFile> target_;
448
      anon::AtomicCounter* counter_;
Y
Yi Wu 已提交
449
      std::atomic<size_t>* bytes_read_;
450 451
    };

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    class RandomFailureFile : public RandomAccessFile {
     public:
      RandomFailureFile(std::unique_ptr<RandomAccessFile>&& target,
                        std::atomic<uint64_t>* failure_cnt, uint32_t fail_odd)
          : target_(std::move(target)),
            fail_cnt_(failure_cnt),
            fail_odd_(fail_odd) {}
      virtual Status Read(uint64_t offset, size_t n, Slice* result,
                          char* scratch) const override {
        if (Random::GetTLSInstance()->OneIn(fail_odd_)) {
          fail_cnt_->fetch_add(1);
          return Status::IOError("random error");
        }
        return target_->Read(offset, n, result, scratch);
      }

      virtual Status Prefetch(uint64_t offset, size_t n) override {
        return target_->Prefetch(offset, n);
      }

     private:
      std::unique_ptr<RandomAccessFile> target_;
      std::atomic<uint64_t>* fail_cnt_;
      uint32_t fail_odd_;
    };

478
    Status s = target()->NewRandomAccessFile(f, r, soptions);
479
    random_file_open_counter_++;
480 481 482 483 484 485 486 487
    if (s.ok()) {
      if (count_random_reads_) {
        r->reset(new CountingFile(std::move(*r), &random_read_counter_,
                                  &random_read_bytes_counter_));
      } else if (rand_reads_fail_odd_ > 0) {
        r->reset(new RandomFailureFile(std::move(*r), &num_reads_fails_,
                                       rand_reads_fail_odd_));
      }
488
    }
489

490 491 492
    if (s.ok() && soptions.compaction_readahead_size > 0) {
      compaction_readahead_size_ = soptions.compaction_readahead_size;
    }
493 494 495
    return s;
  }

S
Siying Dong 已提交
496
  virtual Status NewSequentialFile(const std::string& f,
497
                                   std::unique_ptr<SequentialFile>* r,
S
Siying Dong 已提交
498
                                   const EnvOptions& soptions) override {
499 500
    class CountingFile : public SequentialFile {
     public:
501
      CountingFile(std::unique_ptr<SequentialFile>&& target,
502 503 504 505 506 507 508 509 510
                   anon::AtomicCounter* counter)
          : target_(std::move(target)), counter_(counter) {}
      virtual Status Read(size_t n, Slice* result, char* scratch) override {
        counter_->Increment();
        return target_->Read(n, result, scratch);
      }
      virtual Status Skip(uint64_t n) override { return target_->Skip(n); }

     private:
511
      std::unique_ptr<SequentialFile> target_;
512 513 514 515 516 517 518 519 520 521 522 523
      anon::AtomicCounter* counter_;
    };

    Status s = target()->NewSequentialFile(f, r, soptions);
    if (s.ok() && count_sequential_reads_) {
      r->reset(new CountingFile(std::move(*r), &sequential_read_counter_));
    }
    return s;
  }

  virtual void SleepForMicroseconds(int micros) override {
    sleep_counter_.Increment();
M
Maysam Yabandeh 已提交
524
    if (no_slowdown_ || time_elapse_only_sleep_) {
525
      addon_microseconds_.fetch_add(micros);
526
    }
M
Maysam Yabandeh 已提交
527
    if (!no_slowdown_) {
528 529 530 531
      target()->SleepForMicroseconds(micros);
    }
  }

532 533 534 535 536 537 538 539 540 541 542 543
  void MockSleepForMicroseconds(int64_t micros) {
    sleep_counter_.Increment();
    assert(no_slowdown_);
    addon_microseconds_.fetch_add(micros);
  }

  void MockSleepForSeconds(int64_t seconds) {
    sleep_counter_.Increment();
    assert(no_slowdown_);
    addon_microseconds_.fetch_add(seconds * 1000000);
  }

544
  virtual Status GetCurrentTime(int64_t* unix_time) override {
545
    Status s;
546 547 548
    if (time_elapse_only_sleep_) {
      *unix_time = maybe_starting_time_;
    } else {
549 550
      s = target()->GetCurrentTime(unix_time);
    }
551
    if (s.ok()) {
552 553
      // mock microseconds elapsed to seconds of time
      *unix_time += addon_microseconds_.load() / 1000000;
554 555 556 557
    }
    return s;
  }

558 559 560 561 562
  virtual uint64_t NowCPUNanos() override {
    now_cpu_count_.fetch_add(1);
    return target()->NowCPUNanos();
  }

563
  virtual uint64_t NowNanos() override {
564
    return (time_elapse_only_sleep_ ? 0 : target()->NowNanos()) +
565
           addon_microseconds_.load() * 1000;
566 567 568
  }

  virtual uint64_t NowMicros() override {
569
    return (time_elapse_only_sleep_ ? 0 : target()->NowMicros()) +
570
           addon_microseconds_.load();
571 572
  }

573 574 575 576 577
  virtual Status DeleteFile(const std::string& fname) override {
    delete_count_.fetch_add(1);
    return target()->DeleteFile(fname);
  }

578
  void SetMockSleep(bool enabled = true) { no_slowdown_ = enabled; }
579

580 581 582 583 584 585 586 587 588 589 590
  Status NewDirectory(const std::string& name,
                      std::unique_ptr<Directory>* result) override {
    if (!skip_fsync_) {
      return target()->NewDirectory(name, result);
    } else {
      class NoopDirectory : public Directory {
       public:
        NoopDirectory() {}
        ~NoopDirectory() {}

        Status Fsync() override { return Status::OK(); }
591
        Status Close() override { return Status::OK(); }
592 593 594 595 596 597 598
      };

      result->reset(new NoopDirectory());
      return Status::OK();
    }
  }

599 600 601 602 603 604 605 606
  Status RenameFile(const std::string& src, const std::string& dest) override {
    rename_count_.fetch_add(1);
    if (rename_error_.load(std::memory_order_acquire)) {
      return Status::NotSupported("Simulated `RenameFile()` error.");
    }
    return target()->RenameFile(src, dest);
  }

607 608 609
  // Something to return when mocking current time
  const int64_t maybe_starting_time_;

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
  Random rnd_;
  port::Mutex rnd_mutex_;  // Lock to pretect rnd_

  // sstable Sync() calls are blocked while this pointer is non-nullptr.
  std::atomic<bool> delay_sstable_sync_;

  // Drop writes on the floor while this pointer is non-nullptr.
  std::atomic<bool> drop_writes_;

  // Simulate no-space errors while this pointer is non-nullptr.
  std::atomic<bool> no_space_;

  // Simulate non-writable file system while this pointer is non-nullptr
  std::atomic<bool> non_writable_;

  // Force sync of manifest files to fail while this pointer is non-nullptr
  std::atomic<bool> manifest_sync_error_;

  // Force write to manifest files to fail while this pointer is non-nullptr
  std::atomic<bool> manifest_write_error_;

  // Force write to log files to fail while this pointer is non-nullptr
  std::atomic<bool> log_write_error_;

634 635 636
  // Force `RenameFile()` to fail while this pointer is non-nullptr
  std::atomic<bool> rename_error_{false};

637 638 639
  // Slow down every log write, in micro-seconds.
  std::atomic<int> log_write_slowdown_;

640 641 642
  // If true, returns Status::NotSupported for file overwrite.
  std::atomic<bool> no_file_overwrite_;

643 644 645
  // Number of WAL files that are still open for write.
  std::atomic<int> num_open_wal_file_;

646
  bool count_random_reads_;
647 648
  uint32_t rand_reads_fail_odd_ = 0;
  std::atomic<uint64_t> num_reads_fails_;
649
  anon::AtomicCounter random_read_counter_;
Y
Yi Wu 已提交
650
  std::atomic<size_t> random_read_bytes_counter_;
651
  std::atomic<int> random_file_open_counter_;
652 653 654 655 656 657 658 659 660 661

  bool count_sequential_reads_;
  anon::AtomicCounter sequential_read_counter_;

  anon::AtomicCounter sleep_counter_;

  std::atomic<int64_t> bytes_written_;

  std::atomic<int> sync_counter_;

662 663 664
  // If true, all fsync to files and directories are skipped.
  bool skip_fsync_ = false;

665 666 667
  // If true, ingest the corruption to file during sync.
  bool corrupt_in_sync_ = false;

668 669 670 671 672 673 674 675
  std::atomic<uint32_t> non_writeable_rate_;

  std::atomic<uint32_t> new_writable_count_;

  std::atomic<uint32_t> non_writable_count_;

  std::function<void()>* table_write_callback_;

676 677
  std::atomic<int> now_cpu_count_;

678 679
  std::atomic<int> delete_count_;

680 681
  std::atomic<int> rename_count_{0};

S
sdong 已提交
682
  std::atomic<bool> is_wal_sync_thread_safe_{true};
683

684
  std::atomic<size_t> compaction_readahead_size_{};
685 686 687 688 689 690 691 692 693 694

 private:  // accessing these directly is prone to error
  friend class DBTestBase;

  std::atomic<int64_t> addon_microseconds_{0};

  // Do not modify in the env of a running DB (could cause deadlock)
  std::atomic<bool> time_elapse_only_sleep_;

  bool no_slowdown_;
695 696
};

Y
Yi Wu 已提交
697
#ifndef ROCKSDB_LITE
698 699 700 701 702 703 704 705 706 707 708
class FileTemperatureTestFS : public FileSystemWrapper {
 public:
  explicit FileTemperatureTestFS(const std::shared_ptr<FileSystem>& fs)
      : FileSystemWrapper(fs) {}

  static const char* kClassName() { return "FileTemperatureTestFS"; }
  const char* Name() const override { return kClassName(); }

  IOStatus NewSequentialFile(const std::string& fname, const FileOptions& opts,
                             std::unique_ptr<FSSequentialFile>* result,
                             IODebugContext* dbg) override {
709
    IOStatus s = target()->NewSequentialFile(fname, opts, result, dbg);
710 711
    uint64_t number;
    FileType type;
712 713 714 715 716
    if (ParseFileName(GetFileName(fname), &number, &type) &&
        type == kTableFile) {
      MutexLock lock(&mu_);
      requested_sst_file_temperatures_.emplace_back(number, opts.temperature);
      if (s.ok()) {
717 718 719 720 721 722 723 724 725 726
        if (opts.temperature != Temperature::kUnknown) {
          // Be extra picky and don't open if a wrong non-unknown temperature is
          // provided
          auto e = current_sst_file_temperatures_.find(number);
          if (e != current_sst_file_temperatures_.end() &&
              e->second != opts.temperature) {
            result->reset();
            return IOStatus::PathNotFound("Temperature mismatch on " + fname);
          }
        }
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        *result = WrapWithTemperature<FSSequentialFileOwnerWrapper>(
            number, std::move(*result));
      }
    }
    return s;
  }

  IOStatus NewRandomAccessFile(const std::string& fname,
                               const FileOptions& opts,
                               std::unique_ptr<FSRandomAccessFile>* result,
                               IODebugContext* dbg) override {
    IOStatus s = target()->NewRandomAccessFile(fname, opts, result, dbg);
    uint64_t number;
    FileType type;
    if (ParseFileName(GetFileName(fname), &number, &type) &&
        type == kTableFile) {
      MutexLock lock(&mu_);
      requested_sst_file_temperatures_.emplace_back(number, opts.temperature);
      if (s.ok()) {
746 747 748 749 750 751 752 753 754 755
        if (opts.temperature != Temperature::kUnknown) {
          // Be extra picky and don't open if a wrong non-unknown temperature is
          // provided
          auto e = current_sst_file_temperatures_.find(number);
          if (e != current_sst_file_temperatures_.end() &&
              e->second != opts.temperature) {
            result->reset();
            return IOStatus::PathNotFound("Temperature mismatch on " + fname);
          }
        }
756 757 758
        *result = WrapWithTemperature<FSRandomAccessFileOwnerWrapper>(
            number, std::move(*result));
      }
759
    }
760
    return s;
761 762
  }

763 764 765 766 767 768 769 770 771
  void PopRequestedSstFileTemperatures(
      std::vector<std::pair<uint64_t, Temperature>>* out = nullptr) {
    MutexLock lock(&mu_);
    if (out) {
      *out = std::move(requested_sst_file_temperatures_);
      assert(requested_sst_file_temperatures_.empty());
    } else {
      requested_sst_file_temperatures_.clear();
    }
772 773
  }

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  IOStatus NewWritableFile(const std::string& fname, const FileOptions& opts,
                           std::unique_ptr<FSWritableFile>* result,
                           IODebugContext* dbg) override {
    uint64_t number;
    FileType type;
    if (ParseFileName(GetFileName(fname), &number, &type) &&
        type == kTableFile) {
      MutexLock lock(&mu_);
      current_sst_file_temperatures_[number] = opts.temperature;
    }
    return target()->NewWritableFile(fname, opts, result, dbg);
  }

  void CopyCurrentSstFileTemperatures(std::map<uint64_t, Temperature>* out) {
    MutexLock lock(&mu_);
    *out = current_sst_file_temperatures_;
  }

  void OverrideSstFileTemperature(uint64_t number, Temperature temp) {
    MutexLock lock(&mu_);
    current_sst_file_temperatures_[number] = temp;
795 796 797
  }

 protected:
798 799 800 801
  port::Mutex mu_;
  std::vector<std::pair<uint64_t, Temperature>>
      requested_sst_file_temperatures_;
  std::map<uint64_t, Temperature> current_sst_file_temperatures_;
802 803 804 805 806 807 808 809

  std::string GetFileName(const std::string& fname) {
    auto filename = fname.substr(fname.find_last_of(kFilePathSeparator) + 1);
    // workaround only for Windows that the file path could contain both Windows
    // FilePathSeparator and '/'
    filename = filename.substr(filename.find_last_of('/') + 1);
    return filename;
  }
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

  template <class FileOwnerWrapperT, /*inferred*/ class FileT>
  std::unique_ptr<FileT> WrapWithTemperature(uint64_t number,
                                             std::unique_ptr<FileT>&& t) {
    class FileWithTemp : public FileOwnerWrapperT {
     public:
      FileWithTemp(FileTemperatureTestFS* fs, uint64_t number,
                   std::unique_ptr<FileT>&& t)
          : FileOwnerWrapperT(std::move(t)), fs_(fs), number_(number) {}

      Temperature GetTemperature() const override {
        MutexLock lock(&fs_->mu_);
        return fs_->current_sst_file_temperatures_[number_];
      }

     private:
      FileTemperatureTestFS* fs_;
      uint64_t number_;
    };
    return std::make_unique<FileWithTemp>(this, number, std::move(t));
  }
831 832
};

Y
Yi Wu 已提交
833 834 835
class OnFileDeletionListener : public EventListener {
 public:
  OnFileDeletionListener() : matched_count_(0), expected_file_name_("") {}
836 837
  const char* Name() const override { return kClassName(); }
  static const char* kClassName() { return "OnFileDeletionListener"; }
Y
Yi Wu 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

  void SetExpectedFileName(const std::string file_name) {
    expected_file_name_ = file_name;
  }

  void VerifyMatchedCount(size_t expected_value) {
    ASSERT_EQ(matched_count_, expected_value);
  }

  void OnTableFileDeleted(const TableFileDeletionInfo& info) override {
    if (expected_file_name_ != "") {
      ASSERT_EQ(expected_file_name_, info.file_path);
      expected_file_name_ = "";
      matched_count_++;
    }
  }

 private:
  size_t matched_count_;
  std::string expected_file_name_;
};
859 860 861

class FlushCounterListener : public EventListener {
 public:
862 863
  const char* Name() const override { return kClassName(); }
  static const char* kClassName() { return "FlushCounterListener"; }
864 865 866 867 868 869 870 871
  std::atomic<int> count{0};
  std::atomic<FlushReason> expected_flush_reason{FlushReason::kOthers};

  void OnFlushBegin(DB* /*db*/, const FlushJobInfo& flush_job_info) override {
    count++;
    ASSERT_EQ(expected_flush_reason.load(), flush_job_info.flush_reason);
  }
};
Y
Yi Wu 已提交
872
#endif
Y
Yi Wu 已提交
873

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
// A test merge operator mimics put but also fails if one of merge operands is
// "corrupted".
class TestPutOperator : public MergeOperator {
 public:
  virtual bool FullMergeV2(const MergeOperationInput& merge_in,
                           MergeOperationOutput* merge_out) const override {
    if (merge_in.existing_value != nullptr &&
        *(merge_in.existing_value) == "corrupted") {
      return false;
    }
    for (auto value : merge_in.operand_list) {
      if (value == "corrupted") {
        return false;
      }
    }
    merge_out->existing_operand = merge_in.operand_list.back();
    return true;
  }

  virtual const char* Name() const override { return "TestPutOperator"; }
};

896 897 898 899 900 901 902 903 904
// A wrapper around Cache that can easily be extended with instrumentation,
// etc.
class CacheWrapper : public Cache {
 public:
  explicit CacheWrapper(std::shared_ptr<Cache> target)
      : target_(std::move(target)) {}

  const char* Name() const override { return target_->Name(); }

905
  using Cache::Insert;
906 907 908 909 910 911 912
  Status Insert(const Slice& key, void* value, size_t charge,
                void (*deleter)(const Slice& key, void* value),
                Handle** handle = nullptr,
                Priority priority = Priority::LOW) override {
    return target_->Insert(key, value, charge, deleter, handle, priority);
  }

913
  using Cache::Lookup;
914 915 916 917 918 919
  Handle* Lookup(const Slice& key, Statistics* stats = nullptr) override {
    return target_->Lookup(key, stats);
  }

  bool Ref(Handle* handle) override { return target_->Ref(handle); }

920
  using Cache::Release;
921 922
  bool Release(Handle* handle, bool erase_if_last_ref = false) override {
    return target_->Release(handle, erase_if_last_ref);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
  }

  void* Value(Handle* handle) override { return target_->Value(handle); }

  void Erase(const Slice& key) override { target_->Erase(key); }
  uint64_t NewId() override { return target_->NewId(); }

  void SetCapacity(size_t capacity) override { target_->SetCapacity(capacity); }

  void SetStrictCapacityLimit(bool strict_capacity_limit) override {
    target_->SetStrictCapacityLimit(strict_capacity_limit);
  }

  bool HasStrictCapacityLimit() const override {
    return target_->HasStrictCapacityLimit();
  }

  size_t GetCapacity() const override { return target_->GetCapacity(); }

  size_t GetUsage() const override { return target_->GetUsage(); }

  size_t GetUsage(Handle* handle) const override {
    return target_->GetUsage(handle);
  }

  size_t GetPinnedUsage() const override { return target_->GetPinnedUsage(); }

  size_t GetCharge(Handle* handle) const override {
    return target_->GetCharge(handle);
  }

954 955 956 957
  DeleterFn GetDeleter(Handle* handle) const override {
    return target_->GetDeleter(handle);
  }

958 959 960 961 962
  void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
                              bool thread_safe) override {
    target_->ApplyToAllCacheEntries(callback, thread_safe);
  }

963 964 965 966 967 968 969
  void ApplyToAllEntries(
      const std::function<void(const Slice& key, void* value, size_t charge,
                               DeleterFn deleter)>& callback,
      const ApplyToAllEntriesOptions& opts) override {
    target_->ApplyToAllEntries(callback, opts);
  }

970 971 972 973 974 975
  void EraseUnRefEntries() override { target_->EraseUnRefEntries(); }

 protected:
  std::shared_ptr<Cache> target_;
};

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
/*
 * A cache wrapper that tracks certain CacheEntryRole's cache charge, its
 * peaks and increments
 *
 *        p0
 *       / \   p1
 *      /   \  /\
 *     /     \/  \
 *  a /       b   \
 * peaks = {p0, p1}
 * increments = {p1-a, p2-b}
 */
template <CacheEntryRole R>
class TargetCacheChargeTrackingCache : public CacheWrapper {
 public:
  explicit TargetCacheChargeTrackingCache(std::shared_ptr<Cache> target);

  using Cache::Insert;
  Status Insert(const Slice& key, void* value, size_t charge,
                void (*deleter)(const Slice& key, void* value),
                Handle** handle = nullptr,
                Priority priority = Priority::LOW) override;

  using Cache::Release;
  bool Release(Handle* handle, bool erase_if_last_ref = false) override;

  std::size_t GetCacheCharge() { return cur_cache_charge_; }

  std::deque<std::size_t> GetChargedCachePeaks() { return cache_charge_peaks_; }

  std::size_t GetChargedCacheIncrementSum() {
    return cache_charge_increments_sum_;
  }

 private:
  static const Cache::DeleterFn kNoopDeleter;

  std::size_t cur_cache_charge_;
  std::size_t cache_charge_peak_;
  std::size_t cache_charge_increment_;
  bool last_peak_tracked_;
  std::deque<std::size_t> cache_charge_peaks_;
  std::size_t cache_charge_increments_sum_;
};

1021
class DBTestBase : public testing::Test {
Y
Yi Wu 已提交
1022
 public:
1023
  // Sequence of option configurations to try
Y
Yi Wu 已提交
1024
  enum OptionConfig : int {
1025 1026 1027 1028 1029
    kDefault = 0,
    kBlockBasedTableWithPrefixHashIndex = 1,
    kBlockBasedTableWithWholeKeyHashIndex = 2,
    kPlainTableFirstBytePrefix = 3,
    kPlainTableCappedPrefix = 4,
1030 1031 1032 1033
    kPlainTableCappedPrefixNonMmap = 5,
    kPlainTableAllBytesPrefix = 6,
    kVectorRep = 7,
    kHashLinkList = 8,
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    kMergePut = 9,
    kFilter = 10,
    kFullFilterWithNewTableReaderForCompactions = 11,
    kUncompressed = 12,
    kNumLevel_3 = 13,
    kDBLogDir = 14,
    kWalDirAndMmapReads = 15,
    kManifestFileSize = 16,
    kPerfOptions = 17,
    kHashSkipList = 18,
    kUniversalCompaction = 19,
    kUniversalCompactionMultiLevel = 20,
    kCompressedBlockCache = 21,
    kInfiniteMaxOpenFiles = 22,
1048
    kXXH3Checksum = 23,
1049 1050 1051 1052 1053 1054 1055
    kFIFOCompaction = 24,
    kOptimizeFiltersForHits = 25,
    kRowCache = 26,
    kRecycleLogFiles = 27,
    kConcurrentSkipList = 28,
    kPipelinedWrite = 29,
    kConcurrentWALWrites = 30,
1056 1057 1058 1059
    kDirectIO,
    kLevelSubcompactions,
    kBlockBasedTableWithIndexRestartInterval,
    kBlockBasedTableWithPartitionedIndex,
1060
    kBlockBasedTableWithPartitionedIndexFormat4,
1061
    kBlockBasedTableWithLatestFormat,
1062
    kPartitionedFilterWithNewTableReaderForCompactions,
1063
    kUniversalSubcompactions,
M
Maysam Yabandeh 已提交
1064
    kUnorderedWrite,
1065
    // This must be the last line
1066
    kEnd,
1067 1068 1069 1070 1071
  };

 public:
  std::string dbname_;
  std::string alternative_wal_dir_;
S
sdong 已提交
1072
  std::string alternative_db_log_dir_;
1073
  MockEnv* mem_env_;
E
Ewout Prangsma 已提交
1074
  Env* encrypted_env_;
1075
  SpecialEnv* env_;
1076
  std::shared_ptr<Env> env_guard_;
1077 1078 1079
  DB* db_;
  std::vector<ColumnFamilyHandle*> handles_;

Y
Yi Wu 已提交
1080
  int option_config_;
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  Options last_options_;

  // Skip some options, as they may not be applicable to a specific test.
  // To add more skip constants, use values 4, 8, 16, etc.
  enum OptionSkip {
    kNoSkip = 0,
    kSkipDeletesFilterFirst = 1,
    kSkipUniversalCompaction = 2,
    kSkipMergePut = 4,
    kSkipPlainTable = 8,
    kSkipHashIndex = 16,
    kSkipNoSeekToLast = 32,
    kSkipFIFOCompaction = 128,
    kSkipMmapReads = 256,
  };

1097 1098 1099 1100 1101 1102 1103
  const int kRangeDelSkipConfigs =
      // Plain tables do not support range deletions.
      kSkipPlainTable |
      // MmapReads disables the iterator pinning that RangeDelAggregator
      // requires.
      kSkipMmapReads;

S
sdong 已提交
1104 1105 1106 1107
  // `env_do_fsync` decides whether the special Env would do real
  // fsync for files and directories. Skipping fsync can speed up
  // tests, but won't cover the exact fsync logic.
  DBTestBase(const std::string path, bool env_do_fsync);
1108 1109 1110

  ~DBTestBase();

1111 1112 1113 1114 1115 1116
  static std::string Key(int i) {
    char buf[100];
    snprintf(buf, sizeof(buf), "key%06d", i);
    return std::string(buf);
  }

S
sdong 已提交
1117 1118
  static bool ShouldSkipOptions(int option_config, int skip_mask = kNoSkip);

1119 1120 1121 1122
  // Switch to a fresh database with the next option configuration to
  // test.  Return false if there are no more configurations to test.
  bool ChangeOptions(int skip_mask = kNoSkip);

S
Siying Dong 已提交
1123
  // Switch between different compaction styles.
1124 1125
  bool ChangeCompactOptions();

S
Siying Dong 已提交
1126 1127 1128
  // Switch between different WAL-realted options.
  bool ChangeWalOptions();

1129 1130 1131 1132
  // Switch between different filter policy
  // Jump from kDefault to kFilter to kFullFilter
  bool ChangeFilterOptions();

1133 1134 1135
  // Switch between different DB options for file ingestion tests.
  bool ChangeOptionsForFileIngestionTest();

1136
  // Return the current option configuration.
Y
Yi Wu 已提交
1137 1138 1139 1140 1141 1142 1143
  Options CurrentOptions(const anon::OptionsOverride& options_override =
                             anon::OptionsOverride()) const;

  Options CurrentOptions(const Options& default_options,
                         const anon::OptionsOverride& options_override =
                             anon::OptionsOverride()) const;

1144
  Options GetDefaultOptions() const;
1145

1146 1147 1148 1149 1150
  Options GetOptions(int option_config) const {
    return GetOptions(option_config, GetDefaultOptions());
  }

  Options GetOptions(int option_config, const Options& default_options,
Y
Yi Wu 已提交
1151 1152
                     const anon::OptionsOverride& options_override =
                         anon::OptionsOverride()) const;
1153

1154
  DBImpl* dbfull() { return static_cast_with_check<DBImpl>(db_); }
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

  void CreateColumnFamilies(const std::vector<std::string>& cfs,
                            const Options& options);

  void CreateAndReopenWithCF(const std::vector<std::string>& cfs,
                             const Options& options);

  void ReopenWithColumnFamilies(const std::vector<std::string>& cfs,
                                const std::vector<Options>& options);

  void ReopenWithColumnFamilies(const std::vector<std::string>& cfs,
                                const Options& options);

S
sdong 已提交
1168 1169
  Status TryReopenWithColumnFamilies(const std::vector<std::string>& cfs,
                                     const std::vector<Options>& options);
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

  Status TryReopenWithColumnFamilies(const std::vector<std::string>& cfs,
                                     const Options& options);

  void Reopen(const Options& options);

  void Close();

  void DestroyAndReopen(const Options& options);

1180
  void Destroy(const Options& options, bool delete_cf_paths = false);
1181 1182 1183 1184 1185

  Status ReadOnlyReopen(const Options& options);

  Status TryReopen(const Options& options);

A
Aaron Gao 已提交
1186 1187
  bool IsDirectIOSupported();

E
Ewout Prangsma 已提交
1188 1189
  bool IsMemoryMappedAccessSupported() const;

1190 1191
  Status Flush(int cf = 0);

Y
Yanqin Jin 已提交
1192 1193
  Status Flush(const std::vector<int>& cf_ids);

1194 1195 1196 1197 1198
  Status Put(const Slice& k, const Slice& v, WriteOptions wo = WriteOptions());

  Status Put(int cf, const Slice& k, const Slice& v,
             WriteOptions wo = WriteOptions());

1199 1200 1201 1202 1203 1204
  Status Merge(const Slice& k, const Slice& v,
               WriteOptions wo = WriteOptions());

  Status Merge(int cf, const Slice& k, const Slice& v,
               WriteOptions wo = WriteOptions());

1205 1206 1207 1208
  Status Delete(const std::string& k);

  Status Delete(int cf, const std::string& k);

A
Andres Noetzli 已提交
1209 1210 1211 1212
  Status SingleDelete(const std::string& k);

  Status SingleDelete(int cf, const std::string& k);

1213 1214 1215 1216 1217
  std::string Get(const std::string& k, const Snapshot* snapshot = nullptr);

  std::string Get(int cf, const std::string& k,
                  const Snapshot* snapshot = nullptr);

1218 1219
  Status Get(const std::string& k, PinnableSlice* v);

A
Anand Ananthabhotla 已提交
1220 1221
  std::vector<std::string> MultiGet(std::vector<int> cfs,
                                    const std::vector<std::string>& k,
1222
                                    const Snapshot* snapshot,
1223 1224
                                    const bool batched,
                                    const bool async = false);
A
Anand Ananthabhotla 已提交
1225

1226
  std::vector<std::string> MultiGet(const std::vector<std::string>& k,
1227 1228
                                    const Snapshot* snapshot = nullptr,
                                    const bool async = false);
1229

1230 1231 1232 1233
  uint64_t GetNumSnapshots();

  uint64_t GetTimeOldestSnapshots();

1234 1235
  uint64_t GetSequenceOldestSnapshots();

1236 1237 1238 1239 1240 1241
  // Return a string that contains all key,value pairs in order,
  // formatted like "(k1->v1)(k2->v2)".
  std::string Contents(int cf = 0);

  std::string AllEntriesFor(const Slice& user_key, int cf = 0);

1242
#ifndef ROCKSDB_LITE
1243 1244 1245 1246 1247 1248
  int NumSortedRuns(int cf = 0);

  uint64_t TotalSize(int cf = 0);

  uint64_t SizeAtLevel(int level);

V
Vasili Svirski 已提交
1249
  size_t TotalLiveFiles(int cf = 0);
1250

1251 1252 1253 1254
  size_t CountLiveFiles();

  int NumTableFilesAtLevel(int level, int cf = 0);

1255 1256
  double CompressionRatioAtLevel(int level, int cf = 0);

1257
  int TotalTableFiles(int cf = 0, int levels = -1);
Y
Yi Wu 已提交
1258
#endif  // ROCKSDB_LITE
1259

1260 1261
  std::vector<uint64_t> GetBlobFileNumbers();

1262 1263 1264 1265 1266
  // Return spread of files per level
  std::string FilesPerLevel(int cf = 0);

  size_t CountFiles();

1267 1268 1269 1270 1271 1272 1273
  Status CountFiles(size_t* count);

  Status Size(const Slice& start, const Slice& limit, uint64_t* size) {
    return Size(start, limit, 0, size);
  }

  Status Size(const Slice& start, const Slice& limit, int cf, uint64_t* size);
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291

  void Compact(int cf, const Slice& start, const Slice& limit,
               uint32_t target_path_id);

  void Compact(int cf, const Slice& start, const Slice& limit);

  void Compact(const Slice& start, const Slice& limit);

  // Do n memtable compactions, each of which produces an sstable
  // covering the range [small,large].
  void MakeTables(int n, const std::string& small, const std::string& large,
                  int cf = 0);

  // Prevent pushing of new sstables into deeper levels by adding
  // tables that cover a specified range to all levels.
  void FillLevels(const std::string& smallest, const std::string& largest,
                  int cf);

1292 1293
  void MoveFilesToLevel(int level, int cf = 0);

Y
Yi Wu 已提交
1294
#ifndef ROCKSDB_LITE
1295
  void DumpFileCounts(const char* label);
Y
Yi Wu 已提交
1296
#endif  // ROCKSDB_LITE
1297 1298 1299

  std::string DumpSSTableList();

1300 1301
  static void GetSstFiles(Env* env, std::string path,
                          std::vector<std::string>* files);
D
dyniusz 已提交
1302

1303 1304 1305 1306 1307
  int GetSstFileCount(std::string path);

  // this will generate non-overlapping files since it keeps increasing key_idx
  void GenerateNewFile(Random* rnd, int* key_idx, bool nowait = false);

1308 1309
  void GenerateNewFile(int fd, Random* rnd, int* key_idx, bool nowait = false);

1310
  static const int kNumKeysByGenerateNewRandomFile;
K
krad 已提交
1311
  static const int KNumKeysByGenerateNewFile = 100;
1312

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  void GenerateNewRandomFile(Random* rnd, bool nowait = false);

  std::string IterStatus(Iterator* iter);

  Options OptionsForLogIterTest();

  std::string DummyString(size_t len, char c = 'a');

  void VerifyIterLast(std::string expected_key, int cf = 0);

  // Used to test InplaceUpdate

  // If previous value is nullptr or delta is > than previous value,
  //   sets newValue with delta
  // If previous value is not empty,
  //   updates previous value with 'b' string of previous value size - 1.
S
sdong 已提交
1329 1330 1331
  static UpdateStatus updateInPlaceSmallerSize(char* prevValue,
                                               uint32_t* prevSize, Slice delta,
                                               std::string* newValue);
1332

S
sdong 已提交
1333 1334 1335 1336
  static UpdateStatus updateInPlaceSmallerVarintSize(char* prevValue,
                                                     uint32_t* prevSize,
                                                     Slice delta,
                                                     std::string* newValue);
1337

S
sdong 已提交
1338 1339 1340
  static UpdateStatus updateInPlaceLargerSize(char* prevValue,
                                              uint32_t* prevSize, Slice delta,
                                              std::string* newValue);
1341

S
sdong 已提交
1342 1343
  static UpdateStatus updateInPlaceNoAction(char* prevValue, uint32_t* prevSize,
                                            Slice delta, std::string* newValue);
1344 1345 1346 1347 1348 1349

  // Utility method to test InplaceUpdate
  void validateNumberOfEntries(int numValues, int cf = 0);

  void CopyFile(const std::string& source, const std::string& destination,
                uint64_t size = 0);
1350

1351 1352 1353
  Status GetAllDataFiles(const FileType file_type,
                         std::unordered_map<std::string, uint64_t>* sst_files,
                         uint64_t* total_size = nullptr);
Y
Yi Wu 已提交
1354 1355 1356

  std::vector<std::uint64_t> ListTableFiles(Env* env, const std::string& path);

I
Islam AbdelRahman 已提交
1357 1358 1359 1360
  void VerifyDBFromMap(
      std::map<std::string, std::string> true_data,
      size_t* total_reads_res = nullptr, bool tailing_iter = false,
      std::map<std::string, Status> status = std::map<std::string, Status>());
1361 1362 1363

  void VerifyDBInternal(
      std::vector<std::pair<std::string, std::string>> true_data);
1364

Y
Yi Wu 已提交
1365 1366 1367
#ifndef ROCKSDB_LITE
  uint64_t GetNumberOfSstFilesForColumnFamily(DB* db,
                                              std::string column_family_name);
1368 1369

  uint64_t GetSstSizeHelper(Temperature temperature);
Y
Yi Wu 已提交
1370 1371 1372 1373 1374
#endif  // ROCKSDB_LITE

  uint64_t TestGetTickerCount(const Options& options, Tickers ticker_type) {
    return options.statistics->getTickerCount(ticker_type);
  }
1375 1376 1377 1378 1379

  uint64_t TestGetAndResetTickerCount(const Options& options,
                                      Tickers ticker_type) {
    return options.statistics->getAndResetTickerCount(ticker_type);
  }
1380 1381 1382 1383 1384 1385 1386 1387 1388

  // Note: reverting this setting within the same test run is not yet
  // supported
  void SetTimeElapseOnlySleepOnReopen(DBOptions* options);

 private:  // Prone to error on direct use
  void MaybeInstallTimeElapseOnlySleep(const DBOptions& options);

  bool time_elapse_only_sleep_on_reopen_ = false;
1389 1390
};

1391 1392 1393 1394
// For verifying that all files generated by current version have SST
// unique ids.
void VerifySstUniqueIds(const TablePropertiesCollection& props);

1395
}  // namespace ROCKSDB_NAMESPACE