作者: 韩晨旭 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.

1097 rivejä
31 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/testharness.h"
  13. #include "util/testutil.h"
  14. namespace leveldb {
  15. static std::string RandomString(Random* rnd, int len) {
  16. std::string r;
  17. test::RandomString(rnd, len, &r);
  18. return r;
  19. }
  20. class DBTest {
  21. public:
  22. std::string dbname_;
  23. Env* env_;
  24. DB* db_;
  25. Options last_options_;
  26. DBTest() : env_(Env::Default()) {
  27. dbname_ = test::TmpDir() + "/db_test";
  28. DestroyDB(dbname_, Options());
  29. db_ = NULL;
  30. Reopen();
  31. }
  32. ~DBTest() {
  33. delete db_;
  34. DestroyDB(dbname_, Options());
  35. }
  36. DBImpl* dbfull() {
  37. return reinterpret_cast<DBImpl*>(db_);
  38. }
  39. void Reopen(Options* options = NULL) {
  40. ASSERT_OK(TryReopen(options));
  41. }
  42. void DestroyAndReopen(Options* options = NULL) {
  43. delete db_;
  44. db_ = NULL;
  45. DestroyDB(dbname_, Options());
  46. ASSERT_OK(TryReopen(options));
  47. }
  48. Status TryReopen(Options* options) {
  49. delete db_;
  50. db_ = NULL;
  51. Options opts;
  52. if (options != NULL) {
  53. opts = *options;
  54. } else {
  55. opts.create_if_missing = true;
  56. }
  57. last_options_ = opts;
  58. return DB::Open(opts, dbname_, &db_);
  59. }
  60. Status Put(const std::string& k, const std::string& v) {
  61. return db_->Put(WriteOptions(), k, v);
  62. }
  63. Status Delete(const std::string& k) {
  64. return db_->Delete(WriteOptions(), k);
  65. }
  66. std::string Get(const std::string& k, const Snapshot* snapshot = NULL) {
  67. ReadOptions options;
  68. options.snapshot = snapshot;
  69. std::string result;
  70. Status s = db_->Get(options, k, &result);
  71. if (s.IsNotFound()) {
  72. result = "NOT_FOUND";
  73. } else if (!s.ok()) {
  74. result = s.ToString();
  75. }
  76. return result;
  77. }
  78. std::string AllEntriesFor(const Slice& user_key) {
  79. Iterator* iter = dbfull()->TEST_NewInternalIterator();
  80. InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  81. iter->Seek(target.Encode());
  82. std::string result;
  83. if (!iter->status().ok()) {
  84. result = iter->status().ToString();
  85. } else {
  86. result = "[ ";
  87. bool first = true;
  88. while (iter->Valid()) {
  89. ParsedInternalKey ikey;
  90. if (!ParseInternalKey(iter->key(), &ikey)) {
  91. result += "CORRUPTED";
  92. } else {
  93. if (last_options_.comparator->Compare(
  94. ikey.user_key, user_key) != 0) {
  95. break;
  96. }
  97. if (!first) {
  98. result += ", ";
  99. }
  100. first = false;
  101. switch (ikey.type) {
  102. case kTypeValue:
  103. result += iter->value().ToString();
  104. break;
  105. case kTypeDeletion:
  106. result += "DEL";
  107. break;
  108. }
  109. }
  110. iter->Next();
  111. }
  112. if (!first) {
  113. result += " ";
  114. }
  115. result += "]";
  116. }
  117. delete iter;
  118. return result;
  119. }
  120. int NumTableFilesAtLevel(int level) {
  121. std::string property;
  122. ASSERT_TRUE(
  123. db_->GetProperty("leveldb.num-files-at-level" + NumberToString(level),
  124. &property));
  125. return atoi(property.c_str());
  126. }
  127. uint64_t Size(const Slice& start, const Slice& limit) {
  128. Range r(start, limit);
  129. uint64_t size;
  130. db_->GetApproximateSizes(&r, 1, &size);
  131. return size;
  132. }
  133. void Compact(const Slice& start, const Slice& limit) {
  134. dbfull()->TEST_CompactMemTable();
  135. int max_level_with_files = 1;
  136. for (int level = 1; level < config::kNumLevels; level++) {
  137. if (NumTableFilesAtLevel(level) > 0) {
  138. max_level_with_files = level;
  139. }
  140. }
  141. for (int level = 0; level < max_level_with_files; level++) {
  142. dbfull()->TEST_CompactRange(level, "", "~");
  143. }
  144. }
  145. void DumpFileCounts(const char* label) {
  146. fprintf(stderr, "---\n%s:\n", label);
  147. fprintf(stderr, "maxoverlap: %lld\n",
  148. static_cast<long long>(
  149. dbfull()->TEST_MaxNextLevelOverlappingBytes()));
  150. for (int level = 0; level < config::kNumLevels; level++) {
  151. int num = NumTableFilesAtLevel(level);
  152. if (num > 0) {
  153. fprintf(stderr, " level %3d : %d files\n", level, num);
  154. }
  155. }
  156. }
  157. std::string IterStatus(Iterator* iter) {
  158. std::string result;
  159. if (iter->Valid()) {
  160. result = iter->key().ToString() + "->" + iter->value().ToString();
  161. } else {
  162. result = "(invalid)";
  163. }
  164. return result;
  165. }
  166. };
  167. TEST(DBTest, Empty) {
  168. ASSERT_TRUE(db_ != NULL);
  169. ASSERT_EQ("NOT_FOUND", Get("foo"));
  170. }
  171. TEST(DBTest, ReadWrite) {
  172. ASSERT_OK(Put("foo", "v1"));
  173. ASSERT_EQ("v1", Get("foo"));
  174. ASSERT_OK(Put("bar", "v2"));
  175. ASSERT_OK(Put("foo", "v3"));
  176. ASSERT_EQ("v3", Get("foo"));
  177. ASSERT_EQ("v2", Get("bar"));
  178. }
  179. TEST(DBTest, PutDeleteGet) {
  180. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  181. ASSERT_EQ("v1", Get("foo"));
  182. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  183. ASSERT_EQ("v2", Get("foo"));
  184. ASSERT_OK(db_->Delete(WriteOptions(), "foo"));
  185. ASSERT_EQ("NOT_FOUND", Get("foo"));
  186. }
  187. TEST(DBTest, IterEmpty) {
  188. Iterator* iter = db_->NewIterator(ReadOptions());
  189. iter->SeekToFirst();
  190. ASSERT_EQ(IterStatus(iter), "(invalid)");
  191. iter->SeekToLast();
  192. ASSERT_EQ(IterStatus(iter), "(invalid)");
  193. iter->Seek("foo");
  194. ASSERT_EQ(IterStatus(iter), "(invalid)");
  195. delete iter;
  196. }
  197. TEST(DBTest, IterSingle) {
  198. ASSERT_OK(Put("a", "va"));
  199. Iterator* iter = db_->NewIterator(ReadOptions());
  200. iter->SeekToFirst();
  201. ASSERT_EQ(IterStatus(iter), "a->va");
  202. iter->Next();
  203. ASSERT_EQ(IterStatus(iter), "(invalid)");
  204. iter->SeekToFirst();
  205. ASSERT_EQ(IterStatus(iter), "a->va");
  206. iter->Prev();
  207. ASSERT_EQ(IterStatus(iter), "(invalid)");
  208. iter->SeekToLast();
  209. ASSERT_EQ(IterStatus(iter), "a->va");
  210. iter->Next();
  211. ASSERT_EQ(IterStatus(iter), "(invalid)");
  212. iter->SeekToLast();
  213. ASSERT_EQ(IterStatus(iter), "a->va");
  214. iter->Prev();
  215. ASSERT_EQ(IterStatus(iter), "(invalid)");
  216. iter->Seek("");
  217. ASSERT_EQ(IterStatus(iter), "a->va");
  218. iter->Next();
  219. ASSERT_EQ(IterStatus(iter), "(invalid)");
  220. iter->Seek("a");
  221. ASSERT_EQ(IterStatus(iter), "a->va");
  222. iter->Next();
  223. ASSERT_EQ(IterStatus(iter), "(invalid)");
  224. iter->Seek("b");
  225. ASSERT_EQ(IterStatus(iter), "(invalid)");
  226. delete iter;
  227. }
  228. TEST(DBTest, IterMulti) {
  229. ASSERT_OK(Put("a", "va"));
  230. ASSERT_OK(Put("b", "vb"));
  231. ASSERT_OK(Put("c", "vc"));
  232. Iterator* iter = db_->NewIterator(ReadOptions());
  233. iter->SeekToFirst();
  234. ASSERT_EQ(IterStatus(iter), "a->va");
  235. iter->Next();
  236. ASSERT_EQ(IterStatus(iter), "b->vb");
  237. iter->Next();
  238. ASSERT_EQ(IterStatus(iter), "c->vc");
  239. iter->Next();
  240. ASSERT_EQ(IterStatus(iter), "(invalid)");
  241. iter->SeekToFirst();
  242. ASSERT_EQ(IterStatus(iter), "a->va");
  243. iter->Prev();
  244. ASSERT_EQ(IterStatus(iter), "(invalid)");
  245. iter->SeekToLast();
  246. ASSERT_EQ(IterStatus(iter), "c->vc");
  247. iter->Prev();
  248. ASSERT_EQ(IterStatus(iter), "b->vb");
  249. iter->Prev();
  250. ASSERT_EQ(IterStatus(iter), "a->va");
  251. iter->Prev();
  252. ASSERT_EQ(IterStatus(iter), "(invalid)");
  253. iter->SeekToLast();
  254. ASSERT_EQ(IterStatus(iter), "c->vc");
  255. iter->Next();
  256. ASSERT_EQ(IterStatus(iter), "(invalid)");
  257. iter->Seek("");
  258. ASSERT_EQ(IterStatus(iter), "a->va");
  259. iter->Seek("a");
  260. ASSERT_EQ(IterStatus(iter), "a->va");
  261. iter->Seek("ax");
  262. ASSERT_EQ(IterStatus(iter), "b->vb");
  263. iter->Seek("b");
  264. ASSERT_EQ(IterStatus(iter), "b->vb");
  265. iter->Seek("z");
  266. ASSERT_EQ(IterStatus(iter), "(invalid)");
  267. // Switch from reverse to forward
  268. iter->SeekToLast();
  269. iter->Prev();
  270. iter->Prev();
  271. iter->Next();
  272. ASSERT_EQ(IterStatus(iter), "b->vb");
  273. // Switch from forward to reverse
  274. iter->SeekToFirst();
  275. iter->Next();
  276. iter->Next();
  277. iter->Prev();
  278. ASSERT_EQ(IterStatus(iter), "b->vb");
  279. // Make sure iter stays at snapshot
  280. ASSERT_OK(Put("a", "va2"));
  281. ASSERT_OK(Put("a2", "va3"));
  282. ASSERT_OK(Put("b", "vb2"));
  283. ASSERT_OK(Put("c", "vc2"));
  284. ASSERT_OK(Delete("b"));
  285. iter->SeekToFirst();
  286. ASSERT_EQ(IterStatus(iter), "a->va");
  287. iter->Next();
  288. ASSERT_EQ(IterStatus(iter), "b->vb");
  289. iter->Next();
  290. ASSERT_EQ(IterStatus(iter), "c->vc");
  291. iter->Next();
  292. ASSERT_EQ(IterStatus(iter), "(invalid)");
  293. iter->SeekToLast();
  294. ASSERT_EQ(IterStatus(iter), "c->vc");
  295. iter->Prev();
  296. ASSERT_EQ(IterStatus(iter), "b->vb");
  297. iter->Prev();
  298. ASSERT_EQ(IterStatus(iter), "a->va");
  299. iter->Prev();
  300. ASSERT_EQ(IterStatus(iter), "(invalid)");
  301. delete iter;
  302. }
  303. TEST(DBTest, IterSmallAndLargeMix) {
  304. ASSERT_OK(Put("a", "va"));
  305. ASSERT_OK(Put("b", std::string(100000, 'b')));
  306. ASSERT_OK(Put("c", "vc"));
  307. ASSERT_OK(Put("d", std::string(100000, 'd')));
  308. ASSERT_OK(Put("e", std::string(100000, 'e')));
  309. Iterator* iter = db_->NewIterator(ReadOptions());
  310. iter->SeekToFirst();
  311. ASSERT_EQ(IterStatus(iter), "a->va");
  312. iter->Next();
  313. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  314. iter->Next();
  315. ASSERT_EQ(IterStatus(iter), "c->vc");
  316. iter->Next();
  317. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  318. iter->Next();
  319. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  320. iter->Next();
  321. ASSERT_EQ(IterStatus(iter), "(invalid)");
  322. iter->SeekToLast();
  323. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  324. iter->Prev();
  325. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  326. iter->Prev();
  327. ASSERT_EQ(IterStatus(iter), "c->vc");
  328. iter->Prev();
  329. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  330. iter->Prev();
  331. ASSERT_EQ(IterStatus(iter), "a->va");
  332. iter->Prev();
  333. ASSERT_EQ(IterStatus(iter), "(invalid)");
  334. delete iter;
  335. }
  336. TEST(DBTest, Recover) {
  337. ASSERT_OK(Put("foo", "v1"));
  338. ASSERT_OK(Put("baz", "v5"));
  339. Reopen();
  340. ASSERT_EQ("v1", Get("foo"));
  341. ASSERT_EQ("v1", Get("foo"));
  342. ASSERT_EQ("v5", Get("baz"));
  343. ASSERT_OK(Put("bar", "v2"));
  344. ASSERT_OK(Put("foo", "v3"));
  345. Reopen();
  346. ASSERT_EQ("v3", Get("foo"));
  347. ASSERT_OK(Put("foo", "v4"));
  348. ASSERT_EQ("v4", Get("foo"));
  349. ASSERT_EQ("v2", Get("bar"));
  350. ASSERT_EQ("v5", Get("baz"));
  351. }
  352. TEST(DBTest, RecoveryWithEmptyLog) {
  353. ASSERT_OK(Put("foo", "v1"));
  354. ASSERT_OK(Put("foo", "v2"));
  355. Reopen();
  356. Reopen();
  357. ASSERT_OK(Put("foo", "v3"));
  358. Reopen();
  359. ASSERT_EQ("v3", Get("foo"));
  360. }
  361. static std::string Key(int i) {
  362. char buf[100];
  363. snprintf(buf, sizeof(buf), "key%06d", i);
  364. return std::string(buf);
  365. }
  366. TEST(DBTest, MinorCompactionsHappen) {
  367. Options options;
  368. options.write_buffer_size = 10000;
  369. Reopen(&options);
  370. const int N = 500;
  371. int starting_num_tables = NumTableFilesAtLevel(0);
  372. for (int i = 0; i < N; i++) {
  373. ASSERT_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  374. }
  375. int ending_num_tables = NumTableFilesAtLevel(0);
  376. ASSERT_GT(ending_num_tables, starting_num_tables);
  377. for (int i = 0; i < N; i++) {
  378. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  379. }
  380. Reopen();
  381. for (int i = 0; i < N; i++) {
  382. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  383. }
  384. }
  385. TEST(DBTest, RecoverWithLargeLog) {
  386. {
  387. Options options;
  388. Reopen(&options);
  389. ASSERT_OK(Put("big1", std::string(200000, '1')));
  390. ASSERT_OK(Put("big2", std::string(200000, '2')));
  391. ASSERT_OK(Put("small3", std::string(10, '3')));
  392. ASSERT_OK(Put("small4", std::string(10, '4')));
  393. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  394. }
  395. // Make sure that if we re-open with a small write buffer size that
  396. // we flush table files in the middle of a large log file.
  397. Options options;
  398. options.write_buffer_size = 100000;
  399. Reopen(&options);
  400. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  401. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  402. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  403. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  404. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  405. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  406. }
  407. TEST(DBTest, CompactionsGenerateMultipleFiles) {
  408. Options options;
  409. options.write_buffer_size = 100000000; // Large write buffer
  410. Reopen(&options);
  411. Random rnd(301);
  412. // Write 8MB (80 values, each 100K)
  413. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  414. std::vector<std::string> values;
  415. for (int i = 0; i < 80; i++) {
  416. values.push_back(RandomString(&rnd, 100000));
  417. ASSERT_OK(Put(Key(i), values[i]));
  418. }
  419. // Reopening moves updates to level-0
  420. Reopen(&options);
  421. dbfull()->TEST_CompactRange(0, "", Key(100000));
  422. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  423. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  424. for (int i = 0; i < 80; i++) {
  425. ASSERT_EQ(Get(Key(i)), values[i]);
  426. }
  427. }
  428. TEST(DBTest, SparseMerge) {
  429. Options options;
  430. options.compression = kNoCompression;
  431. Reopen(&options);
  432. // Suppose there is:
  433. // small amount of data with prefix A
  434. // large amount of data with prefix B
  435. // small amount of data with prefix C
  436. // and that recent updates have made small changes to all three prefixes.
  437. // Check that we do not do a compaction that merges all of B in one shot.
  438. const std::string value(1000, 'x');
  439. Put("A", "va");
  440. // Write approximately 100MB of "B" values
  441. for (int i = 0; i < 100000; i++) {
  442. char key[100];
  443. snprintf(key, sizeof(key), "B%010d", i);
  444. Put(key, value);
  445. }
  446. Put("C", "vc");
  447. Compact("", "z");
  448. // Make sparse update
  449. Put("A", "va2");
  450. Put("B100", "bvalue2");
  451. Put("C", "vc2");
  452. dbfull()->TEST_CompactMemTable();
  453. // Compactions should not cause us to create a situation where
  454. // a file overlaps too much data at the next level.
  455. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  456. dbfull()->TEST_CompactRange(0, "", "z");
  457. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  458. dbfull()->TEST_CompactRange(1, "", "z");
  459. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  460. }
  461. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  462. bool result = (val >= low) && (val <= high);
  463. if (!result) {
  464. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  465. (unsigned long long)(val),
  466. (unsigned long long)(low),
  467. (unsigned long long)(high));
  468. }
  469. return result;
  470. }
  471. TEST(DBTest, ApproximateSizes) {
  472. Options options;
  473. options.write_buffer_size = 100000000; // Large write buffer
  474. options.compression = kNoCompression;
  475. DestroyAndReopen();
  476. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  477. Reopen(&options);
  478. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  479. // Write 8MB (80 values, each 100K)
  480. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  481. const int N = 80;
  482. Random rnd(301);
  483. for (int i = 0; i < N; i++) {
  484. ASSERT_OK(Put(Key(i), RandomString(&rnd, 100000)));
  485. }
  486. // 0 because GetApproximateSizes() does not account for memtable space
  487. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  488. // Check sizes across recovery by reopening a few times
  489. for (int run = 0; run < 3; run++) {
  490. Reopen(&options);
  491. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  492. for (int i = 0; i < N; i += 10) {
  493. ASSERT_TRUE(Between(Size("", Key(i)), 100000*i, 100000*i + 10000));
  494. ASSERT_TRUE(Between(Size("", Key(i)+".suffix"),
  495. 100000 * (i+1), 100000 * (i+1) + 10000));
  496. ASSERT_TRUE(Between(Size(Key(i), Key(i+10)),
  497. 100000 * 10, 100000 * 10 + 10000));
  498. }
  499. ASSERT_TRUE(Between(Size("", Key(50)), 5000000, 5010000));
  500. ASSERT_TRUE(Between(Size("", Key(50)+".suffix"), 5100000, 5110000));
  501. dbfull()->TEST_CompactRange(0,
  502. Key(compact_start),
  503. Key(compact_start + 9));
  504. }
  505. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  506. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  507. }
  508. }
  509. TEST(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  510. Options options;
  511. options.compression = kNoCompression;
  512. Reopen();
  513. Random rnd(301);
  514. std::string big1 = RandomString(&rnd, 100000);
  515. ASSERT_OK(Put(Key(0), RandomString(&rnd, 10000)));
  516. ASSERT_OK(Put(Key(1), RandomString(&rnd, 10000)));
  517. ASSERT_OK(Put(Key(2), big1));
  518. ASSERT_OK(Put(Key(3), RandomString(&rnd, 10000)));
  519. ASSERT_OK(Put(Key(4), big1));
  520. ASSERT_OK(Put(Key(5), RandomString(&rnd, 10000)));
  521. ASSERT_OK(Put(Key(6), RandomString(&rnd, 300000)));
  522. ASSERT_OK(Put(Key(7), RandomString(&rnd, 10000)));
  523. // Check sizes across recovery by reopening a few times
  524. for (int run = 0; run < 3; run++) {
  525. Reopen(&options);
  526. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  527. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  528. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  529. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  530. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  531. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  532. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  533. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  534. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 551000));
  535. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  536. dbfull()->TEST_CompactRange(0, Key(0), Key(100));
  537. }
  538. }
  539. TEST(DBTest, IteratorPinsRef) {
  540. Put("foo", "hello");
  541. // Get iterator that will yield the current contents of the DB.
  542. Iterator* iter = db_->NewIterator(ReadOptions());
  543. // Write to force compactions
  544. Put("foo", "newvalue1");
  545. for (int i = 0; i < 100; i++) {
  546. ASSERT_OK(Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  547. }
  548. Put("foo", "newvalue2");
  549. iter->SeekToFirst();
  550. ASSERT_TRUE(iter->Valid());
  551. ASSERT_EQ("foo", iter->key().ToString());
  552. ASSERT_EQ("hello", iter->value().ToString());
  553. iter->Next();
  554. ASSERT_TRUE(!iter->Valid());
  555. delete iter;
  556. }
  557. TEST(DBTest, Snapshot) {
  558. Put("foo", "v1");
  559. const Snapshot* s1 = db_->GetSnapshot();
  560. Put("foo", "v2");
  561. const Snapshot* s2 = db_->GetSnapshot();
  562. Put("foo", "v3");
  563. const Snapshot* s3 = db_->GetSnapshot();
  564. Put("foo", "v4");
  565. ASSERT_EQ("v1", Get("foo", s1));
  566. ASSERT_EQ("v2", Get("foo", s2));
  567. ASSERT_EQ("v3", Get("foo", s3));
  568. ASSERT_EQ("v4", Get("foo"));
  569. db_->ReleaseSnapshot(s3);
  570. ASSERT_EQ("v1", Get("foo", s1));
  571. ASSERT_EQ("v2", Get("foo", s2));
  572. ASSERT_EQ("v4", Get("foo"));
  573. db_->ReleaseSnapshot(s1);
  574. ASSERT_EQ("v2", Get("foo", s2));
  575. ASSERT_EQ("v4", Get("foo"));
  576. db_->ReleaseSnapshot(s2);
  577. ASSERT_EQ("v4", Get("foo"));
  578. }
  579. TEST(DBTest, HiddenValuesAreRemoved) {
  580. Random rnd(301);
  581. std::string big = RandomString(&rnd, 50000);
  582. Put("foo", big);
  583. Put("pastfoo", "v");
  584. const Snapshot* snapshot = db_->GetSnapshot();
  585. Put("foo", "tiny");
  586. Put("pastfoo2", "v2"); // Advance sequence number one more
  587. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  588. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  589. ASSERT_EQ(big, Get("foo", snapshot));
  590. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  591. db_->ReleaseSnapshot(snapshot);
  592. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  593. dbfull()->TEST_CompactRange(0, "", "x");
  594. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  595. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  596. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  597. dbfull()->TEST_CompactRange(1, "", "x");
  598. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  599. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  600. }
  601. TEST(DBTest, DeletionMarkers1) {
  602. Put("foo", "v1");
  603. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  604. dbfull()->TEST_CompactRange(0, "", "z");
  605. dbfull()->TEST_CompactRange(1, "", "z");
  606. ASSERT_EQ(NumTableFilesAtLevel(2), 1); // foo => v1 is now in level 2 file
  607. Delete("foo");
  608. Put("foo", "v2");
  609. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  610. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  611. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  612. dbfull()->TEST_CompactRange(0, "", "z");
  613. // DEL eliminated, but v1 remains because we aren't compacting that level
  614. // (DEL can be eliminated because v2 hides v1).
  615. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  616. dbfull()->TEST_CompactRange(1, "", "z");
  617. // Merging L1 w/ L2, so we are the base level for "foo", so DEL is removed.
  618. // (as is v1).
  619. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  620. }
  621. TEST(DBTest, DeletionMarkers2) {
  622. Put("foo", "v1");
  623. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  624. dbfull()->TEST_CompactRange(0, "", "z");
  625. dbfull()->TEST_CompactRange(1, "", "z");
  626. ASSERT_EQ(NumTableFilesAtLevel(2), 1); // foo => v1 is now in level 2 file
  627. Delete("foo");
  628. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  629. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  630. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  631. dbfull()->TEST_CompactRange(0, "", "z");
  632. // DEL kept: L2 file overlaps
  633. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  634. dbfull()->TEST_CompactRange(1, "", "z");
  635. // Merging L1 w/ L2, so we are the base level for "foo", so DEL is removed.
  636. // (as is v1).
  637. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  638. }
  639. TEST(DBTest, ComparatorCheck) {
  640. class NewComparator : public Comparator {
  641. public:
  642. virtual const char* Name() const { return "leveldb.NewComparator"; }
  643. virtual int Compare(const Slice& a, const Slice& b) const {
  644. return BytewiseComparator()->Compare(a, b);
  645. }
  646. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  647. BytewiseComparator()->FindShortestSeparator(s, l);
  648. }
  649. virtual void FindShortSuccessor(std::string* key) const {
  650. BytewiseComparator()->FindShortSuccessor(key);
  651. }
  652. };
  653. NewComparator cmp;
  654. Options new_options;
  655. new_options.comparator = &cmp;
  656. Status s = TryReopen(&new_options);
  657. ASSERT_TRUE(!s.ok());
  658. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  659. << s.ToString();
  660. }
  661. TEST(DBTest, DBOpen_Options) {
  662. std::string dbname = test::TmpDir() + "/db_options_test";
  663. DestroyDB(dbname, Options());
  664. // Does not exist, and create_if_missing == false: error
  665. DB* db = NULL;
  666. Options opts;
  667. opts.create_if_missing = false;
  668. Status s = DB::Open(opts, dbname, &db);
  669. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != NULL);
  670. ASSERT_TRUE(db == NULL);
  671. // Does not exist, and create_if_missing == true: OK
  672. opts.create_if_missing = true;
  673. s = DB::Open(opts, dbname, &db);
  674. ASSERT_OK(s);
  675. ASSERT_TRUE(db != NULL);
  676. delete db;
  677. db = NULL;
  678. // Does exist, and error_if_exists == true: error
  679. opts.create_if_missing = false;
  680. opts.error_if_exists = true;
  681. s = DB::Open(opts, dbname, &db);
  682. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != NULL);
  683. ASSERT_TRUE(db == NULL);
  684. // Does exist, and error_if_exists == false: OK
  685. opts.create_if_missing = true;
  686. opts.error_if_exists = false;
  687. s = DB::Open(opts, dbname, &db);
  688. ASSERT_OK(s);
  689. ASSERT_TRUE(db != NULL);
  690. delete db;
  691. db = NULL;
  692. }
  693. namespace {
  694. typedef std::map<std::string, std::string> KVMap;
  695. }
  696. class ModelDB: public DB {
  697. public:
  698. class ModelSnapshot : public Snapshot {
  699. public:
  700. KVMap map_;
  701. };
  702. explicit ModelDB(const Options& options): options_(options) { }
  703. ~ModelDB() { }
  704. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  705. return DB::Put(o, k, v);
  706. }
  707. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  708. return DB::Delete(o, key);
  709. }
  710. virtual Status Get(const ReadOptions& options,
  711. const Slice& key, std::string* value) {
  712. assert(false); // Not implemented
  713. return Status::NotFound(key);
  714. }
  715. virtual Iterator* NewIterator(const ReadOptions& options) {
  716. if (options.snapshot == NULL) {
  717. KVMap* saved = new KVMap;
  718. *saved = map_;
  719. return new ModelIter(saved, true);
  720. } else {
  721. const KVMap* snapshot_state =
  722. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  723. return new ModelIter(snapshot_state, false);
  724. }
  725. }
  726. virtual const Snapshot* GetSnapshot() {
  727. ModelSnapshot* snapshot = new ModelSnapshot;
  728. snapshot->map_ = map_;
  729. return snapshot;
  730. }
  731. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  732. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  733. }
  734. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  735. assert(options.post_write_snapshot == NULL); // Not supported
  736. class Handler : public WriteBatch::Handler {
  737. public:
  738. KVMap* map_;
  739. virtual void Put(const Slice& key, const Slice& value) {
  740. (*map_)[key.ToString()] = value.ToString();
  741. }
  742. virtual void Delete(const Slice& key) {
  743. map_->erase(key.ToString());
  744. }
  745. };
  746. Handler handler;
  747. handler.map_ = &map_;
  748. return batch->Iterate(&handler);
  749. }
  750. virtual bool GetProperty(const Slice& property, std::string* value) {
  751. return false;
  752. }
  753. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  754. for (int i = 0; i < n; i++) {
  755. sizes[i] = 0;
  756. }
  757. }
  758. private:
  759. class ModelIter: public Iterator {
  760. public:
  761. ModelIter(const KVMap* map, bool owned)
  762. : map_(map), owned_(owned), iter_(map_->end()) {
  763. }
  764. ~ModelIter() {
  765. if (owned_) delete map_;
  766. }
  767. virtual bool Valid() const { return iter_ != map_->end(); }
  768. virtual void SeekToFirst() { iter_ = map_->begin(); }
  769. virtual void SeekToLast() {
  770. if (map_->empty()) {
  771. iter_ = map_->end();
  772. } else {
  773. iter_ = map_->find(map_->rbegin()->first);
  774. }
  775. }
  776. virtual void Seek(const Slice& k) {
  777. iter_ = map_->lower_bound(k.ToString());
  778. }
  779. virtual void Next() { ++iter_; }
  780. virtual void Prev() { --iter_; }
  781. virtual Slice key() const { return iter_->first; }
  782. virtual Slice value() const { return iter_->second; }
  783. virtual Status status() const { return Status::OK(); }
  784. private:
  785. const KVMap* const map_;
  786. const bool owned_; // Do we own map_
  787. KVMap::const_iterator iter_;
  788. };
  789. const Options options_;
  790. KVMap map_;
  791. };
  792. static std::string RandomKey(Random* rnd) {
  793. int len = (rnd->OneIn(3)
  794. ? 1 // Short sometimes to encourage collisions
  795. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  796. return test::RandomKey(rnd, len);
  797. }
  798. static bool CompareIterators(int step,
  799. DB* model,
  800. DB* db,
  801. const Snapshot* model_snap,
  802. const Snapshot* db_snap) {
  803. ReadOptions options;
  804. options.snapshot = model_snap;
  805. Iterator* miter = model->NewIterator(options);
  806. options.snapshot = db_snap;
  807. Iterator* dbiter = db->NewIterator(options);
  808. bool ok = true;
  809. int count = 0;
  810. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  811. ok && miter->Valid() && dbiter->Valid();
  812. miter->Next(), dbiter->Next()) {
  813. count++;
  814. if (miter->key().compare(dbiter->key()) != 0) {
  815. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  816. step,
  817. EscapeString(miter->key()).c_str(),
  818. EscapeString(dbiter->key()).c_str());
  819. ok = false;
  820. break;
  821. }
  822. if (miter->value().compare(dbiter->value()) != 0) {
  823. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  824. step,
  825. EscapeString(miter->key()).c_str(),
  826. EscapeString(miter->value()).c_str(),
  827. EscapeString(miter->value()).c_str());
  828. ok = false;
  829. }
  830. }
  831. if (ok) {
  832. if (miter->Valid() != dbiter->Valid()) {
  833. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  834. step, miter->Valid(), dbiter->Valid());
  835. ok = false;
  836. }
  837. }
  838. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  839. delete miter;
  840. delete dbiter;
  841. return ok;
  842. }
  843. TEST(DBTest, Randomized) {
  844. Random rnd(test::RandomSeed());
  845. ModelDB model(last_options_);
  846. const int N = 10000;
  847. const Snapshot* model_snap = NULL;
  848. const Snapshot* db_snap = NULL;
  849. std::string k, v;
  850. for (int step = 0; step < N; step++) {
  851. if (step % 100 == 0) {
  852. fprintf(stderr, "Step %d of %d\n", step, N);
  853. }
  854. int p = rnd.Uniform(100);
  855. if (p < 45) { // Put
  856. k = RandomKey(&rnd);
  857. v = RandomString(&rnd,
  858. rnd.OneIn(20)
  859. ? 100 + rnd.Uniform(100)
  860. : rnd.Uniform(8));
  861. ASSERT_OK(model.Put(WriteOptions(), k, v));
  862. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  863. } else if (p < 90) { // Delete
  864. k = RandomKey(&rnd);
  865. ASSERT_OK(model.Delete(WriteOptions(), k));
  866. ASSERT_OK(db_->Delete(WriteOptions(), k));
  867. } else { // Multi-element batch
  868. WriteBatch b;
  869. const int num = rnd.Uniform(8);
  870. for (int i = 0; i < num; i++) {
  871. if (i == 0 || !rnd.OneIn(10)) {
  872. k = RandomKey(&rnd);
  873. } else {
  874. // Periodically re-use the same key from the previous iter, so
  875. // we have multiple entries in the write batch for the same key
  876. }
  877. if (rnd.OneIn(2)) {
  878. v = RandomString(&rnd, rnd.Uniform(10));
  879. b.Put(k, v);
  880. } else {
  881. b.Delete(k);
  882. }
  883. }
  884. ASSERT_OK(model.Write(WriteOptions(), &b));
  885. ASSERT_OK(db_->Write(WriteOptions(), &b));
  886. }
  887. if ((step % 100) == 0) {
  888. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  889. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  890. // Save a snapshot from each DB this time that we'll use next
  891. // time we compare things, to make sure the current state is
  892. // preserved with the snapshot
  893. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  894. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  895. Reopen();
  896. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  897. model_snap = model.GetSnapshot();
  898. db_snap = db_->GetSnapshot();
  899. }
  900. }
  901. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  902. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  903. }
  904. std::string MakeKey(unsigned int num) {
  905. char buf[30];
  906. snprintf(buf, sizeof(buf), "%016u", num);
  907. return std::string(buf);
  908. }
  909. void BM_LogAndApply(int iters, int num_base_files) {
  910. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  911. DestroyDB(dbname, Options());
  912. DB* db = NULL;
  913. Options opts;
  914. opts.create_if_missing = true;
  915. Status s = DB::Open(opts, dbname, &db);
  916. ASSERT_OK(s);
  917. ASSERT_TRUE(db != NULL);
  918. delete db;
  919. db = NULL;
  920. Env* env = Env::Default();
  921. InternalKeyComparator cmp(BytewiseComparator());
  922. Options options;
  923. VersionSet vset(dbname, &options, NULL, &cmp);
  924. ASSERT_OK(vset.Recover());
  925. VersionEdit vbase;
  926. uint64_t fnum = 1;
  927. for (int i = 0; i < num_base_files; i++) {
  928. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  929. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  930. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  931. }
  932. ASSERT_OK(vset.LogAndApply(&vbase));
  933. uint64_t start_micros = env->NowMicros();
  934. for (int i = 0; i < iters; i++) {
  935. VersionEdit vedit;
  936. vedit.DeleteFile(2, fnum);
  937. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  938. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  939. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  940. vset.LogAndApply(&vedit);
  941. }
  942. uint64_t stop_micros = env->NowMicros();
  943. unsigned int us = stop_micros - start_micros;
  944. char buf[16];
  945. snprintf(buf, sizeof(buf), "%d", num_base_files);
  946. fprintf(stderr,
  947. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  948. buf, iters, us, ((float)us) / iters);
  949. }
  950. }
  951. int main(int argc, char** argv) {
  952. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  953. leveldb::BM_LogAndApply(1000, 1);
  954. leveldb::BM_LogAndApply(1000, 100);
  955. leveldb::BM_LogAndApply(1000, 10000);
  956. leveldb::BM_LogAndApply(100, 100000);
  957. return 0;
  958. }
  959. return leveldb::test::RunAllTests();
  960. }