小组成员:姚凯文(kevinyao0901),姜嘉琪
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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