作者: 谢瑞阳 10225101483 徐翔宇 10225101535
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2303 line
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 年之前
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 <string>
  7. #include "gtest/gtest.h"
  8. #include "third_party/benchmark/include/benchmark/benchmark.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, Recover) {
  849. do {
  850. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  851. ASSERT_LEVELDB_OK(Put("baz", "v5"));
  852. Reopen();
  853. ASSERT_EQ("v1", Get("foo"));
  854. ASSERT_EQ("v1", Get("foo"));
  855. ASSERT_EQ("v5", Get("baz"));
  856. ASSERT_LEVELDB_OK(Put("bar", "v2"));
  857. ASSERT_LEVELDB_OK(Put("foo", "v3"));
  858. Reopen();
  859. ASSERT_EQ("v3", Get("foo"));
  860. ASSERT_LEVELDB_OK(Put("foo", "v4"));
  861. ASSERT_EQ("v4", Get("foo"));
  862. ASSERT_EQ("v2", Get("bar"));
  863. ASSERT_EQ("v5", Get("baz"));
  864. } while (ChangeOptions());
  865. }
  866. TEST_F(DBTest, RecoveryWithEmptyLog) {
  867. do {
  868. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  869. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  870. Reopen();
  871. Reopen();
  872. ASSERT_LEVELDB_OK(Put("foo", "v3"));
  873. Reopen();
  874. ASSERT_EQ("v3", Get("foo"));
  875. } while (ChangeOptions());
  876. }
  877. // Check that writes done during a memtable compaction are recovered
  878. // if the database is shutdown during the memtable compaction.
  879. TEST_F(DBTest, RecoverDuringMemtableCompaction) {
  880. do {
  881. Options options = CurrentOptions();
  882. options.env = env_;
  883. options.write_buffer_size = 1000000;
  884. Reopen(&options);
  885. // Trigger a long memtable compaction and reopen the database during it
  886. ASSERT_LEVELDB_OK(Put("foo", "v1")); // Goes to 1st log file
  887. ASSERT_LEVELDB_OK(
  888. Put("big1", std::string(10000000, 'x'))); // Fills memtable
  889. ASSERT_LEVELDB_OK(
  890. Put("big2", std::string(1000, 'y'))); // Triggers compaction
  891. ASSERT_LEVELDB_OK(Put("bar", "v2")); // Goes to new log file
  892. Reopen(&options);
  893. ASSERT_EQ("v1", Get("foo"));
  894. ASSERT_EQ("v2", Get("bar"));
  895. ASSERT_EQ(std::string(10000000, 'x'), Get("big1"));
  896. ASSERT_EQ(std::string(1000, 'y'), Get("big2"));
  897. } while (ChangeOptions());
  898. }
  899. static std::string Key(int i) {
  900. char buf[100];
  901. std::snprintf(buf, sizeof(buf), "key%06d", i);
  902. return std::string(buf);
  903. }
  904. TEST_F(DBTest, MinorCompactionsHappen) {
  905. Options options = CurrentOptions();
  906. options.write_buffer_size = 10000;
  907. Reopen(&options);
  908. const int N = 500;
  909. int starting_num_tables = TotalTableFiles();
  910. for (int i = 0; i < N; i++) {
  911. ASSERT_LEVELDB_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  912. }
  913. int ending_num_tables = TotalTableFiles();
  914. ASSERT_GT(ending_num_tables, starting_num_tables);
  915. for (int i = 0; i < N; i++) {
  916. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  917. }
  918. Reopen();
  919. for (int i = 0; i < N; i++) {
  920. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  921. }
  922. }
  923. TEST_F(DBTest, RecoverWithLargeLog) {
  924. {
  925. Options options = CurrentOptions();
  926. Reopen(&options);
  927. ASSERT_LEVELDB_OK(Put("big1", std::string(200000, '1')));
  928. ASSERT_LEVELDB_OK(Put("big2", std::string(200000, '2')));
  929. ASSERT_LEVELDB_OK(Put("small3", std::string(10, '3')));
  930. ASSERT_LEVELDB_OK(Put("small4", std::string(10, '4')));
  931. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  932. }
  933. // Make sure that if we re-open with a small write buffer size that
  934. // we flush table files in the middle of a large log file.
  935. Options options = CurrentOptions();
  936. options.write_buffer_size = 100000;
  937. Reopen(&options);
  938. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  939. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  940. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  941. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  942. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  943. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  944. }
  945. TEST_F(DBTest, CompactionsGenerateMultipleFiles) {
  946. Options options = CurrentOptions();
  947. options.write_buffer_size = 100000000; // Large write buffer
  948. Reopen(&options);
  949. Random rnd(301);
  950. // Write 8MB (80 values, each 100K)
  951. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  952. std::vector<std::string> values;
  953. for (int i = 0; i < 80; i++) {
  954. values.push_back(RandomString(&rnd, 100000));
  955. ASSERT_LEVELDB_OK(Put(Key(i), values[i]));
  956. }
  957. // Reopening moves updates to level-0
  958. Reopen(&options);
  959. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  960. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  961. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  962. for (int i = 0; i < 80; i++) {
  963. ASSERT_EQ(Get(Key(i)), values[i]);
  964. }
  965. }
  966. TEST_F(DBTest, RepeatedWritesToSameKey) {
  967. Options options = CurrentOptions();
  968. options.env = env_;
  969. options.write_buffer_size = 100000; // Small write buffer
  970. Reopen(&options);
  971. // We must have at most one file per level except for level-0,
  972. // which may have up to kL0_StopWritesTrigger files.
  973. const int kMaxFiles = config::kNumLevels + config::kL0_StopWritesTrigger;
  974. Random rnd(301);
  975. std::string value = RandomString(&rnd, 2 * options.write_buffer_size);
  976. for (int i = 0; i < 5 * kMaxFiles; i++) {
  977. Put("key", value);
  978. ASSERT_LE(TotalTableFiles(), kMaxFiles);
  979. std::fprintf(stderr, "after %d: %d files\n", i + 1, TotalTableFiles());
  980. }
  981. }
  982. TEST_F(DBTest, SparseMerge) {
  983. Options options = CurrentOptions();
  984. options.compression = kNoCompression;
  985. Reopen(&options);
  986. FillLevels("A", "Z");
  987. // Suppose there is:
  988. // small amount of data with prefix A
  989. // large amount of data with prefix B
  990. // small amount of data with prefix C
  991. // and that recent updates have made small changes to all three prefixes.
  992. // Check that we do not do a compaction that merges all of B in one shot.
  993. const std::string value(1000, 'x');
  994. Put("A", "va");
  995. // Write approximately 100MB of "B" values
  996. for (int i = 0; i < 100000; i++) {
  997. char key[100];
  998. std::snprintf(key, sizeof(key), "B%010d", i);
  999. Put(key, value);
  1000. }
  1001. Put("C", "vc");
  1002. dbfull()->TEST_CompactMemTable();
  1003. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1004. // Make sparse update
  1005. Put("A", "va2");
  1006. Put("B100", "bvalue2");
  1007. Put("C", "vc2");
  1008. dbfull()->TEST_CompactMemTable();
  1009. // Compactions should not cause us to create a situation where
  1010. // a file overlaps too much data at the next level.
  1011. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1012. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1013. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1014. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1015. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20 * 1048576);
  1016. }
  1017. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  1018. bool result = (val >= low) && (val <= high);
  1019. if (!result) {
  1020. std::fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  1021. (unsigned long long)(val), (unsigned long long)(low),
  1022. (unsigned long long)(high));
  1023. }
  1024. return result;
  1025. }
  1026. TEST_F(DBTest, ApproximateSizes) {
  1027. do {
  1028. Options options = CurrentOptions();
  1029. options.write_buffer_size = 100000000; // Large write buffer
  1030. options.compression = kNoCompression;
  1031. DestroyAndReopen();
  1032. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1033. Reopen(&options);
  1034. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1035. // Write 8MB (80 values, each 100K)
  1036. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1037. const int N = 80;
  1038. static const int S1 = 100000;
  1039. static const int S2 = 105000; // Allow some expansion from metadata
  1040. Random rnd(301);
  1041. for (int i = 0; i < N; i++) {
  1042. ASSERT_LEVELDB_OK(Put(Key(i), RandomString(&rnd, S1)));
  1043. }
  1044. // 0 because GetApproximateSizes() does not account for memtable space
  1045. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1046. if (options.reuse_logs) {
  1047. // Recovery will reuse memtable, and GetApproximateSizes() does not
  1048. // account for memtable usage;
  1049. Reopen(&options);
  1050. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1051. continue;
  1052. }
  1053. // Check sizes across recovery by reopening a few times
  1054. for (int run = 0; run < 3; run++) {
  1055. Reopen(&options);
  1056. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  1057. for (int i = 0; i < N; i += 10) {
  1058. ASSERT_TRUE(Between(Size("", Key(i)), S1 * i, S2 * i));
  1059. ASSERT_TRUE(Between(Size("", Key(i) + ".suffix"), S1 * (i + 1),
  1060. S2 * (i + 1)));
  1061. ASSERT_TRUE(Between(Size(Key(i), Key(i + 10)), S1 * 10, S2 * 10));
  1062. }
  1063. ASSERT_TRUE(Between(Size("", Key(50)), S1 * 50, S2 * 50));
  1064. ASSERT_TRUE(Between(Size("", Key(50) + ".suffix"), S1 * 50, S2 * 50));
  1065. std::string cstart_str = Key(compact_start);
  1066. std::string cend_str = Key(compact_start + 9);
  1067. Slice cstart = cstart_str;
  1068. Slice cend = cend_str;
  1069. dbfull()->TEST_CompactRange(0, &cstart, &cend);
  1070. }
  1071. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1072. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  1073. }
  1074. } while (ChangeOptions());
  1075. }
  1076. TEST_F(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  1077. do {
  1078. Options options = CurrentOptions();
  1079. options.compression = kNoCompression;
  1080. Reopen();
  1081. Random rnd(301);
  1082. std::string big1 = RandomString(&rnd, 100000);
  1083. ASSERT_LEVELDB_OK(Put(Key(0), RandomString(&rnd, 10000)));
  1084. ASSERT_LEVELDB_OK(Put(Key(1), RandomString(&rnd, 10000)));
  1085. ASSERT_LEVELDB_OK(Put(Key(2), big1));
  1086. ASSERT_LEVELDB_OK(Put(Key(3), RandomString(&rnd, 10000)));
  1087. ASSERT_LEVELDB_OK(Put(Key(4), big1));
  1088. ASSERT_LEVELDB_OK(Put(Key(5), RandomString(&rnd, 10000)));
  1089. ASSERT_LEVELDB_OK(Put(Key(6), RandomString(&rnd, 300000)));
  1090. ASSERT_LEVELDB_OK(Put(Key(7), RandomString(&rnd, 10000)));
  1091. if (options.reuse_logs) {
  1092. // Need to force a memtable compaction since recovery does not do so.
  1093. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1094. }
  1095. // Check sizes across recovery by reopening a few times
  1096. for (int run = 0; run < 3; run++) {
  1097. Reopen(&options);
  1098. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  1099. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  1100. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  1101. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  1102. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  1103. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  1104. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  1105. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  1106. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 560000));
  1107. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  1108. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1109. }
  1110. } while (ChangeOptions());
  1111. }
  1112. TEST_F(DBTest, IteratorPinsRef) {
  1113. Put("foo", "hello");
  1114. // Get iterator that will yield the current contents of the DB.
  1115. Iterator* iter = db_->NewIterator(ReadOptions());
  1116. // Write to force compactions
  1117. Put("foo", "newvalue1");
  1118. for (int i = 0; i < 100; i++) {
  1119. ASSERT_LEVELDB_OK(
  1120. Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  1121. }
  1122. Put("foo", "newvalue2");
  1123. iter->SeekToFirst();
  1124. ASSERT_TRUE(iter->Valid());
  1125. ASSERT_EQ("foo", iter->key().ToString());
  1126. ASSERT_EQ("hello", iter->value().ToString());
  1127. iter->Next();
  1128. ASSERT_TRUE(!iter->Valid());
  1129. delete iter;
  1130. }
  1131. TEST_F(DBTest, Snapshot) {
  1132. do {
  1133. Put("foo", "v1");
  1134. const Snapshot* s1 = db_->GetSnapshot();
  1135. Put("foo", "v2");
  1136. const Snapshot* s2 = db_->GetSnapshot();
  1137. Put("foo", "v3");
  1138. const Snapshot* s3 = db_->GetSnapshot();
  1139. Put("foo", "v4");
  1140. ASSERT_EQ("v1", Get("foo", s1));
  1141. ASSERT_EQ("v2", Get("foo", s2));
  1142. ASSERT_EQ("v3", Get("foo", s3));
  1143. ASSERT_EQ("v4", Get("foo"));
  1144. db_->ReleaseSnapshot(s3);
  1145. ASSERT_EQ("v1", Get("foo", s1));
  1146. ASSERT_EQ("v2", Get("foo", s2));
  1147. ASSERT_EQ("v4", Get("foo"));
  1148. db_->ReleaseSnapshot(s1);
  1149. ASSERT_EQ("v2", Get("foo", s2));
  1150. ASSERT_EQ("v4", Get("foo"));
  1151. db_->ReleaseSnapshot(s2);
  1152. ASSERT_EQ("v4", Get("foo"));
  1153. } while (ChangeOptions());
  1154. }
  1155. TEST_F(DBTest, HiddenValuesAreRemoved) {
  1156. do {
  1157. Random rnd(301);
  1158. FillLevels("a", "z");
  1159. std::string big = RandomString(&rnd, 50000);
  1160. Put("foo", big);
  1161. Put("pastfoo", "v");
  1162. const Snapshot* snapshot = db_->GetSnapshot();
  1163. Put("foo", "tiny");
  1164. Put("pastfoo2", "v2"); // Advance sequence number one more
  1165. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1166. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  1167. ASSERT_EQ(big, Get("foo", snapshot));
  1168. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  1169. db_->ReleaseSnapshot(snapshot);
  1170. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  1171. Slice x("x");
  1172. dbfull()->TEST_CompactRange(0, nullptr, &x);
  1173. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1174. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1175. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  1176. dbfull()->TEST_CompactRange(1, nullptr, &x);
  1177. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1178. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  1179. } while (ChangeOptions());
  1180. }
  1181. TEST_F(DBTest, DeletionMarkers1) {
  1182. Put("foo", "v1");
  1183. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1184. const int last = config::kMaxMemCompactLevel;
  1185. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1186. // Place a table at level last-1 to prevent merging with preceding mutation
  1187. Put("a", "begin");
  1188. Put("z", "end");
  1189. dbfull()->TEST_CompactMemTable();
  1190. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1191. ASSERT_EQ(NumTableFilesAtLevel(last - 1), 1);
  1192. Delete("foo");
  1193. Put("foo", "v2");
  1194. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1195. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1196. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1197. Slice z("z");
  1198. dbfull()->TEST_CompactRange(last - 2, nullptr, &z);
  1199. // DEL eliminated, but v1 remains because we aren't compacting that level
  1200. // (DEL can be eliminated because v2 hides v1).
  1201. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  1202. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr);
  1203. // Merging last-1 w/ last, so we are the base level for "foo", so
  1204. // DEL is removed. (as is v1).
  1205. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  1206. }
  1207. TEST_F(DBTest, DeletionMarkers2) {
  1208. Put("foo", "v1");
  1209. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable());
  1210. const int last = config::kMaxMemCompactLevel;
  1211. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1212. // Place a table at level last-1 to prevent merging with preceding mutation
  1213. Put("a", "begin");
  1214. Put("z", "end");
  1215. dbfull()->TEST_CompactMemTable();
  1216. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1217. ASSERT_EQ(NumTableFilesAtLevel(last - 1), 1);
  1218. Delete("foo");
  1219. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1220. ASSERT_LEVELDB_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1221. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1222. dbfull()->TEST_CompactRange(last - 2, nullptr, nullptr);
  1223. // DEL kept: "last" file overlaps
  1224. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1225. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr);
  1226. // Merging last-1 w/ last, so we are the base level for "foo", so
  1227. // DEL is removed. (as is v1).
  1228. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  1229. }
  1230. TEST_F(DBTest, OverlapInLevel0) {
  1231. do {
  1232. ASSERT_EQ(config::kMaxMemCompactLevel, 2) << "Fix test to match config";
  1233. // Fill levels 1 and 2 to disable the pushing of new memtables to levels >
  1234. // 0.
  1235. ASSERT_LEVELDB_OK(Put("100", "v100"));
  1236. ASSERT_LEVELDB_OK(Put("999", "v999"));
  1237. dbfull()->TEST_CompactMemTable();
  1238. ASSERT_LEVELDB_OK(Delete("100"));
  1239. ASSERT_LEVELDB_OK(Delete("999"));
  1240. dbfull()->TEST_CompactMemTable();
  1241. ASSERT_EQ("0,1,1", FilesPerLevel());
  1242. // Make files spanning the following ranges in level-0:
  1243. // files[0] 200 .. 900
  1244. // files[1] 300 .. 500
  1245. // Note that files are sorted by smallest key.
  1246. ASSERT_LEVELDB_OK(Put("300", "v300"));
  1247. ASSERT_LEVELDB_OK(Put("500", "v500"));
  1248. dbfull()->TEST_CompactMemTable();
  1249. ASSERT_LEVELDB_OK(Put("200", "v200"));
  1250. ASSERT_LEVELDB_OK(Put("600", "v600"));
  1251. ASSERT_LEVELDB_OK(Put("900", "v900"));
  1252. dbfull()->TEST_CompactMemTable();
  1253. ASSERT_EQ("2,1,1", FilesPerLevel());
  1254. // Compact away the placeholder files we created initially
  1255. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1256. dbfull()->TEST_CompactRange(2, nullptr, nullptr);
  1257. ASSERT_EQ("2", FilesPerLevel());
  1258. // Do a memtable compaction. Before bug-fix, the compaction would
  1259. // not detect the overlap with level-0 files and would incorrectly place
  1260. // the deletion in a deeper level.
  1261. ASSERT_LEVELDB_OK(Delete("600"));
  1262. dbfull()->TEST_CompactMemTable();
  1263. ASSERT_EQ("3", FilesPerLevel());
  1264. ASSERT_EQ("NOT_FOUND", Get("600"));
  1265. } while (ChangeOptions());
  1266. }
  1267. TEST_F(DBTest, L0_CompactionBug_Issue44_a) {
  1268. Reopen();
  1269. ASSERT_LEVELDB_OK(Put("b", "v"));
  1270. Reopen();
  1271. ASSERT_LEVELDB_OK(Delete("b"));
  1272. ASSERT_LEVELDB_OK(Delete("a"));
  1273. Reopen();
  1274. ASSERT_LEVELDB_OK(Delete("a"));
  1275. Reopen();
  1276. ASSERT_LEVELDB_OK(Put("a", "v"));
  1277. Reopen();
  1278. Reopen();
  1279. ASSERT_EQ("(a->v)", Contents());
  1280. DelayMilliseconds(1000); // Wait for compaction to finish
  1281. ASSERT_EQ("(a->v)", Contents());
  1282. }
  1283. TEST_F(DBTest, L0_CompactionBug_Issue44_b) {
  1284. Reopen();
  1285. Put("", "");
  1286. Reopen();
  1287. Delete("e");
  1288. Put("", "");
  1289. Reopen();
  1290. Put("c", "cv");
  1291. Reopen();
  1292. Put("", "");
  1293. Reopen();
  1294. Put("", "");
  1295. DelayMilliseconds(1000); // Wait for compaction to finish
  1296. Reopen();
  1297. Put("d", "dv");
  1298. Reopen();
  1299. Put("", "");
  1300. Reopen();
  1301. Delete("d");
  1302. Delete("b");
  1303. Reopen();
  1304. ASSERT_EQ("(->)(c->cv)", Contents());
  1305. DelayMilliseconds(1000); // Wait for compaction to finish
  1306. ASSERT_EQ("(->)(c->cv)", Contents());
  1307. }
  1308. TEST_F(DBTest, Fflush_Issue474) {
  1309. static const int kNum = 100000;
  1310. Random rnd(test::RandomSeed());
  1311. for (int i = 0; i < kNum; i++) {
  1312. std::fflush(nullptr);
  1313. ASSERT_LEVELDB_OK(Put(RandomKey(&rnd), RandomString(&rnd, 100)));
  1314. }
  1315. }
  1316. TEST_F(DBTest, ComparatorCheck) {
  1317. class NewComparator : public Comparator {
  1318. public:
  1319. const char* Name() const override { return "leveldb.NewComparator"; }
  1320. int Compare(const Slice& a, const Slice& b) const override {
  1321. return BytewiseComparator()->Compare(a, b);
  1322. }
  1323. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  1324. BytewiseComparator()->FindShortestSeparator(s, l);
  1325. }
  1326. void FindShortSuccessor(std::string* key) const override {
  1327. BytewiseComparator()->FindShortSuccessor(key);
  1328. }
  1329. };
  1330. NewComparator cmp;
  1331. Options new_options = CurrentOptions();
  1332. new_options.comparator = &cmp;
  1333. Status s = TryReopen(&new_options);
  1334. ASSERT_TRUE(!s.ok());
  1335. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  1336. << s.ToString();
  1337. }
  1338. TEST_F(DBTest, CustomComparator) {
  1339. class NumberComparator : public Comparator {
  1340. public:
  1341. const char* Name() const override { return "test.NumberComparator"; }
  1342. int Compare(const Slice& a, const Slice& b) const override {
  1343. return ToNumber(a) - ToNumber(b);
  1344. }
  1345. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  1346. ToNumber(*s); // Check format
  1347. ToNumber(l); // Check format
  1348. }
  1349. void FindShortSuccessor(std::string* key) const override {
  1350. ToNumber(*key); // Check format
  1351. }
  1352. private:
  1353. static int ToNumber(const Slice& x) {
  1354. // Check that there are no extra characters.
  1355. EXPECT_TRUE(x.size() >= 2 && x[0] == '[' && x[x.size() - 1] == ']')
  1356. << EscapeString(x);
  1357. int val;
  1358. char ignored;
  1359. EXPECT_TRUE(sscanf(x.ToString().c_str(), "[%i]%c", &val, &ignored) == 1)
  1360. << EscapeString(x);
  1361. return val;
  1362. }
  1363. };
  1364. NumberComparator cmp;
  1365. Options new_options = CurrentOptions();
  1366. new_options.create_if_missing = true;
  1367. new_options.comparator = &cmp;
  1368. new_options.filter_policy = nullptr; // Cannot use bloom filters
  1369. new_options.write_buffer_size = 1000; // Compact more often
  1370. DestroyAndReopen(&new_options);
  1371. ASSERT_LEVELDB_OK(Put("[10]", "ten"));
  1372. ASSERT_LEVELDB_OK(Put("[0x14]", "twenty"));
  1373. for (int i = 0; i < 2; i++) {
  1374. ASSERT_EQ("ten", Get("[10]"));
  1375. ASSERT_EQ("ten", Get("[0xa]"));
  1376. ASSERT_EQ("twenty", Get("[20]"));
  1377. ASSERT_EQ("twenty", Get("[0x14]"));
  1378. ASSERT_EQ("NOT_FOUND", Get("[15]"));
  1379. ASSERT_EQ("NOT_FOUND", Get("[0xf]"));
  1380. Compact("[0]", "[9999]");
  1381. }
  1382. for (int run = 0; run < 2; run++) {
  1383. for (int i = 0; i < 1000; i++) {
  1384. char buf[100];
  1385. std::snprintf(buf, sizeof(buf), "[%d]", i * 10);
  1386. ASSERT_LEVELDB_OK(Put(buf, buf));
  1387. }
  1388. Compact("[0]", "[1000000]");
  1389. }
  1390. }
  1391. TEST_F(DBTest, ManualCompaction) {
  1392. ASSERT_EQ(config::kMaxMemCompactLevel, 2)
  1393. << "Need to update this test to match kMaxMemCompactLevel";
  1394. MakeTables(3, "p", "q");
  1395. ASSERT_EQ("1,1,1", FilesPerLevel());
  1396. // Compaction range falls before files
  1397. Compact("", "c");
  1398. ASSERT_EQ("1,1,1", FilesPerLevel());
  1399. // Compaction range falls after files
  1400. Compact("r", "z");
  1401. ASSERT_EQ("1,1,1", FilesPerLevel());
  1402. // Compaction range overlaps files
  1403. Compact("p1", "p9");
  1404. ASSERT_EQ("0,0,1", FilesPerLevel());
  1405. // Populate a different range
  1406. MakeTables(3, "c", "e");
  1407. ASSERT_EQ("1,1,2", FilesPerLevel());
  1408. // Compact just the new range
  1409. Compact("b", "f");
  1410. ASSERT_EQ("0,0,2", FilesPerLevel());
  1411. // Compact all
  1412. MakeTables(1, "a", "z");
  1413. ASSERT_EQ("0,1,2", FilesPerLevel());
  1414. db_->CompactRange(nullptr, nullptr);
  1415. ASSERT_EQ("0,0,1", FilesPerLevel());
  1416. }
  1417. TEST_F(DBTest, DBOpen_Options) {
  1418. std::string dbname = testing::TempDir() + "db_options_test";
  1419. DestroyDB(dbname, Options());
  1420. // Does not exist, and create_if_missing == false: error
  1421. DB* db = nullptr;
  1422. Options opts;
  1423. opts.create_if_missing = false;
  1424. Status s = DB::Open(opts, dbname, &db);
  1425. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != nullptr);
  1426. ASSERT_TRUE(db == nullptr);
  1427. // Does not exist, and create_if_missing == true: OK
  1428. opts.create_if_missing = true;
  1429. s = DB::Open(opts, dbname, &db);
  1430. ASSERT_LEVELDB_OK(s);
  1431. ASSERT_TRUE(db != nullptr);
  1432. delete db;
  1433. db = nullptr;
  1434. // Does exist, and error_if_exists == true: error
  1435. opts.create_if_missing = false;
  1436. opts.error_if_exists = true;
  1437. s = DB::Open(opts, dbname, &db);
  1438. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != nullptr);
  1439. ASSERT_TRUE(db == nullptr);
  1440. // Does exist, and error_if_exists == false: OK
  1441. opts.create_if_missing = true;
  1442. opts.error_if_exists = false;
  1443. s = DB::Open(opts, dbname, &db);
  1444. ASSERT_LEVELDB_OK(s);
  1445. ASSERT_TRUE(db != nullptr);
  1446. delete db;
  1447. db = nullptr;
  1448. }
  1449. TEST_F(DBTest, DestroyEmptyDir) {
  1450. std::string dbname = testing::TempDir() + "db_empty_dir";
  1451. TestEnv env(Env::Default());
  1452. env.RemoveDir(dbname);
  1453. ASSERT_TRUE(!env.FileExists(dbname));
  1454. Options opts;
  1455. opts.env = &env;
  1456. ASSERT_LEVELDB_OK(env.CreateDir(dbname));
  1457. ASSERT_TRUE(env.FileExists(dbname));
  1458. std::vector<std::string> children;
  1459. ASSERT_LEVELDB_OK(env.GetChildren(dbname, &children));
  1460. // The stock Env's do not filter out '.' and '..' special files.
  1461. ASSERT_EQ(2, children.size());
  1462. ASSERT_LEVELDB_OK(DestroyDB(dbname, opts));
  1463. ASSERT_TRUE(!env.FileExists(dbname));
  1464. // Should also be destroyed if Env is filtering out dot files.
  1465. env.SetIgnoreDotFiles(true);
  1466. ASSERT_LEVELDB_OK(env.CreateDir(dbname));
  1467. ASSERT_TRUE(env.FileExists(dbname));
  1468. ASSERT_LEVELDB_OK(env.GetChildren(dbname, &children));
  1469. ASSERT_EQ(0, children.size());
  1470. ASSERT_LEVELDB_OK(DestroyDB(dbname, opts));
  1471. ASSERT_TRUE(!env.FileExists(dbname));
  1472. }
  1473. TEST_F(DBTest, DestroyOpenDB) {
  1474. std::string dbname = testing::TempDir() + "open_db_dir";
  1475. env_->RemoveDir(dbname);
  1476. ASSERT_TRUE(!env_->FileExists(dbname));
  1477. Options opts;
  1478. opts.create_if_missing = true;
  1479. DB* db = nullptr;
  1480. ASSERT_LEVELDB_OK(DB::Open(opts, dbname, &db));
  1481. ASSERT_TRUE(db != nullptr);
  1482. // Must fail to destroy an open db.
  1483. ASSERT_TRUE(env_->FileExists(dbname));
  1484. ASSERT_TRUE(!DestroyDB(dbname, Options()).ok());
  1485. ASSERT_TRUE(env_->FileExists(dbname));
  1486. delete db;
  1487. db = nullptr;
  1488. // Should succeed destroying a closed db.
  1489. ASSERT_LEVELDB_OK(DestroyDB(dbname, Options()));
  1490. ASSERT_TRUE(!env_->FileExists(dbname));
  1491. }
  1492. TEST_F(DBTest, Locking) {
  1493. DB* db2 = nullptr;
  1494. Status s = DB::Open(CurrentOptions(), dbname_, &db2);
  1495. ASSERT_TRUE(!s.ok()) << "Locking did not prevent re-opening db";
  1496. }
  1497. // Check that number of files does not grow when we are out of space
  1498. TEST_F(DBTest, NoSpace) {
  1499. Options options = CurrentOptions();
  1500. options.env = env_;
  1501. Reopen(&options);
  1502. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  1503. ASSERT_EQ("v1", Get("foo"));
  1504. Compact("a", "z");
  1505. const int num_files = CountFiles();
  1506. // Force out-of-space errors.
  1507. env_->no_space_.store(true, std::memory_order_release);
  1508. for (int i = 0; i < 10; i++) {
  1509. for (int level = 0; level < config::kNumLevels - 1; level++) {
  1510. dbfull()->TEST_CompactRange(level, nullptr, nullptr);
  1511. }
  1512. }
  1513. env_->no_space_.store(false, std::memory_order_release);
  1514. ASSERT_LT(CountFiles(), num_files + 3);
  1515. }
  1516. TEST_F(DBTest, NonWritableFileSystem) {
  1517. Options options = CurrentOptions();
  1518. options.write_buffer_size = 1000;
  1519. options.env = env_;
  1520. Reopen(&options);
  1521. ASSERT_LEVELDB_OK(Put("foo", "v1"));
  1522. // Force errors for new files.
  1523. env_->non_writable_.store(true, std::memory_order_release);
  1524. std::string big(100000, 'x');
  1525. int errors = 0;
  1526. for (int i = 0; i < 20; i++) {
  1527. std::fprintf(stderr, "iter %d; errors %d\n", i, errors);
  1528. if (!Put("foo", big).ok()) {
  1529. errors++;
  1530. DelayMilliseconds(100);
  1531. }
  1532. }
  1533. ASSERT_GT(errors, 0);
  1534. env_->non_writable_.store(false, std::memory_order_release);
  1535. }
  1536. TEST_F(DBTest, WriteSyncError) {
  1537. // Check that log sync errors cause the DB to disallow future writes.
  1538. // (a) Cause log sync calls to fail
  1539. Options options = CurrentOptions();
  1540. options.env = env_;
  1541. Reopen(&options);
  1542. env_->data_sync_error_.store(true, std::memory_order_release);
  1543. // (b) Normal write should succeed
  1544. WriteOptions w;
  1545. ASSERT_LEVELDB_OK(db_->Put(w, "k1", "v1"));
  1546. ASSERT_EQ("v1", Get("k1"));
  1547. // (c) Do a sync write; should fail
  1548. w.sync = true;
  1549. ASSERT_TRUE(!db_->Put(w, "k2", "v2").ok());
  1550. ASSERT_EQ("v1", Get("k1"));
  1551. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1552. // (d) make sync behave normally
  1553. env_->data_sync_error_.store(false, std::memory_order_release);
  1554. // (e) Do a non-sync write; should fail
  1555. w.sync = false;
  1556. ASSERT_TRUE(!db_->Put(w, "k3", "v3").ok());
  1557. ASSERT_EQ("v1", Get("k1"));
  1558. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1559. ASSERT_EQ("NOT_FOUND", Get("k3"));
  1560. }
  1561. TEST_F(DBTest, ManifestWriteError) {
  1562. // Test for the following problem:
  1563. // (a) Compaction produces file F
  1564. // (b) Log record containing F is written to MANIFEST file, but Sync() fails
  1565. // (c) GC deletes F
  1566. // (d) After reopening DB, reads fail since deleted F is named in log record
  1567. // We iterate twice. In the second iteration, everything is the
  1568. // same except the log record never makes it to the MANIFEST file.
  1569. for (int iter = 0; iter < 2; iter++) {
  1570. std::atomic<bool>* error_type = (iter == 0) ? &env_->manifest_sync_error_
  1571. : &env_->manifest_write_error_;
  1572. // Insert foo=>bar mapping
  1573. Options options = CurrentOptions();
  1574. options.env = env_;
  1575. options.create_if_missing = true;
  1576. options.error_if_exists = false;
  1577. DestroyAndReopen(&options);
  1578. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1579. ASSERT_EQ("bar", Get("foo"));
  1580. // Memtable compaction (will succeed)
  1581. dbfull()->TEST_CompactMemTable();
  1582. ASSERT_EQ("bar", Get("foo"));
  1583. const int last = config::kMaxMemCompactLevel;
  1584. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo=>bar is now in last level
  1585. // Merging compaction (will fail)
  1586. error_type->store(true, std::memory_order_release);
  1587. dbfull()->TEST_CompactRange(last, nullptr, nullptr); // Should fail
  1588. ASSERT_EQ("bar", Get("foo"));
  1589. // Recovery: should not lose data
  1590. error_type->store(false, std::memory_order_release);
  1591. Reopen(&options);
  1592. ASSERT_EQ("bar", Get("foo"));
  1593. }
  1594. }
  1595. TEST_F(DBTest, MissingSSTFile) {
  1596. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1597. ASSERT_EQ("bar", Get("foo"));
  1598. // Dump the memtable to disk.
  1599. dbfull()->TEST_CompactMemTable();
  1600. ASSERT_EQ("bar", Get("foo"));
  1601. Close();
  1602. ASSERT_TRUE(DeleteAnSSTFile());
  1603. Options options = CurrentOptions();
  1604. options.paranoid_checks = true;
  1605. Status s = TryReopen(&options);
  1606. ASSERT_TRUE(!s.ok());
  1607. ASSERT_TRUE(s.ToString().find("issing") != std::string::npos) << s.ToString();
  1608. }
  1609. TEST_F(DBTest, StillReadSST) {
  1610. ASSERT_LEVELDB_OK(Put("foo", "bar"));
  1611. ASSERT_EQ("bar", Get("foo"));
  1612. // Dump the memtable to disk.
  1613. dbfull()->TEST_CompactMemTable();
  1614. ASSERT_EQ("bar", Get("foo"));
  1615. Close();
  1616. ASSERT_GT(RenameLDBToSST(), 0);
  1617. Options options = CurrentOptions();
  1618. options.paranoid_checks = true;
  1619. Status s = TryReopen(&options);
  1620. ASSERT_TRUE(s.ok());
  1621. ASSERT_EQ("bar", Get("foo"));
  1622. }
  1623. TEST_F(DBTest, FilesDeletedAfterCompaction) {
  1624. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  1625. Compact("a", "z");
  1626. const int num_files = CountFiles();
  1627. for (int i = 0; i < 10; i++) {
  1628. ASSERT_LEVELDB_OK(Put("foo", "v2"));
  1629. Compact("a", "z");
  1630. }
  1631. ASSERT_EQ(CountFiles(), num_files);
  1632. }
  1633. TEST_F(DBTest, BloomFilter) {
  1634. env_->count_random_reads_ = true;
  1635. Options options = CurrentOptions();
  1636. options.env = env_;
  1637. options.block_cache = NewLRUCache(0); // Prevent cache hits
  1638. options.filter_policy = NewBloomFilterPolicy(10);
  1639. Reopen(&options);
  1640. // Populate multiple layers
  1641. const int N = 10000;
  1642. for (int i = 0; i < N; i++) {
  1643. ASSERT_LEVELDB_OK(Put(Key(i), Key(i)));
  1644. }
  1645. Compact("a", "z");
  1646. for (int i = 0; i < N; i += 100) {
  1647. ASSERT_LEVELDB_OK(Put(Key(i), Key(i)));
  1648. }
  1649. dbfull()->TEST_CompactMemTable();
  1650. // Prevent auto compactions triggered by seeks
  1651. env_->delay_data_sync_.store(true, std::memory_order_release);
  1652. // Lookup present keys. Should rarely read from small sstable.
  1653. env_->random_read_counter_.Reset();
  1654. for (int i = 0; i < N; i++) {
  1655. ASSERT_EQ(Key(i), Get(Key(i)));
  1656. }
  1657. int reads = env_->random_read_counter_.Read();
  1658. std::fprintf(stderr, "%d present => %d reads\n", N, reads);
  1659. ASSERT_GE(reads, N);
  1660. ASSERT_LE(reads, N + 2 * N / 100);
  1661. // Lookup present keys. Should rarely read from either sstable.
  1662. env_->random_read_counter_.Reset();
  1663. for (int i = 0; i < N; i++) {
  1664. ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
  1665. }
  1666. reads = env_->random_read_counter_.Read();
  1667. std::fprintf(stderr, "%d missing => %d reads\n", N, reads);
  1668. ASSERT_LE(reads, 3 * N / 100);
  1669. env_->delay_data_sync_.store(false, std::memory_order_release);
  1670. Close();
  1671. delete options.block_cache;
  1672. delete options.filter_policy;
  1673. }
  1674. // Multi-threaded test:
  1675. namespace {
  1676. static const int kNumThreads = 4;
  1677. static const int kTestSeconds = 10;
  1678. static const int kNumKeys = 1000;
  1679. struct MTState {
  1680. DBTest* test;
  1681. std::atomic<bool> stop;
  1682. std::atomic<int> counter[kNumThreads];
  1683. std::atomic<bool> thread_done[kNumThreads];
  1684. };
  1685. struct MTThread {
  1686. MTState* state;
  1687. int id;
  1688. };
  1689. static void MTThreadBody(void* arg) {
  1690. MTThread* t = reinterpret_cast<MTThread*>(arg);
  1691. int id = t->id;
  1692. DB* db = t->state->test->db_;
  1693. int counter = 0;
  1694. std::fprintf(stderr, "... starting thread %d\n", id);
  1695. Random rnd(1000 + id);
  1696. std::string value;
  1697. char valbuf[1500];
  1698. while (!t->state->stop.load(std::memory_order_acquire)) {
  1699. t->state->counter[id].store(counter, std::memory_order_release);
  1700. int key = rnd.Uniform(kNumKeys);
  1701. char keybuf[20];
  1702. std::snprintf(keybuf, sizeof(keybuf), "%016d", key);
  1703. if (rnd.OneIn(2)) {
  1704. // Write values of the form <key, my id, counter>.
  1705. // We add some padding for force compactions.
  1706. std::snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d", key, id,
  1707. static_cast<int>(counter));
  1708. ASSERT_LEVELDB_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  1709. } else {
  1710. // Read a value and verify that it matches the pattern written above.
  1711. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  1712. if (s.IsNotFound()) {
  1713. // Key has not yet been written
  1714. } else {
  1715. // Check that the writer thread counter is >= the counter in the value
  1716. ASSERT_LEVELDB_OK(s);
  1717. int k, w, c;
  1718. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  1719. ASSERT_EQ(k, key);
  1720. ASSERT_GE(w, 0);
  1721. ASSERT_LT(w, kNumThreads);
  1722. ASSERT_LE(c, t->state->counter[w].load(std::memory_order_acquire));
  1723. }
  1724. }
  1725. counter++;
  1726. }
  1727. t->state->thread_done[id].store(true, std::memory_order_release);
  1728. std::fprintf(stderr, "... stopping thread %d after %d ops\n", id, counter);
  1729. }
  1730. } // namespace
  1731. TEST_F(DBTest, MultiThreaded) {
  1732. do {
  1733. // Initialize state
  1734. MTState mt;
  1735. mt.test = this;
  1736. mt.stop.store(false, std::memory_order_release);
  1737. for (int id = 0; id < kNumThreads; id++) {
  1738. mt.counter[id].store(false, std::memory_order_release);
  1739. mt.thread_done[id].store(false, std::memory_order_release);
  1740. }
  1741. // Start threads
  1742. MTThread thread[kNumThreads];
  1743. for (int id = 0; id < kNumThreads; id++) {
  1744. thread[id].state = &mt;
  1745. thread[id].id = id;
  1746. env_->StartThread(MTThreadBody, &thread[id]);
  1747. }
  1748. // Let them run for a while
  1749. DelayMilliseconds(kTestSeconds * 1000);
  1750. // Stop the threads and wait for them to finish
  1751. mt.stop.store(true, std::memory_order_release);
  1752. for (int id = 0; id < kNumThreads; id++) {
  1753. while (!mt.thread_done[id].load(std::memory_order_acquire)) {
  1754. DelayMilliseconds(100);
  1755. }
  1756. }
  1757. } while (ChangeOptions());
  1758. }
  1759. namespace {
  1760. typedef std::map<std::string, std::string> KVMap;
  1761. }
  1762. class ModelDB : public DB {
  1763. public:
  1764. class ModelSnapshot : public Snapshot {
  1765. public:
  1766. KVMap map_;
  1767. };
  1768. explicit ModelDB(const Options& options) : options_(options) {}
  1769. ~ModelDB() override = default;
  1770. Status Put(const WriteOptions& o, const Slice& k, const Slice& v) override {
  1771. return DB::Put(o, k, v);
  1772. }
  1773. Status Delete(const WriteOptions& o, const Slice& key) override {
  1774. return DB::Delete(o, key);
  1775. }
  1776. Status Get(const ReadOptions& options, const Slice& key,
  1777. std::string* value) override {
  1778. assert(false); // Not implemented
  1779. return Status::NotFound(key);
  1780. }
  1781. Iterator* NewIterator(const ReadOptions& options) override {
  1782. if (options.snapshot == nullptr) {
  1783. KVMap* saved = new KVMap;
  1784. *saved = map_;
  1785. return new ModelIter(saved, true);
  1786. } else {
  1787. const KVMap* snapshot_state =
  1788. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1789. return new ModelIter(snapshot_state, false);
  1790. }
  1791. }
  1792. const Snapshot* GetSnapshot() override {
  1793. ModelSnapshot* snapshot = new ModelSnapshot;
  1794. snapshot->map_ = map_;
  1795. return snapshot;
  1796. }
  1797. void ReleaseSnapshot(const Snapshot* snapshot) override {
  1798. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1799. }
  1800. Status Write(const WriteOptions& options, WriteBatch* batch) override {
  1801. class Handler : public WriteBatch::Handler {
  1802. public:
  1803. KVMap* map_;
  1804. void Put(const Slice& key, const Slice& value) override {
  1805. (*map_)[key.ToString()] = value.ToString();
  1806. }
  1807. void Delete(const Slice& key) override { map_->erase(key.ToString()); }
  1808. };
  1809. Handler handler;
  1810. handler.map_ = &map_;
  1811. return batch->Iterate(&handler);
  1812. }
  1813. bool GetProperty(const Slice& property, std::string* value) override {
  1814. return false;
  1815. }
  1816. void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) override {
  1817. for (int i = 0; i < n; i++) {
  1818. sizes[i] = 0;
  1819. }
  1820. }
  1821. void CompactRange(const Slice* start, const Slice* end) override {}
  1822. private:
  1823. class ModelIter : public Iterator {
  1824. public:
  1825. ModelIter(const KVMap* map, bool owned)
  1826. : map_(map), owned_(owned), iter_(map_->end()) {}
  1827. ~ModelIter() override {
  1828. if (owned_) delete map_;
  1829. }
  1830. bool Valid() const override { return iter_ != map_->end(); }
  1831. void SeekToFirst() override { iter_ = map_->begin(); }
  1832. void SeekToLast() override {
  1833. if (map_->empty()) {
  1834. iter_ = map_->end();
  1835. } else {
  1836. iter_ = map_->find(map_->rbegin()->first);
  1837. }
  1838. }
  1839. void Seek(const Slice& k) override {
  1840. iter_ = map_->lower_bound(k.ToString());
  1841. }
  1842. void Next() override { ++iter_; }
  1843. void Prev() override { --iter_; }
  1844. Slice key() const override { return iter_->first; }
  1845. Slice value() const override { return iter_->second; }
  1846. Status status() const override { return Status::OK(); }
  1847. private:
  1848. const KVMap* const map_;
  1849. const bool owned_; // Do we own map_
  1850. KVMap::const_iterator iter_;
  1851. };
  1852. const Options options_;
  1853. KVMap map_;
  1854. };
  1855. static bool CompareIterators(int step, DB* model, DB* db,
  1856. const Snapshot* model_snap,
  1857. const Snapshot* db_snap) {
  1858. ReadOptions options;
  1859. options.snapshot = model_snap;
  1860. Iterator* miter = model->NewIterator(options);
  1861. options.snapshot = db_snap;
  1862. Iterator* dbiter = db->NewIterator(options);
  1863. bool ok = true;
  1864. int count = 0;
  1865. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1866. ok && miter->Valid() && dbiter->Valid(); miter->Next(), dbiter->Next()) {
  1867. count++;
  1868. if (miter->key().compare(dbiter->key()) != 0) {
  1869. std::fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n", step,
  1870. EscapeString(miter->key()).c_str(),
  1871. EscapeString(dbiter->key()).c_str());
  1872. ok = false;
  1873. break;
  1874. }
  1875. if (miter->value().compare(dbiter->value()) != 0) {
  1876. std::fprintf(stderr,
  1877. "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1878. step, EscapeString(miter->key()).c_str(),
  1879. EscapeString(miter->value()).c_str(),
  1880. EscapeString(miter->value()).c_str());
  1881. ok = false;
  1882. }
  1883. }
  1884. if (ok) {
  1885. if (miter->Valid() != dbiter->Valid()) {
  1886. std::fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1887. step, miter->Valid(), dbiter->Valid());
  1888. ok = false;
  1889. }
  1890. }
  1891. std::fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1892. delete miter;
  1893. delete dbiter;
  1894. return ok;
  1895. }
  1896. TEST_F(DBTest, Randomized) {
  1897. Random rnd(test::RandomSeed());
  1898. do {
  1899. ModelDB model(CurrentOptions());
  1900. const int N = 10000;
  1901. const Snapshot* model_snap = nullptr;
  1902. const Snapshot* db_snap = nullptr;
  1903. std::string k, v;
  1904. for (int step = 0; step < N; step++) {
  1905. if (step % 100 == 0) {
  1906. std::fprintf(stderr, "Step %d of %d\n", step, N);
  1907. }
  1908. // TODO(sanjay): Test Get() works
  1909. int p = rnd.Uniform(100);
  1910. if (p < 45) { // Put
  1911. k = RandomKey(&rnd);
  1912. v = RandomString(
  1913. &rnd, rnd.OneIn(20) ? 100 + rnd.Uniform(100) : rnd.Uniform(8));
  1914. ASSERT_LEVELDB_OK(model.Put(WriteOptions(), k, v));
  1915. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), k, v));
  1916. } else if (p < 90) { // Delete
  1917. k = RandomKey(&rnd);
  1918. ASSERT_LEVELDB_OK(model.Delete(WriteOptions(), k));
  1919. ASSERT_LEVELDB_OK(db_->Delete(WriteOptions(), k));
  1920. } else { // Multi-element batch
  1921. WriteBatch b;
  1922. const int num = rnd.Uniform(8);
  1923. for (int i = 0; i < num; i++) {
  1924. if (i == 0 || !rnd.OneIn(10)) {
  1925. k = RandomKey(&rnd);
  1926. } else {
  1927. // Periodically re-use the same key from the previous iter, so
  1928. // we have multiple entries in the write batch for the same key
  1929. }
  1930. if (rnd.OneIn(2)) {
  1931. v = RandomString(&rnd, rnd.Uniform(10));
  1932. b.Put(k, v);
  1933. } else {
  1934. b.Delete(k);
  1935. }
  1936. }
  1937. ASSERT_LEVELDB_OK(model.Write(WriteOptions(), &b));
  1938. ASSERT_LEVELDB_OK(db_->Write(WriteOptions(), &b));
  1939. }
  1940. if ((step % 100) == 0) {
  1941. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  1942. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1943. // Save a snapshot from each DB this time that we'll use next
  1944. // time we compare things, to make sure the current state is
  1945. // preserved with the snapshot
  1946. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  1947. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  1948. Reopen();
  1949. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  1950. model_snap = model.GetSnapshot();
  1951. db_snap = db_->GetSnapshot();
  1952. }
  1953. }
  1954. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  1955. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  1956. } while (ChangeOptions());
  1957. }
  1958. std::string MakeKey(unsigned int num) {
  1959. char buf[30];
  1960. std::snprintf(buf, sizeof(buf), "%016u", num);
  1961. return std::string(buf);
  1962. }
  1963. static void BM_LogAndApply(benchmark::State& state) {
  1964. const int num_base_files = state.range(0);
  1965. std::string dbname = testing::TempDir() + "leveldb_test_benchmark";
  1966. DestroyDB(dbname, Options());
  1967. DB* db = nullptr;
  1968. Options opts;
  1969. opts.create_if_missing = true;
  1970. Status s = DB::Open(opts, dbname, &db);
  1971. ASSERT_LEVELDB_OK(s);
  1972. ASSERT_TRUE(db != nullptr);
  1973. delete db;
  1974. db = nullptr;
  1975. Env* env = Env::Default();
  1976. port::Mutex mu;
  1977. MutexLock l(&mu);
  1978. InternalKeyComparator cmp(BytewiseComparator());
  1979. Options options;
  1980. VersionSet vset(dbname, &options, nullptr, &cmp);
  1981. bool save_manifest;
  1982. ASSERT_LEVELDB_OK(vset.Recover(&save_manifest));
  1983. VersionEdit vbase;
  1984. uint64_t fnum = 1;
  1985. for (int i = 0; i < num_base_files; i++) {
  1986. InternalKey start(MakeKey(2 * fnum), 1, kTypeValue);
  1987. InternalKey limit(MakeKey(2 * fnum + 1), 1, kTypeDeletion);
  1988. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1989. }
  1990. ASSERT_LEVELDB_OK(vset.LogAndApply(&vbase, &mu));
  1991. uint64_t start_micros = env->NowMicros();
  1992. for (auto st : state) {
  1993. VersionEdit vedit;
  1994. vedit.RemoveFile(2, fnum);
  1995. InternalKey start(MakeKey(2 * fnum), 1, kTypeValue);
  1996. InternalKey limit(MakeKey(2 * fnum + 1), 1, kTypeDeletion);
  1997. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1998. vset.LogAndApply(&vedit, &mu);
  1999. }
  2000. uint64_t stop_micros = env->NowMicros();
  2001. unsigned int us = stop_micros - start_micros;
  2002. char buf[16];
  2003. std::snprintf(buf, sizeof(buf), "%d", num_base_files);
  2004. std::fprintf(stderr,
  2005. "BM_LogAndApply/%-6s %8zu iters : %9u us (%7.0f us / iter)\n",
  2006. buf, state.iterations(), us, ((float)us) / state.iterations());
  2007. }
  2008. BENCHMARK(BM_LogAndApply)->Arg(1)->Arg(100)->Arg(10000)->Arg(100000);
  2009. } // namespace leveldb
  2010. int main(int argc, char** argv) {
  2011. testing::InitGoogleTest(&argc, argv);
  2012. benchmark::RunSpecifiedBenchmarks();
  2013. return RUN_ALL_TESTS();
  2014. }