提供基本的ttl测试用例
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.

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