作者: 韩晨旭 10225101440 李畅 10225102463
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2299 rader
67 KiB

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