作者: 韩晨旭 10225101440 李畅 10225102463
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.

1441 lines
41 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 "db/db_impl.h"
  6. #include "db/filename.h"
  7. #include "db/version_set.h"
  8. #include "db/write_batch_internal.h"
  9. #include "leveldb/env.h"
  10. #include "leveldb/table.h"
  11. #include "util/logging.h"
  12. #include "util/mutexlock.h"
  13. #include "util/testharness.h"
  14. #include "util/testutil.h"
  15. namespace leveldb {
  16. static std::string RandomString(Random* rnd, int len) {
  17. std::string r;
  18. test::RandomString(rnd, len, &r);
  19. return r;
  20. }
  21. // Special Env used to delay background operations
  22. class SpecialEnv : public EnvWrapper {
  23. public:
  24. // sstable Sync() calls are blocked while this pointer is non-NULL.
  25. port::AtomicPointer delay_sstable_sync_;
  26. explicit SpecialEnv(Env* base) : EnvWrapper(base) {
  27. delay_sstable_sync_.Release_Store(NULL);
  28. }
  29. Status NewWritableFile(const std::string& f, WritableFile** r) {
  30. class SSTableFile : public WritableFile {
  31. private:
  32. SpecialEnv* env_;
  33. WritableFile* base_;
  34. public:
  35. SSTableFile(SpecialEnv* env, WritableFile* base)
  36. : env_(env),
  37. base_(base) {
  38. }
  39. ~SSTableFile() { delete base_; }
  40. Status Append(const Slice& data) { return base_->Append(data); }
  41. Status Close() { return base_->Close(); }
  42. Status Flush() { return base_->Flush(); }
  43. Status Sync() {
  44. while (env_->delay_sstable_sync_.Acquire_Load() != NULL) {
  45. env_->SleepForMicroseconds(100000);
  46. }
  47. return base_->Sync();
  48. }
  49. };
  50. Status s = target()->NewWritableFile(f, r);
  51. if (s.ok()) {
  52. if (strstr(f.c_str(), ".sst") != NULL) {
  53. *r = new SSTableFile(this, *r);
  54. }
  55. }
  56. return s;
  57. }
  58. };
  59. class DBTest {
  60. public:
  61. std::string dbname_;
  62. SpecialEnv* env_;
  63. DB* db_;
  64. Options last_options_;
  65. DBTest() : env_(new SpecialEnv(Env::Default())) {
  66. dbname_ = test::TmpDir() + "/db_test";
  67. DestroyDB(dbname_, Options());
  68. db_ = NULL;
  69. Reopen();
  70. }
  71. ~DBTest() {
  72. delete db_;
  73. DestroyDB(dbname_, Options());
  74. delete env_;
  75. }
  76. DBImpl* dbfull() {
  77. return reinterpret_cast<DBImpl*>(db_);
  78. }
  79. void Reopen(Options* options = NULL) {
  80. ASSERT_OK(TryReopen(options));
  81. }
  82. void DestroyAndReopen(Options* options = NULL) {
  83. delete db_;
  84. db_ = NULL;
  85. DestroyDB(dbname_, Options());
  86. ASSERT_OK(TryReopen(options));
  87. }
  88. Status TryReopen(Options* options) {
  89. delete db_;
  90. db_ = NULL;
  91. Options opts;
  92. if (options != NULL) {
  93. opts = *options;
  94. } else {
  95. opts.create_if_missing = true;
  96. }
  97. last_options_ = opts;
  98. return DB::Open(opts, dbname_, &db_);
  99. }
  100. Status Put(const std::string& k, const std::string& v) {
  101. return db_->Put(WriteOptions(), k, v);
  102. }
  103. Status Delete(const std::string& k) {
  104. return db_->Delete(WriteOptions(), k);
  105. }
  106. std::string Get(const std::string& k, const Snapshot* snapshot = NULL) {
  107. ReadOptions options;
  108. options.snapshot = snapshot;
  109. std::string result;
  110. Status s = db_->Get(options, k, &result);
  111. if (s.IsNotFound()) {
  112. result = "NOT_FOUND";
  113. } else if (!s.ok()) {
  114. result = s.ToString();
  115. }
  116. return result;
  117. }
  118. std::string AllEntriesFor(const Slice& user_key) {
  119. Iterator* iter = dbfull()->TEST_NewInternalIterator();
  120. InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  121. iter->Seek(target.Encode());
  122. std::string result;
  123. if (!iter->status().ok()) {
  124. result = iter->status().ToString();
  125. } else {
  126. result = "[ ";
  127. bool first = true;
  128. while (iter->Valid()) {
  129. ParsedInternalKey ikey;
  130. if (!ParseInternalKey(iter->key(), &ikey)) {
  131. result += "CORRUPTED";
  132. } else {
  133. if (last_options_.comparator->Compare(
  134. ikey.user_key, user_key) != 0) {
  135. break;
  136. }
  137. if (!first) {
  138. result += ", ";
  139. }
  140. first = false;
  141. switch (ikey.type) {
  142. case kTypeValue:
  143. result += iter->value().ToString();
  144. break;
  145. case kTypeDeletion:
  146. result += "DEL";
  147. break;
  148. }
  149. }
  150. iter->Next();
  151. }
  152. if (!first) {
  153. result += " ";
  154. }
  155. result += "]";
  156. }
  157. delete iter;
  158. return result;
  159. }
  160. int NumTableFilesAtLevel(int level) {
  161. std::string property;
  162. ASSERT_TRUE(
  163. db_->GetProperty("leveldb.num-files-at-level" + NumberToString(level),
  164. &property));
  165. return atoi(property.c_str());
  166. }
  167. int TotalTableFiles() {
  168. int result = 0;
  169. for (int level = 0; level < config::kNumLevels; level++) {
  170. result += NumTableFilesAtLevel(level);
  171. }
  172. return result;
  173. }
  174. uint64_t Size(const Slice& start, const Slice& limit) {
  175. Range r(start, limit);
  176. uint64_t size;
  177. db_->GetApproximateSizes(&r, 1, &size);
  178. return size;
  179. }
  180. void Compact(const Slice& start, const Slice& limit) {
  181. dbfull()->TEST_CompactMemTable();
  182. int max_level_with_files = 1;
  183. for (int level = 1; level < config::kNumLevels; level++) {
  184. if (NumTableFilesAtLevel(level) > 0) {
  185. max_level_with_files = level;
  186. }
  187. }
  188. for (int level = 0; level < max_level_with_files; level++) {
  189. dbfull()->TEST_CompactRange(level, "", "~");
  190. }
  191. }
  192. // Prevent pushing of new sstables into deeper levels by adding
  193. // tables that cover a specified range to all levels.
  194. void FillLevels(const std::string& smallest, const std::string& largest) {
  195. for (int level = 0; level < config::kNumLevels; level++) {
  196. Put(smallest, "begin");
  197. Put(largest, "end");
  198. dbfull()->TEST_CompactMemTable();
  199. }
  200. }
  201. void DumpFileCounts(const char* label) {
  202. fprintf(stderr, "---\n%s:\n", label);
  203. fprintf(stderr, "maxoverlap: %lld\n",
  204. static_cast<long long>(
  205. dbfull()->TEST_MaxNextLevelOverlappingBytes()));
  206. for (int level = 0; level < config::kNumLevels; level++) {
  207. int num = NumTableFilesAtLevel(level);
  208. if (num > 0) {
  209. fprintf(stderr, " level %3d : %d files\n", level, num);
  210. }
  211. }
  212. }
  213. std::string IterStatus(Iterator* iter) {
  214. std::string result;
  215. if (iter->Valid()) {
  216. result = iter->key().ToString() + "->" + iter->value().ToString();
  217. } else {
  218. result = "(invalid)";
  219. }
  220. return result;
  221. }
  222. };
  223. TEST(DBTest, Empty) {
  224. ASSERT_TRUE(db_ != NULL);
  225. ASSERT_EQ("NOT_FOUND", Get("foo"));
  226. }
  227. TEST(DBTest, ReadWrite) {
  228. ASSERT_OK(Put("foo", "v1"));
  229. ASSERT_EQ("v1", Get("foo"));
  230. ASSERT_OK(Put("bar", "v2"));
  231. ASSERT_OK(Put("foo", "v3"));
  232. ASSERT_EQ("v3", Get("foo"));
  233. ASSERT_EQ("v2", Get("bar"));
  234. }
  235. TEST(DBTest, PutDeleteGet) {
  236. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  237. ASSERT_EQ("v1", Get("foo"));
  238. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  239. ASSERT_EQ("v2", Get("foo"));
  240. ASSERT_OK(db_->Delete(WriteOptions(), "foo"));
  241. ASSERT_EQ("NOT_FOUND", Get("foo"));
  242. }
  243. TEST(DBTest, GetFromImmutableLayer) {
  244. Options options;
  245. options.env = env_;
  246. options.write_buffer_size = 100000; // Small write buffer
  247. Reopen(&options);
  248. ASSERT_OK(Put("foo", "v1"));
  249. ASSERT_EQ("v1", Get("foo"));
  250. env_->delay_sstable_sync_.Release_Store(env_); // Block sync calls
  251. Put("k1", std::string(100000, 'x')); // Fill memtable
  252. Put("k2", std::string(100000, 'y')); // Trigger compaction
  253. ASSERT_EQ("v1", Get("foo"));
  254. env_->delay_sstable_sync_.Release_Store(NULL); // Release sync calls
  255. }
  256. TEST(DBTest, GetFromVersions) {
  257. ASSERT_OK(Put("foo", "v1"));
  258. dbfull()->TEST_CompactMemTable();
  259. ASSERT_EQ("v1", Get("foo"));
  260. }
  261. TEST(DBTest, GetSnapshot) {
  262. // Try with both a short key and a long key
  263. for (int i = 0; i < 2; i++) {
  264. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  265. ASSERT_OK(Put(key, "v1"));
  266. const Snapshot* s1 = db_->GetSnapshot();
  267. ASSERT_OK(Put(key, "v2"));
  268. ASSERT_EQ("v2", Get(key));
  269. ASSERT_EQ("v1", Get(key, s1));
  270. dbfull()->TEST_CompactMemTable();
  271. ASSERT_EQ("v2", Get(key));
  272. ASSERT_EQ("v1", Get(key, s1));
  273. db_->ReleaseSnapshot(s1);
  274. }
  275. }
  276. TEST(DBTest, GetLevel0Ordering) {
  277. // Check that we process level-0 files in correct order. The code
  278. // below generates two level-0 files where the earlier one comes
  279. // before the later one in the level-0 file list since the earlier
  280. // one has a smaller "smallest" key.
  281. ASSERT_OK(Put("bar", "b"));
  282. ASSERT_OK(Put("foo", "v1"));
  283. dbfull()->TEST_CompactMemTable();
  284. ASSERT_OK(Put("foo", "v2"));
  285. dbfull()->TEST_CompactMemTable();
  286. ASSERT_EQ("v2", Get("foo"));
  287. }
  288. TEST(DBTest, GetOrderedByLevels) {
  289. ASSERT_OK(Put("foo", "v1"));
  290. Compact("a", "z");
  291. ASSERT_EQ("v1", Get("foo"));
  292. ASSERT_OK(Put("foo", "v2"));
  293. ASSERT_EQ("v2", Get("foo"));
  294. dbfull()->TEST_CompactMemTable();
  295. ASSERT_EQ("v2", Get("foo"));
  296. }
  297. TEST(DBTest, GetPicksCorrectFile) {
  298. // Arrange to have multiple files in a non-level-0 level.
  299. ASSERT_OK(Put("a", "va"));
  300. Compact("a", "b");
  301. ASSERT_OK(Put("x", "vx"));
  302. Compact("x", "y");
  303. ASSERT_OK(Put("f", "vf"));
  304. Compact("f", "g");
  305. ASSERT_EQ("va", Get("a"));
  306. ASSERT_EQ("vf", Get("f"));
  307. ASSERT_EQ("vx", Get("x"));
  308. }
  309. TEST(DBTest, GetEncountersEmptyLevel) {
  310. // Arrange for the following to happen:
  311. // * sstable A in level 0
  312. // * nothing in level 1
  313. // * sstable B in level 2
  314. // Then do enough Get() calls to arrange for an automatic compaction
  315. // of sstable A. A bug would cause the compaction to be marked as
  316. // occuring at level 1 (instead of the correct level 0).
  317. // Step 1: First place sstables in levels 0 and 2
  318. int compaction_count = 0;
  319. while (NumTableFilesAtLevel(0) == 0 ||
  320. NumTableFilesAtLevel(2) == 0) {
  321. ASSERT_LE(compaction_count, 100) << "could not fill levels 0 and 2";
  322. compaction_count++;
  323. Put("a", "begin");
  324. Put("z", "end");
  325. dbfull()->TEST_CompactMemTable();
  326. }
  327. // Step 2: clear level 1 if necessary.
  328. dbfull()->TEST_CompactRange(1, "a", "z");
  329. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  330. ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  331. ASSERT_EQ(NumTableFilesAtLevel(2), 1);
  332. // Step 3: read until level 0 compaction disappears.
  333. int read_count = 0;
  334. while (NumTableFilesAtLevel(0) > 0) {
  335. ASSERT_LE(read_count, 10000) << "did not trigger level 0 compaction";
  336. read_count++;
  337. ASSERT_EQ("NOT_FOUND", Get("missing"));
  338. }
  339. }
  340. TEST(DBTest, IterEmpty) {
  341. Iterator* iter = db_->NewIterator(ReadOptions());
  342. iter->SeekToFirst();
  343. ASSERT_EQ(IterStatus(iter), "(invalid)");
  344. iter->SeekToLast();
  345. ASSERT_EQ(IterStatus(iter), "(invalid)");
  346. iter->Seek("foo");
  347. ASSERT_EQ(IterStatus(iter), "(invalid)");
  348. delete iter;
  349. }
  350. TEST(DBTest, IterSingle) {
  351. ASSERT_OK(Put("a", "va"));
  352. Iterator* iter = db_->NewIterator(ReadOptions());
  353. iter->SeekToFirst();
  354. ASSERT_EQ(IterStatus(iter), "a->va");
  355. iter->Next();
  356. ASSERT_EQ(IterStatus(iter), "(invalid)");
  357. iter->SeekToFirst();
  358. ASSERT_EQ(IterStatus(iter), "a->va");
  359. iter->Prev();
  360. ASSERT_EQ(IterStatus(iter), "(invalid)");
  361. iter->SeekToLast();
  362. ASSERT_EQ(IterStatus(iter), "a->va");
  363. iter->Next();
  364. ASSERT_EQ(IterStatus(iter), "(invalid)");
  365. iter->SeekToLast();
  366. ASSERT_EQ(IterStatus(iter), "a->va");
  367. iter->Prev();
  368. ASSERT_EQ(IterStatus(iter), "(invalid)");
  369. iter->Seek("");
  370. ASSERT_EQ(IterStatus(iter), "a->va");
  371. iter->Next();
  372. ASSERT_EQ(IterStatus(iter), "(invalid)");
  373. iter->Seek("a");
  374. ASSERT_EQ(IterStatus(iter), "a->va");
  375. iter->Next();
  376. ASSERT_EQ(IterStatus(iter), "(invalid)");
  377. iter->Seek("b");
  378. ASSERT_EQ(IterStatus(iter), "(invalid)");
  379. delete iter;
  380. }
  381. TEST(DBTest, IterMulti) {
  382. ASSERT_OK(Put("a", "va"));
  383. ASSERT_OK(Put("b", "vb"));
  384. ASSERT_OK(Put("c", "vc"));
  385. Iterator* iter = db_->NewIterator(ReadOptions());
  386. iter->SeekToFirst();
  387. ASSERT_EQ(IterStatus(iter), "a->va");
  388. iter->Next();
  389. ASSERT_EQ(IterStatus(iter), "b->vb");
  390. iter->Next();
  391. ASSERT_EQ(IterStatus(iter), "c->vc");
  392. iter->Next();
  393. ASSERT_EQ(IterStatus(iter), "(invalid)");
  394. iter->SeekToFirst();
  395. ASSERT_EQ(IterStatus(iter), "a->va");
  396. iter->Prev();
  397. ASSERT_EQ(IterStatus(iter), "(invalid)");
  398. iter->SeekToLast();
  399. ASSERT_EQ(IterStatus(iter), "c->vc");
  400. iter->Prev();
  401. ASSERT_EQ(IterStatus(iter), "b->vb");
  402. iter->Prev();
  403. ASSERT_EQ(IterStatus(iter), "a->va");
  404. iter->Prev();
  405. ASSERT_EQ(IterStatus(iter), "(invalid)");
  406. iter->SeekToLast();
  407. ASSERT_EQ(IterStatus(iter), "c->vc");
  408. iter->Next();
  409. ASSERT_EQ(IterStatus(iter), "(invalid)");
  410. iter->Seek("");
  411. ASSERT_EQ(IterStatus(iter), "a->va");
  412. iter->Seek("a");
  413. ASSERT_EQ(IterStatus(iter), "a->va");
  414. iter->Seek("ax");
  415. ASSERT_EQ(IterStatus(iter), "b->vb");
  416. iter->Seek("b");
  417. ASSERT_EQ(IterStatus(iter), "b->vb");
  418. iter->Seek("z");
  419. ASSERT_EQ(IterStatus(iter), "(invalid)");
  420. // Switch from reverse to forward
  421. iter->SeekToLast();
  422. iter->Prev();
  423. iter->Prev();
  424. iter->Next();
  425. ASSERT_EQ(IterStatus(iter), "b->vb");
  426. // Switch from forward to reverse
  427. iter->SeekToFirst();
  428. iter->Next();
  429. iter->Next();
  430. iter->Prev();
  431. ASSERT_EQ(IterStatus(iter), "b->vb");
  432. // Make sure iter stays at snapshot
  433. ASSERT_OK(Put("a", "va2"));
  434. ASSERT_OK(Put("a2", "va3"));
  435. ASSERT_OK(Put("b", "vb2"));
  436. ASSERT_OK(Put("c", "vc2"));
  437. ASSERT_OK(Delete("b"));
  438. iter->SeekToFirst();
  439. ASSERT_EQ(IterStatus(iter), "a->va");
  440. iter->Next();
  441. ASSERT_EQ(IterStatus(iter), "b->vb");
  442. iter->Next();
  443. ASSERT_EQ(IterStatus(iter), "c->vc");
  444. iter->Next();
  445. ASSERT_EQ(IterStatus(iter), "(invalid)");
  446. iter->SeekToLast();
  447. ASSERT_EQ(IterStatus(iter), "c->vc");
  448. iter->Prev();
  449. ASSERT_EQ(IterStatus(iter), "b->vb");
  450. iter->Prev();
  451. ASSERT_EQ(IterStatus(iter), "a->va");
  452. iter->Prev();
  453. ASSERT_EQ(IterStatus(iter), "(invalid)");
  454. delete iter;
  455. }
  456. TEST(DBTest, IterSmallAndLargeMix) {
  457. ASSERT_OK(Put("a", "va"));
  458. ASSERT_OK(Put("b", std::string(100000, 'b')));
  459. ASSERT_OK(Put("c", "vc"));
  460. ASSERT_OK(Put("d", std::string(100000, 'd')));
  461. ASSERT_OK(Put("e", std::string(100000, 'e')));
  462. Iterator* iter = db_->NewIterator(ReadOptions());
  463. iter->SeekToFirst();
  464. ASSERT_EQ(IterStatus(iter), "a->va");
  465. iter->Next();
  466. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  467. iter->Next();
  468. ASSERT_EQ(IterStatus(iter), "c->vc");
  469. iter->Next();
  470. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  471. iter->Next();
  472. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  473. iter->Next();
  474. ASSERT_EQ(IterStatus(iter), "(invalid)");
  475. iter->SeekToLast();
  476. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  477. iter->Prev();
  478. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  479. iter->Prev();
  480. ASSERT_EQ(IterStatus(iter), "c->vc");
  481. iter->Prev();
  482. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  483. iter->Prev();
  484. ASSERT_EQ(IterStatus(iter), "a->va");
  485. iter->Prev();
  486. ASSERT_EQ(IterStatus(iter), "(invalid)");
  487. delete iter;
  488. }
  489. TEST(DBTest, IterMultiWithDelete) {
  490. ASSERT_OK(Put("a", "va"));
  491. ASSERT_OK(Put("b", "vb"));
  492. ASSERT_OK(Put("c", "vc"));
  493. ASSERT_OK(Delete("b"));
  494. ASSERT_EQ("NOT_FOUND", Get("b"));
  495. Iterator* iter = db_->NewIterator(ReadOptions());
  496. iter->Seek("c");
  497. ASSERT_EQ(IterStatus(iter), "c->vc");
  498. iter->Prev();
  499. ASSERT_EQ(IterStatus(iter), "a->va");
  500. delete iter;
  501. }
  502. TEST(DBTest, Recover) {
  503. ASSERT_OK(Put("foo", "v1"));
  504. ASSERT_OK(Put("baz", "v5"));
  505. Reopen();
  506. ASSERT_EQ("v1", Get("foo"));
  507. ASSERT_EQ("v1", Get("foo"));
  508. ASSERT_EQ("v5", Get("baz"));
  509. ASSERT_OK(Put("bar", "v2"));
  510. ASSERT_OK(Put("foo", "v3"));
  511. Reopen();
  512. ASSERT_EQ("v3", Get("foo"));
  513. ASSERT_OK(Put("foo", "v4"));
  514. ASSERT_EQ("v4", Get("foo"));
  515. ASSERT_EQ("v2", Get("bar"));
  516. ASSERT_EQ("v5", Get("baz"));
  517. }
  518. TEST(DBTest, RecoveryWithEmptyLog) {
  519. ASSERT_OK(Put("foo", "v1"));
  520. ASSERT_OK(Put("foo", "v2"));
  521. Reopen();
  522. Reopen();
  523. ASSERT_OK(Put("foo", "v3"));
  524. Reopen();
  525. ASSERT_EQ("v3", Get("foo"));
  526. }
  527. // Check that writes done during a memtable compaction are recovered
  528. // if the database is shutdown during the memtable compaction.
  529. TEST(DBTest, RecoverDuringMemtableCompaction) {
  530. Options options;
  531. options.env = env_;
  532. options.write_buffer_size = 1000000;
  533. Reopen(&options);
  534. // Trigger a long memtable compaction and reopen the database during it
  535. ASSERT_OK(Put("foo", "v1")); // Goes to 1st log file
  536. ASSERT_OK(Put("big1", std::string(10000000, 'x'))); // Fills memtable
  537. ASSERT_OK(Put("big2", std::string(1000, 'y'))); // Triggers compaction
  538. ASSERT_OK(Put("bar", "v2")); // Goes to new log file
  539. Reopen(&options);
  540. ASSERT_EQ("v1", Get("foo"));
  541. ASSERT_EQ("v2", Get("bar"));
  542. ASSERT_EQ(std::string(10000000, 'x'), Get("big1"));
  543. ASSERT_EQ(std::string(1000, 'y'), Get("big2"));
  544. }
  545. static std::string Key(int i) {
  546. char buf[100];
  547. snprintf(buf, sizeof(buf), "key%06d", i);
  548. return std::string(buf);
  549. }
  550. TEST(DBTest, MinorCompactionsHappen) {
  551. Options options;
  552. options.write_buffer_size = 10000;
  553. Reopen(&options);
  554. const int N = 500;
  555. int starting_num_tables = TotalTableFiles();
  556. for (int i = 0; i < N; i++) {
  557. ASSERT_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  558. }
  559. int ending_num_tables = TotalTableFiles();
  560. ASSERT_GT(ending_num_tables, starting_num_tables);
  561. for (int i = 0; i < N; i++) {
  562. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  563. }
  564. Reopen();
  565. for (int i = 0; i < N; i++) {
  566. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  567. }
  568. }
  569. TEST(DBTest, RecoverWithLargeLog) {
  570. {
  571. Options options;
  572. Reopen(&options);
  573. ASSERT_OK(Put("big1", std::string(200000, '1')));
  574. ASSERT_OK(Put("big2", std::string(200000, '2')));
  575. ASSERT_OK(Put("small3", std::string(10, '3')));
  576. ASSERT_OK(Put("small4", std::string(10, '4')));
  577. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  578. }
  579. // Make sure that if we re-open with a small write buffer size that
  580. // we flush table files in the middle of a large log file.
  581. Options options;
  582. options.write_buffer_size = 100000;
  583. Reopen(&options);
  584. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  585. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  586. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  587. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  588. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  589. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  590. }
  591. TEST(DBTest, CompactionsGenerateMultipleFiles) {
  592. Options options;
  593. options.write_buffer_size = 100000000; // Large write buffer
  594. Reopen(&options);
  595. Random rnd(301);
  596. // Write 8MB (80 values, each 100K)
  597. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  598. std::vector<std::string> values;
  599. for (int i = 0; i < 80; i++) {
  600. values.push_back(RandomString(&rnd, 100000));
  601. ASSERT_OK(Put(Key(i), values[i]));
  602. }
  603. // Reopening moves updates to level-0
  604. Reopen(&options);
  605. dbfull()->TEST_CompactRange(0, "", Key(100000));
  606. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  607. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  608. for (int i = 0; i < 80; i++) {
  609. ASSERT_EQ(Get(Key(i)), values[i]);
  610. }
  611. }
  612. TEST(DBTest, RepeatedWritesToSameKey) {
  613. Options options;
  614. options.env = env_;
  615. options.write_buffer_size = 100000; // Small write buffer
  616. Reopen(&options);
  617. // We must have at most one file per level except for level-0,
  618. // which may have up to kL0_StopWritesTrigger files.
  619. const int kMaxFiles = config::kNumLevels + config::kL0_StopWritesTrigger;
  620. Random rnd(301);
  621. std::string value = RandomString(&rnd, 2 * options.write_buffer_size);
  622. for (int i = 0; i < 5 * kMaxFiles; i++) {
  623. Put("key", value);
  624. ASSERT_LE(TotalTableFiles(), kMaxFiles);
  625. fprintf(stderr, "after %d: %d files\n", int(i+1), TotalTableFiles());
  626. }
  627. }
  628. TEST(DBTest, SparseMerge) {
  629. Options options;
  630. options.compression = kNoCompression;
  631. Reopen(&options);
  632. FillLevels("A", "Z");
  633. // Suppose there is:
  634. // small amount of data with prefix A
  635. // large amount of data with prefix B
  636. // small amount of data with prefix C
  637. // and that recent updates have made small changes to all three prefixes.
  638. // Check that we do not do a compaction that merges all of B in one shot.
  639. const std::string value(1000, 'x');
  640. Put("A", "va");
  641. // Write approximately 100MB of "B" values
  642. for (int i = 0; i < 100000; i++) {
  643. char key[100];
  644. snprintf(key, sizeof(key), "B%010d", i);
  645. Put(key, value);
  646. }
  647. Put("C", "vc");
  648. dbfull()->TEST_CompactMemTable();
  649. dbfull()->TEST_CompactRange(0, "A", "Z");
  650. // Make sparse update
  651. Put("A", "va2");
  652. Put("B100", "bvalue2");
  653. Put("C", "vc2");
  654. dbfull()->TEST_CompactMemTable();
  655. // Compactions should not cause us to create a situation where
  656. // a file overlaps too much data at the next level.
  657. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  658. dbfull()->TEST_CompactRange(0, "", "z");
  659. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  660. dbfull()->TEST_CompactRange(1, "", "z");
  661. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  662. }
  663. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  664. bool result = (val >= low) && (val <= high);
  665. if (!result) {
  666. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  667. (unsigned long long)(val),
  668. (unsigned long long)(low),
  669. (unsigned long long)(high));
  670. }
  671. return result;
  672. }
  673. TEST(DBTest, ApproximateSizes) {
  674. Options options;
  675. options.write_buffer_size = 100000000; // Large write buffer
  676. options.compression = kNoCompression;
  677. DestroyAndReopen();
  678. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  679. Reopen(&options);
  680. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  681. // Write 8MB (80 values, each 100K)
  682. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  683. const int N = 80;
  684. Random rnd(301);
  685. for (int i = 0; i < N; i++) {
  686. ASSERT_OK(Put(Key(i), RandomString(&rnd, 100000)));
  687. }
  688. // 0 because GetApproximateSizes() does not account for memtable space
  689. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  690. // Check sizes across recovery by reopening a few times
  691. for (int run = 0; run < 3; run++) {
  692. Reopen(&options);
  693. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  694. for (int i = 0; i < N; i += 10) {
  695. ASSERT_TRUE(Between(Size("", Key(i)), 100000*i, 100000*i + 10000));
  696. ASSERT_TRUE(Between(Size("", Key(i)+".suffix"),
  697. 100000 * (i+1), 100000 * (i+1) + 10000));
  698. ASSERT_TRUE(Between(Size(Key(i), Key(i+10)),
  699. 100000 * 10, 100000 * 10 + 10000));
  700. }
  701. ASSERT_TRUE(Between(Size("", Key(50)), 5000000, 5010000));
  702. ASSERT_TRUE(Between(Size("", Key(50)+".suffix"), 5100000, 5110000));
  703. dbfull()->TEST_CompactRange(0,
  704. Key(compact_start),
  705. Key(compact_start + 9));
  706. }
  707. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  708. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  709. }
  710. }
  711. TEST(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  712. Options options;
  713. options.compression = kNoCompression;
  714. Reopen();
  715. Random rnd(301);
  716. std::string big1 = RandomString(&rnd, 100000);
  717. ASSERT_OK(Put(Key(0), RandomString(&rnd, 10000)));
  718. ASSERT_OK(Put(Key(1), RandomString(&rnd, 10000)));
  719. ASSERT_OK(Put(Key(2), big1));
  720. ASSERT_OK(Put(Key(3), RandomString(&rnd, 10000)));
  721. ASSERT_OK(Put(Key(4), big1));
  722. ASSERT_OK(Put(Key(5), RandomString(&rnd, 10000)));
  723. ASSERT_OK(Put(Key(6), RandomString(&rnd, 300000)));
  724. ASSERT_OK(Put(Key(7), RandomString(&rnd, 10000)));
  725. // Check sizes across recovery by reopening a few times
  726. for (int run = 0; run < 3; run++) {
  727. Reopen(&options);
  728. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  729. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  730. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  731. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  732. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  733. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  734. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  735. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  736. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 551000));
  737. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  738. dbfull()->TEST_CompactRange(0, Key(0), Key(100));
  739. }
  740. }
  741. TEST(DBTest, IteratorPinsRef) {
  742. Put("foo", "hello");
  743. // Get iterator that will yield the current contents of the DB.
  744. Iterator* iter = db_->NewIterator(ReadOptions());
  745. // Write to force compactions
  746. Put("foo", "newvalue1");
  747. for (int i = 0; i < 100; i++) {
  748. ASSERT_OK(Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  749. }
  750. Put("foo", "newvalue2");
  751. iter->SeekToFirst();
  752. ASSERT_TRUE(iter->Valid());
  753. ASSERT_EQ("foo", iter->key().ToString());
  754. ASSERT_EQ("hello", iter->value().ToString());
  755. iter->Next();
  756. ASSERT_TRUE(!iter->Valid());
  757. delete iter;
  758. }
  759. TEST(DBTest, Snapshot) {
  760. Put("foo", "v1");
  761. const Snapshot* s1 = db_->GetSnapshot();
  762. Put("foo", "v2");
  763. const Snapshot* s2 = db_->GetSnapshot();
  764. Put("foo", "v3");
  765. const Snapshot* s3 = db_->GetSnapshot();
  766. Put("foo", "v4");
  767. ASSERT_EQ("v1", Get("foo", s1));
  768. ASSERT_EQ("v2", Get("foo", s2));
  769. ASSERT_EQ("v3", Get("foo", s3));
  770. ASSERT_EQ("v4", Get("foo"));
  771. db_->ReleaseSnapshot(s3);
  772. ASSERT_EQ("v1", Get("foo", s1));
  773. ASSERT_EQ("v2", Get("foo", s2));
  774. ASSERT_EQ("v4", Get("foo"));
  775. db_->ReleaseSnapshot(s1);
  776. ASSERT_EQ("v2", Get("foo", s2));
  777. ASSERT_EQ("v4", Get("foo"));
  778. db_->ReleaseSnapshot(s2);
  779. ASSERT_EQ("v4", Get("foo"));
  780. }
  781. TEST(DBTest, HiddenValuesAreRemoved) {
  782. Random rnd(301);
  783. FillLevels("a", "z");
  784. std::string big = RandomString(&rnd, 50000);
  785. Put("foo", big);
  786. Put("pastfoo", "v");
  787. const Snapshot* snapshot = db_->GetSnapshot();
  788. Put("foo", "tiny");
  789. Put("pastfoo2", "v2"); // Advance sequence number one more
  790. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  791. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  792. ASSERT_EQ(big, Get("foo", snapshot));
  793. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  794. db_->ReleaseSnapshot(snapshot);
  795. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  796. dbfull()->TEST_CompactRange(0, "", "x");
  797. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  798. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  799. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  800. dbfull()->TEST_CompactRange(1, "", "x");
  801. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  802. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  803. }
  804. TEST(DBTest, DeletionMarkers1) {
  805. Put("foo", "v1");
  806. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  807. const int last = config::kMaxMemCompactLevel;
  808. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  809. // Place a table at level last-1 to prevent merging with preceding mutation
  810. Put("a", "begin");
  811. Put("z", "end");
  812. dbfull()->TEST_CompactMemTable();
  813. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  814. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  815. Delete("foo");
  816. Put("foo", "v2");
  817. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  818. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  819. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  820. dbfull()->TEST_CompactRange(last-2, "", "z");
  821. // DEL eliminated, but v1 remains because we aren't compacting that level
  822. // (DEL can be eliminated because v2 hides v1).
  823. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  824. dbfull()->TEST_CompactRange(last-1, "", "z");
  825. // Merging last-1 w/ last, so we are the base level for "foo", so
  826. // DEL is removed. (as is v1).
  827. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  828. }
  829. TEST(DBTest, DeletionMarkers2) {
  830. Put("foo", "v1");
  831. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  832. const int last = config::kMaxMemCompactLevel;
  833. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  834. // Place a table at level last-1 to prevent merging with preceding mutation
  835. Put("a", "begin");
  836. Put("z", "end");
  837. dbfull()->TEST_CompactMemTable();
  838. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  839. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  840. Delete("foo");
  841. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  842. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  843. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  844. dbfull()->TEST_CompactRange(last-2, "", "z");
  845. // DEL kept: "last" file overlaps
  846. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  847. dbfull()->TEST_CompactRange(last-1, "", "z");
  848. // Merging last-1 w/ last, so we are the base level for "foo", so
  849. // DEL is removed. (as is v1).
  850. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  851. }
  852. TEST(DBTest, ComparatorCheck) {
  853. class NewComparator : public Comparator {
  854. public:
  855. virtual const char* Name() const { return "leveldb.NewComparator"; }
  856. virtual int Compare(const Slice& a, const Slice& b) const {
  857. return BytewiseComparator()->Compare(a, b);
  858. }
  859. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  860. BytewiseComparator()->FindShortestSeparator(s, l);
  861. }
  862. virtual void FindShortSuccessor(std::string* key) const {
  863. BytewiseComparator()->FindShortSuccessor(key);
  864. }
  865. };
  866. NewComparator cmp;
  867. Options new_options;
  868. new_options.comparator = &cmp;
  869. Status s = TryReopen(&new_options);
  870. ASSERT_TRUE(!s.ok());
  871. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  872. << s.ToString();
  873. }
  874. TEST(DBTest, DBOpen_Options) {
  875. std::string dbname = test::TmpDir() + "/db_options_test";
  876. DestroyDB(dbname, Options());
  877. // Does not exist, and create_if_missing == false: error
  878. DB* db = NULL;
  879. Options opts;
  880. opts.create_if_missing = false;
  881. Status s = DB::Open(opts, dbname, &db);
  882. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != NULL);
  883. ASSERT_TRUE(db == NULL);
  884. // Does not exist, and create_if_missing == true: OK
  885. opts.create_if_missing = true;
  886. s = DB::Open(opts, dbname, &db);
  887. ASSERT_OK(s);
  888. ASSERT_TRUE(db != NULL);
  889. delete db;
  890. db = NULL;
  891. // Does exist, and error_if_exists == true: error
  892. opts.create_if_missing = false;
  893. opts.error_if_exists = true;
  894. s = DB::Open(opts, dbname, &db);
  895. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != NULL);
  896. ASSERT_TRUE(db == NULL);
  897. // Does exist, and error_if_exists == false: OK
  898. opts.create_if_missing = true;
  899. opts.error_if_exists = false;
  900. s = DB::Open(opts, dbname, &db);
  901. ASSERT_OK(s);
  902. ASSERT_TRUE(db != NULL);
  903. delete db;
  904. db = NULL;
  905. }
  906. // Multi-threaded test:
  907. namespace {
  908. static const int kNumThreads = 4;
  909. static const int kTestSeconds = 10;
  910. static const int kNumKeys = 1000;
  911. struct MTState {
  912. DBTest* test;
  913. port::AtomicPointer stop;
  914. port::AtomicPointer counter[kNumThreads];
  915. port::AtomicPointer thread_done[kNumThreads];
  916. };
  917. struct MTThread {
  918. MTState* state;
  919. int id;
  920. };
  921. static void MTThreadBody(void* arg) {
  922. MTThread* t = reinterpret_cast<MTThread*>(arg);
  923. DB* db = t->state->test->db_;
  924. uintptr_t counter = 0;
  925. fprintf(stderr, "... starting thread %d\n", t->id);
  926. Random rnd(1000 + t->id);
  927. std::string value;
  928. char valbuf[1500];
  929. while (t->state->stop.Acquire_Load() == NULL) {
  930. t->state->counter[t->id].Release_Store(reinterpret_cast<void*>(counter));
  931. int key = rnd.Uniform(kNumKeys);
  932. char keybuf[20];
  933. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  934. if (rnd.OneIn(2)) {
  935. // Write values of the form <key, my id, counter>.
  936. // We add some padding for force compactions.
  937. snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d",
  938. key, t->id, static_cast<int>(counter));
  939. ASSERT_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  940. } else {
  941. // Read a value and verify that it matches the pattern written above.
  942. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  943. if (s.IsNotFound()) {
  944. // Key has not yet been written
  945. } else {
  946. // Check that the writer thread counter is >= the counter in the value
  947. ASSERT_OK(s);
  948. int k, w, c;
  949. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  950. ASSERT_EQ(k, key);
  951. ASSERT_GE(w, 0);
  952. ASSERT_LT(w, kNumThreads);
  953. ASSERT_LE(c, reinterpret_cast<uintptr_t>(
  954. t->state->counter[w].Acquire_Load()));
  955. }
  956. }
  957. counter++;
  958. }
  959. t->state->thread_done[t->id].Release_Store(t);
  960. fprintf(stderr, "... stopping thread %d after %d ops\n", t->id, int(counter));
  961. }
  962. }
  963. TEST(DBTest, MultiThreaded) {
  964. // Initialize state
  965. MTState mt;
  966. mt.test = this;
  967. mt.stop.Release_Store(0);
  968. for (int id = 0; id < kNumThreads; id++) {
  969. mt.counter[id].Release_Store(0);
  970. mt.thread_done[id].Release_Store(0);
  971. }
  972. // Start threads
  973. MTThread thread[kNumThreads];
  974. for (int id = 0; id < kNumThreads; id++) {
  975. thread[id].state = &mt;
  976. thread[id].id = id;
  977. env_->StartThread(MTThreadBody, &thread[id]);
  978. }
  979. // Let them run for a while
  980. env_->SleepForMicroseconds(kTestSeconds * 1000000);
  981. // Stop the threads and wait for them to finish
  982. mt.stop.Release_Store(&mt);
  983. for (int id = 0; id < kNumThreads; id++) {
  984. while (mt.thread_done[id].Acquire_Load() == NULL) {
  985. env_->SleepForMicroseconds(100000);
  986. }
  987. }
  988. }
  989. namespace {
  990. typedef std::map<std::string, std::string> KVMap;
  991. }
  992. class ModelDB: public DB {
  993. public:
  994. class ModelSnapshot : public Snapshot {
  995. public:
  996. KVMap map_;
  997. };
  998. explicit ModelDB(const Options& options): options_(options) { }
  999. ~ModelDB() { }
  1000. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  1001. return DB::Put(o, k, v);
  1002. }
  1003. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  1004. return DB::Delete(o, key);
  1005. }
  1006. virtual Status Get(const ReadOptions& options,
  1007. const Slice& key, std::string* value) {
  1008. assert(false); // Not implemented
  1009. return Status::NotFound(key);
  1010. }
  1011. virtual Iterator* NewIterator(const ReadOptions& options) {
  1012. if (options.snapshot == NULL) {
  1013. KVMap* saved = new KVMap;
  1014. *saved = map_;
  1015. return new ModelIter(saved, true);
  1016. } else {
  1017. const KVMap* snapshot_state =
  1018. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1019. return new ModelIter(snapshot_state, false);
  1020. }
  1021. }
  1022. virtual const Snapshot* GetSnapshot() {
  1023. ModelSnapshot* snapshot = new ModelSnapshot;
  1024. snapshot->map_ = map_;
  1025. return snapshot;
  1026. }
  1027. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  1028. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1029. }
  1030. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  1031. assert(options.post_write_snapshot == NULL); // Not supported
  1032. class Handler : public WriteBatch::Handler {
  1033. public:
  1034. KVMap* map_;
  1035. virtual void Put(const Slice& key, const Slice& value) {
  1036. (*map_)[key.ToString()] = value.ToString();
  1037. }
  1038. virtual void Delete(const Slice& key) {
  1039. map_->erase(key.ToString());
  1040. }
  1041. };
  1042. Handler handler;
  1043. handler.map_ = &map_;
  1044. return batch->Iterate(&handler);
  1045. }
  1046. virtual bool GetProperty(const Slice& property, std::string* value) {
  1047. return false;
  1048. }
  1049. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  1050. for (int i = 0; i < n; i++) {
  1051. sizes[i] = 0;
  1052. }
  1053. }
  1054. private:
  1055. class ModelIter: public Iterator {
  1056. public:
  1057. ModelIter(const KVMap* map, bool owned)
  1058. : map_(map), owned_(owned), iter_(map_->end()) {
  1059. }
  1060. ~ModelIter() {
  1061. if (owned_) delete map_;
  1062. }
  1063. virtual bool Valid() const { return iter_ != map_->end(); }
  1064. virtual void SeekToFirst() { iter_ = map_->begin(); }
  1065. virtual void SeekToLast() {
  1066. if (map_->empty()) {
  1067. iter_ = map_->end();
  1068. } else {
  1069. iter_ = map_->find(map_->rbegin()->first);
  1070. }
  1071. }
  1072. virtual void Seek(const Slice& k) {
  1073. iter_ = map_->lower_bound(k.ToString());
  1074. }
  1075. virtual void Next() { ++iter_; }
  1076. virtual void Prev() { --iter_; }
  1077. virtual Slice key() const { return iter_->first; }
  1078. virtual Slice value() const { return iter_->second; }
  1079. virtual Status status() const { return Status::OK(); }
  1080. private:
  1081. const KVMap* const map_;
  1082. const bool owned_; // Do we own map_
  1083. KVMap::const_iterator iter_;
  1084. };
  1085. const Options options_;
  1086. KVMap map_;
  1087. };
  1088. static std::string RandomKey(Random* rnd) {
  1089. int len = (rnd->OneIn(3)
  1090. ? 1 // Short sometimes to encourage collisions
  1091. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  1092. return test::RandomKey(rnd, len);
  1093. }
  1094. static bool CompareIterators(int step,
  1095. DB* model,
  1096. DB* db,
  1097. const Snapshot* model_snap,
  1098. const Snapshot* db_snap) {
  1099. ReadOptions options;
  1100. options.snapshot = model_snap;
  1101. Iterator* miter = model->NewIterator(options);
  1102. options.snapshot = db_snap;
  1103. Iterator* dbiter = db->NewIterator(options);
  1104. bool ok = true;
  1105. int count = 0;
  1106. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1107. ok && miter->Valid() && dbiter->Valid();
  1108. miter->Next(), dbiter->Next()) {
  1109. count++;
  1110. if (miter->key().compare(dbiter->key()) != 0) {
  1111. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  1112. step,
  1113. EscapeString(miter->key()).c_str(),
  1114. EscapeString(dbiter->key()).c_str());
  1115. ok = false;
  1116. break;
  1117. }
  1118. if (miter->value().compare(dbiter->value()) != 0) {
  1119. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1120. step,
  1121. EscapeString(miter->key()).c_str(),
  1122. EscapeString(miter->value()).c_str(),
  1123. EscapeString(miter->value()).c_str());
  1124. ok = false;
  1125. }
  1126. }
  1127. if (ok) {
  1128. if (miter->Valid() != dbiter->Valid()) {
  1129. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1130. step, miter->Valid(), dbiter->Valid());
  1131. ok = false;
  1132. }
  1133. }
  1134. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1135. delete miter;
  1136. delete dbiter;
  1137. return ok;
  1138. }
  1139. TEST(DBTest, Randomized) {
  1140. Random rnd(test::RandomSeed());
  1141. ModelDB model(last_options_);
  1142. const int N = 10000;
  1143. const Snapshot* model_snap = NULL;
  1144. const Snapshot* db_snap = NULL;
  1145. std::string k, v;
  1146. for (int step = 0; step < N; step++) {
  1147. if (step % 100 == 0) {
  1148. fprintf(stderr, "Step %d of %d\n", step, N);
  1149. }
  1150. int p = rnd.Uniform(100);
  1151. if (p < 45) { // Put
  1152. k = RandomKey(&rnd);
  1153. v = RandomString(&rnd,
  1154. rnd.OneIn(20)
  1155. ? 100 + rnd.Uniform(100)
  1156. : rnd.Uniform(8));
  1157. ASSERT_OK(model.Put(WriteOptions(), k, v));
  1158. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  1159. } else if (p < 90) { // Delete
  1160. k = RandomKey(&rnd);
  1161. ASSERT_OK(model.Delete(WriteOptions(), k));
  1162. ASSERT_OK(db_->Delete(WriteOptions(), k));
  1163. } else { // Multi-element batch
  1164. WriteBatch b;
  1165. const int num = rnd.Uniform(8);
  1166. for (int i = 0; i < num; i++) {
  1167. if (i == 0 || !rnd.OneIn(10)) {
  1168. k = RandomKey(&rnd);
  1169. } else {
  1170. // Periodically re-use the same key from the previous iter, so
  1171. // we have multiple entries in the write batch for the same key
  1172. }
  1173. if (rnd.OneIn(2)) {
  1174. v = RandomString(&rnd, rnd.Uniform(10));
  1175. b.Put(k, v);
  1176. } else {
  1177. b.Delete(k);
  1178. }
  1179. }
  1180. ASSERT_OK(model.Write(WriteOptions(), &b));
  1181. ASSERT_OK(db_->Write(WriteOptions(), &b));
  1182. }
  1183. if ((step % 100) == 0) {
  1184. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1185. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1186. // Save a snapshot from each DB this time that we'll use next
  1187. // time we compare things, to make sure the current state is
  1188. // preserved with the snapshot
  1189. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1190. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1191. Reopen();
  1192. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1193. model_snap = model.GetSnapshot();
  1194. db_snap = db_->GetSnapshot();
  1195. }
  1196. }
  1197. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1198. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1199. }
  1200. std::string MakeKey(unsigned int num) {
  1201. char buf[30];
  1202. snprintf(buf, sizeof(buf), "%016u", num);
  1203. return std::string(buf);
  1204. }
  1205. void BM_LogAndApply(int iters, int num_base_files) {
  1206. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  1207. DestroyDB(dbname, Options());
  1208. DB* db = NULL;
  1209. Options opts;
  1210. opts.create_if_missing = true;
  1211. Status s = DB::Open(opts, dbname, &db);
  1212. ASSERT_OK(s);
  1213. ASSERT_TRUE(db != NULL);
  1214. delete db;
  1215. db = NULL;
  1216. Env* env = Env::Default();
  1217. port::Mutex mu;
  1218. MutexLock l(&mu);
  1219. InternalKeyComparator cmp(BytewiseComparator());
  1220. Options options;
  1221. VersionSet vset(dbname, &options, NULL, &cmp);
  1222. ASSERT_OK(vset.Recover());
  1223. VersionEdit vbase;
  1224. uint64_t fnum = 1;
  1225. for (int i = 0; i < num_base_files; i++) {
  1226. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1227. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1228. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1229. }
  1230. ASSERT_OK(vset.LogAndApply(&vbase, &mu));
  1231. uint64_t start_micros = env->NowMicros();
  1232. for (int i = 0; i < iters; i++) {
  1233. VersionEdit vedit;
  1234. vedit.DeleteFile(2, fnum);
  1235. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1236. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1237. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1238. vset.LogAndApply(&vedit, &mu);
  1239. }
  1240. uint64_t stop_micros = env->NowMicros();
  1241. unsigned int us = stop_micros - start_micros;
  1242. char buf[16];
  1243. snprintf(buf, sizeof(buf), "%d", num_base_files);
  1244. fprintf(stderr,
  1245. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  1246. buf, iters, us, ((float)us) / iters);
  1247. }
  1248. }
  1249. int main(int argc, char** argv) {
  1250. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  1251. leveldb::BM_LogAndApply(1000, 1);
  1252. leveldb::BM_LogAndApply(1000, 100);
  1253. leveldb::BM_LogAndApply(1000, 10000);
  1254. leveldb::BM_LogAndApply(100, 100000);
  1255. return 0;
  1256. }
  1257. return leveldb::test::RunAllTests();
  1258. }