作者: 谢瑞阳 10225101483 徐翔宇 10225101535
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1192 linhas
34 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. // Multi-threaded test:
  694. namespace {
  695. static const int kNumThreads = 4;
  696. static const int kTestSeconds = 10;
  697. static const int kNumKeys = 1000;
  698. struct MTState {
  699. DBTest* test;
  700. port::AtomicPointer stop;
  701. port::AtomicPointer counter[kNumThreads];
  702. port::AtomicPointer thread_done[kNumThreads];
  703. };
  704. struct MTThread {
  705. MTState* state;
  706. int id;
  707. };
  708. static void MTThreadBody(void* arg) {
  709. MTThread* t = reinterpret_cast<MTThread*>(arg);
  710. DB* db = t->state->test->db_;
  711. uintptr_t counter = 0;
  712. fprintf(stderr, "... starting thread %d\n", t->id);
  713. Random rnd(1000 + t->id);
  714. std::string value;
  715. char valbuf[1500];
  716. while (t->state->stop.Acquire_Load() == NULL) {
  717. t->state->counter[t->id].Release_Store(reinterpret_cast<void*>(counter));
  718. int key = rnd.Uniform(kNumKeys);
  719. char keybuf[20];
  720. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  721. if (rnd.OneIn(2)) {
  722. // Write values of the form <key, my id, counter>.
  723. // We add some padding for force compactions.
  724. snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d",
  725. key, t->id, static_cast<int>(counter));
  726. ASSERT_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  727. } else {
  728. // Read a value and verify that it matches the pattern written above.
  729. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  730. if (s.IsNotFound()) {
  731. // Key has not yet been written
  732. } else {
  733. // Check that the writer thread counter is >= the counter in the value
  734. ASSERT_OK(s);
  735. int k, w, c;
  736. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  737. ASSERT_EQ(k, key);
  738. ASSERT_GE(w, 0);
  739. ASSERT_LT(w, kNumThreads);
  740. ASSERT_LE(c, reinterpret_cast<uintptr_t>(
  741. t->state->counter[w].Acquire_Load()));
  742. }
  743. }
  744. counter++;
  745. }
  746. t->state->thread_done[t->id].Release_Store(t);
  747. fprintf(stderr, "... stopping thread %d after %d ops\n", t->id, int(counter));
  748. }
  749. }
  750. TEST(DBTest, MultiThreaded) {
  751. // Initialize state
  752. MTState mt;
  753. mt.test = this;
  754. mt.stop.Release_Store(0);
  755. for (int id = 0; id < kNumThreads; id++) {
  756. mt.counter[id].Release_Store(0);
  757. mt.thread_done[id].Release_Store(0);
  758. }
  759. // Start threads
  760. MTThread thread[kNumThreads];
  761. for (int id = 0; id < kNumThreads; id++) {
  762. thread[id].state = &mt;
  763. thread[id].id = id;
  764. env_->StartThread(MTThreadBody, &thread[id]);
  765. }
  766. // Let them run for a while
  767. env_->SleepForMicroseconds(kTestSeconds * 1000000);
  768. // Stop the threads and wait for them to finish
  769. mt.stop.Release_Store(&mt);
  770. for (int id = 0; id < kNumThreads; id++) {
  771. while (mt.thread_done[id].Acquire_Load() == NULL) {
  772. env_->SleepForMicroseconds(100000);
  773. }
  774. }
  775. }
  776. namespace {
  777. typedef std::map<std::string, std::string> KVMap;
  778. }
  779. class ModelDB: public DB {
  780. public:
  781. class ModelSnapshot : public Snapshot {
  782. public:
  783. KVMap map_;
  784. };
  785. explicit ModelDB(const Options& options): options_(options) { }
  786. ~ModelDB() { }
  787. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  788. return DB::Put(o, k, v);
  789. }
  790. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  791. return DB::Delete(o, key);
  792. }
  793. virtual Status Get(const ReadOptions& options,
  794. const Slice& key, std::string* value) {
  795. assert(false); // Not implemented
  796. return Status::NotFound(key);
  797. }
  798. virtual Iterator* NewIterator(const ReadOptions& options) {
  799. if (options.snapshot == NULL) {
  800. KVMap* saved = new KVMap;
  801. *saved = map_;
  802. return new ModelIter(saved, true);
  803. } else {
  804. const KVMap* snapshot_state =
  805. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  806. return new ModelIter(snapshot_state, false);
  807. }
  808. }
  809. virtual const Snapshot* GetSnapshot() {
  810. ModelSnapshot* snapshot = new ModelSnapshot;
  811. snapshot->map_ = map_;
  812. return snapshot;
  813. }
  814. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  815. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  816. }
  817. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  818. assert(options.post_write_snapshot == NULL); // Not supported
  819. class Handler : public WriteBatch::Handler {
  820. public:
  821. KVMap* map_;
  822. virtual void Put(const Slice& key, const Slice& value) {
  823. (*map_)[key.ToString()] = value.ToString();
  824. }
  825. virtual void Delete(const Slice& key) {
  826. map_->erase(key.ToString());
  827. }
  828. };
  829. Handler handler;
  830. handler.map_ = &map_;
  831. return batch->Iterate(&handler);
  832. }
  833. virtual bool GetProperty(const Slice& property, std::string* value) {
  834. return false;
  835. }
  836. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  837. for (int i = 0; i < n; i++) {
  838. sizes[i] = 0;
  839. }
  840. }
  841. private:
  842. class ModelIter: public Iterator {
  843. public:
  844. ModelIter(const KVMap* map, bool owned)
  845. : map_(map), owned_(owned), iter_(map_->end()) {
  846. }
  847. ~ModelIter() {
  848. if (owned_) delete map_;
  849. }
  850. virtual bool Valid() const { return iter_ != map_->end(); }
  851. virtual void SeekToFirst() { iter_ = map_->begin(); }
  852. virtual void SeekToLast() {
  853. if (map_->empty()) {
  854. iter_ = map_->end();
  855. } else {
  856. iter_ = map_->find(map_->rbegin()->first);
  857. }
  858. }
  859. virtual void Seek(const Slice& k) {
  860. iter_ = map_->lower_bound(k.ToString());
  861. }
  862. virtual void Next() { ++iter_; }
  863. virtual void Prev() { --iter_; }
  864. virtual Slice key() const { return iter_->first; }
  865. virtual Slice value() const { return iter_->second; }
  866. virtual Status status() const { return Status::OK(); }
  867. private:
  868. const KVMap* const map_;
  869. const bool owned_; // Do we own map_
  870. KVMap::const_iterator iter_;
  871. };
  872. const Options options_;
  873. KVMap map_;
  874. };
  875. static std::string RandomKey(Random* rnd) {
  876. int len = (rnd->OneIn(3)
  877. ? 1 // Short sometimes to encourage collisions
  878. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  879. return test::RandomKey(rnd, len);
  880. }
  881. static bool CompareIterators(int step,
  882. DB* model,
  883. DB* db,
  884. const Snapshot* model_snap,
  885. const Snapshot* db_snap) {
  886. ReadOptions options;
  887. options.snapshot = model_snap;
  888. Iterator* miter = model->NewIterator(options);
  889. options.snapshot = db_snap;
  890. Iterator* dbiter = db->NewIterator(options);
  891. bool ok = true;
  892. int count = 0;
  893. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  894. ok && miter->Valid() && dbiter->Valid();
  895. miter->Next(), dbiter->Next()) {
  896. count++;
  897. if (miter->key().compare(dbiter->key()) != 0) {
  898. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  899. step,
  900. EscapeString(miter->key()).c_str(),
  901. EscapeString(dbiter->key()).c_str());
  902. ok = false;
  903. break;
  904. }
  905. if (miter->value().compare(dbiter->value()) != 0) {
  906. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  907. step,
  908. EscapeString(miter->key()).c_str(),
  909. EscapeString(miter->value()).c_str(),
  910. EscapeString(miter->value()).c_str());
  911. ok = false;
  912. }
  913. }
  914. if (ok) {
  915. if (miter->Valid() != dbiter->Valid()) {
  916. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  917. step, miter->Valid(), dbiter->Valid());
  918. ok = false;
  919. }
  920. }
  921. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  922. delete miter;
  923. delete dbiter;
  924. return ok;
  925. }
  926. TEST(DBTest, Randomized) {
  927. Random rnd(test::RandomSeed());
  928. ModelDB model(last_options_);
  929. const int N = 10000;
  930. const Snapshot* model_snap = NULL;
  931. const Snapshot* db_snap = NULL;
  932. std::string k, v;
  933. for (int step = 0; step < N; step++) {
  934. if (step % 100 == 0) {
  935. fprintf(stderr, "Step %d of %d\n", step, N);
  936. }
  937. int p = rnd.Uniform(100);
  938. if (p < 45) { // Put
  939. k = RandomKey(&rnd);
  940. v = RandomString(&rnd,
  941. rnd.OneIn(20)
  942. ? 100 + rnd.Uniform(100)
  943. : rnd.Uniform(8));
  944. ASSERT_OK(model.Put(WriteOptions(), k, v));
  945. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  946. } else if (p < 90) { // Delete
  947. k = RandomKey(&rnd);
  948. ASSERT_OK(model.Delete(WriteOptions(), k));
  949. ASSERT_OK(db_->Delete(WriteOptions(), k));
  950. } else { // Multi-element batch
  951. WriteBatch b;
  952. const int num = rnd.Uniform(8);
  953. for (int i = 0; i < num; i++) {
  954. if (i == 0 || !rnd.OneIn(10)) {
  955. k = RandomKey(&rnd);
  956. } else {
  957. // Periodically re-use the same key from the previous iter, so
  958. // we have multiple entries in the write batch for the same key
  959. }
  960. if (rnd.OneIn(2)) {
  961. v = RandomString(&rnd, rnd.Uniform(10));
  962. b.Put(k, v);
  963. } else {
  964. b.Delete(k);
  965. }
  966. }
  967. ASSERT_OK(model.Write(WriteOptions(), &b));
  968. ASSERT_OK(db_->Write(WriteOptions(), &b));
  969. }
  970. if ((step % 100) == 0) {
  971. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  972. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  973. // Save a snapshot from each DB this time that we'll use next
  974. // time we compare things, to make sure the current state is
  975. // preserved with the snapshot
  976. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  977. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  978. Reopen();
  979. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  980. model_snap = model.GetSnapshot();
  981. db_snap = db_->GetSnapshot();
  982. }
  983. }
  984. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  985. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  986. }
  987. std::string MakeKey(unsigned int num) {
  988. char buf[30];
  989. snprintf(buf, sizeof(buf), "%016u", num);
  990. return std::string(buf);
  991. }
  992. void BM_LogAndApply(int iters, int num_base_files) {
  993. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  994. DestroyDB(dbname, Options());
  995. DB* db = NULL;
  996. Options opts;
  997. opts.create_if_missing = true;
  998. Status s = DB::Open(opts, dbname, &db);
  999. ASSERT_OK(s);
  1000. ASSERT_TRUE(db != NULL);
  1001. delete db;
  1002. db = NULL;
  1003. Env* env = Env::Default();
  1004. InternalKeyComparator cmp(BytewiseComparator());
  1005. Options options;
  1006. VersionSet vset(dbname, &options, NULL, &cmp);
  1007. ASSERT_OK(vset.Recover());
  1008. VersionEdit vbase;
  1009. uint64_t fnum = 1;
  1010. for (int i = 0; i < num_base_files; i++) {
  1011. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1012. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1013. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1014. }
  1015. ASSERT_OK(vset.LogAndApply(&vbase));
  1016. uint64_t start_micros = env->NowMicros();
  1017. for (int i = 0; i < iters; i++) {
  1018. VersionEdit vedit;
  1019. vedit.DeleteFile(2, fnum);
  1020. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1021. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1022. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1023. vset.LogAndApply(&vedit);
  1024. }
  1025. uint64_t stop_micros = env->NowMicros();
  1026. unsigned int us = stop_micros - start_micros;
  1027. char buf[16];
  1028. snprintf(buf, sizeof(buf), "%d", num_base_files);
  1029. fprintf(stderr,
  1030. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  1031. buf, iters, us, ((float)us) / iters);
  1032. }
  1033. }
  1034. int main(int argc, char** argv) {
  1035. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  1036. leveldb::BM_LogAndApply(1000, 1);
  1037. leveldb::BM_LogAndApply(1000, 100);
  1038. leveldb::BM_LogAndApply(1000, 10000);
  1039. leveldb::BM_LogAndApply(100, 100000);
  1040. return 0;
  1041. }
  1042. return leveldb::test::RunAllTests();
  1043. }