作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2147 lines
62 KiB

Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
  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 "leveldb/filter_policy.h"
  6. #include "db/db_impl.h"
  7. #include "db/filename.h"
  8. #include "db/version_set.h"
  9. #include "db/write_batch_internal.h"
  10. #include "leveldb/cache.h"
  11. #include "leveldb/env.h"
  12. #include "leveldb/table.h"
  13. #include "util/hash.h"
  14. #include "util/logging.h"
  15. #include "util/mutexlock.h"
  16. #include "util/testharness.h"
  17. #include "util/testutil.h"
  18. namespace leveldb {
  19. static std::string RandomString(Random* rnd, int len) {
  20. std::string r;
  21. test::RandomString(rnd, len, &r);
  22. return r;
  23. }
  24. namespace {
  25. class AtomicCounter {
  26. private:
  27. port::Mutex mu_;
  28. int count_;
  29. public:
  30. AtomicCounter() : count_(0) { }
  31. void Increment() {
  32. IncrementBy(1);
  33. }
  34. void IncrementBy(int count) {
  35. MutexLock l(&mu_);
  36. count_ += count;
  37. }
  38. int Read() {
  39. MutexLock l(&mu_);
  40. return count_;
  41. }
  42. void Reset() {
  43. MutexLock l(&mu_);
  44. count_ = 0;
  45. }
  46. };
  47. void DelayMilliseconds(int millis) {
  48. Env::Default()->SleepForMicroseconds(millis * 1000);
  49. }
  50. }
  51. // Special Env used to delay background operations
  52. class SpecialEnv : public EnvWrapper {
  53. public:
  54. // sstable/log Sync() calls are blocked while this pointer is non-NULL.
  55. port::AtomicPointer delay_data_sync_;
  56. // sstable/log Sync() calls return an error.
  57. port::AtomicPointer data_sync_error_;
  58. // Simulate no-space errors while this pointer is non-NULL.
  59. port::AtomicPointer no_space_;
  60. // Simulate non-writable file system while this pointer is non-NULL
  61. port::AtomicPointer non_writable_;
  62. // Force sync of manifest files to fail while this pointer is non-NULL
  63. port::AtomicPointer manifest_sync_error_;
  64. // Force write to manifest files to fail while this pointer is non-NULL
  65. port::AtomicPointer manifest_write_error_;
  66. bool count_random_reads_;
  67. AtomicCounter random_read_counter_;
  68. explicit SpecialEnv(Env* base) : EnvWrapper(base) {
  69. delay_data_sync_.Release_Store(NULL);
  70. data_sync_error_.Release_Store(NULL);
  71. no_space_.Release_Store(NULL);
  72. non_writable_.Release_Store(NULL);
  73. count_random_reads_ = false;
  74. manifest_sync_error_.Release_Store(NULL);
  75. manifest_write_error_.Release_Store(NULL);
  76. }
  77. Status NewWritableFile(const std::string& f, WritableFile** r) {
  78. class DataFile : public WritableFile {
  79. private:
  80. SpecialEnv* env_;
  81. WritableFile* base_;
  82. public:
  83. DataFile(SpecialEnv* env, WritableFile* base)
  84. : env_(env),
  85. base_(base) {
  86. }
  87. ~DataFile() { delete base_; }
  88. Status Append(const Slice& data) {
  89. if (env_->no_space_.Acquire_Load() != NULL) {
  90. // Drop writes on the floor
  91. return Status::OK();
  92. } else {
  93. return base_->Append(data);
  94. }
  95. }
  96. Status Close() { return base_->Close(); }
  97. Status Flush() { return base_->Flush(); }
  98. Status Sync() {
  99. if (env_->data_sync_error_.Acquire_Load() != NULL) {
  100. return Status::IOError("simulated data sync error");
  101. }
  102. while (env_->delay_data_sync_.Acquire_Load() != NULL) {
  103. DelayMilliseconds(100);
  104. }
  105. return base_->Sync();
  106. }
  107. };
  108. class ManifestFile : public WritableFile {
  109. private:
  110. SpecialEnv* env_;
  111. WritableFile* base_;
  112. public:
  113. ManifestFile(SpecialEnv* env, WritableFile* b) : env_(env), base_(b) { }
  114. ~ManifestFile() { delete base_; }
  115. Status Append(const Slice& data) {
  116. if (env_->manifest_write_error_.Acquire_Load() != NULL) {
  117. return Status::IOError("simulated writer error");
  118. } else {
  119. return base_->Append(data);
  120. }
  121. }
  122. Status Close() { return base_->Close(); }
  123. Status Flush() { return base_->Flush(); }
  124. Status Sync() {
  125. if (env_->manifest_sync_error_.Acquire_Load() != NULL) {
  126. return Status::IOError("simulated sync error");
  127. } else {
  128. return base_->Sync();
  129. }
  130. }
  131. };
  132. if (non_writable_.Acquire_Load() != NULL) {
  133. return Status::IOError("simulated write error");
  134. }
  135. Status s = target()->NewWritableFile(f, r);
  136. if (s.ok()) {
  137. if (strstr(f.c_str(), ".ldb") != NULL ||
  138. strstr(f.c_str(), ".log") != NULL) {
  139. *r = new DataFile(this, *r);
  140. } else if (strstr(f.c_str(), "MANIFEST") != NULL) {
  141. *r = new ManifestFile(this, *r);
  142. }
  143. }
  144. return s;
  145. }
  146. Status NewRandomAccessFile(const std::string& f, RandomAccessFile** r) {
  147. class CountingFile : public RandomAccessFile {
  148. private:
  149. RandomAccessFile* target_;
  150. AtomicCounter* counter_;
  151. public:
  152. CountingFile(RandomAccessFile* target, AtomicCounter* counter)
  153. : target_(target), counter_(counter) {
  154. }
  155. virtual ~CountingFile() { delete target_; }
  156. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  157. char* scratch) const {
  158. counter_->Increment();
  159. return target_->Read(offset, n, result, scratch);
  160. }
  161. };
  162. Status s = target()->NewRandomAccessFile(f, r);
  163. if (s.ok() && count_random_reads_) {
  164. *r = new CountingFile(*r, &random_read_counter_);
  165. }
  166. return s;
  167. }
  168. };
  169. class DBTest {
  170. private:
  171. const FilterPolicy* filter_policy_;
  172. // Sequence of option configurations to try
  173. enum OptionConfig {
  174. kDefault,
  175. kReuse,
  176. kFilter,
  177. kUncompressed,
  178. kEnd
  179. };
  180. int option_config_;
  181. public:
  182. std::string dbname_;
  183. SpecialEnv* env_;
  184. DB* db_;
  185. Options last_options_;
  186. DBTest() : option_config_(kDefault),
  187. env_(new SpecialEnv(Env::Default())) {
  188. filter_policy_ = NewBloomFilterPolicy(10);
  189. dbname_ = test::TmpDir() + "/db_test";
  190. DestroyDB(dbname_, Options());
  191. db_ = NULL;
  192. Reopen();
  193. }
  194. ~DBTest() {
  195. delete db_;
  196. DestroyDB(dbname_, Options());
  197. delete env_;
  198. delete filter_policy_;
  199. }
  200. // Switch to a fresh database with the next option configuration to
  201. // test. Return false if there are no more configurations to test.
  202. bool ChangeOptions() {
  203. option_config_++;
  204. if (option_config_ >= kEnd) {
  205. return false;
  206. } else {
  207. DestroyAndReopen();
  208. return true;
  209. }
  210. }
  211. // Return the current option configuration.
  212. Options CurrentOptions() {
  213. Options options;
  214. options.reuse_logs = false;
  215. switch (option_config_) {
  216. case kReuse:
  217. options.reuse_logs = true;
  218. break;
  219. case kFilter:
  220. options.filter_policy = filter_policy_;
  221. break;
  222. case kUncompressed:
  223. options.compression = kNoCompression;
  224. break;
  225. default:
  226. break;
  227. }
  228. return options;
  229. }
  230. DBImpl* dbfull() {
  231. return reinterpret_cast<DBImpl*>(db_);
  232. }
  233. void Reopen(Options* options = NULL) {
  234. ASSERT_OK(TryReopen(options));
  235. }
  236. void Close() {
  237. delete db_;
  238. db_ = NULL;
  239. }
  240. void DestroyAndReopen(Options* options = NULL) {
  241. delete db_;
  242. db_ = NULL;
  243. DestroyDB(dbname_, Options());
  244. ASSERT_OK(TryReopen(options));
  245. }
  246. Status TryReopen(Options* options) {
  247. delete db_;
  248. db_ = NULL;
  249. Options opts;
  250. if (options != NULL) {
  251. opts = *options;
  252. } else {
  253. opts = CurrentOptions();
  254. opts.create_if_missing = true;
  255. }
  256. last_options_ = opts;
  257. return DB::Open(opts, dbname_, &db_);
  258. }
  259. Status Put(const std::string& k, const std::string& v) {
  260. return db_->Put(WriteOptions(), k, v);
  261. }
  262. Status Delete(const std::string& k) {
  263. return db_->Delete(WriteOptions(), k);
  264. }
  265. std::string Get(const std::string& k, const Snapshot* snapshot = NULL) {
  266. ReadOptions options;
  267. options.snapshot = snapshot;
  268. std::string result;
  269. Status s = db_->Get(options, k, &result);
  270. if (s.IsNotFound()) {
  271. result = "NOT_FOUND";
  272. } else if (!s.ok()) {
  273. result = s.ToString();
  274. }
  275. return result;
  276. }
  277. // Return a string that contains all key,value pairs in order,
  278. // formatted like "(k1->v1)(k2->v2)".
  279. std::string Contents() {
  280. std::vector<std::string> forward;
  281. std::string result;
  282. Iterator* iter = db_->NewIterator(ReadOptions());
  283. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  284. std::string s = IterStatus(iter);
  285. result.push_back('(');
  286. result.append(s);
  287. result.push_back(')');
  288. forward.push_back(s);
  289. }
  290. // Check reverse iteration results are the reverse of forward results
  291. size_t matched = 0;
  292. for (iter->SeekToLast(); iter->Valid(); iter->Prev()) {
  293. ASSERT_LT(matched, forward.size());
  294. ASSERT_EQ(IterStatus(iter), forward[forward.size() - matched - 1]);
  295. matched++;
  296. }
  297. ASSERT_EQ(matched, forward.size());
  298. delete iter;
  299. return result;
  300. }
  301. std::string AllEntriesFor(const Slice& user_key) {
  302. Iterator* iter = dbfull()->TEST_NewInternalIterator();
  303. InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  304. iter->Seek(target.Encode());
  305. std::string result;
  306. if (!iter->status().ok()) {
  307. result = iter->status().ToString();
  308. } else {
  309. result = "[ ";
  310. bool first = true;
  311. while (iter->Valid()) {
  312. ParsedInternalKey ikey;
  313. if (!ParseInternalKey(iter->key(), &ikey)) {
  314. result += "CORRUPTED";
  315. } else {
  316. if (last_options_.comparator->Compare(ikey.user_key, user_key) != 0) {
  317. break;
  318. }
  319. if (!first) {
  320. result += ", ";
  321. }
  322. first = false;
  323. switch (ikey.type) {
  324. case kTypeValue:
  325. result += iter->value().ToString();
  326. break;
  327. case kTypeDeletion:
  328. result += "DEL";
  329. break;
  330. }
  331. }
  332. iter->Next();
  333. }
  334. if (!first) {
  335. result += " ";
  336. }
  337. result += "]";
  338. }
  339. delete iter;
  340. return result;
  341. }
  342. int NumTableFilesAtLevel(int level) {
  343. std::string property;
  344. ASSERT_TRUE(
  345. db_->GetProperty("leveldb.num-files-at-level" + NumberToString(level),
  346. &property));
  347. return atoi(property.c_str());
  348. }
  349. int TotalTableFiles() {
  350. int result = 0;
  351. for (int level = 0; level < config::kNumLevels; level++) {
  352. result += NumTableFilesAtLevel(level);
  353. }
  354. return result;
  355. }
  356. // Return spread of files per level
  357. std::string FilesPerLevel() {
  358. std::string result;
  359. int last_non_zero_offset = 0;
  360. for (int level = 0; level < config::kNumLevels; level++) {
  361. int f = NumTableFilesAtLevel(level);
  362. char buf[100];
  363. snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
  364. result += buf;
  365. if (f > 0) {
  366. last_non_zero_offset = result.size();
  367. }
  368. }
  369. result.resize(last_non_zero_offset);
  370. return result;
  371. }
  372. int CountFiles() {
  373. std::vector<std::string> files;
  374. env_->GetChildren(dbname_, &files);
  375. return static_cast<int>(files.size());
  376. }
  377. uint64_t Size(const Slice& start, const Slice& limit) {
  378. Range r(start, limit);
  379. uint64_t size;
  380. db_->GetApproximateSizes(&r, 1, &size);
  381. return size;
  382. }
  383. void Compact(const Slice& start, const Slice& limit) {
  384. db_->CompactRange(&start, &limit);
  385. }
  386. // Do n memtable compactions, each of which produces an sstable
  387. // covering the range [small,large].
  388. void MakeTables(int n, const std::string& small, const std::string& large) {
  389. for (int i = 0; i < n; i++) {
  390. Put(small, "begin");
  391. Put(large, "end");
  392. dbfull()->TEST_CompactMemTable();
  393. }
  394. }
  395. // Prevent pushing of new sstables into deeper levels by adding
  396. // tables that cover a specified range to all levels.
  397. void FillLevels(const std::string& smallest, const std::string& largest) {
  398. MakeTables(config::kNumLevels, smallest, largest);
  399. }
  400. void DumpFileCounts(const char* label) {
  401. fprintf(stderr, "---\n%s:\n", label);
  402. fprintf(stderr, "maxoverlap: %lld\n",
  403. static_cast<long long>(
  404. dbfull()->TEST_MaxNextLevelOverlappingBytes()));
  405. for (int level = 0; level < config::kNumLevels; level++) {
  406. int num = NumTableFilesAtLevel(level);
  407. if (num > 0) {
  408. fprintf(stderr, " level %3d : %d files\n", level, num);
  409. }
  410. }
  411. }
  412. std::string DumpSSTableList() {
  413. std::string property;
  414. db_->GetProperty("leveldb.sstables", &property);
  415. return property;
  416. }
  417. std::string IterStatus(Iterator* iter) {
  418. std::string result;
  419. if (iter->Valid()) {
  420. result = iter->key().ToString() + "->" + iter->value().ToString();
  421. } else {
  422. result = "(invalid)";
  423. }
  424. return result;
  425. }
  426. bool DeleteAnSSTFile() {
  427. std::vector<std::string> filenames;
  428. ASSERT_OK(env_->GetChildren(dbname_, &filenames));
  429. uint64_t number;
  430. FileType type;
  431. for (size_t i = 0; i < filenames.size(); i++) {
  432. if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
  433. ASSERT_OK(env_->DeleteFile(TableFileName(dbname_, number)));
  434. return true;
  435. }
  436. }
  437. return false;
  438. }
  439. // Returns number of files renamed.
  440. int RenameLDBToSST() {
  441. std::vector<std::string> filenames;
  442. ASSERT_OK(env_->GetChildren(dbname_, &filenames));
  443. uint64_t number;
  444. FileType type;
  445. int files_renamed = 0;
  446. for (size_t i = 0; i < filenames.size(); i++) {
  447. if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
  448. const std::string from = TableFileName(dbname_, number);
  449. const std::string to = SSTTableFileName(dbname_, number);
  450. ASSERT_OK(env_->RenameFile(from, to));
  451. files_renamed++;
  452. }
  453. }
  454. return files_renamed;
  455. }
  456. };
  457. TEST(DBTest, Empty) {
  458. do {
  459. ASSERT_TRUE(db_ != NULL);
  460. ASSERT_EQ("NOT_FOUND", Get("foo"));
  461. } while (ChangeOptions());
  462. }
  463. TEST(DBTest, ReadWrite) {
  464. do {
  465. ASSERT_OK(Put("foo", "v1"));
  466. ASSERT_EQ("v1", Get("foo"));
  467. ASSERT_OK(Put("bar", "v2"));
  468. ASSERT_OK(Put("foo", "v3"));
  469. ASSERT_EQ("v3", Get("foo"));
  470. ASSERT_EQ("v2", Get("bar"));
  471. } while (ChangeOptions());
  472. }
  473. TEST(DBTest, PutDeleteGet) {
  474. do {
  475. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  476. ASSERT_EQ("v1", Get("foo"));
  477. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  478. ASSERT_EQ("v2", Get("foo"));
  479. ASSERT_OK(db_->Delete(WriteOptions(), "foo"));
  480. ASSERT_EQ("NOT_FOUND", Get("foo"));
  481. } while (ChangeOptions());
  482. }
  483. TEST(DBTest, GetFromImmutableLayer) {
  484. do {
  485. Options options = CurrentOptions();
  486. options.env = env_;
  487. options.write_buffer_size = 100000; // Small write buffer
  488. Reopen(&options);
  489. ASSERT_OK(Put("foo", "v1"));
  490. ASSERT_EQ("v1", Get("foo"));
  491. env_->delay_data_sync_.Release_Store(env_); // Block sync calls
  492. Put("k1", std::string(100000, 'x')); // Fill memtable
  493. Put("k2", std::string(100000, 'y')); // Trigger compaction
  494. ASSERT_EQ("v1", Get("foo"));
  495. env_->delay_data_sync_.Release_Store(NULL); // Release sync calls
  496. } while (ChangeOptions());
  497. }
  498. TEST(DBTest, GetFromVersions) {
  499. do {
  500. ASSERT_OK(Put("foo", "v1"));
  501. dbfull()->TEST_CompactMemTable();
  502. ASSERT_EQ("v1", Get("foo"));
  503. } while (ChangeOptions());
  504. }
  505. TEST(DBTest, GetSnapshot) {
  506. do {
  507. // Try with both a short key and a long key
  508. for (int i = 0; i < 2; i++) {
  509. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  510. ASSERT_OK(Put(key, "v1"));
  511. const Snapshot* s1 = db_->GetSnapshot();
  512. ASSERT_OK(Put(key, "v2"));
  513. ASSERT_EQ("v2", Get(key));
  514. ASSERT_EQ("v1", Get(key, s1));
  515. dbfull()->TEST_CompactMemTable();
  516. ASSERT_EQ("v2", Get(key));
  517. ASSERT_EQ("v1", Get(key, s1));
  518. db_->ReleaseSnapshot(s1);
  519. }
  520. } while (ChangeOptions());
  521. }
  522. TEST(DBTest, GetLevel0Ordering) {
  523. do {
  524. // Check that we process level-0 files in correct order. The code
  525. // below generates two level-0 files where the earlier one comes
  526. // before the later one in the level-0 file list since the earlier
  527. // one has a smaller "smallest" key.
  528. ASSERT_OK(Put("bar", "b"));
  529. ASSERT_OK(Put("foo", "v1"));
  530. dbfull()->TEST_CompactMemTable();
  531. ASSERT_OK(Put("foo", "v2"));
  532. dbfull()->TEST_CompactMemTable();
  533. ASSERT_EQ("v2", Get("foo"));
  534. } while (ChangeOptions());
  535. }
  536. TEST(DBTest, GetOrderedByLevels) {
  537. do {
  538. ASSERT_OK(Put("foo", "v1"));
  539. Compact("a", "z");
  540. ASSERT_EQ("v1", Get("foo"));
  541. ASSERT_OK(Put("foo", "v2"));
  542. ASSERT_EQ("v2", Get("foo"));
  543. dbfull()->TEST_CompactMemTable();
  544. ASSERT_EQ("v2", Get("foo"));
  545. } while (ChangeOptions());
  546. }
  547. TEST(DBTest, GetPicksCorrectFile) {
  548. do {
  549. // Arrange to have multiple files in a non-level-0 level.
  550. ASSERT_OK(Put("a", "va"));
  551. Compact("a", "b");
  552. ASSERT_OK(Put("x", "vx"));
  553. Compact("x", "y");
  554. ASSERT_OK(Put("f", "vf"));
  555. Compact("f", "g");
  556. ASSERT_EQ("va", Get("a"));
  557. ASSERT_EQ("vf", Get("f"));
  558. ASSERT_EQ("vx", Get("x"));
  559. } while (ChangeOptions());
  560. }
  561. TEST(DBTest, GetEncountersEmptyLevel) {
  562. do {
  563. // Arrange for the following to happen:
  564. // * sstable A in level 0
  565. // * nothing in level 1
  566. // * sstable B in level 2
  567. // Then do enough Get() calls to arrange for an automatic compaction
  568. // of sstable A. A bug would cause the compaction to be marked as
  569. // occurring at level 1 (instead of the correct level 0).
  570. // Step 1: First place sstables in levels 0 and 2
  571. int compaction_count = 0;
  572. while (NumTableFilesAtLevel(0) == 0 ||
  573. NumTableFilesAtLevel(2) == 0) {
  574. ASSERT_LE(compaction_count, 100) << "could not fill levels 0 and 2";
  575. compaction_count++;
  576. Put("a", "begin");
  577. Put("z", "end");
  578. dbfull()->TEST_CompactMemTable();
  579. }
  580. // Step 2: clear level 1 if necessary.
  581. dbfull()->TEST_CompactRange(1, NULL, NULL);
  582. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  583. ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  584. ASSERT_EQ(NumTableFilesAtLevel(2), 1);
  585. // Step 3: read a bunch of times
  586. for (int i = 0; i < 1000; i++) {
  587. ASSERT_EQ("NOT_FOUND", Get("missing"));
  588. }
  589. // Step 4: Wait for compaction to finish
  590. DelayMilliseconds(1000);
  591. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  592. } while (ChangeOptions());
  593. }
  594. TEST(DBTest, IterEmpty) {
  595. Iterator* iter = db_->NewIterator(ReadOptions());
  596. iter->SeekToFirst();
  597. ASSERT_EQ(IterStatus(iter), "(invalid)");
  598. iter->SeekToLast();
  599. ASSERT_EQ(IterStatus(iter), "(invalid)");
  600. iter->Seek("foo");
  601. ASSERT_EQ(IterStatus(iter), "(invalid)");
  602. delete iter;
  603. }
  604. TEST(DBTest, IterSingle) {
  605. ASSERT_OK(Put("a", "va"));
  606. Iterator* iter = db_->NewIterator(ReadOptions());
  607. iter->SeekToFirst();
  608. ASSERT_EQ(IterStatus(iter), "a->va");
  609. iter->Next();
  610. ASSERT_EQ(IterStatus(iter), "(invalid)");
  611. iter->SeekToFirst();
  612. ASSERT_EQ(IterStatus(iter), "a->va");
  613. iter->Prev();
  614. ASSERT_EQ(IterStatus(iter), "(invalid)");
  615. iter->SeekToLast();
  616. ASSERT_EQ(IterStatus(iter), "a->va");
  617. iter->Next();
  618. ASSERT_EQ(IterStatus(iter), "(invalid)");
  619. iter->SeekToLast();
  620. ASSERT_EQ(IterStatus(iter), "a->va");
  621. iter->Prev();
  622. ASSERT_EQ(IterStatus(iter), "(invalid)");
  623. iter->Seek("");
  624. ASSERT_EQ(IterStatus(iter), "a->va");
  625. iter->Next();
  626. ASSERT_EQ(IterStatus(iter), "(invalid)");
  627. iter->Seek("a");
  628. ASSERT_EQ(IterStatus(iter), "a->va");
  629. iter->Next();
  630. ASSERT_EQ(IterStatus(iter), "(invalid)");
  631. iter->Seek("b");
  632. ASSERT_EQ(IterStatus(iter), "(invalid)");
  633. delete iter;
  634. }
  635. TEST(DBTest, IterMulti) {
  636. ASSERT_OK(Put("a", "va"));
  637. ASSERT_OK(Put("b", "vb"));
  638. ASSERT_OK(Put("c", "vc"));
  639. Iterator* iter = db_->NewIterator(ReadOptions());
  640. iter->SeekToFirst();
  641. ASSERT_EQ(IterStatus(iter), "a->va");
  642. iter->Next();
  643. ASSERT_EQ(IterStatus(iter), "b->vb");
  644. iter->Next();
  645. ASSERT_EQ(IterStatus(iter), "c->vc");
  646. iter->Next();
  647. ASSERT_EQ(IterStatus(iter), "(invalid)");
  648. iter->SeekToFirst();
  649. ASSERT_EQ(IterStatus(iter), "a->va");
  650. iter->Prev();
  651. ASSERT_EQ(IterStatus(iter), "(invalid)");
  652. iter->SeekToLast();
  653. ASSERT_EQ(IterStatus(iter), "c->vc");
  654. iter->Prev();
  655. ASSERT_EQ(IterStatus(iter), "b->vb");
  656. iter->Prev();
  657. ASSERT_EQ(IterStatus(iter), "a->va");
  658. iter->Prev();
  659. ASSERT_EQ(IterStatus(iter), "(invalid)");
  660. iter->SeekToLast();
  661. ASSERT_EQ(IterStatus(iter), "c->vc");
  662. iter->Next();
  663. ASSERT_EQ(IterStatus(iter), "(invalid)");
  664. iter->Seek("");
  665. ASSERT_EQ(IterStatus(iter), "a->va");
  666. iter->Seek("a");
  667. ASSERT_EQ(IterStatus(iter), "a->va");
  668. iter->Seek("ax");
  669. ASSERT_EQ(IterStatus(iter), "b->vb");
  670. iter->Seek("b");
  671. ASSERT_EQ(IterStatus(iter), "b->vb");
  672. iter->Seek("z");
  673. ASSERT_EQ(IterStatus(iter), "(invalid)");
  674. // Switch from reverse to forward
  675. iter->SeekToLast();
  676. iter->Prev();
  677. iter->Prev();
  678. iter->Next();
  679. ASSERT_EQ(IterStatus(iter), "b->vb");
  680. // Switch from forward to reverse
  681. iter->SeekToFirst();
  682. iter->Next();
  683. iter->Next();
  684. iter->Prev();
  685. ASSERT_EQ(IterStatus(iter), "b->vb");
  686. // Make sure iter stays at snapshot
  687. ASSERT_OK(Put("a", "va2"));
  688. ASSERT_OK(Put("a2", "va3"));
  689. ASSERT_OK(Put("b", "vb2"));
  690. ASSERT_OK(Put("c", "vc2"));
  691. ASSERT_OK(Delete("b"));
  692. iter->SeekToFirst();
  693. ASSERT_EQ(IterStatus(iter), "a->va");
  694. iter->Next();
  695. ASSERT_EQ(IterStatus(iter), "b->vb");
  696. iter->Next();
  697. ASSERT_EQ(IterStatus(iter), "c->vc");
  698. iter->Next();
  699. ASSERT_EQ(IterStatus(iter), "(invalid)");
  700. iter->SeekToLast();
  701. ASSERT_EQ(IterStatus(iter), "c->vc");
  702. iter->Prev();
  703. ASSERT_EQ(IterStatus(iter), "b->vb");
  704. iter->Prev();
  705. ASSERT_EQ(IterStatus(iter), "a->va");
  706. iter->Prev();
  707. ASSERT_EQ(IterStatus(iter), "(invalid)");
  708. delete iter;
  709. }
  710. TEST(DBTest, IterSmallAndLargeMix) {
  711. ASSERT_OK(Put("a", "va"));
  712. ASSERT_OK(Put("b", std::string(100000, 'b')));
  713. ASSERT_OK(Put("c", "vc"));
  714. ASSERT_OK(Put("d", std::string(100000, 'd')));
  715. ASSERT_OK(Put("e", std::string(100000, 'e')));
  716. Iterator* iter = db_->NewIterator(ReadOptions());
  717. iter->SeekToFirst();
  718. ASSERT_EQ(IterStatus(iter), "a->va");
  719. iter->Next();
  720. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  721. iter->Next();
  722. ASSERT_EQ(IterStatus(iter), "c->vc");
  723. iter->Next();
  724. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  725. iter->Next();
  726. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  727. iter->Next();
  728. ASSERT_EQ(IterStatus(iter), "(invalid)");
  729. iter->SeekToLast();
  730. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  731. iter->Prev();
  732. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  733. iter->Prev();
  734. ASSERT_EQ(IterStatus(iter), "c->vc");
  735. iter->Prev();
  736. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  737. iter->Prev();
  738. ASSERT_EQ(IterStatus(iter), "a->va");
  739. iter->Prev();
  740. ASSERT_EQ(IterStatus(iter), "(invalid)");
  741. delete iter;
  742. }
  743. TEST(DBTest, IterMultiWithDelete) {
  744. do {
  745. ASSERT_OK(Put("a", "va"));
  746. ASSERT_OK(Put("b", "vb"));
  747. ASSERT_OK(Put("c", "vc"));
  748. ASSERT_OK(Delete("b"));
  749. ASSERT_EQ("NOT_FOUND", Get("b"));
  750. Iterator* iter = db_->NewIterator(ReadOptions());
  751. iter->Seek("c");
  752. ASSERT_EQ(IterStatus(iter), "c->vc");
  753. iter->Prev();
  754. ASSERT_EQ(IterStatus(iter), "a->va");
  755. delete iter;
  756. } while (ChangeOptions());
  757. }
  758. TEST(DBTest, Recover) {
  759. do {
  760. ASSERT_OK(Put("foo", "v1"));
  761. ASSERT_OK(Put("baz", "v5"));
  762. Reopen();
  763. ASSERT_EQ("v1", Get("foo"));
  764. ASSERT_EQ("v1", Get("foo"));
  765. ASSERT_EQ("v5", Get("baz"));
  766. ASSERT_OK(Put("bar", "v2"));
  767. ASSERT_OK(Put("foo", "v3"));
  768. Reopen();
  769. ASSERT_EQ("v3", Get("foo"));
  770. ASSERT_OK(Put("foo", "v4"));
  771. ASSERT_EQ("v4", Get("foo"));
  772. ASSERT_EQ("v2", Get("bar"));
  773. ASSERT_EQ("v5", Get("baz"));
  774. } while (ChangeOptions());
  775. }
  776. TEST(DBTest, RecoveryWithEmptyLog) {
  777. do {
  778. ASSERT_OK(Put("foo", "v1"));
  779. ASSERT_OK(Put("foo", "v2"));
  780. Reopen();
  781. Reopen();
  782. ASSERT_OK(Put("foo", "v3"));
  783. Reopen();
  784. ASSERT_EQ("v3", Get("foo"));
  785. } while (ChangeOptions());
  786. }
  787. // Check that writes done during a memtable compaction are recovered
  788. // if the database is shutdown during the memtable compaction.
  789. TEST(DBTest, RecoverDuringMemtableCompaction) {
  790. do {
  791. Options options = CurrentOptions();
  792. options.env = env_;
  793. options.write_buffer_size = 1000000;
  794. Reopen(&options);
  795. // Trigger a long memtable compaction and reopen the database during it
  796. ASSERT_OK(Put("foo", "v1")); // Goes to 1st log file
  797. ASSERT_OK(Put("big1", std::string(10000000, 'x'))); // Fills memtable
  798. ASSERT_OK(Put("big2", std::string(1000, 'y'))); // Triggers compaction
  799. ASSERT_OK(Put("bar", "v2")); // Goes to new log file
  800. Reopen(&options);
  801. ASSERT_EQ("v1", Get("foo"));
  802. ASSERT_EQ("v2", Get("bar"));
  803. ASSERT_EQ(std::string(10000000, 'x'), Get("big1"));
  804. ASSERT_EQ(std::string(1000, 'y'), Get("big2"));
  805. } while (ChangeOptions());
  806. }
  807. static std::string Key(int i) {
  808. char buf[100];
  809. snprintf(buf, sizeof(buf), "key%06d", i);
  810. return std::string(buf);
  811. }
  812. TEST(DBTest, MinorCompactionsHappen) {
  813. Options options = CurrentOptions();
  814. options.write_buffer_size = 10000;
  815. Reopen(&options);
  816. const int N = 500;
  817. int starting_num_tables = TotalTableFiles();
  818. for (int i = 0; i < N; i++) {
  819. ASSERT_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  820. }
  821. int ending_num_tables = TotalTableFiles();
  822. ASSERT_GT(ending_num_tables, starting_num_tables);
  823. for (int i = 0; i < N; i++) {
  824. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  825. }
  826. Reopen();
  827. for (int i = 0; i < N; i++) {
  828. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  829. }
  830. }
  831. TEST(DBTest, RecoverWithLargeLog) {
  832. {
  833. Options options = CurrentOptions();
  834. Reopen(&options);
  835. ASSERT_OK(Put("big1", std::string(200000, '1')));
  836. ASSERT_OK(Put("big2", std::string(200000, '2')));
  837. ASSERT_OK(Put("small3", std::string(10, '3')));
  838. ASSERT_OK(Put("small4", std::string(10, '4')));
  839. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  840. }
  841. // Make sure that if we re-open with a small write buffer size that
  842. // we flush table files in the middle of a large log file.
  843. Options options = CurrentOptions();
  844. options.write_buffer_size = 100000;
  845. Reopen(&options);
  846. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  847. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  848. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  849. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  850. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  851. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  852. }
  853. TEST(DBTest, CompactionsGenerateMultipleFiles) {
  854. Options options = CurrentOptions();
  855. options.write_buffer_size = 100000000; // Large write buffer
  856. Reopen(&options);
  857. Random rnd(301);
  858. // Write 8MB (80 values, each 100K)
  859. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  860. std::vector<std::string> values;
  861. for (int i = 0; i < 80; i++) {
  862. values.push_back(RandomString(&rnd, 100000));
  863. ASSERT_OK(Put(Key(i), values[i]));
  864. }
  865. // Reopening moves updates to level-0
  866. Reopen(&options);
  867. dbfull()->TEST_CompactRange(0, NULL, NULL);
  868. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  869. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  870. for (int i = 0; i < 80; i++) {
  871. ASSERT_EQ(Get(Key(i)), values[i]);
  872. }
  873. }
  874. TEST(DBTest, RepeatedWritesToSameKey) {
  875. Options options = CurrentOptions();
  876. options.env = env_;
  877. options.write_buffer_size = 100000; // Small write buffer
  878. Reopen(&options);
  879. // We must have at most one file per level except for level-0,
  880. // which may have up to kL0_StopWritesTrigger files.
  881. const int kMaxFiles = config::kNumLevels + config::kL0_StopWritesTrigger;
  882. Random rnd(301);
  883. std::string value = RandomString(&rnd, 2 * options.write_buffer_size);
  884. for (int i = 0; i < 5 * kMaxFiles; i++) {
  885. Put("key", value);
  886. ASSERT_LE(TotalTableFiles(), kMaxFiles);
  887. fprintf(stderr, "after %d: %d files\n", int(i+1), TotalTableFiles());
  888. }
  889. }
  890. TEST(DBTest, SparseMerge) {
  891. Options options = CurrentOptions();
  892. options.compression = kNoCompression;
  893. Reopen(&options);
  894. FillLevels("A", "Z");
  895. // Suppose there is:
  896. // small amount of data with prefix A
  897. // large amount of data with prefix B
  898. // small amount of data with prefix C
  899. // and that recent updates have made small changes to all three prefixes.
  900. // Check that we do not do a compaction that merges all of B in one shot.
  901. const std::string value(1000, 'x');
  902. Put("A", "va");
  903. // Write approximately 100MB of "B" values
  904. for (int i = 0; i < 100000; i++) {
  905. char key[100];
  906. snprintf(key, sizeof(key), "B%010d", i);
  907. Put(key, value);
  908. }
  909. Put("C", "vc");
  910. dbfull()->TEST_CompactMemTable();
  911. dbfull()->TEST_CompactRange(0, NULL, NULL);
  912. // Make sparse update
  913. Put("A", "va2");
  914. Put("B100", "bvalue2");
  915. Put("C", "vc2");
  916. dbfull()->TEST_CompactMemTable();
  917. // Compactions should not cause us to create a situation where
  918. // a file overlaps too much data at the next level.
  919. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  920. dbfull()->TEST_CompactRange(0, NULL, NULL);
  921. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  922. dbfull()->TEST_CompactRange(1, NULL, NULL);
  923. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  924. }
  925. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  926. bool result = (val >= low) && (val <= high);
  927. if (!result) {
  928. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  929. (unsigned long long)(val),
  930. (unsigned long long)(low),
  931. (unsigned long long)(high));
  932. }
  933. return result;
  934. }
  935. TEST(DBTest, ApproximateSizes) {
  936. do {
  937. Options options = CurrentOptions();
  938. options.write_buffer_size = 100000000; // Large write buffer
  939. options.compression = kNoCompression;
  940. DestroyAndReopen();
  941. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  942. Reopen(&options);
  943. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  944. // Write 8MB (80 values, each 100K)
  945. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  946. const int N = 80;
  947. static const int S1 = 100000;
  948. static const int S2 = 105000; // Allow some expansion from metadata
  949. Random rnd(301);
  950. for (int i = 0; i < N; i++) {
  951. ASSERT_OK(Put(Key(i), RandomString(&rnd, S1)));
  952. }
  953. // 0 because GetApproximateSizes() does not account for memtable space
  954. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  955. if (options.reuse_logs) {
  956. // Recovery will reuse memtable, and GetApproximateSizes() does not
  957. // account for memtable usage;
  958. Reopen(&options);
  959. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  960. continue;
  961. }
  962. // Check sizes across recovery by reopening a few times
  963. for (int run = 0; run < 3; run++) {
  964. Reopen(&options);
  965. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  966. for (int i = 0; i < N; i += 10) {
  967. ASSERT_TRUE(Between(Size("", Key(i)), S1*i, S2*i));
  968. ASSERT_TRUE(Between(Size("", Key(i)+".suffix"), S1*(i+1), S2*(i+1)));
  969. ASSERT_TRUE(Between(Size(Key(i), Key(i+10)), S1*10, S2*10));
  970. }
  971. ASSERT_TRUE(Between(Size("", Key(50)), S1*50, S2*50));
  972. ASSERT_TRUE(Between(Size("", Key(50)+".suffix"), S1*50, S2*50));
  973. std::string cstart_str = Key(compact_start);
  974. std::string cend_str = Key(compact_start + 9);
  975. Slice cstart = cstart_str;
  976. Slice cend = cend_str;
  977. dbfull()->TEST_CompactRange(0, &cstart, &cend);
  978. }
  979. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  980. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  981. }
  982. } while (ChangeOptions());
  983. }
  984. TEST(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  985. do {
  986. Options options = CurrentOptions();
  987. options.compression = kNoCompression;
  988. Reopen();
  989. Random rnd(301);
  990. std::string big1 = RandomString(&rnd, 100000);
  991. ASSERT_OK(Put(Key(0), RandomString(&rnd, 10000)));
  992. ASSERT_OK(Put(Key(1), RandomString(&rnd, 10000)));
  993. ASSERT_OK(Put(Key(2), big1));
  994. ASSERT_OK(Put(Key(3), RandomString(&rnd, 10000)));
  995. ASSERT_OK(Put(Key(4), big1));
  996. ASSERT_OK(Put(Key(5), RandomString(&rnd, 10000)));
  997. ASSERT_OK(Put(Key(6), RandomString(&rnd, 300000)));
  998. ASSERT_OK(Put(Key(7), RandomString(&rnd, 10000)));
  999. if (options.reuse_logs) {
  1000. // Need to force a memtable compaction since recovery does not do so.
  1001. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1002. }
  1003. // Check sizes across recovery by reopening a few times
  1004. for (int run = 0; run < 3; run++) {
  1005. Reopen(&options);
  1006. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  1007. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  1008. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  1009. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  1010. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  1011. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  1012. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  1013. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  1014. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 560000));
  1015. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  1016. dbfull()->TEST_CompactRange(0, NULL, NULL);
  1017. }
  1018. } while (ChangeOptions());
  1019. }
  1020. TEST(DBTest, IteratorPinsRef) {
  1021. Put("foo", "hello");
  1022. // Get iterator that will yield the current contents of the DB.
  1023. Iterator* iter = db_->NewIterator(ReadOptions());
  1024. // Write to force compactions
  1025. Put("foo", "newvalue1");
  1026. for (int i = 0; i < 100; i++) {
  1027. ASSERT_OK(Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  1028. }
  1029. Put("foo", "newvalue2");
  1030. iter->SeekToFirst();
  1031. ASSERT_TRUE(iter->Valid());
  1032. ASSERT_EQ("foo", iter->key().ToString());
  1033. ASSERT_EQ("hello", iter->value().ToString());
  1034. iter->Next();
  1035. ASSERT_TRUE(!iter->Valid());
  1036. delete iter;
  1037. }
  1038. TEST(DBTest, Snapshot) {
  1039. do {
  1040. Put("foo", "v1");
  1041. const Snapshot* s1 = db_->GetSnapshot();
  1042. Put("foo", "v2");
  1043. const Snapshot* s2 = db_->GetSnapshot();
  1044. Put("foo", "v3");
  1045. const Snapshot* s3 = db_->GetSnapshot();
  1046. Put("foo", "v4");
  1047. ASSERT_EQ("v1", Get("foo", s1));
  1048. ASSERT_EQ("v2", Get("foo", s2));
  1049. ASSERT_EQ("v3", Get("foo", s3));
  1050. ASSERT_EQ("v4", Get("foo"));
  1051. db_->ReleaseSnapshot(s3);
  1052. ASSERT_EQ("v1", Get("foo", s1));
  1053. ASSERT_EQ("v2", Get("foo", s2));
  1054. ASSERT_EQ("v4", Get("foo"));
  1055. db_->ReleaseSnapshot(s1);
  1056. ASSERT_EQ("v2", Get("foo", s2));
  1057. ASSERT_EQ("v4", Get("foo"));
  1058. db_->ReleaseSnapshot(s2);
  1059. ASSERT_EQ("v4", Get("foo"));
  1060. } while (ChangeOptions());
  1061. }
  1062. TEST(DBTest, HiddenValuesAreRemoved) {
  1063. do {
  1064. Random rnd(301);
  1065. FillLevels("a", "z");
  1066. std::string big = RandomString(&rnd, 50000);
  1067. Put("foo", big);
  1068. Put("pastfoo", "v");
  1069. const Snapshot* snapshot = db_->GetSnapshot();
  1070. Put("foo", "tiny");
  1071. Put("pastfoo2", "v2"); // Advance sequence number one more
  1072. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1073. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  1074. ASSERT_EQ(big, Get("foo", snapshot));
  1075. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  1076. db_->ReleaseSnapshot(snapshot);
  1077. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  1078. Slice x("x");
  1079. dbfull()->TEST_CompactRange(0, NULL, &x);
  1080. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1081. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1082. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  1083. dbfull()->TEST_CompactRange(1, NULL, &x);
  1084. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1085. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  1086. } while (ChangeOptions());
  1087. }
  1088. TEST(DBTest, DeletionMarkers1) {
  1089. Put("foo", "v1");
  1090. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1091. const int last = config::kMaxMemCompactLevel;
  1092. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1093. // Place a table at level last-1 to prevent merging with preceding mutation
  1094. Put("a", "begin");
  1095. Put("z", "end");
  1096. dbfull()->TEST_CompactMemTable();
  1097. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1098. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  1099. Delete("foo");
  1100. Put("foo", "v2");
  1101. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1102. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1103. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1104. Slice z("z");
  1105. dbfull()->TEST_CompactRange(last-2, NULL, &z);
  1106. // DEL eliminated, but v1 remains because we aren't compacting that level
  1107. // (DEL can be eliminated because v2 hides v1).
  1108. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  1109. dbfull()->TEST_CompactRange(last-1, NULL, NULL);
  1110. // Merging last-1 w/ last, so we are the base level for "foo", so
  1111. // DEL is removed. (as is v1).
  1112. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  1113. }
  1114. TEST(DBTest, DeletionMarkers2) {
  1115. Put("foo", "v1");
  1116. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1117. const int last = config::kMaxMemCompactLevel;
  1118. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1119. // Place a table at level last-1 to prevent merging with preceding mutation
  1120. Put("a", "begin");
  1121. Put("z", "end");
  1122. dbfull()->TEST_CompactMemTable();
  1123. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1124. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  1125. Delete("foo");
  1126. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1127. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1128. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1129. dbfull()->TEST_CompactRange(last-2, NULL, NULL);
  1130. // DEL kept: "last" file overlaps
  1131. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1132. dbfull()->TEST_CompactRange(last-1, NULL, NULL);
  1133. // Merging last-1 w/ last, so we are the base level for "foo", so
  1134. // DEL is removed. (as is v1).
  1135. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  1136. }
  1137. TEST(DBTest, OverlapInLevel0) {
  1138. do {
  1139. ASSERT_EQ(config::kMaxMemCompactLevel, 2) << "Fix test to match config";
  1140. // Fill levels 1 and 2 to disable the pushing of new memtables to levels > 0.
  1141. ASSERT_OK(Put("100", "v100"));
  1142. ASSERT_OK(Put("999", "v999"));
  1143. dbfull()->TEST_CompactMemTable();
  1144. ASSERT_OK(Delete("100"));
  1145. ASSERT_OK(Delete("999"));
  1146. dbfull()->TEST_CompactMemTable();
  1147. ASSERT_EQ("0,1,1", FilesPerLevel());
  1148. // Make files spanning the following ranges in level-0:
  1149. // files[0] 200 .. 900
  1150. // files[1] 300 .. 500
  1151. // Note that files are sorted by smallest key.
  1152. ASSERT_OK(Put("300", "v300"));
  1153. ASSERT_OK(Put("500", "v500"));
  1154. dbfull()->TEST_CompactMemTable();
  1155. ASSERT_OK(Put("200", "v200"));
  1156. ASSERT_OK(Put("600", "v600"));
  1157. ASSERT_OK(Put("900", "v900"));
  1158. dbfull()->TEST_CompactMemTable();
  1159. ASSERT_EQ("2,1,1", FilesPerLevel());
  1160. // Compact away the placeholder files we created initially
  1161. dbfull()->TEST_CompactRange(1, NULL, NULL);
  1162. dbfull()->TEST_CompactRange(2, NULL, NULL);
  1163. ASSERT_EQ("2", FilesPerLevel());
  1164. // Do a memtable compaction. Before bug-fix, the compaction would
  1165. // not detect the overlap with level-0 files and would incorrectly place
  1166. // the deletion in a deeper level.
  1167. ASSERT_OK(Delete("600"));
  1168. dbfull()->TEST_CompactMemTable();
  1169. ASSERT_EQ("3", FilesPerLevel());
  1170. ASSERT_EQ("NOT_FOUND", Get("600"));
  1171. } while (ChangeOptions());
  1172. }
  1173. TEST(DBTest, L0_CompactionBug_Issue44_a) {
  1174. Reopen();
  1175. ASSERT_OK(Put("b", "v"));
  1176. Reopen();
  1177. ASSERT_OK(Delete("b"));
  1178. ASSERT_OK(Delete("a"));
  1179. Reopen();
  1180. ASSERT_OK(Delete("a"));
  1181. Reopen();
  1182. ASSERT_OK(Put("a", "v"));
  1183. Reopen();
  1184. Reopen();
  1185. ASSERT_EQ("(a->v)", Contents());
  1186. DelayMilliseconds(1000); // Wait for compaction to finish
  1187. ASSERT_EQ("(a->v)", Contents());
  1188. }
  1189. TEST(DBTest, L0_CompactionBug_Issue44_b) {
  1190. Reopen();
  1191. Put("","");
  1192. Reopen();
  1193. Delete("e");
  1194. Put("","");
  1195. Reopen();
  1196. Put("c", "cv");
  1197. Reopen();
  1198. Put("","");
  1199. Reopen();
  1200. Put("","");
  1201. DelayMilliseconds(1000); // Wait for compaction to finish
  1202. Reopen();
  1203. Put("d","dv");
  1204. Reopen();
  1205. Put("","");
  1206. Reopen();
  1207. Delete("d");
  1208. Delete("b");
  1209. Reopen();
  1210. ASSERT_EQ("(->)(c->cv)", Contents());
  1211. DelayMilliseconds(1000); // Wait for compaction to finish
  1212. ASSERT_EQ("(->)(c->cv)", Contents());
  1213. }
  1214. TEST(DBTest, ComparatorCheck) {
  1215. class NewComparator : public Comparator {
  1216. public:
  1217. virtual const char* Name() const { return "leveldb.NewComparator"; }
  1218. virtual int Compare(const Slice& a, const Slice& b) const {
  1219. return BytewiseComparator()->Compare(a, b);
  1220. }
  1221. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  1222. BytewiseComparator()->FindShortestSeparator(s, l);
  1223. }
  1224. virtual void FindShortSuccessor(std::string* key) const {
  1225. BytewiseComparator()->FindShortSuccessor(key);
  1226. }
  1227. };
  1228. NewComparator cmp;
  1229. Options new_options = CurrentOptions();
  1230. new_options.comparator = &cmp;
  1231. Status s = TryReopen(&new_options);
  1232. ASSERT_TRUE(!s.ok());
  1233. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  1234. << s.ToString();
  1235. }
  1236. TEST(DBTest, CustomComparator) {
  1237. class NumberComparator : public Comparator {
  1238. public:
  1239. virtual const char* Name() const { return "test.NumberComparator"; }
  1240. virtual int Compare(const Slice& a, const Slice& b) const {
  1241. return ToNumber(a) - ToNumber(b);
  1242. }
  1243. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  1244. ToNumber(*s); // Check format
  1245. ToNumber(l); // Check format
  1246. }
  1247. virtual void FindShortSuccessor(std::string* key) const {
  1248. ToNumber(*key); // Check format
  1249. }
  1250. private:
  1251. static int ToNumber(const Slice& x) {
  1252. // Check that there are no extra characters.
  1253. ASSERT_TRUE(x.size() >= 2 && x[0] == '[' && x[x.size()-1] == ']')
  1254. << EscapeString(x);
  1255. int val;
  1256. char ignored;
  1257. ASSERT_TRUE(sscanf(x.ToString().c_str(), "[%i]%c", &val, &ignored) == 1)
  1258. << EscapeString(x);
  1259. return val;
  1260. }
  1261. };
  1262. NumberComparator cmp;
  1263. Options new_options = CurrentOptions();
  1264. new_options.create_if_missing = true;
  1265. new_options.comparator = &cmp;
  1266. new_options.filter_policy = NULL; // Cannot use bloom filters
  1267. new_options.write_buffer_size = 1000; // Compact more often
  1268. DestroyAndReopen(&new_options);
  1269. ASSERT_OK(Put("[10]", "ten"));
  1270. ASSERT_OK(Put("[0x14]", "twenty"));
  1271. for (int i = 0; i < 2; i++) {
  1272. ASSERT_EQ("ten", Get("[10]"));
  1273. ASSERT_EQ("ten", Get("[0xa]"));
  1274. ASSERT_EQ("twenty", Get("[20]"));
  1275. ASSERT_EQ("twenty", Get("[0x14]"));
  1276. ASSERT_EQ("NOT_FOUND", Get("[15]"));
  1277. ASSERT_EQ("NOT_FOUND", Get("[0xf]"));
  1278. Compact("[0]", "[9999]");
  1279. }
  1280. for (int run = 0; run < 2; run++) {
  1281. for (int i = 0; i < 1000; i++) {
  1282. char buf[100];
  1283. snprintf(buf, sizeof(buf), "[%d]", i*10);
  1284. ASSERT_OK(Put(buf, buf));
  1285. }
  1286. Compact("[0]", "[1000000]");
  1287. }
  1288. }
  1289. TEST(DBTest, ManualCompaction) {
  1290. ASSERT_EQ(config::kMaxMemCompactLevel, 2)
  1291. << "Need to update this test to match kMaxMemCompactLevel";
  1292. MakeTables(3, "p", "q");
  1293. ASSERT_EQ("1,1,1", FilesPerLevel());
  1294. // Compaction range falls before files
  1295. Compact("", "c");
  1296. ASSERT_EQ("1,1,1", FilesPerLevel());
  1297. // Compaction range falls after files
  1298. Compact("r", "z");
  1299. ASSERT_EQ("1,1,1", FilesPerLevel());
  1300. // Compaction range overlaps files
  1301. Compact("p1", "p9");
  1302. ASSERT_EQ("0,0,1", FilesPerLevel());
  1303. // Populate a different range
  1304. MakeTables(3, "c", "e");
  1305. ASSERT_EQ("1,1,2", FilesPerLevel());
  1306. // Compact just the new range
  1307. Compact("b", "f");
  1308. ASSERT_EQ("0,0,2", FilesPerLevel());
  1309. // Compact all
  1310. MakeTables(1, "a", "z");
  1311. ASSERT_EQ("0,1,2", FilesPerLevel());
  1312. db_->CompactRange(NULL, NULL);
  1313. ASSERT_EQ("0,0,1", FilesPerLevel());
  1314. }
  1315. TEST(DBTest, DBOpen_Options) {
  1316. std::string dbname = test::TmpDir() + "/db_options_test";
  1317. DestroyDB(dbname, Options());
  1318. // Does not exist, and create_if_missing == false: error
  1319. DB* db = NULL;
  1320. Options opts;
  1321. opts.create_if_missing = false;
  1322. Status s = DB::Open(opts, dbname, &db);
  1323. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != NULL);
  1324. ASSERT_TRUE(db == NULL);
  1325. // Does not exist, and create_if_missing == true: OK
  1326. opts.create_if_missing = true;
  1327. s = DB::Open(opts, dbname, &db);
  1328. ASSERT_OK(s);
  1329. ASSERT_TRUE(db != NULL);
  1330. delete db;
  1331. db = NULL;
  1332. // Does exist, and error_if_exists == true: error
  1333. opts.create_if_missing = false;
  1334. opts.error_if_exists = true;
  1335. s = DB::Open(opts, dbname, &db);
  1336. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != NULL);
  1337. ASSERT_TRUE(db == NULL);
  1338. // Does exist, and error_if_exists == false: OK
  1339. opts.create_if_missing = true;
  1340. opts.error_if_exists = false;
  1341. s = DB::Open(opts, dbname, &db);
  1342. ASSERT_OK(s);
  1343. ASSERT_TRUE(db != NULL);
  1344. delete db;
  1345. db = NULL;
  1346. }
  1347. TEST(DBTest, Locking) {
  1348. DB* db2 = NULL;
  1349. Status s = DB::Open(CurrentOptions(), dbname_, &db2);
  1350. ASSERT_TRUE(!s.ok()) << "Locking did not prevent re-opening db";
  1351. }
  1352. // Check that number of files does not grow when we are out of space
  1353. TEST(DBTest, NoSpace) {
  1354. Options options = CurrentOptions();
  1355. options.env = env_;
  1356. Reopen(&options);
  1357. ASSERT_OK(Put("foo", "v1"));
  1358. ASSERT_EQ("v1", Get("foo"));
  1359. Compact("a", "z");
  1360. const int num_files = CountFiles();
  1361. env_->no_space_.Release_Store(env_); // Force out-of-space errors
  1362. for (int i = 0; i < 10; i++) {
  1363. for (int level = 0; level < config::kNumLevels-1; level++) {
  1364. dbfull()->TEST_CompactRange(level, NULL, NULL);
  1365. }
  1366. }
  1367. env_->no_space_.Release_Store(NULL);
  1368. ASSERT_LT(CountFiles(), num_files + 3);
  1369. }
  1370. TEST(DBTest, NonWritableFileSystem) {
  1371. Options options = CurrentOptions();
  1372. options.write_buffer_size = 1000;
  1373. options.env = env_;
  1374. Reopen(&options);
  1375. ASSERT_OK(Put("foo", "v1"));
  1376. env_->non_writable_.Release_Store(env_); // Force errors for new files
  1377. std::string big(100000, 'x');
  1378. int errors = 0;
  1379. for (int i = 0; i < 20; i++) {
  1380. fprintf(stderr, "iter %d; errors %d\n", i, errors);
  1381. if (!Put("foo", big).ok()) {
  1382. errors++;
  1383. DelayMilliseconds(100);
  1384. }
  1385. }
  1386. ASSERT_GT(errors, 0);
  1387. env_->non_writable_.Release_Store(NULL);
  1388. }
  1389. TEST(DBTest, WriteSyncError) {
  1390. // Check that log sync errors cause the DB to disallow future writes.
  1391. // (a) Cause log sync calls to fail
  1392. Options options = CurrentOptions();
  1393. options.env = env_;
  1394. Reopen(&options);
  1395. env_->data_sync_error_.Release_Store(env_);
  1396. // (b) Normal write should succeed
  1397. WriteOptions w;
  1398. ASSERT_OK(db_->Put(w, "k1", "v1"));
  1399. ASSERT_EQ("v1", Get("k1"));
  1400. // (c) Do a sync write; should fail
  1401. w.sync = true;
  1402. ASSERT_TRUE(!db_->Put(w, "k2", "v2").ok());
  1403. ASSERT_EQ("v1", Get("k1"));
  1404. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1405. // (d) make sync behave normally
  1406. env_->data_sync_error_.Release_Store(NULL);
  1407. // (e) Do a non-sync write; should fail
  1408. w.sync = false;
  1409. ASSERT_TRUE(!db_->Put(w, "k3", "v3").ok());
  1410. ASSERT_EQ("v1", Get("k1"));
  1411. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1412. ASSERT_EQ("NOT_FOUND", Get("k3"));
  1413. }
  1414. TEST(DBTest, ManifestWriteError) {
  1415. // Test for the following problem:
  1416. // (a) Compaction produces file F
  1417. // (b) Log record containing F is written to MANIFEST file, but Sync() fails
  1418. // (c) GC deletes F
  1419. // (d) After reopening DB, reads fail since deleted F is named in log record
  1420. // We iterate twice. In the second iteration, everything is the
  1421. // same except the log record never makes it to the MANIFEST file.
  1422. for (int iter = 0; iter < 2; iter++) {
  1423. port::AtomicPointer* error_type = (iter == 0)
  1424. ? &env_->manifest_sync_error_
  1425. : &env_->manifest_write_error_;
  1426. // Insert foo=>bar mapping
  1427. Options options = CurrentOptions();
  1428. options.env = env_;
  1429. options.create_if_missing = true;
  1430. options.error_if_exists = false;
  1431. DestroyAndReopen(&options);
  1432. ASSERT_OK(Put("foo", "bar"));
  1433. ASSERT_EQ("bar", Get("foo"));
  1434. // Memtable compaction (will succeed)
  1435. dbfull()->TEST_CompactMemTable();
  1436. ASSERT_EQ("bar", Get("foo"));
  1437. const int last = config::kMaxMemCompactLevel;
  1438. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo=>bar is now in last level
  1439. // Merging compaction (will fail)
  1440. error_type->Release_Store(env_);
  1441. dbfull()->TEST_CompactRange(last, NULL, NULL); // Should fail
  1442. ASSERT_EQ("bar", Get("foo"));
  1443. // Recovery: should not lose data
  1444. error_type->Release_Store(NULL);
  1445. Reopen(&options);
  1446. ASSERT_EQ("bar", Get("foo"));
  1447. }
  1448. }
  1449. TEST(DBTest, MissingSSTFile) {
  1450. ASSERT_OK(Put("foo", "bar"));
  1451. ASSERT_EQ("bar", Get("foo"));
  1452. // Dump the memtable to disk.
  1453. dbfull()->TEST_CompactMemTable();
  1454. ASSERT_EQ("bar", Get("foo"));
  1455. Close();
  1456. ASSERT_TRUE(DeleteAnSSTFile());
  1457. Options options = CurrentOptions();
  1458. options.paranoid_checks = true;
  1459. Status s = TryReopen(&options);
  1460. ASSERT_TRUE(!s.ok());
  1461. ASSERT_TRUE(s.ToString().find("issing") != std::string::npos)
  1462. << s.ToString();
  1463. }
  1464. TEST(DBTest, StillReadSST) {
  1465. ASSERT_OK(Put("foo", "bar"));
  1466. ASSERT_EQ("bar", Get("foo"));
  1467. // Dump the memtable to disk.
  1468. dbfull()->TEST_CompactMemTable();
  1469. ASSERT_EQ("bar", Get("foo"));
  1470. Close();
  1471. ASSERT_GT(RenameLDBToSST(), 0);
  1472. Options options = CurrentOptions();
  1473. options.paranoid_checks = true;
  1474. Status s = TryReopen(&options);
  1475. ASSERT_TRUE(s.ok());
  1476. ASSERT_EQ("bar", Get("foo"));
  1477. }
  1478. TEST(DBTest, FilesDeletedAfterCompaction) {
  1479. ASSERT_OK(Put("foo", "v2"));
  1480. Compact("a", "z");
  1481. const int num_files = CountFiles();
  1482. for (int i = 0; i < 10; i++) {
  1483. ASSERT_OK(Put("foo", "v2"));
  1484. Compact("a", "z");
  1485. }
  1486. ASSERT_EQ(CountFiles(), num_files);
  1487. }
  1488. TEST(DBTest, BloomFilter) {
  1489. env_->count_random_reads_ = true;
  1490. Options options = CurrentOptions();
  1491. options.env = env_;
  1492. options.block_cache = NewLRUCache(0); // Prevent cache hits
  1493. options.filter_policy = NewBloomFilterPolicy(10);
  1494. Reopen(&options);
  1495. // Populate multiple layers
  1496. const int N = 10000;
  1497. for (int i = 0; i < N; i++) {
  1498. ASSERT_OK(Put(Key(i), Key(i)));
  1499. }
  1500. Compact("a", "z");
  1501. for (int i = 0; i < N; i += 100) {
  1502. ASSERT_OK(Put(Key(i), Key(i)));
  1503. }
  1504. dbfull()->TEST_CompactMemTable();
  1505. // Prevent auto compactions triggered by seeks
  1506. env_->delay_data_sync_.Release_Store(env_);
  1507. // Lookup present keys. Should rarely read from small sstable.
  1508. env_->random_read_counter_.Reset();
  1509. for (int i = 0; i < N; i++) {
  1510. ASSERT_EQ(Key(i), Get(Key(i)));
  1511. }
  1512. int reads = env_->random_read_counter_.Read();
  1513. fprintf(stderr, "%d present => %d reads\n", N, reads);
  1514. ASSERT_GE(reads, N);
  1515. ASSERT_LE(reads, N + 2*N/100);
  1516. // Lookup present keys. Should rarely read from either sstable.
  1517. env_->random_read_counter_.Reset();
  1518. for (int i = 0; i < N; i++) {
  1519. ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
  1520. }
  1521. reads = env_->random_read_counter_.Read();
  1522. fprintf(stderr, "%d missing => %d reads\n", N, reads);
  1523. ASSERT_LE(reads, 3*N/100);
  1524. env_->delay_data_sync_.Release_Store(NULL);
  1525. Close();
  1526. delete options.block_cache;
  1527. delete options.filter_policy;
  1528. }
  1529. // Multi-threaded test:
  1530. namespace {
  1531. static const int kNumThreads = 4;
  1532. static const int kTestSeconds = 10;
  1533. static const int kNumKeys = 1000;
  1534. struct MTState {
  1535. DBTest* test;
  1536. port::AtomicPointer stop;
  1537. port::AtomicPointer counter[kNumThreads];
  1538. port::AtomicPointer thread_done[kNumThreads];
  1539. };
  1540. struct MTThread {
  1541. MTState* state;
  1542. int id;
  1543. };
  1544. static void MTThreadBody(void* arg) {
  1545. MTThread* t = reinterpret_cast<MTThread*>(arg);
  1546. int id = t->id;
  1547. DB* db = t->state->test->db_;
  1548. uintptr_t counter = 0;
  1549. fprintf(stderr, "... starting thread %d\n", id);
  1550. Random rnd(1000 + id);
  1551. std::string value;
  1552. char valbuf[1500];
  1553. while (t->state->stop.Acquire_Load() == NULL) {
  1554. t->state->counter[id].Release_Store(reinterpret_cast<void*>(counter));
  1555. int key = rnd.Uniform(kNumKeys);
  1556. char keybuf[20];
  1557. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  1558. if (rnd.OneIn(2)) {
  1559. // Write values of the form <key, my id, counter>.
  1560. // We add some padding for force compactions.
  1561. snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d",
  1562. key, id, static_cast<int>(counter));
  1563. ASSERT_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  1564. } else {
  1565. // Read a value and verify that it matches the pattern written above.
  1566. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  1567. if (s.IsNotFound()) {
  1568. // Key has not yet been written
  1569. } else {
  1570. // Check that the writer thread counter is >= the counter in the value
  1571. ASSERT_OK(s);
  1572. int k, w, c;
  1573. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  1574. ASSERT_EQ(k, key);
  1575. ASSERT_GE(w, 0);
  1576. ASSERT_LT(w, kNumThreads);
  1577. ASSERT_LE(static_cast<uintptr_t>(c), reinterpret_cast<uintptr_t>(
  1578. t->state->counter[w].Acquire_Load()));
  1579. }
  1580. }
  1581. counter++;
  1582. }
  1583. t->state->thread_done[id].Release_Store(t);
  1584. fprintf(stderr, "... stopping thread %d after %d ops\n", id, int(counter));
  1585. }
  1586. } // namespace
  1587. TEST(DBTest, MultiThreaded) {
  1588. do {
  1589. // Initialize state
  1590. MTState mt;
  1591. mt.test = this;
  1592. mt.stop.Release_Store(0);
  1593. for (int id = 0; id < kNumThreads; id++) {
  1594. mt.counter[id].Release_Store(0);
  1595. mt.thread_done[id].Release_Store(0);
  1596. }
  1597. // Start threads
  1598. MTThread thread[kNumThreads];
  1599. for (int id = 0; id < kNumThreads; id++) {
  1600. thread[id].state = &mt;
  1601. thread[id].id = id;
  1602. env_->StartThread(MTThreadBody, &thread[id]);
  1603. }
  1604. // Let them run for a while
  1605. DelayMilliseconds(kTestSeconds * 1000);
  1606. // Stop the threads and wait for them to finish
  1607. mt.stop.Release_Store(&mt);
  1608. for (int id = 0; id < kNumThreads; id++) {
  1609. while (mt.thread_done[id].Acquire_Load() == NULL) {
  1610. DelayMilliseconds(100);
  1611. }
  1612. }
  1613. } while (ChangeOptions());
  1614. }
  1615. namespace {
  1616. typedef std::map<std::string, std::string> KVMap;
  1617. }
  1618. class ModelDB: public DB {
  1619. public:
  1620. class ModelSnapshot : public Snapshot {
  1621. public:
  1622. KVMap map_;
  1623. };
  1624. explicit ModelDB(const Options& options): options_(options) { }
  1625. ~ModelDB() { }
  1626. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  1627. return DB::Put(o, k, v);
  1628. }
  1629. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  1630. return DB::Delete(o, key);
  1631. }
  1632. virtual Status Get(const ReadOptions& options,
  1633. const Slice& key, std::string* value) {
  1634. assert(false); // Not implemented
  1635. return Status::NotFound(key);
  1636. }
  1637. virtual Iterator* NewIterator(const ReadOptions& options) {
  1638. if (options.snapshot == NULL) {
  1639. KVMap* saved = new KVMap;
  1640. *saved = map_;
  1641. return new ModelIter(saved, true);
  1642. } else {
  1643. const KVMap* snapshot_state =
  1644. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1645. return new ModelIter(snapshot_state, false);
  1646. }
  1647. }
  1648. virtual const Snapshot* GetSnapshot() {
  1649. ModelSnapshot* snapshot = new ModelSnapshot;
  1650. snapshot->map_ = map_;
  1651. return snapshot;
  1652. }
  1653. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  1654. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1655. }
  1656. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  1657. class Handler : public WriteBatch::Handler {
  1658. public:
  1659. KVMap* map_;
  1660. virtual void Put(const Slice& key, const Slice& value) {
  1661. (*map_)[key.ToString()] = value.ToString();
  1662. }
  1663. virtual void Delete(const Slice& key) {
  1664. map_->erase(key.ToString());
  1665. }
  1666. };
  1667. Handler handler;
  1668. handler.map_ = &map_;
  1669. return batch->Iterate(&handler);
  1670. }
  1671. virtual bool GetProperty(const Slice& property, std::string* value) {
  1672. return false;
  1673. }
  1674. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  1675. for (int i = 0; i < n; i++) {
  1676. sizes[i] = 0;
  1677. }
  1678. }
  1679. virtual void CompactRange(const Slice* start, const Slice* end) {
  1680. }
  1681. private:
  1682. class ModelIter: public Iterator {
  1683. public:
  1684. ModelIter(const KVMap* map, bool owned)
  1685. : map_(map), owned_(owned), iter_(map_->end()) {
  1686. }
  1687. ~ModelIter() {
  1688. if (owned_) delete map_;
  1689. }
  1690. virtual bool Valid() const { return iter_ != map_->end(); }
  1691. virtual void SeekToFirst() { iter_ = map_->begin(); }
  1692. virtual void SeekToLast() {
  1693. if (map_->empty()) {
  1694. iter_ = map_->end();
  1695. } else {
  1696. iter_ = map_->find(map_->rbegin()->first);
  1697. }
  1698. }
  1699. virtual void Seek(const Slice& k) {
  1700. iter_ = map_->lower_bound(k.ToString());
  1701. }
  1702. virtual void Next() { ++iter_; }
  1703. virtual void Prev() { --iter_; }
  1704. virtual Slice key() const { return iter_->first; }
  1705. virtual Slice value() const { return iter_->second; }
  1706. virtual Status status() const { return Status::OK(); }
  1707. private:
  1708. const KVMap* const map_;
  1709. const bool owned_; // Do we own map_
  1710. KVMap::const_iterator iter_;
  1711. };
  1712. const Options options_;
  1713. KVMap map_;
  1714. };
  1715. static std::string RandomKey(Random* rnd) {
  1716. int len = (rnd->OneIn(3)
  1717. ? 1 // Short sometimes to encourage collisions
  1718. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  1719. return test::RandomKey(rnd, len);
  1720. }
  1721. static bool CompareIterators(int step,
  1722. DB* model,
  1723. DB* db,
  1724. const Snapshot* model_snap,
  1725. const Snapshot* db_snap) {
  1726. ReadOptions options;
  1727. options.snapshot = model_snap;
  1728. Iterator* miter = model->NewIterator(options);
  1729. options.snapshot = db_snap;
  1730. Iterator* dbiter = db->NewIterator(options);
  1731. bool ok = true;
  1732. int count = 0;
  1733. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1734. ok && miter->Valid() && dbiter->Valid();
  1735. miter->Next(), dbiter->Next()) {
  1736. count++;
  1737. if (miter->key().compare(dbiter->key()) != 0) {
  1738. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  1739. step,
  1740. EscapeString(miter->key()).c_str(),
  1741. EscapeString(dbiter->key()).c_str());
  1742. ok = false;
  1743. break;
  1744. }
  1745. if (miter->value().compare(dbiter->value()) != 0) {
  1746. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1747. step,
  1748. EscapeString(miter->key()).c_str(),
  1749. EscapeString(miter->value()).c_str(),
  1750. EscapeString(miter->value()).c_str());
  1751. ok = false;
  1752. }
  1753. }
  1754. if (ok) {
  1755. if (miter->Valid() != dbiter->Valid()) {
  1756. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1757. step, miter->Valid(), dbiter->Valid());
  1758. ok = false;
  1759. }
  1760. }
  1761. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1762. delete miter;
  1763. delete dbiter;
  1764. return ok;
  1765. }
  1766. TEST(DBTest, Randomized) {
  1767. Random rnd(test::RandomSeed());
  1768. do {
  1769. ModelDB model(CurrentOptions());
  1770. const int N = 10000;
  1771. const Snapshot* model_snap = NULL;
  1772. const Snapshot* db_snap = NULL;
  1773. std::string k, v;
  1774. for (int step = 0; step < N; step++) {
  1775. if (step % 100 == 0) {
  1776. fprintf(stderr, "Step %d of %d\n", step, N);
  1777. }
  1778. // TODO(sanjay): Test Get() works
  1779. int p = rnd.Uniform(100);
  1780. if (p < 45) { // Put
  1781. k = RandomKey(&rnd);
  1782. v = RandomString(&rnd,
  1783. rnd.OneIn(20)
  1784. ? 100 + rnd.Uniform(100)
  1785. : rnd.Uniform(8));
  1786. ASSERT_OK(model.Put(WriteOptions(), k, v));
  1787. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  1788. } else if (p < 90) { // Delete
  1789. k = RandomKey(&rnd);
  1790. ASSERT_OK(model.Delete(WriteOptions(), k));
  1791. ASSERT_OK(db_->Delete(WriteOptions(), k));
  1792. } else { // Multi-element batch
  1793. WriteBatch b;
  1794. const int num = rnd.Uniform(8);
  1795. for (int i = 0; i < num; i++) {
  1796. if (i == 0 || !rnd.OneIn(10)) {
  1797. k = RandomKey(&rnd);
  1798. } else {
  1799. // Periodically re-use the same key from the previous iter, so
  1800. // we have multiple entries in the write batch for the same key
  1801. }
  1802. if (rnd.OneIn(2)) {
  1803. v = RandomString(&rnd, rnd.Uniform(10));
  1804. b.Put(k, v);
  1805. } else {
  1806. b.Delete(k);
  1807. }
  1808. }
  1809. ASSERT_OK(model.Write(WriteOptions(), &b));
  1810. ASSERT_OK(db_->Write(WriteOptions(), &b));
  1811. }
  1812. if ((step % 100) == 0) {
  1813. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1814. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1815. // Save a snapshot from each DB this time that we'll use next
  1816. // time we compare things, to make sure the current state is
  1817. // preserved with the snapshot
  1818. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1819. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1820. Reopen();
  1821. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  1822. model_snap = model.GetSnapshot();
  1823. db_snap = db_->GetSnapshot();
  1824. }
  1825. }
  1826. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  1827. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  1828. } while (ChangeOptions());
  1829. }
  1830. std::string MakeKey(unsigned int num) {
  1831. char buf[30];
  1832. snprintf(buf, sizeof(buf), "%016u", num);
  1833. return std::string(buf);
  1834. }
  1835. void BM_LogAndApply(int iters, int num_base_files) {
  1836. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  1837. DestroyDB(dbname, Options());
  1838. DB* db = NULL;
  1839. Options opts;
  1840. opts.create_if_missing = true;
  1841. Status s = DB::Open(opts, dbname, &db);
  1842. ASSERT_OK(s);
  1843. ASSERT_TRUE(db != NULL);
  1844. delete db;
  1845. db = NULL;
  1846. Env* env = Env::Default();
  1847. port::Mutex mu;
  1848. MutexLock l(&mu);
  1849. InternalKeyComparator cmp(BytewiseComparator());
  1850. Options options;
  1851. VersionSet vset(dbname, &options, NULL, &cmp);
  1852. bool save_manifest;
  1853. ASSERT_OK(vset.Recover(&save_manifest));
  1854. VersionEdit vbase;
  1855. uint64_t fnum = 1;
  1856. for (int i = 0; i < num_base_files; i++) {
  1857. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1858. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1859. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1860. }
  1861. ASSERT_OK(vset.LogAndApply(&vbase, &mu));
  1862. uint64_t start_micros = env->NowMicros();
  1863. for (int i = 0; i < iters; i++) {
  1864. VersionEdit vedit;
  1865. vedit.DeleteFile(2, fnum);
  1866. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  1867. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  1868. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  1869. vset.LogAndApply(&vedit, &mu);
  1870. }
  1871. uint64_t stop_micros = env->NowMicros();
  1872. unsigned int us = stop_micros - start_micros;
  1873. char buf[16];
  1874. snprintf(buf, sizeof(buf), "%d", num_base_files);
  1875. fprintf(stderr,
  1876. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  1877. buf, iters, us, ((float)us) / iters);
  1878. }
  1879. } // namespace leveldb
  1880. int main(int argc, char** argv) {
  1881. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  1882. leveldb::BM_LogAndApply(1000, 1);
  1883. leveldb::BM_LogAndApply(1000, 100);
  1884. leveldb::BM_LogAndApply(1000, 10000);
  1885. leveldb::BM_LogAndApply(100, 100000);
  1886. return 0;
  1887. }
  1888. return leveldb::test::RunAllTests();
  1889. }