作者: 韩晨旭 10225101440 李畅 10225102463
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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