You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2126 lines
61 KiB

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