提供基本的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.

1946 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. // Check that number of files does not grow when we are out of space
  1262. TEST(DBTest, NoSpace) {
  1263. Options options = CurrentOptions();
  1264. options.env = env_;
  1265. Reopen(&options);
  1266. ASSERT_OK(Put("foo", "v1"));
  1267. ASSERT_EQ("v1", Get("foo"));
  1268. Compact("a", "z");
  1269. const int num_files = CountFiles();
  1270. env_->no_space_.Release_Store(env_); // Force out-of-space errors
  1271. env_->sleep_counter_.Reset();
  1272. for (int i = 0; i < 5; i++) {
  1273. for (int level = 0; level < config::kNumLevels-1; level++) {
  1274. dbfull()->TEST_CompactRange(level, NULL, NULL);
  1275. }
  1276. }
  1277. env_->no_space_.Release_Store(NULL);
  1278. ASSERT_LT(CountFiles(), num_files + 3);
  1279. // Check that compaction attempts slept after errors
  1280. ASSERT_GE(env_->sleep_counter_.Read(), 5);
  1281. }
  1282. TEST(DBTest, NonWritableFileSystem) {
  1283. Options options = CurrentOptions();
  1284. options.write_buffer_size = 1000;
  1285. options.env = env_;
  1286. Reopen(&options);
  1287. ASSERT_OK(Put("foo", "v1"));
  1288. env_->non_writable_.Release_Store(env_); // Force errors for new files
  1289. std::string big(100000, 'x');
  1290. int errors = 0;
  1291. for (int i = 0; i < 20; i++) {
  1292. fprintf(stderr, "iter %d; errors %d\n", i, errors);
  1293. if (!Put("foo", big).ok()) {
  1294. errors++;
  1295. env_->SleepForMicroseconds(100000);
  1296. }
  1297. }
  1298. ASSERT_GT(errors, 0);
  1299. env_->non_writable_.Release_Store(NULL);
  1300. }
  1301. TEST(DBTest, FilesDeletedAfterCompaction) {
  1302. ASSERT_OK(Put("foo", "v2"));
  1303. Compact("a", "z");
  1304. const int num_files = CountFiles();
  1305. for (int i = 0; i < 10; i++) {
  1306. ASSERT_OK(Put("foo", "v2"));
  1307. Compact("a", "z");
  1308. }
  1309. ASSERT_EQ(CountFiles(), num_files);
  1310. }
  1311. TEST(DBTest, BloomFilter) {
  1312. env_->count_random_reads_ = true;
  1313. Options options = CurrentOptions();
  1314. options.env = env_;
  1315. options.block_cache = NewLRUCache(0); // Prevent cache hits
  1316. options.filter_policy = NewBloomFilterPolicy(10);
  1317. Reopen(&options);
  1318. // Populate multiple layers
  1319. const int N = 10000;
  1320. for (int i = 0; i < N; i++) {
  1321. ASSERT_OK(Put(Key(i), Key(i)));
  1322. }
  1323. Compact("a", "z");
  1324. for (int i = 0; i < N; i += 100) {
  1325. ASSERT_OK(Put(Key(i), Key(i)));
  1326. }
  1327. dbfull()->TEST_CompactMemTable();
  1328. // Prevent auto compactions triggered by seeks
  1329. env_->delay_sstable_sync_.Release_Store(env_);
  1330. // Lookup present keys. Should rarely read from small sstable.
  1331. env_->random_read_counter_.Reset();
  1332. for (int i = 0; i < N; i++) {
  1333. ASSERT_EQ(Key(i), Get(Key(i)));
  1334. }
  1335. int reads = env_->random_read_counter_.Read();
  1336. fprintf(stderr, "%d present => %d reads\n", N, reads);
  1337. ASSERT_GE(reads, N);
  1338. ASSERT_LE(reads, N + 2*N/100);
  1339. // Lookup present keys. Should rarely read from either sstable.
  1340. env_->random_read_counter_.Reset();
  1341. for (int i = 0; i < N; i++) {
  1342. ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
  1343. }
  1344. reads = env_->random_read_counter_.Read();
  1345. fprintf(stderr, "%d missing => %d reads\n", N, reads);
  1346. ASSERT_LE(reads, 3*N/100);
  1347. env_->delay_sstable_sync_.Release_Store(NULL);
  1348. Close();
  1349. delete options.block_cache;
  1350. delete options.filter_policy;
  1351. }
  1352. // Multi-threaded test:
  1353. namespace {
  1354. static const int kNumThreads = 4;
  1355. static const int kTestSeconds = 10;
  1356. static const int kNumKeys = 1000;
  1357. struct MTState {
  1358. DBTest* test;
  1359. port::AtomicPointer stop;
  1360. port::AtomicPointer counter[kNumThreads];
  1361. port::AtomicPointer thread_done[kNumThreads];
  1362. };
  1363. struct MTThread {
  1364. MTState* state;
  1365. int id;
  1366. };
  1367. static void MTThreadBody(void* arg) {
  1368. MTThread* t = reinterpret_cast<MTThread*>(arg);
  1369. int id = t->id;
  1370. DB* db = t->state->test->db_;
  1371. uintptr_t counter = 0;
  1372. fprintf(stderr, "... starting thread %d\n", id);
  1373. Random rnd(1000 + id);
  1374. std::string value;
  1375. char valbuf[1500];
  1376. while (t->state->stop.Acquire_Load() == NULL) {
  1377. t->state->counter[id].Release_Store(reinterpret_cast<void*>(counter));
  1378. int key = rnd.Uniform(kNumKeys);
  1379. char keybuf[20];
  1380. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  1381. if (rnd.OneIn(2)) {
  1382. // Write values of the form <key, my id, counter>.
  1383. // We add some padding for force compactions.
  1384. snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d",
  1385. key, id, static_cast<int>(counter));
  1386. ASSERT_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  1387. } else {
  1388. // Read a value and verify that it matches the pattern written above.
  1389. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  1390. if (s.IsNotFound()) {
  1391. // Key has not yet been written
  1392. } else {
  1393. // Check that the writer thread counter is >= the counter in the value
  1394. ASSERT_OK(s);
  1395. int k, w, c;
  1396. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  1397. ASSERT_EQ(k, key);
  1398. ASSERT_GE(w, 0);
  1399. ASSERT_LT(w, kNumThreads);
  1400. ASSERT_LE(c, reinterpret_cast<uintptr_t>(
  1401. t->state->counter[w].Acquire_Load()));
  1402. }
  1403. }
  1404. counter++;
  1405. }
  1406. t->state->thread_done[id].Release_Store(t);
  1407. fprintf(stderr, "... stopping thread %d after %d ops\n", id, int(counter));
  1408. }
  1409. } // namespace
  1410. TEST(DBTest, MultiThreaded) {
  1411. do {
  1412. // Initialize state
  1413. MTState mt;
  1414. mt.test = this;
  1415. mt.stop.Release_Store(0);
  1416. for (int id = 0; id < kNumThreads; id++) {
  1417. mt.counter[id].Release_Store(0);
  1418. mt.thread_done[id].Release_Store(0);
  1419. }
  1420. // Start threads
  1421. MTThread thread[kNumThreads];
  1422. for (int id = 0; id < kNumThreads; id++) {
  1423. thread[id].state = &mt;
  1424. thread[id].id = id;
  1425. env_->StartThread(MTThreadBody, &thread[id]);
  1426. }
  1427. // Let them run for a while
  1428. env_->SleepForMicroseconds(kTestSeconds * 1000000);
  1429. // Stop the threads and wait for them to finish
  1430. mt.stop.Release_Store(&mt);
  1431. for (int id = 0; id < kNumThreads; id++) {
  1432. while (mt.thread_done[id].Acquire_Load() == NULL) {
  1433. env_->SleepForMicroseconds(100000);
  1434. }
  1435. }
  1436. } while (ChangeOptions());
  1437. }
  1438. namespace {
  1439. typedef std::map<std::string, std::string> KVMap;
  1440. }
  1441. class ModelDB: public DB {
  1442. public:
  1443. class ModelSnapshot : public Snapshot {
  1444. public:
  1445. KVMap map_;
  1446. };
  1447. explicit ModelDB(const Options& options): options_(options) { }
  1448. ~ModelDB() { }
  1449. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  1450. return DB::Put(o, k, v);
  1451. }
  1452. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  1453. return DB::Delete(o, key);
  1454. }
  1455. virtual Status Get(const ReadOptions& options,
  1456. const Slice& key, std::string* value) {
  1457. assert(false); // Not implemented
  1458. return Status::NotFound(key);
  1459. }
  1460. virtual Iterator* NewIterator(const ReadOptions& options) {
  1461. if (options.snapshot == NULL) {
  1462. KVMap* saved = new KVMap;
  1463. *saved = map_;
  1464. return new ModelIter(saved, true);
  1465. } else {
  1466. const KVMap* snapshot_state =
  1467. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1468. return new ModelIter(snapshot_state, false);
  1469. }
  1470. }
  1471. virtual const Snapshot* GetSnapshot() {
  1472. ModelSnapshot* snapshot = new ModelSnapshot;
  1473. snapshot->map_ = map_;
  1474. return snapshot;
  1475. }
  1476. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  1477. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1478. }
  1479. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  1480. class Handler : public WriteBatch::Handler {
  1481. public:
  1482. KVMap* map_;
  1483. virtual void Put(const Slice& key, const Slice& value) {
  1484. (*map_)[key.ToString()] = value.ToString();
  1485. }
  1486. virtual void Delete(const Slice& key) {
  1487. map_->erase(key.ToString());
  1488. }
  1489. };
  1490. Handler handler;
  1491. handler.map_ = &map_;
  1492. return batch->Iterate(&handler);
  1493. }
  1494. virtual bool GetProperty(const Slice& property, std::string* value) {
  1495. return false;
  1496. }
  1497. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  1498. for (int i = 0; i < n; i++) {
  1499. sizes[i] = 0;
  1500. }
  1501. }
  1502. virtual void CompactRange(const Slice* start, const Slice* end) {
  1503. }
  1504. private:
  1505. class ModelIter: public Iterator {
  1506. public:
  1507. ModelIter(const KVMap* map, bool owned)
  1508. : map_(map), owned_(owned), iter_(map_->end()) {
  1509. }
  1510. ~ModelIter() {
  1511. if (owned_) delete map_;
  1512. }
  1513. virtual bool Valid() const { return iter_ != map_->end(); }
  1514. virtual void SeekToFirst() { iter_ = map_->begin(); }
  1515. virtual void SeekToLast() {
  1516. if (map_->empty()) {
  1517. iter_ = map_->end();
  1518. } else {
  1519. iter_ = map_->find(map_->rbegin()->first);
  1520. }
  1521. }
  1522. virtual void Seek(const Slice& k) {
  1523. iter_ = map_->lower_bound(k.ToString());
  1524. }
  1525. virtual void Next() { ++iter_; }
  1526. virtual void Prev() { --iter_; }
  1527. virtual Slice key() const { return iter_->first; }
  1528. virtual Slice value() const { return iter_->second; }
  1529. virtual Status status() const { return Status::OK(); }
  1530. private:
  1531. const KVMap* const map_;
  1532. const bool owned_; // Do we own map_
  1533. KVMap::const_iterator iter_;
  1534. };
  1535. const Options options_;
  1536. KVMap map_;
  1537. };
  1538. static std::string RandomKey(Random* rnd) {
  1539. int len = (rnd->OneIn(3)
  1540. ? 1 // Short sometimes to encourage collisions
  1541. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  1542. return test::RandomKey(rnd, len);
  1543. }
  1544. static bool CompareIterators(int step,
  1545. DB* model,
  1546. DB* db,
  1547. const Snapshot* model_snap,
  1548. const Snapshot* db_snap) {
  1549. ReadOptions options;
  1550. options.snapshot = model_snap;
  1551. Iterator* miter = model->NewIterator(options);
  1552. options.snapshot = db_snap;
  1553. Iterator* dbiter = db->NewIterator(options);
  1554. bool ok = true;
  1555. int count = 0;
  1556. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1557. ok && miter->Valid() && dbiter->Valid();
  1558. miter->Next(), dbiter->Next()) {
  1559. count++;
  1560. if (miter->key().compare(dbiter->key()) != 0) {
  1561. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  1562. step,
  1563. EscapeString(miter->key()).c_str(),
  1564. EscapeString(dbiter->key()).c_str());
  1565. ok = false;
  1566. break;
  1567. }
  1568. if (miter->value().compare(dbiter->value()) != 0) {
  1569. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1570. step,
  1571. EscapeString(miter->key()).c_str(),
  1572. EscapeString(miter->value()).c_str(),
  1573. EscapeString(miter->value()).c_str());
  1574. ok = false;
  1575. }
  1576. }
  1577. if (ok) {
  1578. if (miter->Valid() != dbiter->Valid()) {
  1579. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1580. step, miter->Valid(), dbiter->Valid());
  1581. ok = false;
  1582. }
  1583. }
  1584. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1585. delete miter;
  1586. delete dbiter;
  1587. return ok;
  1588. }
  1589. TEST(DBTest, Randomized) {
  1590. Random rnd(test::RandomSeed());
  1591. do {
  1592. ModelDB model(CurrentOptions());
  1593. const int N = 10000;
  1594. const Snapshot* model_snap = NULL;
  1595. const Snapshot* db_snap = NULL;
  1596. std::string k, v;
  1597. for (int step = 0; step < N; step++) {
  1598. if (step % 100 == 0) {
  1599. fprintf(stderr, "Step %d of %d\n", step, N);
  1600. }
  1601. // TODO(sanjay): Test Get() works
  1602. int p = rnd.Uniform(100);
  1603. if (p < 45) { // Put
  1604. k = RandomKey(&rnd);
  1605. v = RandomString(&rnd,
  1606. rnd.OneIn(20)
  1607. ? 100 + rnd.Uniform(100)
  1608. : rnd.Uniform(8));
  1609. ASSERT_OK(model.Put(WriteOptions(), k, v));
  1610. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  1611. } else if (p < 90) { // Delete
  1612. k = RandomKey(&rnd);
  1613. ASSERT_OK(model.Delete(WriteOptions(), k));
  1614. ASSERT_OK(db_->Delete(WriteOptions(), k));
  1615. } else { // Multi-element batch
  1616. WriteBatch b;
  1617. const int num = rnd.Uniform(8);
  1618. for (int i = 0; i < num; i++) {
  1619. if (i == 0 || !rnd.OneIn(10)) {
  1620. k = RandomKey(&rnd);
  1621. } else {
  1622. // Periodically re-use the same key from the previous iter, so
  1623. // we have multiple entries in the write batch for the same key
  1624. }
  1625. if (rnd.OneIn(2)) {
  1626. v = RandomString(&rnd, rnd.Uniform(10));
  1627. b.Put(k, v);
  1628. } else {
  1629. b.Delete(k);
  1630. }
  1631. }
  1632. ASSERT_OK(model.Write(WriteOptions(), &b));
  1633. ASSERT_OK(db_->Write(WriteOptions(), &b));
  1634. }
  1635. if ((step % 100) == 0) {
  1636. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1637. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1638. // Save a snapshot from each DB this time that we'll use next
  1639. // time we compare things, to make sure the current state is
  1640. // preserved with the snapshot
  1641. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1642. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1643. Reopen();
  1644. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1645. model_snap = model.GetSnapshot();
  1646. db_snap = db_->GetSnapshot();
  1647. }
  1648. }
  1649. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1650. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1651. } while (ChangeOptions());
  1652. }
  1653. std::string MakeKey(unsigned int num) {
  1654. char buf[30];
  1655. snprintf(buf, sizeof(buf), "%016u", num);
  1656. return std::string(buf);
  1657. }
  1658. void BM_LogAndApply(int iters, int num_base_files) {
  1659. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  1660. DestroyDB(dbname, Options());
  1661. DB* db = NULL;
  1662. Options opts;
  1663. opts.create_if_missing = true;
  1664. Status s = DB::Open(opts, dbname, &db);
  1665. ASSERT_OK(s);
  1666. ASSERT_TRUE(db != NULL);
  1667. delete db;
  1668. db = NULL;
  1669. Env* env = Env::Default();
  1670. port::Mutex mu;
  1671. MutexLock l(&mu);
  1672. InternalKeyComparator cmp(BytewiseComparator());
  1673. Options options;
  1674. VersionSet vset(dbname, &options, NULL, &cmp);
  1675. ASSERT_OK(vset.Recover());
  1676. VersionEdit vbase;
  1677. uint64_t fnum = 1;
  1678. for (int i = 0; i < num_base_files; i++) {
  1679. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1680. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1681. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1682. }
  1683. ASSERT_OK(vset.LogAndApply(&vbase, &mu));
  1684. uint64_t start_micros = env->NowMicros();
  1685. for (int i = 0; i < iters; i++) {
  1686. VersionEdit vedit;
  1687. vedit.DeleteFile(2, fnum);
  1688. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1689. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1690. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1691. vset.LogAndApply(&vedit, &mu);
  1692. }
  1693. uint64_t stop_micros = env->NowMicros();
  1694. unsigned int us = stop_micros - start_micros;
  1695. char buf[16];
  1696. snprintf(buf, sizeof(buf), "%d", num_base_files);
  1697. fprintf(stderr,
  1698. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  1699. buf, iters, us, ((float)us) / iters);
  1700. }
  1701. } // namespace leveldb
  1702. int main(int argc, char** argv) {
  1703. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  1704. leveldb::BM_LogAndApply(1000, 1);
  1705. leveldb::BM_LogAndApply(1000, 100);
  1706. leveldb::BM_LogAndApply(1000, 10000);
  1707. leveldb::BM_LogAndApply(100, 100000);
  1708. return 0;
  1709. }
  1710. return leveldb::test::RunAllTests();
  1711. }