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

2328 řádky
67 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, EmptyKey) {
  499. do {
  500. ASSERT_OK(Put("", "v1"));
  501. ASSERT_EQ("v1", Get(""));
  502. ASSERT_OK(Put("", "v2"));
  503. ASSERT_EQ("v2", Get(""));
  504. } while (ChangeOptions());
  505. }
  506. TEST(DBTest, EmptyValue) {
  507. do {
  508. ASSERT_OK(Put("key", "v1"));
  509. ASSERT_EQ("v1", Get("key"));
  510. ASSERT_OK(Put("key", ""));
  511. ASSERT_EQ("", Get("key"));
  512. ASSERT_OK(Put("key", "v2"));
  513. ASSERT_EQ("v2", Get("key"));
  514. } while (ChangeOptions());
  515. }
  516. TEST(DBTest, ReadWrite) {
  517. do {
  518. ASSERT_OK(Put("foo", "v1"));
  519. ASSERT_EQ("v1", Get("foo"));
  520. ASSERT_OK(Put("bar", "v2"));
  521. ASSERT_OK(Put("foo", "v3"));
  522. ASSERT_EQ("v3", Get("foo"));
  523. ASSERT_EQ("v2", Get("bar"));
  524. } while (ChangeOptions());
  525. }
  526. TEST(DBTest, PutDeleteGet) {
  527. do {
  528. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  529. ASSERT_EQ("v1", Get("foo"));
  530. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  531. ASSERT_EQ("v2", Get("foo"));
  532. ASSERT_OK(db_->Delete(WriteOptions(), "foo"));
  533. ASSERT_EQ("NOT_FOUND", Get("foo"));
  534. } while (ChangeOptions());
  535. }
  536. TEST(DBTest, GetFromImmutableLayer) {
  537. do {
  538. Options options = CurrentOptions();
  539. options.env = env_;
  540. options.write_buffer_size = 100000; // Small write buffer
  541. Reopen(&options);
  542. ASSERT_OK(Put("foo", "v1"));
  543. ASSERT_EQ("v1", Get("foo"));
  544. // Block sync calls.
  545. env_->delay_data_sync_.store(true, std::memory_order_release);
  546. Put("k1", std::string(100000, 'x')); // Fill memtable.
  547. Put("k2", std::string(100000, 'y')); // Trigger compaction.
  548. ASSERT_EQ("v1", Get("foo"));
  549. // Release sync calls.
  550. env_->delay_data_sync_.store(false, std::memory_order_release);
  551. } while (ChangeOptions());
  552. }
  553. TEST(DBTest, GetFromVersions) {
  554. do {
  555. ASSERT_OK(Put("foo", "v1"));
  556. dbfull()->TEST_CompactMemTable();
  557. ASSERT_EQ("v1", Get("foo"));
  558. } while (ChangeOptions());
  559. }
  560. TEST(DBTest, GetMemUsage) {
  561. do {
  562. ASSERT_OK(Put("foo", "v1"));
  563. std::string val;
  564. ASSERT_TRUE(db_->GetProperty("leveldb.approximate-memory-usage", &val));
  565. int mem_usage = std::stoi(val);
  566. ASSERT_GT(mem_usage, 0);
  567. ASSERT_LT(mem_usage, 5*1024*1024);
  568. } while (ChangeOptions());
  569. }
  570. TEST(DBTest, GetSnapshot) {
  571. do {
  572. // Try with both a short key and a long key
  573. for (int i = 0; i < 2; i++) {
  574. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  575. ASSERT_OK(Put(key, "v1"));
  576. const Snapshot* s1 = db_->GetSnapshot();
  577. ASSERT_OK(Put(key, "v2"));
  578. ASSERT_EQ("v2", Get(key));
  579. ASSERT_EQ("v1", Get(key, s1));
  580. dbfull()->TEST_CompactMemTable();
  581. ASSERT_EQ("v2", Get(key));
  582. ASSERT_EQ("v1", Get(key, s1));
  583. db_->ReleaseSnapshot(s1);
  584. }
  585. } while (ChangeOptions());
  586. }
  587. TEST(DBTest, GetIdenticalSnapshots) {
  588. do {
  589. // Try with both a short key and a long key
  590. for (int i = 0; i < 2; i++) {
  591. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  592. ASSERT_OK(Put(key, "v1"));
  593. const Snapshot* s1 = db_->GetSnapshot();
  594. const Snapshot* s2 = db_->GetSnapshot();
  595. const Snapshot* s3 = db_->GetSnapshot();
  596. ASSERT_OK(Put(key, "v2"));
  597. ASSERT_EQ("v2", Get(key));
  598. ASSERT_EQ("v1", Get(key, s1));
  599. ASSERT_EQ("v1", Get(key, s2));
  600. ASSERT_EQ("v1", Get(key, s3));
  601. db_->ReleaseSnapshot(s1);
  602. dbfull()->TEST_CompactMemTable();
  603. ASSERT_EQ("v2", Get(key));
  604. ASSERT_EQ("v1", Get(key, s2));
  605. db_->ReleaseSnapshot(s2);
  606. ASSERT_EQ("v1", Get(key, s3));
  607. db_->ReleaseSnapshot(s3);
  608. }
  609. } while (ChangeOptions());
  610. }
  611. TEST(DBTest, IterateOverEmptySnapshot) {
  612. do {
  613. const Snapshot* snapshot = db_->GetSnapshot();
  614. ReadOptions read_options;
  615. read_options.snapshot = snapshot;
  616. ASSERT_OK(Put("foo", "v1"));
  617. ASSERT_OK(Put("foo", "v2"));
  618. Iterator* iterator1 = db_->NewIterator(read_options);
  619. iterator1->SeekToFirst();
  620. ASSERT_TRUE(!iterator1->Valid());
  621. delete iterator1;
  622. dbfull()->TEST_CompactMemTable();
  623. Iterator* iterator2 = db_->NewIterator(read_options);
  624. iterator2->SeekToFirst();
  625. ASSERT_TRUE(!iterator2->Valid());
  626. delete iterator2;
  627. db_->ReleaseSnapshot(snapshot);
  628. } while (ChangeOptions());
  629. }
  630. TEST(DBTest, GetLevel0Ordering) {
  631. do {
  632. // Check that we process level-0 files in correct order. The code
  633. // below generates two level-0 files where the earlier one comes
  634. // before the later one in the level-0 file list since the earlier
  635. // one has a smaller "smallest" key.
  636. ASSERT_OK(Put("bar", "b"));
  637. ASSERT_OK(Put("foo", "v1"));
  638. dbfull()->TEST_CompactMemTable();
  639. ASSERT_OK(Put("foo", "v2"));
  640. dbfull()->TEST_CompactMemTable();
  641. ASSERT_EQ("v2", Get("foo"));
  642. } while (ChangeOptions());
  643. }
  644. TEST(DBTest, GetOrderedByLevels) {
  645. do {
  646. ASSERT_OK(Put("foo", "v1"));
  647. Compact("a", "z");
  648. ASSERT_EQ("v1", Get("foo"));
  649. ASSERT_OK(Put("foo", "v2"));
  650. ASSERT_EQ("v2", Get("foo"));
  651. dbfull()->TEST_CompactMemTable();
  652. ASSERT_EQ("v2", Get("foo"));
  653. } while (ChangeOptions());
  654. }
  655. TEST(DBTest, GetPicksCorrectFile) {
  656. do {
  657. // Arrange to have multiple files in a non-level-0 level.
  658. ASSERT_OK(Put("a", "va"));
  659. Compact("a", "b");
  660. ASSERT_OK(Put("x", "vx"));
  661. Compact("x", "y");
  662. ASSERT_OK(Put("f", "vf"));
  663. Compact("f", "g");
  664. ASSERT_EQ("va", Get("a"));
  665. ASSERT_EQ("vf", Get("f"));
  666. ASSERT_EQ("vx", Get("x"));
  667. } while (ChangeOptions());
  668. }
  669. TEST(DBTest, GetEncountersEmptyLevel) {
  670. do {
  671. // Arrange for the following to happen:
  672. // * sstable A in level 0
  673. // * nothing in level 1
  674. // * sstable B in level 2
  675. // Then do enough Get() calls to arrange for an automatic compaction
  676. // of sstable A. A bug would cause the compaction to be marked as
  677. // occurring at level 1 (instead of the correct level 0).
  678. // Step 1: First place sstables in levels 0 and 2
  679. int compaction_count = 0;
  680. while (NumTableFilesAtLevel(0) == 0 ||
  681. NumTableFilesAtLevel(2) == 0) {
  682. ASSERT_LE(compaction_count, 100) << "could not fill levels 0 and 2";
  683. compaction_count++;
  684. Put("a", "begin");
  685. Put("z", "end");
  686. dbfull()->TEST_CompactMemTable();
  687. }
  688. // Step 2: clear level 1 if necessary.
  689. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  690. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  691. ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  692. ASSERT_EQ(NumTableFilesAtLevel(2), 1);
  693. // Step 3: read a bunch of times
  694. for (int i = 0; i < 1000; i++) {
  695. ASSERT_EQ("NOT_FOUND", Get("missing"));
  696. }
  697. // Step 4: Wait for compaction to finish
  698. DelayMilliseconds(1000);
  699. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  700. } while (ChangeOptions());
  701. }
  702. TEST(DBTest, IterEmpty) {
  703. Iterator* iter = db_->NewIterator(ReadOptions());
  704. iter->SeekToFirst();
  705. ASSERT_EQ(IterStatus(iter), "(invalid)");
  706. iter->SeekToLast();
  707. ASSERT_EQ(IterStatus(iter), "(invalid)");
  708. iter->Seek("foo");
  709. ASSERT_EQ(IterStatus(iter), "(invalid)");
  710. delete iter;
  711. }
  712. TEST(DBTest, IterSingle) {
  713. ASSERT_OK(Put("a", "va"));
  714. Iterator* iter = db_->NewIterator(ReadOptions());
  715. iter->SeekToFirst();
  716. ASSERT_EQ(IterStatus(iter), "a->va");
  717. iter->Next();
  718. ASSERT_EQ(IterStatus(iter), "(invalid)");
  719. iter->SeekToFirst();
  720. ASSERT_EQ(IterStatus(iter), "a->va");
  721. iter->Prev();
  722. ASSERT_EQ(IterStatus(iter), "(invalid)");
  723. iter->SeekToLast();
  724. ASSERT_EQ(IterStatus(iter), "a->va");
  725. iter->Next();
  726. ASSERT_EQ(IterStatus(iter), "(invalid)");
  727. iter->SeekToLast();
  728. ASSERT_EQ(IterStatus(iter), "a->va");
  729. iter->Prev();
  730. ASSERT_EQ(IterStatus(iter), "(invalid)");
  731. iter->Seek("");
  732. ASSERT_EQ(IterStatus(iter), "a->va");
  733. iter->Next();
  734. ASSERT_EQ(IterStatus(iter), "(invalid)");
  735. iter->Seek("a");
  736. ASSERT_EQ(IterStatus(iter), "a->va");
  737. iter->Next();
  738. ASSERT_EQ(IterStatus(iter), "(invalid)");
  739. iter->Seek("b");
  740. ASSERT_EQ(IterStatus(iter), "(invalid)");
  741. delete iter;
  742. }
  743. TEST(DBTest, IterMulti) {
  744. ASSERT_OK(Put("a", "va"));
  745. ASSERT_OK(Put("b", "vb"));
  746. ASSERT_OK(Put("c", "vc"));
  747. Iterator* iter = db_->NewIterator(ReadOptions());
  748. iter->SeekToFirst();
  749. ASSERT_EQ(IterStatus(iter), "a->va");
  750. iter->Next();
  751. ASSERT_EQ(IterStatus(iter), "b->vb");
  752. iter->Next();
  753. ASSERT_EQ(IterStatus(iter), "c->vc");
  754. iter->Next();
  755. ASSERT_EQ(IterStatus(iter), "(invalid)");
  756. iter->SeekToFirst();
  757. ASSERT_EQ(IterStatus(iter), "a->va");
  758. iter->Prev();
  759. ASSERT_EQ(IterStatus(iter), "(invalid)");
  760. iter->SeekToLast();
  761. ASSERT_EQ(IterStatus(iter), "c->vc");
  762. iter->Prev();
  763. ASSERT_EQ(IterStatus(iter), "b->vb");
  764. iter->Prev();
  765. ASSERT_EQ(IterStatus(iter), "a->va");
  766. iter->Prev();
  767. ASSERT_EQ(IterStatus(iter), "(invalid)");
  768. iter->SeekToLast();
  769. ASSERT_EQ(IterStatus(iter), "c->vc");
  770. iter->Next();
  771. ASSERT_EQ(IterStatus(iter), "(invalid)");
  772. iter->Seek("");
  773. ASSERT_EQ(IterStatus(iter), "a->va");
  774. iter->Seek("a");
  775. ASSERT_EQ(IterStatus(iter), "a->va");
  776. iter->Seek("ax");
  777. ASSERT_EQ(IterStatus(iter), "b->vb");
  778. iter->Seek("b");
  779. ASSERT_EQ(IterStatus(iter), "b->vb");
  780. iter->Seek("z");
  781. ASSERT_EQ(IterStatus(iter), "(invalid)");
  782. // Switch from reverse to forward
  783. iter->SeekToLast();
  784. iter->Prev();
  785. iter->Prev();
  786. iter->Next();
  787. ASSERT_EQ(IterStatus(iter), "b->vb");
  788. // Switch from forward to reverse
  789. iter->SeekToFirst();
  790. iter->Next();
  791. iter->Next();
  792. iter->Prev();
  793. ASSERT_EQ(IterStatus(iter), "b->vb");
  794. // Make sure iter stays at snapshot
  795. ASSERT_OK(Put("a", "va2"));
  796. ASSERT_OK(Put("a2", "va3"));
  797. ASSERT_OK(Put("b", "vb2"));
  798. ASSERT_OK(Put("c", "vc2"));
  799. ASSERT_OK(Delete("b"));
  800. iter->SeekToFirst();
  801. ASSERT_EQ(IterStatus(iter), "a->va");
  802. iter->Next();
  803. ASSERT_EQ(IterStatus(iter), "b->vb");
  804. iter->Next();
  805. ASSERT_EQ(IterStatus(iter), "c->vc");
  806. iter->Next();
  807. ASSERT_EQ(IterStatus(iter), "(invalid)");
  808. iter->SeekToLast();
  809. ASSERT_EQ(IterStatus(iter), "c->vc");
  810. iter->Prev();
  811. ASSERT_EQ(IterStatus(iter), "b->vb");
  812. iter->Prev();
  813. ASSERT_EQ(IterStatus(iter), "a->va");
  814. iter->Prev();
  815. ASSERT_EQ(IterStatus(iter), "(invalid)");
  816. delete iter;
  817. }
  818. TEST(DBTest, IterSmallAndLargeMix) {
  819. ASSERT_OK(Put("a", "va"));
  820. ASSERT_OK(Put("b", std::string(100000, 'b')));
  821. ASSERT_OK(Put("c", "vc"));
  822. ASSERT_OK(Put("d", std::string(100000, 'd')));
  823. ASSERT_OK(Put("e", std::string(100000, 'e')));
  824. Iterator* iter = db_->NewIterator(ReadOptions());
  825. iter->SeekToFirst();
  826. ASSERT_EQ(IterStatus(iter), "a->va");
  827. iter->Next();
  828. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  829. iter->Next();
  830. ASSERT_EQ(IterStatus(iter), "c->vc");
  831. iter->Next();
  832. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  833. iter->Next();
  834. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  835. iter->Next();
  836. ASSERT_EQ(IterStatus(iter), "(invalid)");
  837. iter->SeekToLast();
  838. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  839. iter->Prev();
  840. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  841. iter->Prev();
  842. ASSERT_EQ(IterStatus(iter), "c->vc");
  843. iter->Prev();
  844. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  845. iter->Prev();
  846. ASSERT_EQ(IterStatus(iter), "a->va");
  847. iter->Prev();
  848. ASSERT_EQ(IterStatus(iter), "(invalid)");
  849. delete iter;
  850. }
  851. TEST(DBTest, IterMultiWithDelete) {
  852. do {
  853. ASSERT_OK(Put("a", "va"));
  854. ASSERT_OK(Put("b", "vb"));
  855. ASSERT_OK(Put("c", "vc"));
  856. ASSERT_OK(Delete("b"));
  857. ASSERT_EQ("NOT_FOUND", Get("b"));
  858. Iterator* iter = db_->NewIterator(ReadOptions());
  859. iter->Seek("c");
  860. ASSERT_EQ(IterStatus(iter), "c->vc");
  861. iter->Prev();
  862. ASSERT_EQ(IterStatus(iter), "a->va");
  863. delete iter;
  864. } while (ChangeOptions());
  865. }
  866. TEST(DBTest, Recover) {
  867. do {
  868. ASSERT_OK(Put("foo", "v1"));
  869. ASSERT_OK(Put("baz", "v5"));
  870. Reopen();
  871. ASSERT_EQ("v1", Get("foo"));
  872. ASSERT_EQ("v1", Get("foo"));
  873. ASSERT_EQ("v5", Get("baz"));
  874. ASSERT_OK(Put("bar", "v2"));
  875. ASSERT_OK(Put("foo", "v3"));
  876. Reopen();
  877. ASSERT_EQ("v3", Get("foo"));
  878. ASSERT_OK(Put("foo", "v4"));
  879. ASSERT_EQ("v4", Get("foo"));
  880. ASSERT_EQ("v2", Get("bar"));
  881. ASSERT_EQ("v5", Get("baz"));
  882. } while (ChangeOptions());
  883. }
  884. TEST(DBTest, RecoveryWithEmptyLog) {
  885. do {
  886. ASSERT_OK(Put("foo", "v1"));
  887. ASSERT_OK(Put("foo", "v2"));
  888. Reopen();
  889. Reopen();
  890. ASSERT_OK(Put("foo", "v3"));
  891. Reopen();
  892. ASSERT_EQ("v3", Get("foo"));
  893. } while (ChangeOptions());
  894. }
  895. // Check that writes done during a memtable compaction are recovered
  896. // if the database is shutdown during the memtable compaction.
  897. TEST(DBTest, RecoverDuringMemtableCompaction) {
  898. do {
  899. Options options = CurrentOptions();
  900. options.env = env_;
  901. options.write_buffer_size = 1000000;
  902. Reopen(&options);
  903. // Trigger a long memtable compaction and reopen the database during it
  904. ASSERT_OK(Put("foo", "v1")); // Goes to 1st log file
  905. ASSERT_OK(Put("big1", std::string(10000000, 'x'))); // Fills memtable
  906. ASSERT_OK(Put("big2", std::string(1000, 'y'))); // Triggers compaction
  907. ASSERT_OK(Put("bar", "v2")); // Goes to new log file
  908. Reopen(&options);
  909. ASSERT_EQ("v1", Get("foo"));
  910. ASSERT_EQ("v2", Get("bar"));
  911. ASSERT_EQ(std::string(10000000, 'x'), Get("big1"));
  912. ASSERT_EQ(std::string(1000, 'y'), Get("big2"));
  913. } while (ChangeOptions());
  914. }
  915. static std::string Key(int i) {
  916. char buf[100];
  917. snprintf(buf, sizeof(buf), "key%06d", i);
  918. return std::string(buf);
  919. }
  920. TEST(DBTest, MinorCompactionsHappen) {
  921. Options options = CurrentOptions();
  922. options.write_buffer_size = 10000;
  923. Reopen(&options);
  924. const int N = 500;
  925. int starting_num_tables = TotalTableFiles();
  926. for (int i = 0; i < N; i++) {
  927. ASSERT_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  928. }
  929. int ending_num_tables = TotalTableFiles();
  930. ASSERT_GT(ending_num_tables, starting_num_tables);
  931. for (int i = 0; i < N; i++) {
  932. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  933. }
  934. Reopen();
  935. for (int i = 0; i < N; i++) {
  936. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  937. }
  938. }
  939. TEST(DBTest, RecoverWithLargeLog) {
  940. {
  941. Options options = CurrentOptions();
  942. Reopen(&options);
  943. ASSERT_OK(Put("big1", std::string(200000, '1')));
  944. ASSERT_OK(Put("big2", std::string(200000, '2')));
  945. ASSERT_OK(Put("small3", std::string(10, '3')));
  946. ASSERT_OK(Put("small4", std::string(10, '4')));
  947. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  948. }
  949. // Make sure that if we re-open with a small write buffer size that
  950. // we flush table files in the middle of a large log file.
  951. Options options = CurrentOptions();
  952. options.write_buffer_size = 100000;
  953. Reopen(&options);
  954. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  955. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  956. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  957. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  958. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  959. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  960. }
  961. TEST(DBTest, CompactionsGenerateMultipleFiles) {
  962. Options options = CurrentOptions();
  963. options.write_buffer_size = 100000000; // Large write buffer
  964. Reopen(&options);
  965. Random rnd(301);
  966. // Write 8MB (80 values, each 100K)
  967. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  968. std::vector<std::string> values;
  969. for (int i = 0; i < 80; i++) {
  970. values.push_back(RandomString(&rnd, 100000));
  971. ASSERT_OK(Put(Key(i), values[i]));
  972. }
  973. // Reopening moves updates to level-0
  974. Reopen(&options);
  975. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  976. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  977. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  978. for (int i = 0; i < 80; i++) {
  979. ASSERT_EQ(Get(Key(i)), values[i]);
  980. }
  981. }
  982. TEST(DBTest, RepeatedWritesToSameKey) {
  983. Options options = CurrentOptions();
  984. options.env = env_;
  985. options.write_buffer_size = 100000; // Small write buffer
  986. Reopen(&options);
  987. // We must have at most one file per level except for level-0,
  988. // which may have up to kL0_StopWritesTrigger files.
  989. const int kMaxFiles = config::kNumLevels + config::kL0_StopWritesTrigger;
  990. Random rnd(301);
  991. std::string value = RandomString(&rnd, 2 * options.write_buffer_size);
  992. for (int i = 0; i < 5 * kMaxFiles; i++) {
  993. Put("key", value);
  994. ASSERT_LE(TotalTableFiles(), kMaxFiles);
  995. fprintf(stderr, "after %d: %d files\n", i + 1, TotalTableFiles());
  996. }
  997. }
  998. TEST(DBTest, SparseMerge) {
  999. Options options = CurrentOptions();
  1000. options.compression = kNoCompression;
  1001. Reopen(&options);
  1002. FillLevels("A", "Z");
  1003. // Suppose there is:
  1004. // small amount of data with prefix A
  1005. // large amount of data with prefix B
  1006. // small amount of data with prefix C
  1007. // and that recent updates have made small changes to all three prefixes.
  1008. // Check that we do not do a compaction that merges all of B in one shot.
  1009. const std::string value(1000, 'x');
  1010. Put("A", "va");
  1011. // Write approximately 100MB of "B" values
  1012. for (int i = 0; i < 100000; i++) {
  1013. char key[100];
  1014. snprintf(key, sizeof(key), "B%010d", i);
  1015. Put(key, value);
  1016. }
  1017. Put("C", "vc");
  1018. dbfull()->TEST_CompactMemTable();
  1019. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1020. // Make sparse update
  1021. Put("A", "va2");
  1022. Put("B100", "bvalue2");
  1023. Put("C", "vc2");
  1024. dbfull()->TEST_CompactMemTable();
  1025. // Compactions should not cause us to create a situation where
  1026. // a file overlaps too much data at the next level.
  1027. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  1028. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1029. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  1030. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1031. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  1032. }
  1033. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  1034. bool result = (val >= low) && (val <= high);
  1035. if (!result) {
  1036. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  1037. (unsigned long long)(val),
  1038. (unsigned long long)(low),
  1039. (unsigned long long)(high));
  1040. }
  1041. return result;
  1042. }
  1043. TEST(DBTest, ApproximateSizes) {
  1044. do {
  1045. Options options = CurrentOptions();
  1046. options.write_buffer_size = 100000000; // Large write buffer
  1047. options.compression = kNoCompression;
  1048. DestroyAndReopen();
  1049. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1050. Reopen(&options);
  1051. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  1052. // Write 8MB (80 values, each 100K)
  1053. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1054. const int N = 80;
  1055. static const int S1 = 100000;
  1056. static const int S2 = 105000; // Allow some expansion from metadata
  1057. Random rnd(301);
  1058. for (int i = 0; i < N; i++) {
  1059. ASSERT_OK(Put(Key(i), RandomString(&rnd, S1)));
  1060. }
  1061. // 0 because GetApproximateSizes() does not account for memtable space
  1062. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1063. if (options.reuse_logs) {
  1064. // Recovery will reuse memtable, and GetApproximateSizes() does not
  1065. // account for memtable usage;
  1066. Reopen(&options);
  1067. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  1068. continue;
  1069. }
  1070. // Check sizes across recovery by reopening a few times
  1071. for (int run = 0; run < 3; run++) {
  1072. Reopen(&options);
  1073. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  1074. for (int i = 0; i < N; i += 10) {
  1075. ASSERT_TRUE(Between(Size("", Key(i)), S1*i, S2*i));
  1076. ASSERT_TRUE(Between(Size("", Key(i)+".suffix"), S1*(i+1), S2*(i+1)));
  1077. ASSERT_TRUE(Between(Size(Key(i), Key(i+10)), S1*10, S2*10));
  1078. }
  1079. ASSERT_TRUE(Between(Size("", Key(50)), S1*50, S2*50));
  1080. ASSERT_TRUE(Between(Size("", Key(50)+".suffix"), S1*50, S2*50));
  1081. std::string cstart_str = Key(compact_start);
  1082. std::string cend_str = Key(compact_start + 9);
  1083. Slice cstart = cstart_str;
  1084. Slice cend = cend_str;
  1085. dbfull()->TEST_CompactRange(0, &cstart, &cend);
  1086. }
  1087. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1088. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  1089. }
  1090. } while (ChangeOptions());
  1091. }
  1092. TEST(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  1093. do {
  1094. Options options = CurrentOptions();
  1095. options.compression = kNoCompression;
  1096. Reopen();
  1097. Random rnd(301);
  1098. std::string big1 = RandomString(&rnd, 100000);
  1099. ASSERT_OK(Put(Key(0), RandomString(&rnd, 10000)));
  1100. ASSERT_OK(Put(Key(1), RandomString(&rnd, 10000)));
  1101. ASSERT_OK(Put(Key(2), big1));
  1102. ASSERT_OK(Put(Key(3), RandomString(&rnd, 10000)));
  1103. ASSERT_OK(Put(Key(4), big1));
  1104. ASSERT_OK(Put(Key(5), RandomString(&rnd, 10000)));
  1105. ASSERT_OK(Put(Key(6), RandomString(&rnd, 300000)));
  1106. ASSERT_OK(Put(Key(7), RandomString(&rnd, 10000)));
  1107. if (options.reuse_logs) {
  1108. // Need to force a memtable compaction since recovery does not do so.
  1109. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1110. }
  1111. // Check sizes across recovery by reopening a few times
  1112. for (int run = 0; run < 3; run++) {
  1113. Reopen(&options);
  1114. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  1115. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  1116. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  1117. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  1118. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  1119. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  1120. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  1121. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  1122. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 560000));
  1123. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  1124. dbfull()->TEST_CompactRange(0, nullptr, nullptr);
  1125. }
  1126. } while (ChangeOptions());
  1127. }
  1128. TEST(DBTest, IteratorPinsRef) {
  1129. Put("foo", "hello");
  1130. // Get iterator that will yield the current contents of the DB.
  1131. Iterator* iter = db_->NewIterator(ReadOptions());
  1132. // Write to force compactions
  1133. Put("foo", "newvalue1");
  1134. for (int i = 0; i < 100; i++) {
  1135. ASSERT_OK(Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  1136. }
  1137. Put("foo", "newvalue2");
  1138. iter->SeekToFirst();
  1139. ASSERT_TRUE(iter->Valid());
  1140. ASSERT_EQ("foo", iter->key().ToString());
  1141. ASSERT_EQ("hello", iter->value().ToString());
  1142. iter->Next();
  1143. ASSERT_TRUE(!iter->Valid());
  1144. delete iter;
  1145. }
  1146. TEST(DBTest, Snapshot) {
  1147. do {
  1148. Put("foo", "v1");
  1149. const Snapshot* s1 = db_->GetSnapshot();
  1150. Put("foo", "v2");
  1151. const Snapshot* s2 = db_->GetSnapshot();
  1152. Put("foo", "v3");
  1153. const Snapshot* s3 = db_->GetSnapshot();
  1154. Put("foo", "v4");
  1155. ASSERT_EQ("v1", Get("foo", s1));
  1156. ASSERT_EQ("v2", Get("foo", s2));
  1157. ASSERT_EQ("v3", Get("foo", s3));
  1158. ASSERT_EQ("v4", Get("foo"));
  1159. db_->ReleaseSnapshot(s3);
  1160. ASSERT_EQ("v1", Get("foo", s1));
  1161. ASSERT_EQ("v2", Get("foo", s2));
  1162. ASSERT_EQ("v4", Get("foo"));
  1163. db_->ReleaseSnapshot(s1);
  1164. ASSERT_EQ("v2", Get("foo", s2));
  1165. ASSERT_EQ("v4", Get("foo"));
  1166. db_->ReleaseSnapshot(s2);
  1167. ASSERT_EQ("v4", Get("foo"));
  1168. } while (ChangeOptions());
  1169. }
  1170. TEST(DBTest, HiddenValuesAreRemoved) {
  1171. do {
  1172. Random rnd(301);
  1173. FillLevels("a", "z");
  1174. std::string big = RandomString(&rnd, 50000);
  1175. Put("foo", big);
  1176. Put("pastfoo", "v");
  1177. const Snapshot* snapshot = db_->GetSnapshot();
  1178. Put("foo", "tiny");
  1179. Put("pastfoo2", "v2"); // Advance sequence number one more
  1180. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1181. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  1182. ASSERT_EQ(big, Get("foo", snapshot));
  1183. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  1184. db_->ReleaseSnapshot(snapshot);
  1185. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  1186. Slice x("x");
  1187. dbfull()->TEST_CompactRange(0, nullptr, &x);
  1188. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1189. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  1190. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  1191. dbfull()->TEST_CompactRange(1, nullptr, &x);
  1192. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  1193. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  1194. } while (ChangeOptions());
  1195. }
  1196. TEST(DBTest, DeletionMarkers1) {
  1197. Put("foo", "v1");
  1198. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1199. const int last = config::kMaxMemCompactLevel;
  1200. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1201. // Place a table at level last-1 to prevent merging with preceding mutation
  1202. Put("a", "begin");
  1203. Put("z", "end");
  1204. dbfull()->TEST_CompactMemTable();
  1205. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1206. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  1207. Delete("foo");
  1208. Put("foo", "v2");
  1209. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1210. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1211. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  1212. Slice z("z");
  1213. dbfull()->TEST_CompactRange(last-2, nullptr, &z);
  1214. // DEL eliminated, but v1 remains because we aren't compacting that level
  1215. // (DEL can be eliminated because v2 hides v1).
  1216. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  1217. dbfull()->TEST_CompactRange(last-1, nullptr, nullptr);
  1218. // Merging last-1 w/ last, so we are the base level for "foo", so
  1219. // DEL is removed. (as is v1).
  1220. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  1221. }
  1222. TEST(DBTest, DeletionMarkers2) {
  1223. Put("foo", "v1");
  1224. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  1225. const int last = config::kMaxMemCompactLevel;
  1226. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo => v1 is now in last level
  1227. // Place a table at level last-1 to prevent merging with preceding mutation
  1228. Put("a", "begin");
  1229. Put("z", "end");
  1230. dbfull()->TEST_CompactMemTable();
  1231. ASSERT_EQ(NumTableFilesAtLevel(last), 1);
  1232. ASSERT_EQ(NumTableFilesAtLevel(last-1), 1);
  1233. Delete("foo");
  1234. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1235. ASSERT_OK(dbfull()->TEST_CompactMemTable()); // Moves to level last-2
  1236. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1237. dbfull()->TEST_CompactRange(last-2, nullptr, nullptr);
  1238. // DEL kept: "last" file overlaps
  1239. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  1240. dbfull()->TEST_CompactRange(last-1, nullptr, nullptr);
  1241. // Merging last-1 w/ last, so we are the base level for "foo", so
  1242. // DEL is removed. (as is v1).
  1243. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  1244. }
  1245. TEST(DBTest, OverlapInLevel0) {
  1246. do {
  1247. ASSERT_EQ(config::kMaxMemCompactLevel, 2) << "Fix test to match config";
  1248. // Fill levels 1 and 2 to disable the pushing of new memtables to levels > 0.
  1249. ASSERT_OK(Put("100", "v100"));
  1250. ASSERT_OK(Put("999", "v999"));
  1251. dbfull()->TEST_CompactMemTable();
  1252. ASSERT_OK(Delete("100"));
  1253. ASSERT_OK(Delete("999"));
  1254. dbfull()->TEST_CompactMemTable();
  1255. ASSERT_EQ("0,1,1", FilesPerLevel());
  1256. // Make files spanning the following ranges in level-0:
  1257. // files[0] 200 .. 900
  1258. // files[1] 300 .. 500
  1259. // Note that files are sorted by smallest key.
  1260. ASSERT_OK(Put("300", "v300"));
  1261. ASSERT_OK(Put("500", "v500"));
  1262. dbfull()->TEST_CompactMemTable();
  1263. ASSERT_OK(Put("200", "v200"));
  1264. ASSERT_OK(Put("600", "v600"));
  1265. ASSERT_OK(Put("900", "v900"));
  1266. dbfull()->TEST_CompactMemTable();
  1267. ASSERT_EQ("2,1,1", FilesPerLevel());
  1268. // Compact away the placeholder files we created initially
  1269. dbfull()->TEST_CompactRange(1, nullptr, nullptr);
  1270. dbfull()->TEST_CompactRange(2, nullptr, nullptr);
  1271. ASSERT_EQ("2", FilesPerLevel());
  1272. // Do a memtable compaction. Before bug-fix, the compaction would
  1273. // not detect the overlap with level-0 files and would incorrectly place
  1274. // the deletion in a deeper level.
  1275. ASSERT_OK(Delete("600"));
  1276. dbfull()->TEST_CompactMemTable();
  1277. ASSERT_EQ("3", FilesPerLevel());
  1278. ASSERT_EQ("NOT_FOUND", Get("600"));
  1279. } while (ChangeOptions());
  1280. }
  1281. TEST(DBTest, L0_CompactionBug_Issue44_a) {
  1282. Reopen();
  1283. ASSERT_OK(Put("b", "v"));
  1284. Reopen();
  1285. ASSERT_OK(Delete("b"));
  1286. ASSERT_OK(Delete("a"));
  1287. Reopen();
  1288. ASSERT_OK(Delete("a"));
  1289. Reopen();
  1290. ASSERT_OK(Put("a", "v"));
  1291. Reopen();
  1292. Reopen();
  1293. ASSERT_EQ("(a->v)", Contents());
  1294. DelayMilliseconds(1000); // Wait for compaction to finish
  1295. ASSERT_EQ("(a->v)", Contents());
  1296. }
  1297. TEST(DBTest, L0_CompactionBug_Issue44_b) {
  1298. Reopen();
  1299. Put("", "");
  1300. Reopen();
  1301. Delete("e");
  1302. Put("", "");
  1303. Reopen();
  1304. Put("c", "cv");
  1305. Reopen();
  1306. Put("", "");
  1307. Reopen();
  1308. Put("", "");
  1309. DelayMilliseconds(1000); // Wait for compaction to finish
  1310. Reopen();
  1311. Put("d", "dv");
  1312. Reopen();
  1313. Put("", "");
  1314. Reopen();
  1315. Delete("d");
  1316. Delete("b");
  1317. Reopen();
  1318. ASSERT_EQ("(->)(c->cv)", Contents());
  1319. DelayMilliseconds(1000); // Wait for compaction to finish
  1320. ASSERT_EQ("(->)(c->cv)", Contents());
  1321. }
  1322. TEST(DBTest, Fflush_Issue474) {
  1323. static const int kNum = 100000;
  1324. Random rnd(test::RandomSeed());
  1325. for (int i = 0; i < kNum; i++) {
  1326. fflush(nullptr);
  1327. ASSERT_OK(Put(RandomKey(&rnd), RandomString(&rnd, 100)));
  1328. }
  1329. }
  1330. TEST(DBTest, ComparatorCheck) {
  1331. class NewComparator : public Comparator {
  1332. public:
  1333. virtual const char* Name() const { return "leveldb.NewComparator"; }
  1334. virtual int Compare(const Slice& a, const Slice& b) const {
  1335. return BytewiseComparator()->Compare(a, b);
  1336. }
  1337. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  1338. BytewiseComparator()->FindShortestSeparator(s, l);
  1339. }
  1340. virtual void FindShortSuccessor(std::string* key) const {
  1341. BytewiseComparator()->FindShortSuccessor(key);
  1342. }
  1343. };
  1344. NewComparator cmp;
  1345. Options new_options = CurrentOptions();
  1346. new_options.comparator = &cmp;
  1347. Status s = TryReopen(&new_options);
  1348. ASSERT_TRUE(!s.ok());
  1349. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  1350. << s.ToString();
  1351. }
  1352. TEST(DBTest, CustomComparator) {
  1353. class NumberComparator : public Comparator {
  1354. public:
  1355. virtual const char* Name() const { return "test.NumberComparator"; }
  1356. virtual int Compare(const Slice& a, const Slice& b) const {
  1357. return ToNumber(a) - ToNumber(b);
  1358. }
  1359. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  1360. ToNumber(*s); // Check format
  1361. ToNumber(l); // Check format
  1362. }
  1363. virtual void FindShortSuccessor(std::string* key) const {
  1364. ToNumber(*key); // Check format
  1365. }
  1366. private:
  1367. static int ToNumber(const Slice& x) {
  1368. // Check that there are no extra characters.
  1369. ASSERT_TRUE(x.size() >= 2 && x[0] == '[' && x[x.size()-1] == ']')
  1370. << EscapeString(x);
  1371. int val;
  1372. char ignored;
  1373. ASSERT_TRUE(sscanf(x.ToString().c_str(), "[%i]%c", &val, &ignored) == 1)
  1374. << EscapeString(x);
  1375. return val;
  1376. }
  1377. };
  1378. NumberComparator cmp;
  1379. Options new_options = CurrentOptions();
  1380. new_options.create_if_missing = true;
  1381. new_options.comparator = &cmp;
  1382. new_options.filter_policy = nullptr; // Cannot use bloom filters
  1383. new_options.write_buffer_size = 1000; // Compact more often
  1384. DestroyAndReopen(&new_options);
  1385. ASSERT_OK(Put("[10]", "ten"));
  1386. ASSERT_OK(Put("[0x14]", "twenty"));
  1387. for (int i = 0; i < 2; i++) {
  1388. ASSERT_EQ("ten", Get("[10]"));
  1389. ASSERT_EQ("ten", Get("[0xa]"));
  1390. ASSERT_EQ("twenty", Get("[20]"));
  1391. ASSERT_EQ("twenty", Get("[0x14]"));
  1392. ASSERT_EQ("NOT_FOUND", Get("[15]"));
  1393. ASSERT_EQ("NOT_FOUND", Get("[0xf]"));
  1394. Compact("[0]", "[9999]");
  1395. }
  1396. for (int run = 0; run < 2; run++) {
  1397. for (int i = 0; i < 1000; i++) {
  1398. char buf[100];
  1399. snprintf(buf, sizeof(buf), "[%d]", i*10);
  1400. ASSERT_OK(Put(buf, buf));
  1401. }
  1402. Compact("[0]", "[1000000]");
  1403. }
  1404. }
  1405. TEST(DBTest, ManualCompaction) {
  1406. ASSERT_EQ(config::kMaxMemCompactLevel, 2)
  1407. << "Need to update this test to match kMaxMemCompactLevel";
  1408. MakeTables(3, "p", "q");
  1409. ASSERT_EQ("1,1,1", FilesPerLevel());
  1410. // Compaction range falls before files
  1411. Compact("", "c");
  1412. ASSERT_EQ("1,1,1", FilesPerLevel());
  1413. // Compaction range falls after files
  1414. Compact("r", "z");
  1415. ASSERT_EQ("1,1,1", FilesPerLevel());
  1416. // Compaction range overlaps files
  1417. Compact("p1", "p9");
  1418. ASSERT_EQ("0,0,1", FilesPerLevel());
  1419. // Populate a different range
  1420. MakeTables(3, "c", "e");
  1421. ASSERT_EQ("1,1,2", FilesPerLevel());
  1422. // Compact just the new range
  1423. Compact("b", "f");
  1424. ASSERT_EQ("0,0,2", FilesPerLevel());
  1425. // Compact all
  1426. MakeTables(1, "a", "z");
  1427. ASSERT_EQ("0,1,2", FilesPerLevel());
  1428. db_->CompactRange(nullptr, nullptr);
  1429. ASSERT_EQ("0,0,1", FilesPerLevel());
  1430. }
  1431. TEST(DBTest, DBOpen_Options) {
  1432. std::string dbname = test::TmpDir() + "/db_options_test";
  1433. DestroyDB(dbname, Options());
  1434. // Does not exist, and create_if_missing == false: error
  1435. DB* db = nullptr;
  1436. Options opts;
  1437. opts.create_if_missing = false;
  1438. Status s = DB::Open(opts, dbname, &db);
  1439. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != nullptr);
  1440. ASSERT_TRUE(db == nullptr);
  1441. // Does not exist, and create_if_missing == true: OK
  1442. opts.create_if_missing = true;
  1443. s = DB::Open(opts, dbname, &db);
  1444. ASSERT_OK(s);
  1445. ASSERT_TRUE(db != nullptr);
  1446. delete db;
  1447. db = nullptr;
  1448. // Does exist, and error_if_exists == true: error
  1449. opts.create_if_missing = false;
  1450. opts.error_if_exists = true;
  1451. s = DB::Open(opts, dbname, &db);
  1452. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != nullptr);
  1453. ASSERT_TRUE(db == nullptr);
  1454. // Does exist, and error_if_exists == false: OK
  1455. opts.create_if_missing = true;
  1456. opts.error_if_exists = false;
  1457. s = DB::Open(opts, dbname, &db);
  1458. ASSERT_OK(s);
  1459. ASSERT_TRUE(db != nullptr);
  1460. delete db;
  1461. db = nullptr;
  1462. }
  1463. TEST(DBTest, DestroyEmptyDir) {
  1464. std::string dbname = test::TmpDir() + "/db_empty_dir";
  1465. TestEnv env(Env::Default());
  1466. env.DeleteDir(dbname);
  1467. ASSERT_TRUE(!env.FileExists(dbname));
  1468. Options opts;
  1469. opts.env = &env;
  1470. ASSERT_OK(env.CreateDir(dbname));
  1471. ASSERT_TRUE(env.FileExists(dbname));
  1472. std::vector<std::string> children;
  1473. ASSERT_OK(env.GetChildren(dbname, &children));
  1474. // The stock Env's do not filter out '.' and '..' special files.
  1475. ASSERT_EQ(2, children.size());
  1476. ASSERT_OK(DestroyDB(dbname, opts));
  1477. ASSERT_TRUE(!env.FileExists(dbname));
  1478. // Should also be destroyed if Env is filtering out dot files.
  1479. env.SetIgnoreDotFiles(true);
  1480. ASSERT_OK(env.CreateDir(dbname));
  1481. ASSERT_TRUE(env.FileExists(dbname));
  1482. ASSERT_OK(env.GetChildren(dbname, &children));
  1483. ASSERT_EQ(0, children.size());
  1484. ASSERT_OK(DestroyDB(dbname, opts));
  1485. ASSERT_TRUE(!env.FileExists(dbname));
  1486. }
  1487. TEST(DBTest, DestroyOpenDB) {
  1488. std::string dbname = test::TmpDir() + "/open_db_dir";
  1489. env_->DeleteDir(dbname);
  1490. ASSERT_TRUE(!env_->FileExists(dbname));
  1491. Options opts;
  1492. opts.create_if_missing = true;
  1493. DB* db = nullptr;
  1494. ASSERT_OK(DB::Open(opts, dbname, &db));
  1495. ASSERT_TRUE(db != nullptr);
  1496. // Must fail to destroy an open db.
  1497. ASSERT_TRUE(env_->FileExists(dbname));
  1498. ASSERT_TRUE(!DestroyDB(dbname, Options()).ok());
  1499. ASSERT_TRUE(env_->FileExists(dbname));
  1500. delete db;
  1501. db = nullptr;
  1502. // Should succeed destroying a closed db.
  1503. ASSERT_OK(DestroyDB(dbname, Options()));
  1504. ASSERT_TRUE(!env_->FileExists(dbname));
  1505. }
  1506. TEST(DBTest, Locking) {
  1507. DB* db2 = nullptr;
  1508. Status s = DB::Open(CurrentOptions(), dbname_, &db2);
  1509. ASSERT_TRUE(!s.ok()) << "Locking did not prevent re-opening db";
  1510. }
  1511. // Check that number of files does not grow when we are out of space
  1512. TEST(DBTest, NoSpace) {
  1513. Options options = CurrentOptions();
  1514. options.env = env_;
  1515. Reopen(&options);
  1516. ASSERT_OK(Put("foo", "v1"));
  1517. ASSERT_EQ("v1", Get("foo"));
  1518. Compact("a", "z");
  1519. const int num_files = CountFiles();
  1520. // Force out-of-space errors.
  1521. env_->no_space_.store(true, std::memory_order_release);
  1522. for (int i = 0; i < 10; i++) {
  1523. for (int level = 0; level < config::kNumLevels-1; level++) {
  1524. dbfull()->TEST_CompactRange(level, nullptr, nullptr);
  1525. }
  1526. }
  1527. env_->no_space_.store(false, std::memory_order_release);
  1528. ASSERT_LT(CountFiles(), num_files + 3);
  1529. }
  1530. TEST(DBTest, NonWritableFileSystem) {
  1531. Options options = CurrentOptions();
  1532. options.write_buffer_size = 1000;
  1533. options.env = env_;
  1534. Reopen(&options);
  1535. ASSERT_OK(Put("foo", "v1"));
  1536. // Force errors for new files.
  1537. env_->non_writable_.store(true, std::memory_order_release);
  1538. std::string big(100000, 'x');
  1539. int errors = 0;
  1540. for (int i = 0; i < 20; i++) {
  1541. fprintf(stderr, "iter %d; errors %d\n", i, errors);
  1542. if (!Put("foo", big).ok()) {
  1543. errors++;
  1544. DelayMilliseconds(100);
  1545. }
  1546. }
  1547. ASSERT_GT(errors, 0);
  1548. env_->non_writable_.store(false, std::memory_order_release);
  1549. }
  1550. TEST(DBTest, WriteSyncError) {
  1551. // Check that log sync errors cause the DB to disallow future writes.
  1552. // (a) Cause log sync calls to fail
  1553. Options options = CurrentOptions();
  1554. options.env = env_;
  1555. Reopen(&options);
  1556. env_->data_sync_error_.store(true, std::memory_order_release);
  1557. // (b) Normal write should succeed
  1558. WriteOptions w;
  1559. ASSERT_OK(db_->Put(w, "k1", "v1"));
  1560. ASSERT_EQ("v1", Get("k1"));
  1561. // (c) Do a sync write; should fail
  1562. w.sync = true;
  1563. ASSERT_TRUE(!db_->Put(w, "k2", "v2").ok());
  1564. ASSERT_EQ("v1", Get("k1"));
  1565. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1566. // (d) make sync behave normally
  1567. env_->data_sync_error_.store(false, std::memory_order_release);
  1568. // (e) Do a non-sync write; should fail
  1569. w.sync = false;
  1570. ASSERT_TRUE(!db_->Put(w, "k3", "v3").ok());
  1571. ASSERT_EQ("v1", Get("k1"));
  1572. ASSERT_EQ("NOT_FOUND", Get("k2"));
  1573. ASSERT_EQ("NOT_FOUND", Get("k3"));
  1574. }
  1575. TEST(DBTest, ManifestWriteError) {
  1576. // Test for the following problem:
  1577. // (a) Compaction produces file F
  1578. // (b) Log record containing F is written to MANIFEST file, but Sync() fails
  1579. // (c) GC deletes F
  1580. // (d) After reopening DB, reads fail since deleted F is named in log record
  1581. // We iterate twice. In the second iteration, everything is the
  1582. // same except the log record never makes it to the MANIFEST file.
  1583. for (int iter = 0; iter < 2; iter++) {
  1584. std::atomic<bool>* error_type = (iter == 0)
  1585. ? &env_->manifest_sync_error_
  1586. : &env_->manifest_write_error_;
  1587. // Insert foo=>bar mapping
  1588. Options options = CurrentOptions();
  1589. options.env = env_;
  1590. options.create_if_missing = true;
  1591. options.error_if_exists = false;
  1592. DestroyAndReopen(&options);
  1593. ASSERT_OK(Put("foo", "bar"));
  1594. ASSERT_EQ("bar", Get("foo"));
  1595. // Memtable compaction (will succeed)
  1596. dbfull()->TEST_CompactMemTable();
  1597. ASSERT_EQ("bar", Get("foo"));
  1598. const int last = config::kMaxMemCompactLevel;
  1599. ASSERT_EQ(NumTableFilesAtLevel(last), 1); // foo=>bar is now in last level
  1600. // Merging compaction (will fail)
  1601. error_type->store(true, std::memory_order_release);
  1602. dbfull()->TEST_CompactRange(last, nullptr, nullptr); // Should fail
  1603. ASSERT_EQ("bar", Get("foo"));
  1604. // Recovery: should not lose data
  1605. error_type->store(false, std::memory_order_release);
  1606. Reopen(&options);
  1607. ASSERT_EQ("bar", Get("foo"));
  1608. }
  1609. }
  1610. TEST(DBTest, MissingSSTFile) {
  1611. ASSERT_OK(Put("foo", "bar"));
  1612. ASSERT_EQ("bar", Get("foo"));
  1613. // Dump the memtable to disk.
  1614. dbfull()->TEST_CompactMemTable();
  1615. ASSERT_EQ("bar", Get("foo"));
  1616. Close();
  1617. ASSERT_TRUE(DeleteAnSSTFile());
  1618. Options options = CurrentOptions();
  1619. options.paranoid_checks = true;
  1620. Status s = TryReopen(&options);
  1621. ASSERT_TRUE(!s.ok());
  1622. ASSERT_TRUE(s.ToString().find("issing") != std::string::npos)
  1623. << s.ToString();
  1624. }
  1625. TEST(DBTest, StillReadSST) {
  1626. ASSERT_OK(Put("foo", "bar"));
  1627. ASSERT_EQ("bar", Get("foo"));
  1628. // Dump the memtable to disk.
  1629. dbfull()->TEST_CompactMemTable();
  1630. ASSERT_EQ("bar", Get("foo"));
  1631. Close();
  1632. ASSERT_GT(RenameLDBToSST(), 0);
  1633. Options options = CurrentOptions();
  1634. options.paranoid_checks = true;
  1635. Status s = TryReopen(&options);
  1636. ASSERT_TRUE(s.ok());
  1637. ASSERT_EQ("bar", Get("foo"));
  1638. }
  1639. TEST(DBTest, FilesDeletedAfterCompaction) {
  1640. ASSERT_OK(Put("foo", "v2"));
  1641. Compact("a", "z");
  1642. const int num_files = CountFiles();
  1643. for (int i = 0; i < 10; i++) {
  1644. ASSERT_OK(Put("foo", "v2"));
  1645. Compact("a", "z");
  1646. }
  1647. ASSERT_EQ(CountFiles(), num_files);
  1648. }
  1649. TEST(DBTest, BloomFilter) {
  1650. env_->count_random_reads_ = true;
  1651. Options options = CurrentOptions();
  1652. options.env = env_;
  1653. options.block_cache = NewLRUCache(0); // Prevent cache hits
  1654. options.filter_policy = NewBloomFilterPolicy(10);
  1655. Reopen(&options);
  1656. // Populate multiple layers
  1657. const int N = 10000;
  1658. for (int i = 0; i < N; i++) {
  1659. ASSERT_OK(Put(Key(i), Key(i)));
  1660. }
  1661. Compact("a", "z");
  1662. for (int i = 0; i < N; i += 100) {
  1663. ASSERT_OK(Put(Key(i), Key(i)));
  1664. }
  1665. dbfull()->TEST_CompactMemTable();
  1666. // Prevent auto compactions triggered by seeks
  1667. env_->delay_data_sync_.store(true, std::memory_order_release);
  1668. // Lookup present keys. Should rarely read from small sstable.
  1669. env_->random_read_counter_.Reset();
  1670. for (int i = 0; i < N; i++) {
  1671. ASSERT_EQ(Key(i), Get(Key(i)));
  1672. }
  1673. int reads = env_->random_read_counter_.Read();
  1674. fprintf(stderr, "%d present => %d reads\n", N, reads);
  1675. ASSERT_GE(reads, N);
  1676. ASSERT_LE(reads, N + 2*N/100);
  1677. // Lookup present keys. Should rarely read from either sstable.
  1678. env_->random_read_counter_.Reset();
  1679. for (int i = 0; i < N; i++) {
  1680. ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
  1681. }
  1682. reads = env_->random_read_counter_.Read();
  1683. fprintf(stderr, "%d missing => %d reads\n", N, reads);
  1684. ASSERT_LE(reads, 3*N/100);
  1685. env_->delay_data_sync_.store(false, std::memory_order_release);
  1686. Close();
  1687. delete options.block_cache;
  1688. delete options.filter_policy;
  1689. }
  1690. // Multi-threaded test:
  1691. namespace {
  1692. static const int kNumThreads = 4;
  1693. static const int kTestSeconds = 10;
  1694. static const int kNumKeys = 1000;
  1695. struct MTState {
  1696. DBTest* test;
  1697. std::atomic<bool> stop;
  1698. std::atomic<int> counter[kNumThreads];
  1699. std::atomic<bool> thread_done[kNumThreads];
  1700. };
  1701. struct MTThread {
  1702. MTState* state;
  1703. int id;
  1704. };
  1705. static void MTThreadBody(void* arg) {
  1706. MTThread* t = reinterpret_cast<MTThread*>(arg);
  1707. int id = t->id;
  1708. DB* db = t->state->test->db_;
  1709. int counter = 0;
  1710. fprintf(stderr, "... starting thread %d\n", id);
  1711. Random rnd(1000 + id);
  1712. std::string value;
  1713. char valbuf[1500];
  1714. while (!t->state->stop.load(std::memory_order_acquire)) {
  1715. t->state->counter[id].store(counter, std::memory_order_release);
  1716. int key = rnd.Uniform(kNumKeys);
  1717. char keybuf[20];
  1718. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  1719. if (rnd.OneIn(2)) {
  1720. // Write values of the form <key, my id, counter>.
  1721. // We add some padding for force compactions.
  1722. snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d",
  1723. key, id, static_cast<int>(counter));
  1724. ASSERT_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
  1725. } else {
  1726. // Read a value and verify that it matches the pattern written above.
  1727. Status s = db->Get(ReadOptions(), Slice(keybuf), &value);
  1728. if (s.IsNotFound()) {
  1729. // Key has not yet been written
  1730. } else {
  1731. // Check that the writer thread counter is >= the counter in the value
  1732. ASSERT_OK(s);
  1733. int k, w, c;
  1734. ASSERT_EQ(3, sscanf(value.c_str(), "%d.%d.%d", &k, &w, &c)) << value;
  1735. ASSERT_EQ(k, key);
  1736. ASSERT_GE(w, 0);
  1737. ASSERT_LT(w, kNumThreads);
  1738. ASSERT_LE(c, t->state->counter[w].load(std::memory_order_acquire));
  1739. }
  1740. }
  1741. counter++;
  1742. }
  1743. t->state->thread_done[id].store(true, std::memory_order_release);
  1744. fprintf(stderr, "... stopping thread %d after %d ops\n", id, counter);
  1745. }
  1746. } // namespace
  1747. TEST(DBTest, MultiThreaded) {
  1748. do {
  1749. // Initialize state
  1750. MTState mt;
  1751. mt.test = this;
  1752. mt.stop.store(false, std::memory_order_release);
  1753. for (int id = 0; id < kNumThreads; id++) {
  1754. mt.counter[id].store(false, std::memory_order_release);
  1755. mt.thread_done[id].store(false, std::memory_order_release);
  1756. }
  1757. // Start threads
  1758. MTThread thread[kNumThreads];
  1759. for (int id = 0; id < kNumThreads; id++) {
  1760. thread[id].state = &mt;
  1761. thread[id].id = id;
  1762. env_->StartThread(MTThreadBody, &thread[id]);
  1763. }
  1764. // Let them run for a while
  1765. DelayMilliseconds(kTestSeconds * 1000);
  1766. // Stop the threads and wait for them to finish
  1767. mt.stop.store(true, std::memory_order_release);
  1768. for (int id = 0; id < kNumThreads; id++) {
  1769. while (!mt.thread_done[id].load(std::memory_order_acquire)) {
  1770. DelayMilliseconds(100);
  1771. }
  1772. }
  1773. } while (ChangeOptions());
  1774. }
  1775. namespace {
  1776. typedef std::map<std::string, std::string> KVMap;
  1777. }
  1778. class ModelDB: public DB {
  1779. public:
  1780. class ModelSnapshot : public Snapshot {
  1781. public:
  1782. KVMap map_;
  1783. };
  1784. explicit ModelDB(const Options& options): options_(options) { }
  1785. ~ModelDB() { }
  1786. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  1787. return DB::Put(o, k, v);
  1788. }
  1789. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  1790. return DB::Delete(o, key);
  1791. }
  1792. virtual Status Get(const ReadOptions& options,
  1793. const Slice& key, std::string* value) {
  1794. assert(false); // Not implemented
  1795. return Status::NotFound(key);
  1796. }
  1797. virtual Iterator* NewIterator(const ReadOptions& options) {
  1798. if (options.snapshot == nullptr) {
  1799. KVMap* saved = new KVMap;
  1800. *saved = map_;
  1801. return new ModelIter(saved, true);
  1802. } else {
  1803. const KVMap* snapshot_state =
  1804. &(reinterpret_cast<const ModelSnapshot*>(options.snapshot)->map_);
  1805. return new ModelIter(snapshot_state, false);
  1806. }
  1807. }
  1808. virtual const Snapshot* GetSnapshot() {
  1809. ModelSnapshot* snapshot = new ModelSnapshot;
  1810. snapshot->map_ = map_;
  1811. return snapshot;
  1812. }
  1813. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  1814. delete reinterpret_cast<const ModelSnapshot*>(snapshot);
  1815. }
  1816. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  1817. class Handler : public WriteBatch::Handler {
  1818. public:
  1819. KVMap* map_;
  1820. virtual void Put(const Slice& key, const Slice& value) {
  1821. (*map_)[key.ToString()] = value.ToString();
  1822. }
  1823. virtual void Delete(const Slice& key) {
  1824. map_->erase(key.ToString());
  1825. }
  1826. };
  1827. Handler handler;
  1828. handler.map_ = &map_;
  1829. return batch->Iterate(&handler);
  1830. }
  1831. virtual bool GetProperty(const Slice& property, std::string* value) {
  1832. return false;
  1833. }
  1834. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  1835. for (int i = 0; i < n; i++) {
  1836. sizes[i] = 0;
  1837. }
  1838. }
  1839. virtual void CompactRange(const Slice* start, const Slice* end) {
  1840. }
  1841. private:
  1842. class ModelIter: public Iterator {
  1843. public:
  1844. ModelIter(const KVMap* map, bool owned)
  1845. : map_(map), owned_(owned), iter_(map_->end()) {
  1846. }
  1847. ~ModelIter() {
  1848. if (owned_) delete map_;
  1849. }
  1850. virtual bool Valid() const { return iter_ != map_->end(); }
  1851. virtual void SeekToFirst() { iter_ = map_->begin(); }
  1852. virtual void SeekToLast() {
  1853. if (map_->empty()) {
  1854. iter_ = map_->end();
  1855. } else {
  1856. iter_ = map_->find(map_->rbegin()->first);
  1857. }
  1858. }
  1859. virtual void Seek(const Slice& k) {
  1860. iter_ = map_->lower_bound(k.ToString());
  1861. }
  1862. virtual void Next() { ++iter_; }
  1863. virtual void Prev() { --iter_; }
  1864. virtual Slice key() const { return iter_->first; }
  1865. virtual Slice value() const { return iter_->second; }
  1866. virtual Status status() const { return Status::OK(); }
  1867. private:
  1868. const KVMap* const map_;
  1869. const bool owned_; // Do we own map_
  1870. KVMap::const_iterator iter_;
  1871. };
  1872. const Options options_;
  1873. KVMap map_;
  1874. };
  1875. static bool CompareIterators(int step,
  1876. DB* model,
  1877. DB* db,
  1878. const Snapshot* model_snap,
  1879. const Snapshot* db_snap) {
  1880. ReadOptions options;
  1881. options.snapshot = model_snap;
  1882. Iterator* miter = model->NewIterator(options);
  1883. options.snapshot = db_snap;
  1884. Iterator* dbiter = db->NewIterator(options);
  1885. bool ok = true;
  1886. int count = 0;
  1887. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  1888. ok && miter->Valid() && dbiter->Valid();
  1889. miter->Next(), dbiter->Next()) {
  1890. count++;
  1891. if (miter->key().compare(dbiter->key()) != 0) {
  1892. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  1893. step,
  1894. EscapeString(miter->key()).c_str(),
  1895. EscapeString(dbiter->key()).c_str());
  1896. ok = false;
  1897. break;
  1898. }
  1899. if (miter->value().compare(dbiter->value()) != 0) {
  1900. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  1901. step,
  1902. EscapeString(miter->key()).c_str(),
  1903. EscapeString(miter->value()).c_str(),
  1904. EscapeString(miter->value()).c_str());
  1905. ok = false;
  1906. }
  1907. }
  1908. if (ok) {
  1909. if (miter->Valid() != dbiter->Valid()) {
  1910. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  1911. step, miter->Valid(), dbiter->Valid());
  1912. ok = false;
  1913. }
  1914. }
  1915. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  1916. delete miter;
  1917. delete dbiter;
  1918. return ok;
  1919. }
  1920. TEST(DBTest, Randomized) {
  1921. Random rnd(test::RandomSeed());
  1922. do {
  1923. ModelDB model(CurrentOptions());
  1924. const int N = 10000;
  1925. const Snapshot* model_snap = nullptr;
  1926. const Snapshot* db_snap = nullptr;
  1927. std::string k, v;
  1928. for (int step = 0; step < N; step++) {
  1929. if (step % 100 == 0) {
  1930. fprintf(stderr, "Step %d of %d\n", step, N);
  1931. }
  1932. // TODO(sanjay): Test Get() works
  1933. int p = rnd.Uniform(100);
  1934. if (p < 45) { // Put
  1935. k = RandomKey(&rnd);
  1936. v = RandomString(&rnd,
  1937. rnd.OneIn(20)
  1938. ? 100 + rnd.Uniform(100)
  1939. : rnd.Uniform(8));
  1940. ASSERT_OK(model.Put(WriteOptions(), k, v));
  1941. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  1942. } else if (p < 90) { // Delete
  1943. k = RandomKey(&rnd);
  1944. ASSERT_OK(model.Delete(WriteOptions(), k));
  1945. ASSERT_OK(db_->Delete(WriteOptions(), k));
  1946. } else { // Multi-element batch
  1947. WriteBatch b;
  1948. const int num = rnd.Uniform(8);
  1949. for (int i = 0; i < num; i++) {
  1950. if (i == 0 || !rnd.OneIn(10)) {
  1951. k = RandomKey(&rnd);
  1952. } else {
  1953. // Periodically re-use the same key from the previous iter, so
  1954. // we have multiple entries in the write batch for the same key
  1955. }
  1956. if (rnd.OneIn(2)) {
  1957. v = RandomString(&rnd, rnd.Uniform(10));
  1958. b.Put(k, v);
  1959. } else {
  1960. b.Delete(k);
  1961. }
  1962. }
  1963. ASSERT_OK(model.Write(WriteOptions(), &b));
  1964. ASSERT_OK(db_->Write(WriteOptions(), &b));
  1965. }
  1966. if ((step % 100) == 0) {
  1967. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  1968. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  1969. // Save a snapshot from each DB this time that we'll use next
  1970. // time we compare things, to make sure the current state is
  1971. // preserved with the snapshot
  1972. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  1973. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  1974. Reopen();
  1975. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  1976. model_snap = model.GetSnapshot();
  1977. db_snap = db_->GetSnapshot();
  1978. }
  1979. }
  1980. if (model_snap != nullptr) model.ReleaseSnapshot(model_snap);
  1981. if (db_snap != nullptr) db_->ReleaseSnapshot(db_snap);
  1982. } while (ChangeOptions());
  1983. }
  1984. std::string MakeKey(unsigned int num) {
  1985. char buf[30];
  1986. snprintf(buf, sizeof(buf), "%016u", num);
  1987. return std::string(buf);
  1988. }
  1989. void BM_LogAndApply(int iters, int num_base_files) {
  1990. std::string dbname = test::TmpDir() + "/leveldb_test_benchmark";
  1991. DestroyDB(dbname, Options());
  1992. DB* db = nullptr;
  1993. Options opts;
  1994. opts.create_if_missing = true;
  1995. Status s = DB::Open(opts, dbname, &db);
  1996. ASSERT_OK(s);
  1997. ASSERT_TRUE(db != nullptr);
  1998. delete db;
  1999. db = nullptr;
  2000. Env* env = Env::Default();
  2001. port::Mutex mu;
  2002. MutexLock l(&mu);
  2003. InternalKeyComparator cmp(BytewiseComparator());
  2004. Options options;
  2005. VersionSet vset(dbname, &options, nullptr, &cmp);
  2006. bool save_manifest;
  2007. ASSERT_OK(vset.Recover(&save_manifest));
  2008. VersionEdit vbase;
  2009. uint64_t fnum = 1;
  2010. for (int i = 0; i < num_base_files; i++) {
  2011. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  2012. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  2013. vbase.AddFile(2, fnum++, 1 /* file size */, start, limit);
  2014. }
  2015. ASSERT_OK(vset.LogAndApply(&vbase, &mu));
  2016. uint64_t start_micros = env->NowMicros();
  2017. for (int i = 0; i < iters; i++) {
  2018. VersionEdit vedit;
  2019. vedit.DeleteFile(2, fnum);
  2020. InternalKey start(MakeKey(2*fnum), 1, kTypeValue);
  2021. InternalKey limit(MakeKey(2*fnum+1), 1, kTypeDeletion);
  2022. vedit.AddFile(2, fnum++, 1 /* file size */, start, limit);
  2023. vset.LogAndApply(&vedit, &mu);
  2024. }
  2025. uint64_t stop_micros = env->NowMicros();
  2026. unsigned int us = stop_micros - start_micros;
  2027. char buf[16];
  2028. snprintf(buf, sizeof(buf), "%d", num_base_files);
  2029. fprintf(stderr,
  2030. "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
  2031. buf, iters, us, ((float)us) / iters);
  2032. }
  2033. } // namespace leveldb
  2034. int main(int argc, char** argv) {
  2035. if (argc > 1 && std::string(argv[1]) == "--benchmark") {
  2036. leveldb::BM_LogAndApply(1000, 1);
  2037. leveldb::BM_LogAndApply(1000, 100);
  2038. leveldb::BM_LogAndApply(1000, 10000);
  2039. leveldb::BM_LogAndApply(100, 100000);
  2040. return 0;
  2041. }
  2042. return leveldb::test::RunAllTests();
  2043. }