作者: 谢瑞阳 10225101483 徐翔宇 10225101535
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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