作者: 韩晨旭 10225101440 李畅 10225102463
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

2167 строки
62 KiB

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