小组成员:姚凯文(kevinyao0901),姜嘉琪
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

2297 строки
68 KiB

Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 лет назад
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 лет назад
Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 лет назад
Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 лет назад
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "leveldb/db.h"
  5. #include <atomic>
  6. #include <cinttypes>
  7. #include <string>
  8. #include "gtest/gtest.h"
  9. #include "db/db_impl.h"
  10. #include "db/filename.h"
  11. #include "db/version_set.h"
  12. #include "db/write_batch_internal.h"
  13. #include "leveldb/cache.h"
  14. #include "leveldb/env.h"
  15. #include "leveldb/filter_policy.h"
  16. #include "leveldb/table.h"
  17. #include "port/port.h"
  18. #include "port/thread_annotations.h"
  19. #include "util/hash.h"
  20. #include "util/logging.h"
  21. #include "util/mutexlock.h"
  22. #include "util/testutil.h"
  23. namespace leveldb {
  24. static std::string RandomString(Random* rnd, int len) {
  25. std::string r;
  26. test::RandomString(rnd, len, &r);
  27. return r;
  28. }
  29. static std::string RandomKey(Random* rnd) {
  30. int len =
  31. (rnd->OneIn(3) ? 1 // Short sometimes to encourage collisions
  32. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  33. return test::RandomKey(rnd, len);
  34. }
  35. namespace {
  36. class AtomicCounter {
  37. public:
  38. AtomicCounter() : count_(0) {}
  39. void Increment() { IncrementBy(1); }
  40. void IncrementBy(int count) LOCKS_EXCLUDED(mu_) {
  41. MutexLock l(&mu_);
  42. count_ += count;
  43. }
  44. int Read() LOCKS_EXCLUDED(mu_) {
  45. MutexLock l(&mu_);
  46. return count_;
  47. }
  48. void Reset() LOCKS_EXCLUDED(mu_) {
  49. MutexLock l(&mu_);
  50. count_ = 0;
  51. }
  52. private:
  53. port::Mutex mu_;
  54. int count_ GUARDED_BY(mu_);
  55. };
  56. void DelayMilliseconds(int millis) {
  57. Env::Default()->SleepForMicroseconds(millis * 1000);
  58. }
  59. } // namespace
  60. // Test Env to override default Env behavior for testing.
  61. class TestEnv : public EnvWrapper {
  62. public:
  63. explicit TestEnv(Env* base) : EnvWrapper(base), ignore_dot_files_(false) {}
  64. void SetIgnoreDotFiles(bool ignored) { ignore_dot_files_ = ignored; }
  65. Status GetChildren(const std::string& dir,
  66. std::vector<std::string>* result) override {
  67. Status s = target()->GetChildren(dir, result);
  68. if (!s.ok() || !ignore_dot_files_) {
  69. return s;
  70. }
  71. std::vector<std::string>::iterator it = result->begin();
  72. while (it != result->end()) {
  73. if ((*it == ".") || (*it == "..")) {
  74. it = result->erase(it);
  75. } else {
  76. ++it;
  77. }
  78. }
  79. return s;
  80. }
  81. private:
  82. bool ignore_dot_files_;
  83. };
  84. // Special Env used to delay background operations.
  85. class SpecialEnv : public EnvWrapper {
  86. public:
  87. // sstable/log Sync() calls are blocked while this pointer is non-null.
  88. std::atomic<bool> delay_data_sync_;
  89. // sstable/log Sync() calls return an error.
  90. std::atomic<bool> data_sync_error_;
  91. // Simulate no-space errors while this pointer is non-null.
  92. std::atomic<bool> no_space_;
  93. // Simulate non-writable file system while this pointer is non-null.
  94. std::atomic<bool> non_writable_;
  95. // Force sync of manifest files to fail while this pointer is non-null.
  96. std::atomic<bool> manifest_sync_error_;
  97. // Force write to manifest files to fail while this pointer is non-null.
  98. std::atomic<bool> manifest_write_error_;
  99. bool count_random_reads_;
  100. AtomicCounter random_read_counter_;
  101. explicit SpecialEnv(Env* base)
  102. : EnvWrapper(base),
  103. delay_data_sync_(false),
  104. data_sync_error_(false),
  105. no_space_(false),
  106. non_writable_(false),
  107. manifest_sync_error_(false),
  108. manifest_write_error_(false),
  109. count_random_reads_(false) {}
  110. Status NewWritableFile(const std::string& f, WritableFile** r) {
  111. class DataFile : public WritableFile {
  112. private:
  113. SpecialEnv* const env_;
  114. WritableFile* const base_;
  115. public:
  116. DataFile(SpecialEnv* env, WritableFile* base) : env_(env), base_(base) {}
  117. ~DataFile() { delete base_; }
  118. Status Append(const Slice& data) {
  119. if (env_->no_space_.load(std::memory_order_acquire)) {
  120. // Drop writes on the floor
  121. return Status::OK();
  122. } else {
  123. return base_->Append(data);
  124. }
  125. }
  126. Status Close() { return base_->Close(); }
  127. Status Flush() { return base_->Flush(); }
  128. Status Sync() {
  129. if (env_->data_sync_error_.load(std::memory_order_acquire)) {
  130. return Status::IOError("simulated data sync error");
  131. }
  132. while (env_->delay_data_sync_.load(std::memory_order_acquire)) {
  133. DelayMilliseconds(100);
  134. }
  135. return base_->Sync();
  136. }
  137. };
  138. class ManifestFile : public WritableFile {
  139. private:
  140. SpecialEnv* env_;
  141. WritableFile* base_;
  142. public:
  143. ManifestFile(SpecialEnv* env, WritableFile* b) : env_(env), base_(b) {}
  144. ~ManifestFile() { delete base_; }
  145. Status Append(const Slice& data) {
  146. if (env_->manifest_write_error_.load(std::memory_order_acquire)) {
  147. return Status::IOError("simulated writer error");
  148. } else {
  149. return base_->Append(data);
  150. }
  151. }
  152. Status Close() { return base_->Close(); }
  153. Status Flush() { return base_->Flush(); }
  154. Status Sync() {
  155. if (env_->manifest_sync_error_.load(std::memory_order_acquire)) {
  156. return Status::IOError("simulated sync error");
  157. } else {
  158. return base_->Sync();
  159. }
  160. }
  161. };
  162. if (non_writable_.load(std::memory_order_acquire)) {
  163. return Status::IOError("simulated write error");
  164. }
  165. Status s = target()->NewWritableFile(f, r);
  166. if (s.ok()) {
  167. if (strstr(f.c_str(), ".ldb") != nullptr ||
  168. strstr(f.c_str(), ".log") != nullptr) {
  169. *r = new DataFile(this, *r);
  170. } else if (strstr(f.c_str(), "MANIFEST") != nullptr) {
  171. *r = new ManifestFile(this, *r);
  172. }
  173. }
  174. return s;
  175. }
  176. Status NewRandomAccessFile(const std::string& f, RandomAccessFile** r) {
  177. class CountingFile : public RandomAccessFile {
  178. private:
  179. RandomAccessFile* target_;
  180. AtomicCounter* counter_;
  181. public:
  182. CountingFile(RandomAccessFile* target, AtomicCounter* counter)
  183. : target_(target), counter_(counter) {}
  184. ~CountingFile() override { delete target_; }
  185. Status Read(uint64_t offset, size_t n, Slice* result,
  186. char* scratch) const override {
  187. counter_->Increment();
  188. return target_->Read(offset, n, result, scratch);
  189. }
  190. };
  191. Status s = target()->NewRandomAccessFile(f, r);
  192. if (s.ok() && count_random_reads_) {
  193. *r = new CountingFile(*r, &random_read_counter_);
  194. }
  195. return s;
  196. }
  197. };
  198. class DBTest : public testing::Test {
  199. public:
  200. std::string dbname_;
  201. SpecialEnv* env_;
  202. DB* db_;
  203. Options last_options_;
  204. DBTest() : env_(new SpecialEnv(Env::Default())), option_config_(kDefault) {
  205. filter_policy_ = NewBloomFilterPolicy(10);
  206. dbname_ = testing::TempDir() + "db_test";
  207. DestroyDB(dbname_, Options());
  208. db_ = nullptr;
  209. Reopen();
  210. }
  211. ~DBTest() {
  212. delete db_;
  213. DestroyDB(dbname_, Options());
  214. delete env_;
  215. delete filter_policy_;
  216. }
  217. // Switch to a fresh database with the next option configuration to
  218. // test. Return false if there are no more configurations to test.
  219. bool ChangeOptions() {
  220. option_config_++;
  221. if (option_config_ >= kEnd) {
  222. return false;
  223. } else {
  224. DestroyAndReopen();
  225. return true;
  226. }
  227. }
  228. // Return the current option configuration.
  229. Options CurrentOptions() {
  230. Options options;
  231. options.reuse_logs = false;
  232. switch (option_config_) {
  233. case kReuse:
  234. options.reuse_logs = true;
  235. break;
  236. case kFilter:
  237. options.filter_policy = filter_policy_;
  238. break;
  239. case kUncompressed:
  240. options.compression = kNoCompression;
  241. break;
  242. default:
  243. break;
  244. }
  245. return options;
  246. }
  247. DBImpl* dbfull() { return reinterpret_cast<DBImpl*>(db_); }
  248. void Reopen(Options* options = nullptr) {
  249. ASSERT_LEVELDB_OK(TryReopen(options));
  250. }
  251. void Close() {
  252. delete db_;
  253. db_ = nullptr;
  254. }
  255. void DestroyAndReopen(Options* options = nullptr) {
  256. delete db_;
  257. db_ = nullptr;
  258. DestroyDB(dbname_, Options());
  259. ASSERT_LEVELDB_OK(TryReopen(options));
  260. }
  261. Status TryReopen(Options* options) {
  262. delete db_;
  263. db_ = nullptr;
  264. Options opts;
  265. if (options != nullptr) {
  266. opts = *options;
  267. } else {
  268. opts = CurrentOptions();
  269. opts.create_if_missing = true;
  270. }
  271. last_options_ = opts;
  272. return DB::Open(opts, dbname_, &db_);
  273. }
  274. Status Put(const std::string& k, const std::string& v) {
  275. return db_->Put(WriteOptions(), k, v);
  276. }
  277. Status Delete(const std::string& k) { return db_->Delete(WriteOptions(), k); }
  278. std::string Get(const std::string& k, const Snapshot* snapshot = nullptr) {
  279. ReadOptions options;
  280. options.snapshot = snapshot;
  281. std::string result;
  282. Status s = db_->Get(options, k, &result);
  283. if (s.IsNotFound()) {
  284. result = "NOT_FOUND";
  285. } else if (!s.ok()) {
  286. result = s.ToString();
  287. }
  288. return result;
  289. }
  290. // Return a string that contains all key,value pairs in order,
  291. // formatted like "(k1->v1)(k2->v2)".
  292. std::string Contents() {
  293. std::vector<std::string> forward;
  294. std::string result;
  295. Iterator* iter = db_->NewIterator(ReadOptions());
  296. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  297. std::string s = IterStatus(iter);
  298. result.push_back('(');
  299. result.append(s);
  300. result.push_back(')');
  301. forward.push_back(s);
  302. }
  303. // Check reverse iteration results are the reverse of forward results
  304. size_t matched = 0;
  305. for (iter->SeekToLast(); iter->Valid(); iter->Prev()) {
  306. EXPECT_LT(matched, forward.size());
  307. EXPECT_EQ(IterStatus(iter), forward[forward.size() - matched - 1]);
  308. matched++;
  309. }
  310. EXPECT_EQ(matched, forward.size());
  311. delete iter;
  312. return result;
  313. }
  314. std::string AllEntriesFor(const Slice& user_key) {
  315. Iterator* iter = dbfull()->TEST_NewInternalIterator();
  316. InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  317. iter->Seek(target.Encode());
  318. std::string result;
  319. if (!iter->status().ok()) {
  320. result = iter->status().ToString();
  321. } else {
  322. result = "[ ";
  323. bool first = true;
  324. while (iter->Valid()) {
  325. ParsedInternalKey ikey;
  326. if (!ParseInternalKey(iter->key(), &ikey)) {
  327. result += "CORRUPTED";
  328. } else {
  329. if (last_options_.comparator->Compare(ikey.user_key, user_key) != 0) {
  330. break;
  331. }
  332. if (!first) {
  333. result += ", ";
  334. }
  335. first = false;
  336. switch (ikey.type) {
  337. case kTypeValue:
  338. result += iter->value().ToString();
  339. break;
  340. case kTypeDeletion:
  341. result += "DEL";
  342. break;
  343. }
  344. }
  345. iter->Next();
  346. }
  347. if (!first) {
  348. result += " ";
  349. }
  350. result += "]";
  351. }
  352. delete iter;
  353. return result;
  354. }
  355. int NumTableFilesAtLevel(int level) {
  356. std::string property;
  357. EXPECT_TRUE(db_->GetProperty(
  358. "leveldb.num-files-at-level" + NumberToString(level), &property));
  359. return std::stoi(property);
  360. }
  361. int TotalTableFiles() {
  362. int result = 0;
  363. for (int level = 0; level < config::kNumLevels; level++) {
  364. result += NumTableFilesAtLevel(level);
  365. }
  366. return result;
  367. }
  368. // Return spread of files per level
  369. std::string FilesPerLevel() {
  370. std::string result;
  371. int last_non_zero_offset = 0;
  372. for (int level = 0; level < config::kNumLevels; level++) {
  373. int f = NumTableFilesAtLevel(level);
  374. char buf[100];
  375. std::snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
  376. result += buf;
  377. if (f > 0) {
  378. last_non_zero_offset = result.size();
  379. }
  380. }
  381. result.resize(last_non_zero_offset);
  382. return result;
  383. }
  384. int CountFiles() {
  385. std::vector<std::string> files;
  386. env_->GetChildren(dbname_, &files);
  387. return static_cast<int>(files.size());
  388. }
  389. uint64_t Size(const Slice& start, const Slice& limit) {
  390. Range r(start, limit);
  391. uint64_t size;
  392. db_->GetApproximateSizes(&r, 1, &size);
  393. return size;
  394. }
  395. void Compact(const Slice& start, const Slice& limit) {
  396. db_->CompactRange(&start, &limit);
  397. }
  398. // Do n memtable compactions, each of which produces an sstable
  399. // covering the range [small_key,large_key].
  400. void MakeTables(int n, const std::string& small_key,
  401. const std::string& large_key) {
  402. for (int i = 0; i < n; i++) {
  403. Put(small_key, "begin");
  404. Put(large_key, "end");
  405. dbfull()->TEST_CompactMemTable();
  406. }
  407. }
  408. // Prevent pushing of new sstables into deeper levels by adding
  409. // tables that cover a specified range to all levels.
  410. void FillLevels(const std::string& smallest, const std::string& largest) {
  411. MakeTables(config::kNumLevels, smallest, largest);
  412. }
  413. void DumpFileCounts(const char* label) {
  414. std::fprintf(stderr, "---\n%s:\n", label);
  415. std::fprintf(
  416. stderr, "maxoverlap: %lld\n",
  417. static_cast<long long>(dbfull()->TEST_MaxNextLevelOverlappingBytes()));
  418. for (int level = 0; level < config::kNumLevels; level++) {
  419. int num = NumTableFilesAtLevel(level);
  420. if (num > 0) {
  421. std::fprintf(stderr, " level %3d : %d files\n", level, num);
  422. }
  423. }
  424. }
  425. std::string DumpSSTableList() {
  426. std::string property;
  427. db_->GetProperty("leveldb.sstables", &property);
  428. return property;
  429. }
  430. std::string IterStatus(Iterator* iter) {
  431. std::string result;
  432. if (iter->Valid()) {
  433. result = iter->key().ToString() + "->" + iter->value().ToString();
  434. } else {
  435. result = "(invalid)";
  436. }
  437. return result;
  438. }
  439. bool DeleteAnSSTFile() {
  440. std::vector<std::string> filenames;
  441. EXPECT_LEVELDB_OK(env_->GetChildren(dbname_, &filenames));
  442. uint64_t number;
  443. FileType type;
  444. for (size_t i = 0; i < filenames.size(); i++) {
  445. if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
  446. EXPECT_LEVELDB_OK(env_->RemoveFile(TableFileName(dbname_, number)));
  447. return true;
  448. }
  449. }
  450. return false;
  451. }
  452. // Returns number of files renamed.
  453. int RenameLDBToSST() {
  454. std::vector<std::string> filenames;
  455. EXPECT_LEVELDB_OK(env_->GetChildren(dbname_, &filenames));
  456. uint64_t number;
  457. FileType type;
  458. int files_renamed = 0;
  459. for (size_t i = 0; i < filenames.size(); i++) {
  460. if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
  461. const std::string from = TableFileName(dbname_, number);
  462. const std::string to = SSTTableFileName(dbname_, number);
  463. EXPECT_LEVELDB_OK(env_->RenameFile(from, to));
  464. files_renamed++;
  465. }
  466. }
  467. return files_renamed;
  468. }
  469. private:
  470. // Sequence of option configurations to try
  471. enum OptionConfig { kDefault, kReuse, kFilter, kUncompressed, kEnd };
  472. const FilterPolicy* filter_policy_;
  473. int option_config_;
  474. };
  475. TEST_F(DBTest, Empty) {
  476. do {
  477. ASSERT_TRUE(db_ != nullptr);
  478. ASSERT_EQ("NOT_FOUND", Get("foo"));
  479. } while (ChangeOptions());
  480. }
  481. TEST_F(DBTest, EmptyKey) {
  482. do {
  483. ASSERT_LEVELDB_OK(Put("", "v1"));
  484. ASSERT_EQ("v1", Get(""));
  485. ASSERT_LEVELDB_OK(Put("", "v2"));
  486. ASSERT_EQ("v2", Get(""));
  487. } while (ChangeOptions());
  488. }
  489. TEST_F(DBTest, EmptyValue) {
  490. do {
  491. ASSERT_LEVELDB_OK(Put("key", "v1"));
  492. ASSERT_EQ("v1", Get("key"));
  493. ASSERT_LEVELDB_OK(Put("key", ""));
  494. ASSERT_EQ("", Get("key"));
  495. ASSERT_LEVELDB_OK(Put("key", "v2"));
  496. ASSERT_EQ("v2", Get("key"));
  497. } while (ChangeOptions());
  498. }
  499. TEST_F(DBTest, ReadWrite) {
  500. do {
  501. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  502. ASSERT_EQ("v1", Get("foo"));
  503. ASSERT_LEVELDB_OK(Put("bar", "v2"));
  504. ASSERT_LEVELDB_OK(Put("foo", "v3"));
  505. ASSERT_EQ("v3", Get("foo"));
  506. ASSERT_EQ("v2", Get("bar"));
  507. } while (ChangeOptions());
  508. }
  509. TEST_F(DBTest, PutDeleteGet) {
  510. do {
  511. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v1"));
  512. ASSERT_EQ("v1", Get("foo"));
  513. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v2"));
  514. ASSERT_EQ("v2", Get("foo"));
  515. ASSERT_LEVELDB_OK(db_->Delete(WriteOptions(), "foo"));
  516. ASSERT_EQ("NOT_FOUND", Get("foo"));
  517. } while (ChangeOptions());
  518. }
  519. TEST_F(DBTest, GetFromImmutableLayer) {
  520. do {
  521. Options options = CurrentOptions();
  522. options.env = env_;
  523. options.write_buffer_size = 100000; // Small write buffer
  524. Reopen(&options);
  525. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  526. ASSERT_EQ("v1", Get("foo"));
  527. // Block sync calls.
  528. env_->delay_data_sync_.store(true, std::memory_order_release);
  529. Put("k1", std::string(100000, 'x')); // Fill memtable.
  530. Put("k2", std::string(100000, 'y')); // Trigger compaction.
  531. ASSERT_EQ("v1", Get("foo"));
  532. // Release sync calls.
  533. env_->delay_data_sync_.store(false, std::memory_order_release);
  534. } while (ChangeOptions());
  535. }
  536. TEST_F(DBTest, GetFromVersions) {
  537. do {
  538. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  539. dbfull()->TEST_CompactMemTable();
  540. ASSERT_EQ("v1", Get("foo"));
  541. } while (ChangeOptions());
  542. }
  543. TEST_F(DBTest, GetMemUsage) {
  544. do {
  545. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  546. std::string val;
  547. ASSERT_TRUE(db_->GetProperty("leveldb.approximate-memory-usage", &val));
  548. int mem_usage = std::stoi(val);
  549. ASSERT_GT(mem_usage, 0);
  550. ASSERT_LT(mem_usage, 5 * 1024 * 1024);
  551. } while (ChangeOptions());
  552. }
  553. TEST_F(DBTest, GetSnapshot) {
  554. do {
  555. // Try with both a short key and a long key
  556. for (int i = 0; i < 2; i++) {
  557. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  558. ASSERT_LEVELDB_OK(Put(key, "v1"));
  559. const Snapshot* s1 = db_->GetSnapshot();
  560. ASSERT_LEVELDB_OK(Put(key, "v2"));
  561. ASSERT_EQ("v2", Get(key));
  562. ASSERT_EQ("v1", Get(key, s1));
  563. dbfull()->TEST_CompactMemTable();
  564. ASSERT_EQ("v2", Get(key));
  565. ASSERT_EQ("v1", Get(key, s1));
  566. db_->ReleaseSnapshot(s1);
  567. }
  568. } while (ChangeOptions());
  569. }
  570. TEST_F(DBTest, GetIdenticalSnapshots) {
  571. do {
  572. // Try with both a short key and a long key
  573. for (int i = 0; i < 2; i++) {
  574. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  575. ASSERT_LEVELDB_OK(Put(key, "v1"));
  576. const Snapshot* s1 = db_->GetSnapshot();
  577. const Snapshot* s2 = db_->GetSnapshot();
  578. const Snapshot* s3 = db_->GetSnapshot();
  579. ASSERT_LEVELDB_OK(Put(key, "v2"));
  580. ASSERT_EQ("v2", Get(key));
  581. ASSERT_EQ("v1", Get(key, s1));
  582. ASSERT_EQ("v1", Get(key, s2));
  583. ASSERT_EQ("v1", Get(key, s3));
  584. db_->ReleaseSnapshot(s1);
  585. dbfull()->TEST_CompactMemTable();
  586. ASSERT_EQ("v2", Get(key));
  587. ASSERT_EQ("v1", Get(key, s2));
  588. db_->ReleaseSnapshot(s2);
  589. ASSERT_EQ("v1", Get(key, s3));
  590. db_->ReleaseSnapshot(s3);
  591. }
  592. } while (ChangeOptions());
  593. }
  594. TEST_F(DBTest, IterateOverEmptySnapshot) {
  595. do {
  596. const Snapshot* snapshot = db_->GetSnapshot();
  597. ReadOptions read_options;
  598. read_options.snapshot = snapshot;
  599. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  600. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  601. Iterator* iterator1 = db_->NewIterator(read_options);
  602. iterator1->SeekToFirst();
  603. ASSERT_TRUE(!iterator1->Valid());
  604. delete iterator1;
  605. dbfull()->TEST_CompactMemTable();
  606. Iterator* iterator2 = db_->NewIterator(read_options);
  607. iterator2->SeekToFirst();
  608. ASSERT_TRUE(!iterator2->Valid());
  609. delete iterator2;
  610. db_->ReleaseSnapshot(snapshot);
  611. } while (ChangeOptions());
  612. }
  613. TEST_F(DBTest, GetLevel0Ordering) {
  614. do {
  615. // Check that we process level-0 files in correct order. The code
  616. // below generates two level-0 files where the earlier one comes
  617. // before the later one in the level-0 file list since the earlier
  618. // one has a smaller "smallest" key.
  619. ASSERT_LEVELDB_OK(Put("bar", "b"));
  620. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  621. dbfull()->TEST_CompactMemTable();
  622. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  623. dbfull()->TEST_CompactMemTable();
  624. ASSERT_EQ("v2", Get("foo"));
  625. } while (ChangeOptions());
  626. }
  627. TEST_F(DBTest, GetOrderedByLevels) {
  628. do {
  629. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  630. Compact("a", "z");
  631. ASSERT_EQ("v1", Get("foo"));
  632. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  633. ASSERT_EQ("v2", Get("foo"));
  634. dbfull()->TEST_CompactMemTable();
  635. ASSERT_EQ("v2", Get("foo"));
  636. } while (ChangeOptions());
  637. }
  638. TEST_F(DBTest, GetPicksCorrectFile) {
  639. do {
  640. // Arrange to have multiple files in a non-level-0 level.
  641. ASSERT_LEVELDB_OK(Put("a", "va"));
  642. Compact("a", "b");
  643. ASSERT_LEVELDB_OK(Put("x", "vx"));
  644. Compact("x", "y");
  645. ASSERT_LEVELDB_OK(Put("f", "vf"));
  646. Compact("f", "g");
  647. ASSERT_EQ("va", Get("a"));
  648. ASSERT_EQ("vf", Get("f"));
  649. ASSERT_EQ("vx", Get("x"));
  650. } while (ChangeOptions());
  651. }
  652. TEST_F(DBTest, GetEncountersEmptyLevel) {
  653. do {
  654. // Arrange for the following to happen:
  655. // * sstable A in level 0
  656. // * nothing in level 1
  657. // * sstable B in level 2
  658. // Then do enough Get() calls to arrange for an automatic compaction
  659. // of sstable A. A bug would cause the compaction to be marked as
  660. // occurring at level 1 (instead of the correct level 0).
  661. // Step 1: First place sstables in levels 0 and 2
  662. int compaction_count = 0;
  663. while (NumTableFilesAtLevel(0) == 0 || NumTableFilesAtLevel(2) == 0) {
  664. ASSERT_LE(compaction_count, 100) << "could not fill levels 0 and 2";
  665. compaction_count++;
  666. Put("a", "begin");
  667. Put("z", "end");
  668. dbfull()->TEST_CompactMemTable();
  669. }
  670. // Step 2: clear level 1 if necessary.
  671. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  672. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  673. ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  674. ASSERT_EQ(NumTableFilesAtLevel(2), 1);
  675. // Step 3: read a bunch of times
  676. for (int i = 0; i < 1000; i++) {
  677. ASSERT_EQ("NOT_FOUND", Get("missing"));
  678. }
  679. // Step 4: Wait for compaction to finish
  680. DelayMilliseconds(1000);
  681. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  682. } while (ChangeOptions());
  683. }
  684. TEST_F(DBTest, IterEmpty) {
  685. Iterator* iter = db_->NewIterator(ReadOptions());
  686. iter->SeekToFirst();
  687. ASSERT_EQ(IterStatus(iter), "(invalid)");
  688. iter->SeekToLast();
  689. ASSERT_EQ(IterStatus(iter), "(invalid)");
  690. iter->Seek("foo");
  691. ASSERT_EQ(IterStatus(iter), "(invalid)");
  692. delete iter;
  693. }
  694. TEST_F(DBTest, IterSingle) {
  695. ASSERT_LEVELDB_OK(Put("a", "va"));
  696. Iterator* iter = db_->NewIterator(ReadOptions());
  697. iter->SeekToFirst();
  698. ASSERT_EQ(IterStatus(iter), "a->va");
  699. iter->Next();
  700. ASSERT_EQ(IterStatus(iter), "(invalid)");
  701. iter->SeekToFirst();
  702. ASSERT_EQ(IterStatus(iter), "a->va");
  703. iter->Prev();
  704. ASSERT_EQ(IterStatus(iter), "(invalid)");
  705. iter->SeekToLast();
  706. ASSERT_EQ(IterStatus(iter), "a->va");
  707. iter->Next();
  708. ASSERT_EQ(IterStatus(iter), "(invalid)");
  709. iter->SeekToLast();
  710. ASSERT_EQ(IterStatus(iter), "a->va");
  711. iter->Prev();
  712. ASSERT_EQ(IterStatus(iter), "(invalid)");
  713. iter->Seek("");
  714. ASSERT_EQ(IterStatus(iter), "a->va");
  715. iter->Next();
  716. ASSERT_EQ(IterStatus(iter), "(invalid)");
  717. iter->Seek("a");
  718. ASSERT_EQ(IterStatus(iter), "a->va");
  719. iter->Next();
  720. ASSERT_EQ(IterStatus(iter), "(invalid)");
  721. iter->Seek("b");
  722. ASSERT_EQ(IterStatus(iter), "(invalid)");
  723. delete iter;
  724. }
  725. TEST_F(DBTest, IterMulti) {
  726. ASSERT_LEVELDB_OK(Put("a", "va"));
  727. ASSERT_LEVELDB_OK(Put("b", "vb"));
  728. ASSERT_LEVELDB_OK(Put("c", "vc"));
  729. Iterator* iter = db_->NewIterator(ReadOptions());
  730. iter->SeekToFirst();
  731. ASSERT_EQ(IterStatus(iter), "a->va");
  732. iter->Next();
  733. ASSERT_EQ(IterStatus(iter), "b->vb");
  734. iter->Next();
  735. ASSERT_EQ(IterStatus(iter), "c->vc");
  736. iter->Next();
  737. ASSERT_EQ(IterStatus(iter), "(invalid)");
  738. iter->SeekToFirst();
  739. ASSERT_EQ(IterStatus(iter), "a->va");
  740. iter->Prev();
  741. ASSERT_EQ(IterStatus(iter), "(invalid)");
  742. iter->SeekToLast();
  743. ASSERT_EQ(IterStatus(iter), "c->vc");
  744. iter->Prev();
  745. ASSERT_EQ(IterStatus(iter), "b->vb");
  746. iter->Prev();
  747. ASSERT_EQ(IterStatus(iter), "a->va");
  748. iter->Prev();
  749. ASSERT_EQ(IterStatus(iter), "(invalid)");
  750. iter->SeekToLast();
  751. ASSERT_EQ(IterStatus(iter), "c->vc");
  752. iter->Next();
  753. ASSERT_EQ(IterStatus(iter), "(invalid)");
  754. iter->Seek("");
  755. ASSERT_EQ(IterStatus(iter), "a->va");
  756. iter->Seek("a");
  757. ASSERT_EQ(IterStatus(iter), "a->va");
  758. iter->Seek("ax");
  759. ASSERT_EQ(IterStatus(iter), "b->vb");
  760. iter->Seek("b");
  761. ASSERT_EQ(IterStatus(iter), "b->vb");
  762. iter->Seek("z");
  763. ASSERT_EQ(IterStatus(iter), "(invalid)");
  764. // Switch from reverse to forward
  765. iter->SeekToLast();
  766. iter->Prev();
  767. iter->Prev();
  768. iter->Next();
  769. ASSERT_EQ(IterStatus(iter), "b->vb");
  770. // Switch from forward to reverse
  771. iter->SeekToFirst();
  772. iter->Next();
  773. iter->Next();
  774. iter->Prev();
  775. ASSERT_EQ(IterStatus(iter), "b->vb");
  776. // Make sure iter stays at snapshot
  777. ASSERT_LEVELDB_OK(Put("a", "va2"));
  778. ASSERT_LEVELDB_OK(Put("a2", "va3"));
  779. ASSERT_LEVELDB_OK(Put("b", "vb2"));
  780. ASSERT_LEVELDB_OK(Put("c", "vc2"));
  781. ASSERT_LEVELDB_OK(Delete("b"));
  782. iter->SeekToFirst();
  783. ASSERT_EQ(IterStatus(iter), "a->va");
  784. iter->Next();
  785. ASSERT_EQ(IterStatus(iter), "b->vb");
  786. iter->Next();
  787. ASSERT_EQ(IterStatus(iter), "c->vc");
  788. iter->Next();
  789. ASSERT_EQ(IterStatus(iter), "(invalid)");
  790. iter->SeekToLast();
  791. ASSERT_EQ(IterStatus(iter), "c->vc");
  792. iter->Prev();
  793. ASSERT_EQ(IterStatus(iter), "b->vb");
  794. iter->Prev();
  795. ASSERT_EQ(IterStatus(iter), "a->va");
  796. iter->Prev();
  797. ASSERT_EQ(IterStatus(iter), "(invalid)");
  798. delete iter;
  799. }
  800. TEST_F(DBTest, IterSmallAndLargeMix) {
  801. ASSERT_LEVELDB_OK(Put("a", "va"));
  802. ASSERT_LEVELDB_OK(Put("b", std::string(100000, 'b')));
  803. ASSERT_LEVELDB_OK(Put("c", "vc"));
  804. ASSERT_LEVELDB_OK(Put("d", std::string(100000, 'd')));
  805. ASSERT_LEVELDB_OK(Put("e", std::string(100000, 'e')));
  806. Iterator* iter = db_->NewIterator(ReadOptions());
  807. iter->SeekToFirst();
  808. ASSERT_EQ(IterStatus(iter), "a->va");
  809. iter->Next();
  810. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  811. iter->Next();
  812. ASSERT_EQ(IterStatus(iter), "c->vc");
  813. iter->Next();
  814. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  815. iter->Next();
  816. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  817. iter->Next();
  818. ASSERT_EQ(IterStatus(iter), "(invalid)");
  819. iter->SeekToLast();
  820. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  821. iter->Prev();
  822. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  823. iter->Prev();
  824. ASSERT_EQ(IterStatus(iter), "c->vc");
  825. iter->Prev();
  826. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  827. iter->Prev();
  828. ASSERT_EQ(IterStatus(iter), "a->va");
  829. iter->Prev();
  830. ASSERT_EQ(IterStatus(iter), "(invalid)");
  831. delete iter;
  832. }
  833. TEST_F(DBTest, IterMultiWithDelete) {
  834. do {
  835. ASSERT_LEVELDB_OK(Put("a", "va"));
  836. ASSERT_LEVELDB_OK(Put("b", "vb"));
  837. ASSERT_LEVELDB_OK(Put("c", "vc"));
  838. ASSERT_LEVELDB_OK(Delete("b"));
  839. ASSERT_EQ("NOT_FOUND", Get("b"));
  840. Iterator* iter = db_->NewIterator(ReadOptions());
  841. iter->Seek("c");
  842. ASSERT_EQ(IterStatus(iter), "c->vc");
  843. iter->Prev();
  844. ASSERT_EQ(IterStatus(iter), "a->va");
  845. delete iter;
  846. } while (ChangeOptions());
  847. }
  848. TEST_F(DBTest, IterMultiWithDeleteAndCompaction) {
  849. do {
  850. ASSERT_LEVELDB_OK(Put("b", "vb"));
  851. ASSERT_LEVELDB_OK(Put("c", "vc"));
  852. ASSERT_LEVELDB_OK(Put("a", "va"));
  853. dbfull()->TEST_CompactMemTable();
  854. ASSERT_LEVELDB_OK(Delete("b"));
  855. ASSERT_EQ("NOT_FOUND", Get("b"));
  856. Iterator* iter = db_->NewIterator(ReadOptions());
  857. iter->Seek("c");
  858. ASSERT_EQ(IterStatus(iter), "c->vc");
  859. iter->Prev();
  860. ASSERT_EQ(IterStatus(iter), "a->va");
  861. iter->Seek("b");
  862. ASSERT_EQ(IterStatus(iter), "c->vc");
  863. delete iter;
  864. } while (ChangeOptions());
  865. }
  866. TEST_F(DBTest, Recover) {
  867. do {
  868. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  869. ASSERT_LEVELDB_OK(Put("baz", "v5"));
  870. Reopen();
  871. ASSERT_EQ("v1", Get("foo"));
  872. ASSERT_EQ("v1", Get("foo"));
  873. ASSERT_EQ("v5", Get("baz"));
  874. ASSERT_LEVELDB_OK(Put("bar", "v2"));
  875. ASSERT_LEVELDB_OK(Put("foo", "v3"));
  876. Reopen();
  877. ASSERT_EQ("v3", Get("foo"));
  878. ASSERT_LEVELDB_OK(Put("foo", "v4"));
  879. ASSERT_EQ("v4", Get("foo"));
  880. ASSERT_EQ("v2", Get("bar"));
  881. ASSERT_EQ("v5", Get("baz"));
  882. } while (ChangeOptions());
  883. }
  884. TEST_F(DBTest, RecoveryWithEmptyLog) {
  885. do {
  886. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  887. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  888. Reopen();
  889. Reopen();
  890. ASSERT_LEVELDB_OK(Put("foo", "v3"));
  891. Reopen();
  892. ASSERT_EQ("v3", Get("foo"));
  893. } while (ChangeOptions());
  894. }
  895. // Check that writes done during a memtable compaction are recovered
  896. // if the database is shutdown during the memtable compaction.
  897. TEST_F(DBTest, RecoverDuringMemtableCompaction) {
  898. do {
  899. Options options = CurrentOptions();
  900. options.env = env_;
  901. options.write_buffer_size = 1000000;
  902. Reopen(&options);
  903. // Trigger a long memtable compaction and reopen the database during it
  904. ASSERT_LEVELDB_OK(Put("foo", "v1")); // Goes to 1st log file
  905. ASSERT_LEVELDB_OK(
  906. Put("big1", std::string(10000000, 'x'))); // Fills memtable
  907. ASSERT_LEVELDB_OK(
  908. Put("big2", std::string(1000, 'y'))); // Triggers compaction
  909. ASSERT_LEVELDB_OK(Put("bar", "v2")); // Goes to new log file
  910. Reopen(&options);
  911. ASSERT_EQ("v1", Get("foo"));
  912. ASSERT_EQ("v2", Get("bar"));
  913. ASSERT_EQ(std::string(10000000, 'x'), Get("big1"));
  914. ASSERT_EQ(std::string(1000, 'y'), Get("big2"));
  915. } while (ChangeOptions());
  916. }
  917. static std::string Key(int i) {
  918. char buf[100];
  919. std::snprintf(buf, sizeof(buf), "key%06d", i);
  920. return std::string(buf);
  921. }
  922. TEST_F(DBTest, MinorCompactionsHappen) {
  923. Options options = CurrentOptions();
  924. options.write_buffer_size = 10000;
  925. Reopen(&options);
  926. const int N = 500;
  927. int starting_num_tables = TotalTableFiles();
  928. for (int i = 0; i < N; i++) {
  929. ASSERT_LEVELDB_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  930. }
  931. int ending_num_tables = TotalTableFiles();
  932. ASSERT_GT(ending_num_tables, starting_num_tables);
  933. for (int i = 0; i < N; i++) {
  934. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  935. }
  936. Reopen();
  937. for (int i = 0; i < N; i++) {
  938. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  939. }
  940. }
  941. TEST_F(DBTest, RecoverWithLargeLog) {
  942. {
  943. Options options = CurrentOptions();
  944. Reopen(&options);
  945. ASSERT_LEVELDB_OK(Put("big1", std::string(200000, '1')));
  946. ASSERT_LEVELDB_OK(Put("big2", std::string(200000, '2')));
  947. ASSERT_LEVELDB_OK(Put("small3", std::string(10, '3')));
  948. ASSERT_LEVELDB_OK(Put("small4", std::string(10, '4')));
  949. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  950. }
  951. // Make sure that if we re-open with a small write buffer size that
  952. // we flush table files in the middle of a large log file.
  953. Options options = CurrentOptions();
  954. options.write_buffer_size = 100000;
  955. Reopen(&options);
  956. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  957. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  958. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  959. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  960. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  961. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  962. }
  963. TEST_F(DBTest, CompactionsGenerateMultipleFiles) {
  964. Options options = CurrentOptions();
  965. options.write_buffer_size = 100000000; // Large write buffer
  966. Reopen(&options);
  967. Random rnd(301);
  968. // Write 8MB (80 values, each 100K)
  969. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  970. std::vector<std::string> values;
  971. for (int i = 0; i < 80; i++) {
  972. values.push_back(RandomString(&rnd, 100000));
  973. ASSERT_LEVELDB_OK(Put(Key(i), values[i]));
  974. }
  975. // Reopening moves updates to level-0
  976. Reopen(&options);
  977. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  978. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  979. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  980. for (int i = 0; i < 80; i++) {
  981. ASSERT_EQ(Get(Key(i)), values[i]);
  982. }
  983. }
  984. TEST_F(DBTest, RepeatedWritesToSameKey) {
  985. Options options = CurrentOptions();
  986. options.env = env_;
  987. options.write_buffer_size = 100000; // Small write buffer
  988. Reopen(&options);
  989. // We must have at most one file per level except for level-0,
  990. // which may have up to kL0_StopWritesTrigger files.
  991. const int kMaxFiles = config::kNumLevels + config::kL0_StopWritesTrigger;
  992. Random rnd(301);
  993. std::string value = RandomString(&rnd, 2 * options.write_buffer_size);
  994. for (int i = 0; i < 5 * kMaxFiles; i++) {
  995. Put("key", value);
  996. ASSERT_LE(TotalTableFiles(), kMaxFiles);
  997. std::fprintf(stderr, "after %d: %d files\n", i + 1, TotalTableFiles());
  998. }
  999. }
  1000. TEST_F(DBTest, SparseMerge) {
  1001. Options options = CurrentOptions();
  1002. options.compression = kNoCompression;
  1003. Reopen(&options);
  1004. FillLevels("A", "Z");
  1005. // Suppose there is:
  1006. // small amount of data with prefix A
  1007. // large amount of data with prefix B
  1008. // small amount of data with prefix C
  1009. // and that recent updates have made small changes to all three prefixes.
  1010. // Check that we do not do a compaction that merges all of B in one shot.
  1011. const std::string value(1000, 'x');
  1012. Put("A", "va");
  1013. // Write approximately 100MB of "B" values
  1014. for (int i = 0; i < 100000; i++) {
  1015. char key[100];
  1016. std::snprintf(key, sizeof(key), "B%010d", i);
  1017. Put(key, value);
  1018. }
  1019. Put("C", "vc");
  1020. dbfull()->TEST_CompactMemTable();
  1021. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1022. // Make sparse update
  1023. Put("A", "va2");
  1024. Put("B100", "bvalue2");
  1025. Put("C", "vc2");
  1026. dbfull()->TEST_CompactMemTable();
  1027. // Compactions should not cause us to create a situation where
  1028. // a file overlaps too much data at the next level.
  1029. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1030. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1031. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1032. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1033. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1034. }
  1035. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  1036. bool result = (val >= low) && (val <= high);
  1037. if (!result) {
  1038. std::fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  1039. (unsigned long long)(val), (unsigned long long)(low),
  1040. (unsigned long long)(high));
  1041. }
  1042. return result;
  1043. }
  1044. TEST_F(DBTest, ApproximateSizes) {
  1045. do {
  1046. Options options = CurrentOptions();
  1047. options.write_buffer_size = 100000000; // Large write buffer
  1048. options.compression = kNoCompression;
  1049. DestroyAndReopen();
  1050. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1051. Reopen(&options);
  1052. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1053. // Write 8MB (80 values, each 100K)
  1054. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1055. const int N = 80;
  1056. static const int S1 = 100000;
  1057. static const int S2 = 105000; // Allow some expansion from metadata
  1058. Random rnd(301);
  1059. for (int i = 0; i < N; i++) {
  1060. ASSERT_LEVELDB_OK(Put(Key(i), RandomString(&rnd, S1)));
  1061. }
  1062. // 0 because GetApproximateSizes() does not account for memtable space
  1063. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1064. if (options.reuse_logs) {
  1065. // Recovery will reuse memtable, and GetApproximateSizes() does not
  1066. // account for memtable usage;
  1067. Reopen(&options);
  1068. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1069. continue;
  1070. }
  1071. // Check sizes across recovery by reopening a few times
  1072. for (int run = 0; run < 3; run++) {
  1073. Reopen(&options);
  1074. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  1075. for (int i = 0; i < N; i += 10) {
  1076. ASSERT_TRUE(Between(Size("", Key(i)), S1 * i, S2 * i));
  1077. ASSERT_TRUE(Between(Size("", Key(i) + ".suffix"), S1 * (i + 1),
  1078. S2 * (i + 1)));
  1079. ASSERT_TRUE(Between(Size(Key(i), Key(i + 10)), S1 * 10, S2 * 10));
  1080. }
  1081. ASSERT_TRUE(Between(Size("", Key(50)), S1 * 50, S2 * 50));
  1082. ASSERT_TRUE(Between(Size("", Key(50) + ".suffix"), S1 * 50, S2 * 50));
  1083. std::string cstart_str = Key(compact_start);
  1084. std::string cend_str = Key(compact_start + 9);
  1085. Slice cstart = cstart_str;
  1086. Slice cend = cend_str;
  1087. dbfull()->TEST_CompactRange(0, &cstart, &cend);
  1088. }
  1089. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1090. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  1091. }
  1092. } while (ChangeOptions());
  1093. }
  1094. TEST_F(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  1095. do {
  1096. Options options = CurrentOptions();
  1097. options.compression = kNoCompression;
  1098. Reopen();
  1099. Random rnd(301);
  1100. std::string big1 = RandomString(&rnd, 100000);
  1101. ASSERT_LEVELDB_OK(Put(Key(0), RandomString(&rnd, 10000)));
  1102. ASSERT_LEVELDB_OK(Put(Key(1), RandomString(&rnd, 10000)));
  1103. ASSERT_LEVELDB_OK(Put(Key(2), big1));
  1104. ASSERT_LEVELDB_OK(Put(Key(3), RandomString(&rnd, 10000)));
  1105. ASSERT_LEVELDB_OK(Put(Key(4), big1));
  1106. ASSERT_LEVELDB_OK(Put(Key(5), RandomString(&rnd, 10000)));
  1107. ASSERT_LEVELDB_OK(Put(Key(6), RandomString(&rnd, 300000)));
  1108. ASSERT_LEVELDB_OK(Put(Key(7), RandomString(&rnd, 10000)));
  1109. if (options.reuse_logs) {
  1110. // Need to force a memtable compaction since recovery does not do so.
  1111. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1112. }
  1113. // Check sizes across recovery by reopening a few times
  1114. for (int run = 0; run < 3; run++) {
  1115. Reopen(&options);
  1116. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  1117. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  1118. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  1119. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  1120. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  1121. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  1122. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  1123. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  1124. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 560000));
  1125. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  1126. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1127. }
  1128. } while (ChangeOptions());
  1129. }
  1130. TEST_F(DBTest, IteratorPinsRef) {
  1131. Put("foo", "hello");
  1132. // Get iterator that will yield the current contents of the DB.
  1133. Iterator* iter = db_->NewIterator(ReadOptions());
  1134. // Write to force compactions
  1135. Put("foo", "newvalue1");
  1136. for (int i = 0; i < 100; i++) {
  1137. ASSERT_LEVELDB_OK(
  1138. Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  1139. }
  1140. Put("foo", "newvalue2");
  1141. iter->SeekToFirst();
  1142. ASSERT_TRUE(iter->Valid());
  1143. ASSERT_EQ("foo", iter->key().ToString());
  1144. ASSERT_EQ("hello", iter->value().ToString());
  1145. iter->Next();
  1146. ASSERT_TRUE(!iter->Valid());
  1147. delete iter;
  1148. }
  1149. TEST_F(DBTest, Snapshot) {
  1150. do {
  1151. Put("foo", "v1");
  1152. const Snapshot* s1 = db_->GetSnapshot();
  1153. Put("foo", "v2");
  1154. const Snapshot* s2 = db_->GetSnapshot();
  1155. Put("foo", "v3");
  1156. const Snapshot* s3 = db_->GetSnapshot();
  1157. Put("foo", "v4");
  1158. ASSERT_EQ("v1", Get("foo", s1));
  1159. ASSERT_EQ("v2", Get("foo", s2));
  1160. ASSERT_EQ("v3", Get("foo", s3));
  1161. ASSERT_EQ("v4", Get("foo"));
  1162. db_->ReleaseSnapshot(s3);
  1163. ASSERT_EQ("v1", Get("foo", s1));
  1164. ASSERT_EQ("v2", Get("foo", s2));
  1165. ASSERT_EQ("v4", Get("foo"));
  1166. db_->ReleaseSnapshot(s1);
  1167. ASSERT_EQ("v2", Get("foo", s2));
  1168. ASSERT_EQ("v4", Get("foo"));
  1169. db_->ReleaseSnapshot(s2);
  1170. ASSERT_EQ("v4", Get("foo"));
  1171. } while (ChangeOptions());
  1172. }
  1173. TEST_F(DBTest, HiddenValuesAreRemoved) {
  1174. do {
  1175. Random rnd(301);
  1176. FillLevels("a", "z");
  1177. std::string big = RandomString(&rnd, 50000);
  1178. Put("foo", big);
  1179. Put("pastfoo", "v");
  1180. const Snapshot* snapshot = db_->GetSnapshot();
  1181. Put("foo", "tiny");
  1182. Put("pastfoo2", "v2"); // Advance sequence number one more
  1183. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1184. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  1185. ASSERT_EQ(big, Get("foo", snapshot));
  1186. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  1187. db_->ReleaseSnapshot(snapshot);
  1188. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  1189. Slice x("x");
  1190. dbfull()->TEST_CompactRange(0, nullptr, &x);
  1191. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1192. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1193. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  1194. dbfull()->TEST_CompactRange(1, nullptr, &x);
  1195. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1196. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  1197. } while (ChangeOptions());
  1198. }
  1199. TEST_F(DBTest, DeletionMarkers1) {
  1200. Put("foo", "v1");
  1201. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1202. const int last = config::kMaxMemCompactLevel;
  1203. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1204. // Place a table at level last-1 to prevent merging with preceding mutation
  1205. Put("a", "begin");
  1206. Put("z", "end");
  1207. dbfull()->TEST_CompactMemTable();
  1208. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1209. ASSERT_EQ(NumTableFilesAtLevel(last - 1), 1);
  1210. Delete("foo");
  1211. Put("foo", "v2");
  1212. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1213. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1214. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1215. Slice z("z");
  1216. dbfull()->TEST_CompactRange(last - 2, nullptr, &z);
  1217. // DEL eliminated, but v1 remains because we aren't compacting that level
  1218. // (DEL can be eliminated because v2 hides v1).
  1219. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  1220. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr);
  1221. // Merging last-1 w/ last, so we are the base level for "foo", so
  1222. // DEL is removed. (as is v1).
  1223. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  1224. }
  1225. TEST_F(DBTest, DeletionMarkers2) {
  1226. Put("foo", "v1");
  1227. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1228. const int last = config::kMaxMemCompactLevel;
  1229. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1230. // Place a table at level last-1 to prevent merging with preceding mutation
  1231. Put("a", "begin");
  1232. Put("z", "end");
  1233. dbfull()->TEST_CompactMemTable();
  1234. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1235. ASSERT_EQ(NumTableFilesAtLevel(last - 1), 1);
  1236. Delete("foo");
  1237. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1238. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1239. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1240. dbfull()->TEST_CompactRange(last - 2, nullptr, nullptr);
  1241. // DEL kept: "last" file overlaps
  1242. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1243. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr);
  1244. // Merging last-1 w/ last, so we are the base level for "foo", so
  1245. // DEL is removed. (as is v1).
  1246. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  1247. }
  1248. TEST_F(DBTest, OverlapInLevel0) {
  1249. do {
  1250. ASSERT_EQ(config::kMaxMemCompactLevel, 2) << "Fix test to match config";
  1251. // Fill levels 1 and 2 to disable the pushing of new memtables to levels >
  1252. // 0.
  1253. ASSERT_LEVELDB_OK(Put("100", "v100"));
  1254. ASSERT_LEVELDB_OK(Put("999", "v999"));
  1255. dbfull()->TEST_CompactMemTable();
  1256. ASSERT_LEVELDB_OK(Delete("100"));
  1257. ASSERT_LEVELDB_OK(Delete("999"));
  1258. dbfull()->TEST_CompactMemTable();
  1259. ASSERT_EQ("0,1,1", FilesPerLevel());
  1260. // Make files spanning the following ranges in level-0:
  1261. // files[0] 200 .. 900
  1262. // files[1] 300 .. 500
  1263. // Note that files are sorted by smallest key.
  1264. ASSERT_LEVELDB_OK(Put("300", "v300"));
  1265. ASSERT_LEVELDB_OK(Put("500", "v500"));
  1266. dbfull()->TEST_CompactMemTable();
  1267. ASSERT_LEVELDB_OK(Put("200", "v200"));
  1268. ASSERT_LEVELDB_OK(Put("600", "v600"));
  1269. ASSERT_LEVELDB_OK(Put("900", "v900"));
  1270. dbfull()->TEST_CompactMemTable();
  1271. ASSERT_EQ("2,1,1", FilesPerLevel());
  1272. // Compact away the placeholder files we created initially
  1273. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1274. dbfull()->TEST_CompactRange(2, nullptr, nullptr);
  1275. ASSERT_EQ("2", FilesPerLevel());
  1276. // Do a memtable compaction. Before bug-fix, the compaction would
  1277. // not detect the overlap with level-0 files and would incorrectly place
  1278. // the deletion in a deeper level.
  1279. ASSERT_LEVELDB_OK(Delete("600"));
  1280. dbfull()->TEST_CompactMemTable();
  1281. ASSERT_EQ("3", FilesPerLevel());
  1282. ASSERT_EQ("NOT_FOUND", Get("600"));
  1283. } while (ChangeOptions());
  1284. }
  1285. TEST_F(DBTest, L0_CompactionBug_Issue44_a) {
  1286. Reopen();
  1287. ASSERT_LEVELDB_OK(Put("b", "v"));
  1288. Reopen();
  1289. ASSERT_LEVELDB_OK(Delete("b"));
  1290. ASSERT_LEVELDB_OK(Delete("a"));
  1291. Reopen();
  1292. ASSERT_LEVELDB_OK(Delete("a"));
  1293. Reopen();
  1294. ASSERT_LEVELDB_OK(Put("a", "v"));
  1295. Reopen();
  1296. Reopen();
  1297. ASSERT_EQ("(a->v)", Contents());
  1298. DelayMilliseconds(1000); // Wait for compaction to finish
  1299. ASSERT_EQ("(a->v)", Contents());
  1300. }
  1301. TEST_F(DBTest, L0_CompactionBug_Issue44_b) {
  1302. Reopen();
  1303. Put("", "");
  1304. Reopen();
  1305. Delete("e");
  1306. Put("", "");
  1307. Reopen();
  1308. Put("c", "cv");
  1309. Reopen();
  1310. Put("", "");
  1311. Reopen();
  1312. Put("", "");
  1313. DelayMilliseconds(1000); // Wait for compaction to finish
  1314. Reopen();
  1315. Put("d", "dv");
  1316. Reopen();
  1317. Put("", "");
  1318. Reopen();
  1319. Delete("d");
  1320. Delete("b");
  1321. Reopen();
  1322. ASSERT_EQ("(->)(c->cv)", Contents());
  1323. DelayMilliseconds(1000); // Wait for compaction to finish
  1324. ASSERT_EQ("(->)(c->cv)", Contents());
  1325. }
  1326. TEST_F(DBTest, Fflush_Issue474) {
  1327. static const int kNum = 100000;
  1328. Random rnd(test::RandomSeed());
  1329. for (int i = 0; i < kNum; i++) {
  1330. std::fflush(nullptr);
  1331. ASSERT_LEVELDB_OK(Put(RandomKey(&rnd), RandomString(&rnd, 100)));
  1332. }
  1333. }
  1334. TEST_F(DBTest, ComparatorCheck) {
  1335. class NewComparator : public Comparator {
  1336. public:
  1337. const char* Name() const override { return "leveldb.NewComparator"; }
  1338. int Compare(const Slice& a, const Slice& b) const override {
  1339. return BytewiseComparator()->Compare(a, b);
  1340. }
  1341. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  1342. BytewiseComparator()->FindShortestSeparator(s, l);
  1343. }
  1344. void FindShortSuccessor(std::string* key) const override {
  1345. BytewiseComparator()->FindShortSuccessor(key);
  1346. }
  1347. };
  1348. NewComparator cmp;
  1349. Options new_options = CurrentOptions();
  1350. new_options.comparator = &cmp;
  1351. Status s = TryReopen(&new_options);
  1352. ASSERT_TRUE(!s.ok());
  1353. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  1354. << s.ToString();
  1355. }
  1356. TEST_F(DBTest, CustomComparator) {
  1357. class NumberComparator : public Comparator {
  1358. public:
  1359. const char* Name() const override { return "test.NumberComparator"; }
  1360. int Compare(const Slice& a, const Slice& b) const override {
  1361. return ToNumber(a) - ToNumber(b);
  1362. }
  1363. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  1364. ToNumber(*s); // Check format
  1365. ToNumber(l); // Check format
  1366. }
  1367. void FindShortSuccessor(std::string* key) const override {
  1368. ToNumber(*key); // Check format
  1369. }
  1370. private:
  1371. static int ToNumber(const Slice& x) {
  1372. // Check that there are no extra characters.
  1373. EXPECT_TRUE(x.size() >= 2 && x[0] == '[' && x[x.size() - 1] == ']')
  1374. << EscapeString(x);
  1375. int val;
  1376. char ignored;
  1377. EXPECT_TRUE(sscanf(x.ToString().c_str(), "[%i]%c", &val, &ignored) == 1)
  1378. << EscapeString(x);
  1379. return val;
  1380. }
  1381. };
  1382. NumberComparator cmp;
  1383. Options new_options = CurrentOptions();
  1384. new_options.create_if_missing = true;
  1385. new_options.comparator = &cmp;
  1386. new_options.filter_policy = nullptr; // Cannot use bloom filters
  1387. new_options.write_buffer_size = 1000; // Compact more often
  1388. DestroyAndReopen(&new_options);
  1389. ASSERT_LEVELDB_OK(Put("[10]", "ten"));
  1390. ASSERT_LEVELDB_OK(Put("[0x14]", "twenty"));
  1391. for (int i = 0; i < 2; i++) {
  1392. ASSERT_EQ("ten", Get("[10]"));
  1393. ASSERT_EQ("ten", Get("[0xa]"));
  1394. ASSERT_EQ("twenty", Get("[20]"));
  1395. ASSERT_EQ("twenty", Get("[0x14]"));
  1396. ASSERT_EQ("NOT_FOUND", Get("[15]"));
  1397. ASSERT_EQ("NOT_FOUND", Get("[0xf]"));
  1398. Compact("[0]", "[9999]");
  1399. }
  1400. for (int run = 0; run < 2; run++) {
  1401. for (int i = 0; i < 1000; i++) {
  1402. char buf[100];
  1403. std::snprintf(buf, sizeof(buf), "[%d]", i * 10);
  1404. ASSERT_LEVELDB_OK(Put(buf, buf));
  1405. }
  1406. Compact("[0]", "[1000000]");
  1407. }
  1408. }
  1409. TEST_F(DBTest, ManualCompaction) {
  1410. ASSERT_EQ(config::kMaxMemCompactLevel, 2)
  1411. << "Need to update this test to match kMaxMemCompactLevel";
  1412. MakeTables(3, "p", "q");
  1413. ASSERT_EQ("1,1,1", FilesPerLevel());
  1414. // Compaction range falls before files
  1415. Compact("", "c");
  1416. ASSERT_EQ("1,1,1", FilesPerLevel());
  1417. // Compaction range falls after files
  1418. Compact("r", "z");
  1419. ASSERT_EQ("1,1,1", FilesPerLevel());
  1420. // Compaction range overlaps files
  1421. Compact("p1", "p9");
  1422. ASSERT_EQ("0,0,1", FilesPerLevel());
  1423. // Populate a different range
  1424. MakeTables(3, "c", "e");
  1425. ASSERT_EQ("1,1,2", FilesPerLevel());
  1426. // Compact just the new range
  1427. Compact("b", "f");
  1428. ASSERT_EQ("0,0,2", FilesPerLevel());
  1429. // Compact all
  1430. MakeTables(1, "a", "z");
  1431. ASSERT_EQ("0,1,2", FilesPerLevel());
  1432. db_->CompactRange(nullptr, nullptr);
  1433. ASSERT_EQ("0,0,1", FilesPerLevel());
  1434. }
  1435. TEST_F(DBTest, DBOpen_Options) {
  1436. std::string dbname = testing::TempDir() + "db_options_test";
  1437. DestroyDB(dbname, Options());
  1438. // Does not exist, and create_if_missing == false: error
  1439. DB* db = nullptr;
  1440. Options opts;
  1441. opts.create_if_missing = false;
  1442. Status s = DB::Open(opts, dbname, &db);
  1443. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != nullptr);
  1444. ASSERT_TRUE(db == nullptr);
  1445. // Does not exist, and create_if_missing == true: OK
  1446. opts.create_if_missing = true;
  1447. s = DB::Open(opts, dbname, &db);
  1448. ASSERT_LEVELDB_OK(s);
  1449. ASSERT_TRUE(db != nullptr);
  1450. delete db;
  1451. db = nullptr;
  1452. // Does exist, and error_if_exists == true: error
  1453. opts.create_if_missing = false;
  1454. opts.error_if_exists = true;
  1455. s = DB::Open(opts, dbname, &db);
  1456. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != nullptr);
  1457. ASSERT_TRUE(db == nullptr);
  1458. // Does exist, and error_if_exists == false: OK
  1459. opts.create_if_missing = true;
  1460. opts.error_if_exists = false;
  1461. s = DB::Open(opts, dbname, &db);
  1462. ASSERT_LEVELDB_OK(s);
  1463. ASSERT_TRUE(db != nullptr);
  1464. delete db;
  1465. db = nullptr;
  1466. }
  1467. TEST_F(DBTest, DestroyEmptyDir) {
  1468. std::string dbname = testing::TempDir() + "db_empty_dir";
  1469. TestEnv env(Env::Default());
  1470. env.RemoveDir(dbname);
  1471. ASSERT_TRUE(!env.FileExists(dbname));
  1472. Options opts;
  1473. opts.env = &env;
  1474. ASSERT_LEVELDB_OK(env.CreateDir(dbname));
  1475. ASSERT_TRUE(env.FileExists(dbname));
  1476. std::vector<std::string> children;
  1477. ASSERT_LEVELDB_OK(env.GetChildren(dbname, &children));
  1478. // The stock Env's do not filter out '.' and '..' special files.
  1479. ASSERT_EQ(2, children.size());
  1480. ASSERT_LEVELDB_OK(DestroyDB(dbname, opts));
  1481. ASSERT_TRUE(!env.FileExists(dbname));
  1482. // Should also be destroyed if Env is filtering out dot files.
  1483. env.SetIgnoreDotFiles(true);
  1484. ASSERT_LEVELDB_OK(env.CreateDir(dbname));
  1485. ASSERT_TRUE(env.FileExists(dbname));
  1486. ASSERT_LEVELDB_OK(env.GetChildren(dbname, &children));
  1487. ASSERT_EQ(0, children.size());
  1488. ASSERT_LEVELDB_OK(DestroyDB(dbname, opts));
  1489. ASSERT_TRUE(!env.FileExists(dbname));
  1490. }
  1491. TEST_F(DBTest, DestroyOpenDB) {
  1492. std::string dbname = testing::TempDir() + "open_db_dir";
  1493. env_->RemoveDir(dbname);
  1494. ASSERT_TRUE(!env_->FileExists(dbname));
  1495. Options opts;
  1496. opts.create_if_missing = true;
  1497. DB* db = nullptr;
  1498. ASSERT_LEVELDB_OK(DB::Open(opts, dbname, &db));
  1499. ASSERT_TRUE(db != nullptr);
  1500. // Must fail to destroy an open db.
  1501. ASSERT_TRUE(env_->FileExists(dbname));
  1502. ASSERT_TRUE(!DestroyDB(dbname, Options()).ok());
  1503. ASSERT_TRUE(env_->FileExists(dbname));
  1504. delete db;
  1505. db = nullptr;
  1506. // Should succeed destroying a closed db.
  1507. ASSERT_LEVELDB_OK(DestroyDB(dbname, Options()));
  1508. ASSERT_TRUE(!env_->FileExists(dbname));
  1509. }
  1510. TEST_F(DBTest, Locking) {
  1511. DB* db2 = nullptr;
  1512. Status s = DB::Open(CurrentOptions(), dbname_, &db2);
  1513. ASSERT_TRUE(!s.ok()) << "Locking did not prevent re-opening db";
  1514. }
  1515. // Check that number of files does not grow when we are out of space
  1516. TEST_F(DBTest, NoSpace) {
  1517. Options options = CurrentOptions();
  1518. options.env = env_;
  1519. Reopen(&options);
  1520. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  1521. ASSERT_EQ("v1", Get("foo"));
  1522. Compact("a", "z");
  1523. const int num_files = CountFiles();
  1524. // Force out-of-space errors.
  1525. env_->no_space_.store(true, std::memory_order_release);
  1526. for (int i = 0; i < 10; i++) {
  1527. for (int level = 0; level < config::kNumLevels - 1; level++) {
  1528. dbfull()->TEST_CompactRange(level, nullptr, nullptr);
  1529. }
  1530. }
  1531. env_->no_space_.store(false, std::memory_order_release);
  1532. ASSERT_LT(CountFiles(), num_files + 3);
  1533. }
  1534. TEST_F(DBTest, NonWritableFileSystem) {
  1535. Options options = CurrentOptions();
  1536. options.write_buffer_size = 1000;
  1537. options.env = env_;
  1538. Reopen(&options);
  1539. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  1540. // Force errors for new files.
  1541. env_->non_writable_.store(true, std::memory_order_release);
  1542. std::string big(100000, 'x');
  1543. int errors = 0;
  1544. for (int i = 0; i < 20; i++) {
  1545. std::fprintf(stderr, "iter %d; errors %d\n", i, errors);
  1546. if (!Put("foo", big).ok()) {
  1547. errors++;
  1548. DelayMilliseconds(100);
  1549. }
  1550. }
  1551. ASSERT_GT(errors, 0);
  1552. env_->non_writable_.store(false, std::memory_order_release);
  1553. }
  1554. TEST_F(DBTest, WriteSyncError) {
  1555. // Check that log sync errors cause the DB to disallow future writes.
  1556. // (a) Cause log sync calls to fail
  1557. Options options = CurrentOptions();
  1558. options.env = env_;
  1559. Reopen(&options);
  1560. env_->data_sync_error_.store(true, std::memory_order_release);
  1561. // (b) Normal write should succeed
  1562. WriteOptions w;
  1563. ASSERT_LEVELDB_OK(db_->Put(w, "k1", "v1"));
  1564. ASSERT_EQ("v1", Get("k1"));
  1565. // (c) Do a sync write; should fail
  1566. w.sync = true;
  1567. ASSERT_TRUE(!db_->Put(w, "k2", "v2").ok());
  1568. ASSERT_EQ("v1", Get("k1"));
  1569. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1570. // (d) make sync behave normally
  1571. env_->data_sync_error_.store(false, std::memory_order_release);
  1572. // (e) Do a non-sync write; should fail
  1573. w.sync = false;
  1574. ASSERT_TRUE(!db_->Put(w, "k3", "v3").ok());
  1575. ASSERT_EQ("v1", Get("k1"));
  1576. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1577. ASSERT_EQ("NOT_FOUND", Get("k3"));
  1578. }
  1579. TEST_F(DBTest, ManifestWriteError) {
  1580. // Test for the following problem:
  1581. // (a) Compaction produces file F
  1582. // (b) Log record containing F is written to MANIFEST file, but Sync() fails
  1583. // (c) GC deletes F
  1584. // (d) After reopening DB, reads fail since deleted F is named in log record
  1585. // We iterate twice. In the second iteration, everything is the
  1586. // same except the log record never makes it to the MANIFEST file.
  1587. for (int iter = 0; iter < 2; iter++) {
  1588. std::atomic<bool>* error_type = (iter == 0) ? &env_->manifest_sync_error_
  1589. : &env_->manifest_write_error_;
  1590. // Insert foo=>bar mapping
  1591. Options options = CurrentOptions();
  1592. options.env = env_;
  1593. options.create_if_missing = true;
  1594. options.error_if_exists = false;
  1595. DestroyAndReopen(&options);
  1596. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1597. ASSERT_EQ("bar", Get("foo"));
  1598. // Memtable compaction (will succeed)
  1599. dbfull()->TEST_CompactMemTable();
  1600. ASSERT_EQ("bar", Get("foo"));
  1601. const int last = config::kMaxMemCompactLevel;
  1602. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo=>bar is now in last level
  1603. // Merging compaction (will fail)
  1604. error_type->store(true, std::memory_order_release);
  1605. dbfull()->TEST_CompactRange(last, nullptr, nullptr); // Should fail
  1606. ASSERT_EQ("bar", Get("foo"));
  1607. // Recovery: should not lose data
  1608. error_type->store(false, std::memory_order_release);
  1609. Reopen(&options);
  1610. ASSERT_EQ("bar", Get("foo"));
  1611. }
  1612. }
  1613. TEST_F(DBTest, MissingSSTFile) {
  1614. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1615. ASSERT_EQ("bar", Get("foo"));
  1616. // Dump the memtable to disk.
  1617. dbfull()->TEST_CompactMemTable();
  1618. ASSERT_EQ("bar", Get("foo"));
  1619. Close();
  1620. ASSERT_TRUE(DeleteAnSSTFile());
  1621. Options options = CurrentOptions();
  1622. options.paranoid_checks = true;
  1623. Status s = TryReopen(&options);
  1624. ASSERT_TRUE(!s.ok());
  1625. ASSERT_TRUE(s.ToString().find("issing") != std::string::npos) << s.ToString();
  1626. }
  1627. TEST_F(DBTest, StillReadSST) {
  1628. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1629. ASSERT_EQ("bar", Get("foo"));
  1630. // Dump the memtable to disk.
  1631. dbfull()->TEST_CompactMemTable();
  1632. ASSERT_EQ("bar", Get("foo"));
  1633. Close();
  1634. ASSERT_GT(RenameLDBToSST(), 0);
  1635. Options options = CurrentOptions();
  1636. options.paranoid_checks = true;
  1637. Status s = TryReopen(&options);
  1638. ASSERT_TRUE(s.ok());
  1639. ASSERT_EQ("bar", Get("foo"));
  1640. }
  1641. TEST_F(DBTest, FilesDeletedAfterCompaction) {
  1642. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  1643. Compact("a", "z");
  1644. const int num_files = CountFiles();
  1645. for (int i = 0; i < 10; i++) {
  1646. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  1647. Compact("a", "z");
  1648. }
  1649. ASSERT_EQ(CountFiles(), num_files);
  1650. }
  1651. TEST_F(DBTest, BloomFilter) {
  1652. env_->count_random_reads_ = true;
  1653. Options options = CurrentOptions();
  1654. options.env = env_;
  1655. options.block_cache = NewLRUCache(0); // Prevent cache hits
  1656. options.filter_policy = NewBloomFilterPolicy(10);
  1657. Reopen(&options);
  1658. // Populate multiple layers
  1659. const int N = 10000;
  1660. for (int i = 0; i < N; i++) {
  1661. ASSERT_LEVELDB_OK(Put(Key(i), Key(i)));
  1662. }
  1663. Compact("a", "z");
  1664. for (int i = 0; i < N; i += 100) {
  1665. ASSERT_LEVELDB_OK(Put(Key(i), Key(i)));
  1666. }
  1667. dbfull()->TEST_CompactMemTable();
  1668. // Prevent auto compactions triggered by seeks
  1669. env_->delay_data_sync_.store(true, std::memory_order_release);
  1670. // Lookup present keys. Should rarely read from small sstable.
  1671. env_->random_read_counter_.Reset();
  1672. for (int i = 0; i < N; i++) {
  1673. ASSERT_EQ(Key(i), Get(Key(i)));
  1674. }
  1675. int reads = env_->random_read_counter_.Read();
  1676. std::fprintf(stderr, "%d present => %d reads\n", N, reads);
  1677. ASSERT_GE(reads, N);
  1678. ASSERT_LE(reads, N + 2 * N / 100);
  1679. // Lookup present keys. Should rarely read from either sstable.
  1680. env_->random_read_counter_.Reset();
  1681. for (int i = 0; i < N; i++) {
  1682. ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
  1683. }
  1684. reads = env_->random_read_counter_.Read();
  1685. std::fprintf(stderr, "%d missing => %d reads\n", N, reads);
  1686. ASSERT_LE(reads, 3 * N / 100);
  1687. env_->delay_data_sync_.store(false, std::memory_order_release);
  1688. Close();
  1689. delete options.block_cache;
  1690. delete options.filter_policy;
  1691. }
  1692. // Multi-threaded test:
  1693. namespace {
  1694. static const int kNumThreads = 4;
  1695. static const int kTestSeconds = 10;
  1696. static const int kNumKeys = 1000;
  1697. struct MTState {
  1698. DBTest* test;
  1699. std::atomic<bool> stop;
  1700. std::atomic<int> counter[kNumThreads];
  1701. std::atomic<bool> thread_done[kNumThreads];
  1702. };
  1703. struct MTThread {
  1704. MTState* state;
  1705. int id;
  1706. };
  1707. static void MTThreadBody(void* arg) {
  1708. MTThread* t = reinterpret_cast<MTThread*>(arg);
  1709. int id = t->id;
  1710. DB* db = t->state->test->db_;
  1711. int counter = 0;
  1712. std::fprintf(stderr, "... starting thread %d\n", id);
  1713. Random rnd(1000 + id);
  1714. std::string value;
  1715. char valbuf[1500];
  1716. while (!t->state->stop.load(std::memory_order_acquire)) {
  1717. t->state->counter[id].store(counter, std::memory_order_release);
  1718. int key = rnd.Uniform(kNumKeys);
  1719. char keybuf[20];
  1720. std::snprintf(keybuf, sizeof(keybuf), "%016d", key);
  1721. if (rnd.OneIn(2)) {
  1722. // Write values of the form <key, my id, counter>.
  1723. // We add some padding for force compactions.
  1724. std::snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d", key, id,
  1725. static_cast<int>(counter));
  1726. ASSERT_LEVELDB_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  1727. } else {
  1728. // Read a value and verify that it matches the pattern written above.
  1729. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  1730. if (s.IsNotFound()) {
  1731. // Key has not yet been written
  1732. } else {
  1733. // Check that the writer thread counter is >= the counter in the value
  1734. ASSERT_LEVELDB_OK(s);
  1735. int k, w, c;
  1736. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  1737. ASSERT_EQ(k, key);
  1738. ASSERT_GE(w, 0);
  1739. ASSERT_LT(w, kNumThreads);
  1740. ASSERT_LE(c, t->state->counter[w].load(std::memory_order_acquire));
  1741. }
  1742. }
  1743. counter++;
  1744. }
  1745. t->state->thread_done[id].store(true, std::memory_order_release);
  1746. std::fprintf(stderr, "... stopping thread %d after %d ops\n", id, counter);
  1747. }
  1748. } // namespace
  1749. TEST_F(DBTest, MultiThreaded) {
  1750. do {
  1751. // Initialize state
  1752. MTState mt;
  1753. mt.test = this;
  1754. mt.stop.store(false, std::memory_order_release);
  1755. for (int id = 0; id < kNumThreads; id++) {
  1756. mt.counter[id].store(false, std::memory_order_release);
  1757. mt.thread_done[id].store(false, std::memory_order_release);
  1758. }
  1759. // Start threads
  1760. MTThread thread[kNumThreads];
  1761. for (int id = 0; id < kNumThreads; id++) {
  1762. thread[id].state = &mt;
  1763. thread[id].id = id;
  1764. env_->StartThread(MTThreadBody, &thread[id]);
  1765. }
  1766. // Let them run for a while
  1767. DelayMilliseconds(kTestSeconds * 1000);
  1768. // Stop the threads and wait for them to finish
  1769. mt.stop.store(true, std::memory_order_release);
  1770. for (int id = 0; id < kNumThreads; id++) {
  1771. while (!mt.thread_done[id].load(std::memory_order_acquire)) {
  1772. DelayMilliseconds(100);
  1773. }
  1774. }
  1775. } while (ChangeOptions());
  1776. }
  1777. namespace {
  1778. typedef std::map<std::string, std::string> KVMap;
  1779. }
  1780. class ModelDB : public DB {
  1781. public:
  1782. class ModelSnapshot : public Snapshot {
  1783. public:
  1784. KVMap map_;
  1785. };
  1786. explicit ModelDB(const Options& options) : options_(options) {}
  1787. ~ModelDB() override = default;
  1788. Status Put(const WriteOptions& o, const Slice& k, const Slice& v) override {
  1789. return DB::Put(o, k, v);
  1790. }
  1791. Status Delete(const WriteOptions& o, const Slice& key) override {
  1792. return DB::Delete(o, key);
  1793. }
  1794. Status Get(const ReadOptions& options, const Slice& key,
  1795. std::string* value) override {
  1796. assert(false); // Not implemented
  1797. return Status::NotFound(key);
  1798. }
  1799. Iterator* NewIterator(const ReadOptions& options) override {
  1800. if (options.snapshot == nullptr) {
  1801. KVMap* saved = new KVMap;
  1802. *saved = map_;
  1803. return new ModelIter(saved, true);
  1804. } else {
  1805. const KVMap* snapshot_state =
  1806. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1807. return new ModelIter(snapshot_state, false);
  1808. }
  1809. }
  1810. const Snapshot* GetSnapshot() override {
  1811. ModelSnapshot* snapshot = new ModelSnapshot;
  1812. snapshot->map_ = map_;
  1813. return snapshot;
  1814. }
  1815. void ReleaseSnapshot(const Snapshot* snapshot) override {
  1816. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1817. }
  1818. Status Write(const WriteOptions& options, WriteBatch* batch) override {
  1819. class Handler : public WriteBatch::Handler {
  1820. public:
  1821. KVMap* map_;
  1822. void Put(const Slice& key, const Slice& value) override {
  1823. (*map_)[key.ToString()] = value.ToString();
  1824. }
  1825. void Delete(const Slice& key) override { map_->erase(key.ToString()); }
  1826. };
  1827. Handler handler;
  1828. handler.map_ = &map_;
  1829. return batch->Iterate(&handler);
  1830. }
  1831. bool GetProperty(const Slice& property, std::string* value) override {
  1832. return false;
  1833. }
  1834. void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) override {
  1835. for (int i = 0; i < n; i++) {
  1836. sizes[i] = 0;
  1837. }
  1838. }
  1839. void CompactRange(const Slice* start, const Slice* end) override {}
  1840. private:
  1841. class ModelIter : public Iterator {
  1842. public:
  1843. ModelIter(const KVMap* map, bool owned)
  1844. : map_(map), owned_(owned), iter_(map_->end()) {}
  1845. ~ModelIter() override {
  1846. if (owned_) delete map_;
  1847. }
  1848. bool Valid() const override { return iter_ != map_->end(); }
  1849. void SeekToFirst() override { iter_ = map_->begin(); }
  1850. void SeekToLast() override {
  1851. if (map_->empty()) {
  1852. iter_ = map_->end();
  1853. } else {
  1854. iter_ = map_->find(map_->rbegin()->first);
  1855. }
  1856. }
  1857. void Seek(const Slice& k) override {
  1858. iter_ = map_->lower_bound(k.ToString());
  1859. }
  1860. void Next() override { ++iter_; }
  1861. void Prev() override { --iter_; }
  1862. Slice key() const override { return iter_->first; }
  1863. Slice value() const override { return iter_->second; }
  1864. Status status() const override { return Status::OK(); }
  1865. private:
  1866. const KVMap* const map_;
  1867. const bool owned_; // Do we own map_
  1868. KVMap::const_iterator iter_;
  1869. };
  1870. const Options options_;
  1871. KVMap map_;
  1872. };
  1873. static bool CompareIterators(int step, DB* model, DB* db,
  1874. const Snapshot* model_snap,
  1875. const Snapshot* db_snap) {
  1876. ReadOptions options;
  1877. options.snapshot = model_snap;
  1878. Iterator* miter = model->NewIterator(options);
  1879. options.snapshot = db_snap;
  1880. Iterator* dbiter = db->NewIterator(options);
  1881. bool ok = true;
  1882. int count = 0;
  1883. std::vector<std::string> seek_keys;
  1884. // Compare equality of all elements using Next(). Save some of the keys for
  1885. // comparing Seek equality.
  1886. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1887. ok && miter->Valid() && dbiter->Valid(); miter->Next(), dbiter->Next()) {
  1888. count++;
  1889. if (miter->key().compare(dbiter->key()) != 0) {
  1890. std::fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n", step,
  1891. EscapeString(miter->key()).c_str(),
  1892. EscapeString(dbiter->key()).c_str());
  1893. ok = false;
  1894. break;
  1895. }
  1896. if (miter->value().compare(dbiter->value()) != 0) {
  1897. std::fprintf(stderr,
  1898. "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1899. step, EscapeString(miter->key()).c_str(),
  1900. EscapeString(miter->value()).c_str(),
  1901. EscapeString(miter->value()).c_str());
  1902. ok = false;
  1903. break;
  1904. }
  1905. if (count % 10 == 0) {
  1906. seek_keys.push_back(miter->key().ToString());
  1907. }
  1908. }
  1909. if (ok) {
  1910. if (miter->Valid() != dbiter->Valid()) {
  1911. std::fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1912. step, miter->Valid(), dbiter->Valid());
  1913. ok = false;
  1914. }
  1915. }
  1916. if (ok) {
  1917. // Validate iterator equality when performing seeks.
  1918. for (auto kiter = seek_keys.begin(); ok && kiter != seek_keys.end();
  1919. ++kiter) {
  1920. miter->Seek(*kiter);
  1921. dbiter->Seek(*kiter);
  1922. if (!miter->Valid() || !dbiter->Valid()) {
  1923. std::fprintf(stderr, "step %d: Seek iterators invalid: %d vs. %d\n",
  1924. step, miter->Valid(), dbiter->Valid());
  1925. ok = false;
  1926. }
  1927. if (miter->key().compare(dbiter->key()) != 0) {
  1928. std::fprintf(stderr, "step %d: Seek key mismatch: '%s' vs. '%s'\n",
  1929. step, EscapeString(miter->key()).c_str(),
  1930. EscapeString(dbiter->key()).c_str());
  1931. ok = false;
  1932. break;
  1933. }
  1934. if (miter->value().compare(dbiter->value()) != 0) {
  1935. std::fprintf(
  1936. stderr,
  1937. "step %d: Seek value mismatch for key '%s': '%s' vs. '%s'\n", step,
  1938. EscapeString(miter->key()).c_str(),
  1939. EscapeString(miter->value()).c_str(),
  1940. EscapeString(miter->value()).c_str());
  1941. ok = false;
  1942. break;
  1943. }
  1944. }
  1945. }
  1946. std::fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1947. delete miter;
  1948. delete dbiter;
  1949. return ok;
  1950. }
  1951. TEST_F(DBTest, Randomized) {
  1952. Random rnd(test::RandomSeed());
  1953. do {
  1954. ModelDB model(CurrentOptions());
  1955. const int N = 10000;
  1956. const Snapshot* model_snap = nullptr;
  1957. const Snapshot* db_snap = nullptr;
  1958. std::string k, v;
  1959. for (int step = 0; step < N; step++) {
  1960. if (step % 100 == 0) {
  1961. std::fprintf(stderr, "Step %d of %d\n", step, N);
  1962. }
  1963. // TODO(sanjay): Test Get() works
  1964. int p = rnd.Uniform(100);
  1965. if (p < 45) { // Put
  1966. k = RandomKey(&rnd);
  1967. v = RandomString(
  1968. &rnd, rnd.OneIn(20) ? 100 + rnd.Uniform(100) : rnd.Uniform(8));
  1969. ASSERT_LEVELDB_OK(model.Put(WriteOptions(), k, v));
  1970. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), k, v));
  1971. } else if (p < 90) { // Delete
  1972. k = RandomKey(&rnd);
  1973. ASSERT_LEVELDB_OK(model.Delete(WriteOptions(), k));
  1974. ASSERT_LEVELDB_OK(db_->Delete(WriteOptions(), k));
  1975. } else { // Multi-element batch
  1976. WriteBatch b;
  1977. const int num = rnd.Uniform(8);
  1978. for (int i = 0; i < num; i++) {
  1979. if (i == 0 || !rnd.OneIn(10)) {
  1980. k = RandomKey(&rnd);
  1981. } else {
  1982. // Periodically re-use the same key from the previous iter, so
  1983. // we have multiple entries in the write batch for the same key
  1984. }
  1985. if (rnd.OneIn(2)) {
  1986. v = RandomString(&rnd, rnd.Uniform(10));
  1987. b.Put(k, v);
  1988. } else {
  1989. b.Delete(k);
  1990. }
  1991. }
  1992. ASSERT_LEVELDB_OK(model.Write(WriteOptions(), &b));
  1993. ASSERT_LEVELDB_OK(db_->Write(WriteOptions(), &b));
  1994. }
  1995. if ((step % 100) == 0) {
  1996. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  1997. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1998. // Save a snapshot from each DB this time that we'll use next
  1999. // time we compare things, to make sure the current state is
  2000. // preserved with the snapshot
  2001. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  2002. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  2003. Reopen();
  2004. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  2005. model_snap = model.GetSnapshot();
  2006. db_snap = db_->GetSnapshot();
  2007. }
  2008. }
  2009. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  2010. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  2011. } while (ChangeOptions());
  2012. }
  2013. } // namespace leveldb