db_test_util.h 31.2 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 11 12 13 14 15 16 17 18
//
// 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
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <fcntl.h>
#include <inttypes.h>

#include <algorithm>
19
#include <map>
20 21 22 23 24 25 26 27 28
#include <set>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>

#include "db/db_impl.h"
#include "db/dbformat.h"
29
#include "env/mock_env.h"
30
#include "memtable/hash_linklist_rep.h"
31 32
#include "rocksdb/cache.h"
#include "rocksdb/compaction_filter.h"
A
agiardullo 已提交
33
#include "rocksdb/convenience.h"
34 35 36 37 38
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/filter_policy.h"
#include "rocksdb/options.h"
#include "rocksdb/slice.h"
39
#include "rocksdb/sst_file_writer.h"
Y
Yi Wu 已提交
40
#include "rocksdb/statistics.h"
41 42 43 44 45
#include "rocksdb/table.h"
#include "rocksdb/utilities/checkpoint.h"
#include "table/block_based_table_factory.h"
#include "table/mock_table.h"
#include "table/plain_table_factory.h"
S
sdong 已提交
46
#include "table/scoped_arena_iterator.h"
47
#include "util/compression.h"
48
#include "util/filename.h"
49
#include "util/mock_time_env.h"
50
#include "util/mutexlock.h"
S
sdong 已提交
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#include "util/string_util.h"
#include "util/sync_point.h"
#include "util/testharness.h"
#include "util/testutil.h"
#include "utilities/merge_operators.h"

namespace rocksdb {

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();
83 84
      cond_count_.TimedWait(now + /*1s*/ 1 * 1000 * 1000);
      if (env_->NowMicros() - start > /*10s*/ 10 * 1000 * 1000) {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        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 已提交
110 111
  // These will be used only if filter_policy is set
  bool partition_filters = false;
M
Maysam Yabandeh 已提交
112
  uint64_t metadata_block_size = 1024;
113 114 115 116 117 118 119

  // 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 已提交
120 121
enum SkipPolicy { kSkipNone = 0, kSkipNoSnapshot = 1, kSkipNoPrefix = 2 };

122 123 124
// A hacky skip list mem table that triggers flush after number of entries.
class SpecialMemTableRep : public MemTableRep {
 public:
125 126
  explicit SpecialMemTableRep(Allocator* allocator, MemTableRep* memtable,
                              int num_entries_flush)
127 128 129 130 131 132 133 134 135 136 137
      : MemTableRep(allocator),
        memtable_(memtable),
        num_entries_flush_(num_entries_flush),
        num_entries_(0) {}

  virtual KeyHandle Allocate(const size_t len, char** buf) override {
    return memtable_->Allocate(len, buf);
  }

  // Insert key into the list.
  // REQUIRES: nothing that compares equal to key is currently in the list.
M
Maysam Yabandeh 已提交
138
  virtual void Insert(KeyHandle handle) override {
139
    num_entries_++;
M
Maysam Yabandeh 已提交
140
    memtable_->Insert(handle);
141 142
  }

M
Maysam Yabandeh 已提交
143 144 145 146 147
  void InsertConcurrently(KeyHandle handle) override {
    num_entries_++;
    memtable_->Insert(handle);
  }

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  // Returns true iff an entry that compares equal to key is in the list.
  virtual bool Contains(const char* key) const override {
    return memtable_->Contains(key);
  }

  virtual size_t ApproximateMemoryUsage() override {
    // Return a high memory usage when number of entries exceeds the threshold
    // to trigger a flush.
    return (num_entries_ < num_entries_flush_) ? 0 : 1024 * 1024 * 1024;
  }

  virtual void Get(const LookupKey& k, void* callback_args,
                   bool (*callback_func)(void* arg,
                                         const char* entry)) override {
    memtable_->Get(k, callback_args, callback_func);
  }

  uint64_t ApproximateNumEntries(const Slice& start_ikey,
                                 const Slice& end_ikey) override {
    return memtable_->ApproximateNumEntries(start_ikey, end_ikey);
  }

  virtual MemTableRep::Iterator* GetIterator(Arena* arena = nullptr) override {
    return memtable_->GetIterator(arena);
  }

  virtual ~SpecialMemTableRep() override {}

 private:
177
  std::unique_ptr<MemTableRep> memtable_;
178 179 180 181 182 183 184 185 186 187 188 189 190
  int num_entries_flush_;
  int num_entries_;
};

// The factory for the hacky skip list mem table that triggers flush after
// number of entries exceeds a threshold.
class SpecialSkipListFactory : public MemTableRepFactory {
 public:
  // After number of inserts exceeds `num_entries_flush` in a mem table, trigger
  // flush.
  explicit SpecialSkipListFactory(int num_entries_flush)
      : num_entries_flush_(num_entries_flush) {}

191
  using MemTableRepFactory::CreateMemTableRep;
192
  virtual MemTableRep* CreateMemTableRep(
193
      const MemTableRep::KeyComparator& compare, Allocator* allocator,
A
Andrew Kryczka 已提交
194
      const SliceTransform* transform, Logger* /*logger*/) override {
195 196 197 198 199 200
    return new SpecialMemTableRep(
        allocator, factory_.CreateMemTableRep(compare, allocator, transform, 0),
        num_entries_flush_);
  }
  virtual const char* Name() const override { return "SkipListFactory"; }

201 202 203 204
  bool IsInsertConcurrentlySupported() const override {
    return factory_.IsInsertConcurrentlySupported();
  }

205 206 207 208 209
 private:
  SkipListFactory factory_;
  int num_entries_flush_;
};

210 211 212 213 214
// Special Env used to delay background operations
class SpecialEnv : public EnvWrapper {
 public:
  explicit SpecialEnv(Env* base);

215
  Status NewWritableFile(const std::string& f, std::unique_ptr<WritableFile>* r,
216 217 218 219
                         const EnvOptions& soptions) override {
    class SSTableFile : public WritableFile {
     private:
      SpecialEnv* env_;
220
      std::unique_ptr<WritableFile> base_;
221 222

     public:
223
      SSTableFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& base)
S
sdong 已提交
224
          : env_(env), base_(std::move(base)) {}
225 226 227 228 229 230 231 232
      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)) {
233
          return Status::NoSpace("No space left on device");
234 235 236 237 238
        } else {
          env_->bytes_written_ += data.size();
          return base_->Append(data);
        }
      }
A
Aaron Gao 已提交
239
      Status PositionedAppend(const Slice& data, uint64_t offset) override {
A
Aaron Gao 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252
        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);
        }
      }
S
sdong 已提交
253
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
254 255 256 257 258 259 260
      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;
      }
261
      Status Close() override {
262 263
// SyncPoint is not supported in Released Windows Mode.
#if !(defined NDEBUG) || !defined(OS_WIN)
264 265 266 267 268
        // 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);
269
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
270 271 272 273 274
        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;
275 276 277 278 279 280 281
      }
      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);
        }
282 283 284 285 286
        Status s = base_->Sync();
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT_CALLBACK("SpecialEnv::SStableFile::Sync", &s);
#endif  // !(defined NDEBUG) || !defined(OS_WIN)
        return s;
287 288 289 290
      }
      void SetIOPriority(Env::IOPriority pri) override {
        base_->SetIOPriority(pri);
      }
291 292 293
      Env::IOPriority GetIOPriority() override {
        return base_->GetIOPriority();
      }
A
Aaron Gao 已提交
294 295 296
      bool use_direct_io() const override {
        return base_->use_direct_io();
      }
297 298 299
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
300 301 302
    };
    class ManifestFile : public WritableFile {
     public:
303
      ManifestFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& b)
S
sdong 已提交
304
          : env_(env), base_(std::move(b)) {}
305 306 307 308 309 310 311
      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);
        }
      }
312
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
313 314 315 316 317 318 319 320 321 322 323
      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 {
          return base_->Sync();
        }
      }
      uint64_t GetFileSize() override { return base_->GetFileSize(); }
324 325 326
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
327 328 329

     private:
      SpecialEnv* env_;
330
      std::unique_ptr<WritableFile> base_;
331 332 333
    };
    class WalFile : public WritableFile {
     public:
334
      WalFile(SpecialEnv* env, std::unique_ptr<WritableFile>&& b)
335 336 337 338
          : env_(env), base_(std::move(b)) {
        env_->num_open_wal_file_.fetch_add(1);
      }
      virtual ~WalFile() { env_->num_open_wal_file_.fetch_add(-1); }
339
      Status Append(const Slice& data) override {
S
sdong 已提交
340 341 342 343
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT("SpecialEnv::WalFile::Append:1");
#endif
        Status s;
344
        if (env_->log_write_error_.load(std::memory_order_acquire)) {
S
sdong 已提交
345
          s = Status::IOError("simulated writer error");
346 347 348 349 350 351
        } else {
          int slowdown =
              env_->log_write_slowdown_.load(std::memory_order_acquire);
          if (slowdown > 0) {
            env_->SleepForMicroseconds(slowdown);
          }
S
sdong 已提交
352
          s = base_->Append(data);
353
        }
S
sdong 已提交
354 355 356 357
#if !(defined NDEBUG) || !defined(OS_WIN)
        TEST_SYNC_POINT("SpecialEnv::WalFile::Append:2");
#endif
        return s;
358
      }
359
      Status Truncate(uint64_t size) override { return base_->Truncate(size); }
360 361 362 363 364 365 366 367 368 369 370 371
      Status Close() override {
// SyncPoint is not supported in Released Windows Mode.
#if !(defined NDEBUG) || !defined(OS_WIN)
        // Check preallocation size
        // preallocation size is never passed to base file.
        size_t preallocation_size = preallocation_block_size();
        TEST_SYNC_POINT_CALLBACK("DBTestWalFile.GetPreallocationStatus",
                                 &preallocation_size);
#endif  // !(defined NDEBUG) || !defined(OS_WIN)

        return base_->Close();
      }
372 373 374 375 376
      Status Flush() override { return base_->Flush(); }
      Status Sync() override {
        ++env_->sync_counter_;
        return base_->Sync();
      }
377 378 379
      bool IsSyncThreadSafe() const override {
        return env_->is_wal_sync_thread_safe_.load();
      }
380 381 382
      Status Allocate(uint64_t offset, uint64_t len) override {
        return base_->Allocate(offset, len);
      }
383 384 385

     private:
      SpecialEnv* env_;
386
      std::unique_ptr<WritableFile> base_;
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    };

    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 已提交
407 408 409 410 411 412 413 414
    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);
415 416 417 418 419 420 421 422 423 424 425 426 427
    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)));
      }
    }
    return s;
  }

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

446 447 448 449 450 451
      virtual Status Prefetch(uint64_t offset, size_t n) override {
        Status s = target_->Prefetch(offset, n);
        *bytes_read_ += n;
        return s;
      }

452
     private:
453
      std::unique_ptr<RandomAccessFile> target_;
454
      anon::AtomicCounter* counter_;
Y
Yi Wu 已提交
455
      std::atomic<size_t>* bytes_read_;
456 457 458
    };

    Status s = target()->NewRandomAccessFile(f, r, soptions);
459
    random_file_open_counter_++;
460
    if (s.ok() && count_random_reads_) {
461 462
      r->reset(new CountingFile(std::move(*r), &random_read_counter_,
                                &random_read_bytes_counter_));
463
    }
464 465 466
    if (s.ok() && soptions.compaction_readahead_size > 0) {
      compaction_readahead_size_ = soptions.compaction_readahead_size;
    }
467 468 469
    return s;
  }

S
Siying Dong 已提交
470
  virtual Status NewSequentialFile(const std::string& f,
471
                                   std::unique_ptr<SequentialFile>* r,
S
Siying Dong 已提交
472
                                   const EnvOptions& soptions) override {
473 474
    class CountingFile : public SequentialFile {
     public:
475
      CountingFile(std::unique_ptr<SequentialFile>&& target,
476 477 478 479 480 481 482 483 484
                   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:
485
      std::unique_ptr<SequentialFile> target_;
486 487 488 489 490 491 492 493 494 495 496 497
      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 已提交
498
    if (no_slowdown_ || time_elapse_only_sleep_) {
499
      addon_time_.fetch_add(micros);
500
    }
M
Maysam Yabandeh 已提交
501
    if (!no_slowdown_) {
502 503 504 505 506
      target()->SleepForMicroseconds(micros);
    }
  }

  virtual Status GetCurrentTime(int64_t* unix_time) override {
507 508 509 510
    Status s;
    if (!time_elapse_only_sleep_) {
      s = target()->GetCurrentTime(unix_time);
    }
511 512 513 514 515 516
    if (s.ok()) {
      *unix_time += addon_time_.load();
    }
    return s;
  }

517 518 519 520 521
  virtual uint64_t NowCPUNanos() override {
    now_cpu_count_.fetch_add(1);
    return target()->NowCPUNanos();
  }

522
  virtual uint64_t NowNanos() override {
523 524
    return (time_elapse_only_sleep_ ? 0 : target()->NowNanos()) +
           addon_time_.load() * 1000;
525 526 527
  }

  virtual uint64_t NowMicros() override {
528 529
    return (time_elapse_only_sleep_ ? 0 : target()->NowMicros()) +
           addon_time_.load();
530 531
  }

532 533 534 535 536
  virtual Status DeleteFile(const std::string& fname) override {
    delete_count_.fetch_add(1);
    return target()->DeleteFile(fname);
  }

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  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_;

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

564 565 566
  // Number of WAL files that are still open for write.
  std::atomic<int> num_open_wal_file_;

567 568
  bool count_random_reads_;
  anon::AtomicCounter random_read_counter_;
Y
Yi Wu 已提交
569
  std::atomic<size_t> random_read_bytes_counter_;
570
  std::atomic<int> random_file_open_counter_;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

  bool count_sequential_reads_;
  anon::AtomicCounter sequential_read_counter_;

  anon::AtomicCounter sleep_counter_;

  std::atomic<int64_t> bytes_written_;

  std::atomic<int> sync_counter_;

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

  std::atomic<int64_t> addon_time_;
590

591 592
  std::atomic<int> now_cpu_count_;

593 594
  std::atomic<int> delete_count_;

595
  std::atomic<bool> time_elapse_only_sleep_;
596

M
Maysam Yabandeh 已提交
597
  bool no_slowdown_;
598

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

601
  std::atomic<size_t> compaction_readahead_size_{};
602 603
};

Y
Yi Wu 已提交
604
#ifndef ROCKSDB_LITE
Y
Yi Wu 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
class OnFileDeletionListener : public EventListener {
 public:
  OnFileDeletionListener() : matched_count_(0), expected_file_name_("") {}

  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_;
};
Y
Yi Wu 已提交
629
#endif
Y
Yi Wu 已提交
630

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
// 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"; }
};

653
class DBTestBase : public testing::Test {
Y
Yi Wu 已提交
654
 public:
655
  // Sequence of option configurations to try
Y
Yi Wu 已提交
656
  enum OptionConfig : int {
657 658 659 660 661
    kDefault = 0,
    kBlockBasedTableWithPrefixHashIndex = 1,
    kBlockBasedTableWithWholeKeyHashIndex = 2,
    kPlainTableFirstBytePrefix = 3,
    kPlainTableCappedPrefix = 4,
662 663 664 665
    kPlainTableCappedPrefixNonMmap = 5,
    kPlainTableAllBytesPrefix = 6,
    kVectorRep = 7,
    kHashLinkList = 8,
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    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,
    kxxHashChecksum = 23,
    kFIFOCompaction = 24,
    kOptimizeFiltersForHits = 25,
    kRowCache = 26,
    kRecycleLogFiles = 27,
    kConcurrentSkipList = 28,
    kPipelinedWrite = 29,
    kConcurrentWALWrites = 30,
688 689 690 691
    kDirectIO,
    kLevelSubcompactions,
    kBlockBasedTableWithIndexRestartInterval,
    kBlockBasedTableWithPartitionedIndex,
692
    kBlockBasedTableWithPartitionedIndexFormat4,
693
    kPartitionedFilterWithNewTableReaderForCompactions,
694
    kUniversalSubcompactions,
B
Bo Hou 已提交
695
    kxxHash64Checksum,
M
Maysam Yabandeh 已提交
696
    kUnorderedWrite,
697
    // This must be the last line
698
    kEnd,
699 700 701 702 703
  };

 public:
  std::string dbname_;
  std::string alternative_wal_dir_;
S
sdong 已提交
704
  std::string alternative_db_log_dir_;
705
  MockEnv* mem_env_;
E
Ewout Prangsma 已提交
706
  Env* encrypted_env_;
707 708 709 710
  SpecialEnv* env_;
  DB* db_;
  std::vector<ColumnFamilyHandle*> handles_;

Y
Yi Wu 已提交
711
  int option_config_;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
  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,
  };

728 729 730 731 732 733 734
  const int kRangeDelSkipConfigs =
      // Plain tables do not support range deletions.
      kSkipPlainTable |
      // MmapReads disables the iterator pinning that RangeDelAggregator
      // requires.
      kSkipMmapReads;

735 736 737 738
  explicit DBTestBase(const std::string path);

  ~DBTestBase();

739 740 741 742 743 744 745 746 747 748 749 750
  static std::string RandomString(Random* rnd, int len) {
    std::string r;
    test::RandomString(rnd, len, &r);
    return r;
  }

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

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

753 754 755 756
  // 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 已提交
757
  // Switch between different compaction styles.
758 759
  bool ChangeCompactOptions();

S
Siying Dong 已提交
760 761 762
  // Switch between different WAL-realted options.
  bool ChangeWalOptions();

763 764 765 766
  // Switch between different filter policy
  // Jump from kDefault to kFilter to kFullFilter
  bool ChangeFilterOptions();

767 768 769
  // Switch between different DB options for file ingestion tests.
  bool ChangeOptionsForFileIngestionTest();

770
  // Return the current option configuration.
Y
Yi Wu 已提交
771 772 773 774 775 776 777 778
  Options CurrentOptions(const anon::OptionsOverride& options_override =
                             anon::OptionsOverride()) const;

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

  static Options GetDefaultOptions();
779

Y
Yi Wu 已提交
780 781 782 783
  Options GetOptions(int option_config,
                     const Options& default_options = GetDefaultOptions(),
                     const anon::OptionsOverride& options_override =
                         anon::OptionsOverride()) const;
784

S
sdong 已提交
785
  DBImpl* dbfull() { return reinterpret_cast<DBImpl*>(db_); }
786 787 788 789 790 791 792 793 794 795 796 797 798

  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 已提交
799 800
  Status TryReopenWithColumnFamilies(const std::vector<std::string>& cfs,
                                     const std::vector<Options>& options);
801 802 803 804 805 806 807 808 809 810

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

  void Reopen(const Options& options);

  void Close();

  void DestroyAndReopen(const Options& options);

811
  void Destroy(const Options& options, bool delete_cf_paths = false);
812 813 814 815 816

  Status ReadOnlyReopen(const Options& options);

  Status TryReopen(const Options& options);

A
Aaron Gao 已提交
817 818
  bool IsDirectIOSupported();

E
Ewout Prangsma 已提交
819 820
  bool IsMemoryMappedAccessSupported() const;

821 822
  Status Flush(int cf = 0);

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

825 826 827 828 829
  Status Put(const Slice& k, const Slice& v, WriteOptions wo = WriteOptions());

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

830 831 832 833 834 835
  Status Merge(const Slice& k, const Slice& v,
               WriteOptions wo = WriteOptions());

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

836 837 838 839
  Status Delete(const std::string& k);

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

A
Andres Noetzli 已提交
840 841 842 843
  Status SingleDelete(const std::string& k);

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

844 845
  bool SetPreserveDeletesSequenceNumber(SequenceNumber sn);

846 847 848 849 850
  std::string Get(const std::string& k, const Snapshot* snapshot = nullptr);

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

851 852
  Status Get(const std::string& k, PinnableSlice* v);

A
Anand Ananthabhotla 已提交
853 854 855 856
  std::vector<std::string> MultiGet(std::vector<int> cfs,
                                    const std::vector<std::string>& k,
                                    const Snapshot* snapshot = nullptr);

857 858 859
  std::vector<std::string> MultiGet(const std::vector<std::string>& k,
                                    const Snapshot* snapshot = nullptr);

860 861 862 863 864 865 866 867 868 869
  uint64_t GetNumSnapshots();

  uint64_t GetTimeOldestSnapshots();

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

870
#ifndef ROCKSDB_LITE
871 872 873 874 875 876
  int NumSortedRuns(int cf = 0);

  uint64_t TotalSize(int cf = 0);

  uint64_t SizeAtLevel(int level);

V
Vasili Svirski 已提交
877
  size_t TotalLiveFiles(int cf = 0);
878

879 880 881 882
  size_t CountLiveFiles();

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

883 884
  double CompressionRatioAtLevel(int level, int cf = 0);

885
  int TotalTableFiles(int cf = 0, int levels = -1);
Y
Yi Wu 已提交
886
#endif  // ROCKSDB_LITE
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

  // Return spread of files per level
  std::string FilesPerLevel(int cf = 0);

  size_t CountFiles();

  uint64_t Size(const Slice& start, const Slice& limit, int cf = 0);

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

912 913
  void MoveFilesToLevel(int level, int cf = 0);

Y
Yi Wu 已提交
914
#ifndef ROCKSDB_LITE
915
  void DumpFileCounts(const char* label);
Y
Yi Wu 已提交
916
#endif  // ROCKSDB_LITE
917 918 919

  std::string DumpSSTableList();

920 921
  static void GetSstFiles(Env* env, std::string path,
                          std::vector<std::string>* files);
D
dyniusz 已提交
922

923 924 925 926 927
  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);

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

930
  static const int kNumKeysByGenerateNewRandomFile;
K
krad 已提交
931
  static const int KNumKeysByGenerateNewFile = 100;
932

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
  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 已提交
949 950 951
  static UpdateStatus updateInPlaceSmallerSize(char* prevValue,
                                               uint32_t* prevSize, Slice delta,
                                               std::string* newValue);
952

S
sdong 已提交
953 954 955 956
  static UpdateStatus updateInPlaceSmallerVarintSize(char* prevValue,
                                                     uint32_t* prevSize,
                                                     Slice delta,
                                                     std::string* newValue);
957

S
sdong 已提交
958 959 960
  static UpdateStatus updateInPlaceLargerSize(char* prevValue,
                                              uint32_t* prevSize, Slice delta,
                                              std::string* newValue);
961

S
sdong 已提交
962 963
  static UpdateStatus updateInPlaceNoAction(char* prevValue, uint32_t* prevSize,
                                            Slice delta, std::string* newValue);
964 965 966 967 968 969

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

971 972
  std::unordered_map<std::string, uint64_t> GetAllSSTFiles(
      uint64_t* total_size = nullptr);
Y
Yi Wu 已提交
973 974 975

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

I
Islam AbdelRahman 已提交
976 977 978 979
  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>());
980 981 982

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

Y
Yi Wu 已提交
984 985 986 987 988 989 990 991
#ifndef ROCKSDB_LITE
  uint64_t GetNumberOfSstFilesForColumnFamily(DB* db,
                                              std::string column_family_name);
#endif  // ROCKSDB_LITE

  uint64_t TestGetTickerCount(const Options& options, Tickers ticker_type) {
    return options.statistics->getTickerCount(ticker_type);
  }
992 993 994
};

}  // namespace rocksdb