作者: 韩晨旭 10225101440 李畅 10225102463
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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