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

1287 lines
40 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "db/version_set.h"
  5. #include <algorithm>
  6. #include <stdio.h>
  7. #include "db/filename.h"
  8. #include "db/log_reader.h"
  9. #include "db/log_writer.h"
  10. #include "db/memtable.h"
  11. #include "db/table_cache.h"
  12. #include "leveldb/env.h"
  13. #include "leveldb/table_builder.h"
  14. #include "table/merger.h"
  15. #include "table/two_level_iterator.h"
  16. #include "util/coding.h"
  17. #include "util/logging.h"
  18. namespace leveldb {
  19. static const int kTargetFileSize = 2 * 1048576;
  20. // Maximum bytes of overlaps in grandparent (i.e., level+2) before we
  21. // stop building a single file in a level->level+1 compaction.
  22. static const int64_t kMaxGrandParentOverlapBytes = 10 * kTargetFileSize;
  23. static double MaxBytesForLevel(int level) {
  24. // Note: the result for level zero is not really used since we set
  25. // the level-0 compaction threshold based on number of files.
  26. double result = 10 * 1048576.0; // Result for both level-0 and level-1
  27. while (level > 1) {
  28. result *= 10;
  29. level--;
  30. }
  31. return result;
  32. }
  33. static uint64_t MaxFileSizeForLevel(int level) {
  34. return kTargetFileSize; // We could vary per level to reduce number of files?
  35. }
  36. namespace {
  37. std::string IntSetToString(const std::set<uint64_t>& s) {
  38. std::string result = "{";
  39. for (std::set<uint64_t>::const_iterator it = s.begin();
  40. it != s.end();
  41. ++it) {
  42. result += (result.size() > 1) ? "," : "";
  43. result += NumberToString(*it);
  44. }
  45. result += "}";
  46. return result;
  47. }
  48. }
  49. Version::~Version() {
  50. assert(refs_ == 0);
  51. // Remove from linked list
  52. prev_->next_ = next_;
  53. next_->prev_ = prev_;
  54. // Drop references to files
  55. for (int level = 0; level < config::kNumLevels; level++) {
  56. for (size_t i = 0; i < files_[level].size(); i++) {
  57. FileMetaData* f = files_[level][i];
  58. assert(f->refs > 0);
  59. f->refs--;
  60. if (f->refs <= 0) {
  61. delete f;
  62. }
  63. }
  64. }
  65. }
  66. int FindFile(const InternalKeyComparator& icmp,
  67. const std::vector<FileMetaData*>& files,
  68. const Slice& key) {
  69. uint32_t left = 0;
  70. uint32_t right = files.size();
  71. while (left < right) {
  72. uint32_t mid = (left + right) / 2;
  73. const FileMetaData* f = files[mid];
  74. if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) {
  75. // Key at "mid.largest" is < "target". Therefore all
  76. // files at or before "mid" are uninteresting.
  77. left = mid + 1;
  78. } else {
  79. // Key at "mid.largest" is >= "target". Therefore all files
  80. // after "mid" are uninteresting.
  81. right = mid;
  82. }
  83. }
  84. return right;
  85. }
  86. bool SomeFileOverlapsRange(
  87. const InternalKeyComparator& icmp,
  88. const std::vector<FileMetaData*>& files,
  89. const Slice& smallest_user_key,
  90. const Slice& largest_user_key) {
  91. // Find the earliest possible internal key for smallest_user_key
  92. InternalKey small(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
  93. const uint32_t index = FindFile(icmp, files, small.Encode());
  94. return ((index < files.size()) &&
  95. icmp.user_comparator()->Compare(
  96. largest_user_key, files[index]->smallest.user_key()) >= 0);
  97. }
  98. // An internal iterator. For a given version/level pair, yields
  99. // information about the files in the level. For a given entry, key()
  100. // is the largest key that occurs in the file, and value() is an
  101. // 16-byte value containing the file number and file size, both
  102. // encoded using EncodeFixed64.
  103. class Version::LevelFileNumIterator : public Iterator {
  104. public:
  105. LevelFileNumIterator(const InternalKeyComparator& icmp,
  106. const std::vector<FileMetaData*>* flist)
  107. : icmp_(icmp),
  108. flist_(flist),
  109. index_(flist->size()) { // Marks as invalid
  110. }
  111. virtual bool Valid() const {
  112. return index_ < flist_->size();
  113. }
  114. virtual void Seek(const Slice& target) {
  115. index_ = FindFile(icmp_, *flist_, target);
  116. }
  117. virtual void SeekToFirst() { index_ = 0; }
  118. virtual void SeekToLast() {
  119. index_ = flist_->empty() ? 0 : flist_->size() - 1;
  120. }
  121. virtual void Next() {
  122. assert(Valid());
  123. index_++;
  124. }
  125. virtual void Prev() {
  126. assert(Valid());
  127. if (index_ == 0) {
  128. index_ = flist_->size(); // Marks as invalid
  129. } else {
  130. index_--;
  131. }
  132. }
  133. Slice key() const {
  134. assert(Valid());
  135. return (*flist_)[index_]->largest.Encode();
  136. }
  137. Slice value() const {
  138. assert(Valid());
  139. EncodeFixed64(value_buf_, (*flist_)[index_]->number);
  140. EncodeFixed64(value_buf_+8, (*flist_)[index_]->file_size);
  141. return Slice(value_buf_, sizeof(value_buf_));
  142. }
  143. virtual Status status() const { return Status::OK(); }
  144. private:
  145. const InternalKeyComparator icmp_;
  146. const std::vector<FileMetaData*>* const flist_;
  147. uint32_t index_;
  148. // Backing store for value(). Holds the file number and size.
  149. mutable char value_buf_[16];
  150. };
  151. static Iterator* GetFileIterator(void* arg,
  152. const ReadOptions& options,
  153. const Slice& file_value) {
  154. TableCache* cache = reinterpret_cast<TableCache*>(arg);
  155. if (file_value.size() != 16) {
  156. return NewErrorIterator(
  157. Status::Corruption("FileReader invoked with unexpected value"));
  158. } else {
  159. return cache->NewIterator(options,
  160. DecodeFixed64(file_value.data()),
  161. DecodeFixed64(file_value.data() + 8));
  162. }
  163. }
  164. Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
  165. int level) const {
  166. return NewTwoLevelIterator(
  167. new LevelFileNumIterator(vset_->icmp_, &files_[level]),
  168. &GetFileIterator, vset_->table_cache_, options);
  169. }
  170. void Version::AddIterators(const ReadOptions& options,
  171. std::vector<Iterator*>* iters) {
  172. // Merge all level zero files together since they may overlap
  173. for (size_t i = 0; i < files_[0].size(); i++) {
  174. iters->push_back(
  175. vset_->table_cache_->NewIterator(
  176. options, files_[0][i]->number, files_[0][i]->file_size));
  177. }
  178. // For levels > 0, we can use a concatenating iterator that sequentially
  179. // walks through the non-overlapping files in the level, opening them
  180. // lazily.
  181. for (int level = 1; level < config::kNumLevels; level++) {
  182. if (!files_[level].empty()) {
  183. iters->push_back(NewConcatenatingIterator(options, level));
  184. }
  185. }
  186. }
  187. // If "*iter" points at a value or deletion for user_key, store
  188. // either the value, or a NotFound error and return true.
  189. // Else return false.
  190. static bool GetValue(Iterator* iter, const Slice& user_key,
  191. std::string* value,
  192. Status* s) {
  193. if (!iter->Valid()) {
  194. return false;
  195. }
  196. ParsedInternalKey parsed_key;
  197. if (!ParseInternalKey(iter->key(), &parsed_key)) {
  198. *s = Status::Corruption("corrupted key for ", user_key);
  199. return true;
  200. }
  201. if (parsed_key.user_key != user_key) {
  202. return false;
  203. }
  204. switch (parsed_key.type) {
  205. case kTypeDeletion:
  206. *s = Status::NotFound(Slice()); // Use an empty error message for speed
  207. break;
  208. case kTypeValue: {
  209. Slice v = iter->value();
  210. value->assign(v.data(), v.size());
  211. break;
  212. }
  213. }
  214. return true;
  215. }
  216. static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
  217. return a->number > b->number;
  218. }
  219. Status Version::Get(const ReadOptions& options,
  220. const LookupKey& k,
  221. std::string* value,
  222. GetStats* stats) {
  223. Slice ikey = k.internal_key();
  224. Slice user_key = k.user_key();
  225. const Comparator* ucmp = vset_->icmp_.user_comparator();
  226. Status s;
  227. stats->seek_file = NULL;
  228. stats->seek_file_level = -1;
  229. FileMetaData* last_file_read = NULL;
  230. int last_file_read_level = -1;
  231. // We can search level-by-level since entries never hop across
  232. // levels. Therefore we are guaranteed that if we find data
  233. // in an smaller level, later levels are irrelevant.
  234. std::vector<FileMetaData*> tmp;
  235. FileMetaData* tmp2;
  236. for (int level = 0; level < config::kNumLevels; level++) {
  237. size_t num_files = files_[level].size();
  238. if (num_files == 0) continue;
  239. // Get the list of files to search in this level
  240. FileMetaData* const* files = &files_[level][0];
  241. if (level == 0) {
  242. // Level-0 files may overlap each other. Find all files that
  243. // overlap user_key and process them in order from newest to oldest.
  244. tmp.reserve(num_files);
  245. for (uint32_t i = 0; i < num_files; i++) {
  246. FileMetaData* f = files[i];
  247. if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
  248. ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
  249. tmp.push_back(f);
  250. }
  251. }
  252. if (tmp.empty()) continue;
  253. std::sort(tmp.begin(), tmp.end(), NewestFirst);
  254. files = &tmp[0];
  255. num_files = tmp.size();
  256. } else {
  257. // Binary search to find earliest index whose largest key >= ikey.
  258. uint32_t index = FindFile(vset_->icmp_, files_[level], ikey);
  259. if (index >= num_files) {
  260. files = NULL;
  261. num_files = 0;
  262. } else {
  263. tmp2 = files[index];
  264. if (ucmp->Compare(user_key, tmp2->smallest.user_key()) < 0) {
  265. // All of "tmp2" is past any data for user_key
  266. files = NULL;
  267. num_files = 0;
  268. } else {
  269. files = &tmp2;
  270. num_files = 1;
  271. }
  272. }
  273. }
  274. for (uint32_t i = 0; i < num_files; ++i) {
  275. if (last_file_read != NULL && stats->seek_file == NULL) {
  276. // We have had more than one seek for this read. Charge the 1st file.
  277. stats->seek_file = last_file_read;
  278. stats->seek_file_level = last_file_read_level;
  279. }
  280. FileMetaData* f = files[i];
  281. last_file_read = f;
  282. last_file_read_level = level;
  283. Iterator* iter = vset_->table_cache_->NewIterator(
  284. options,
  285. f->number,
  286. f->file_size);
  287. iter->Seek(ikey);
  288. const bool done = GetValue(iter, user_key, value, &s);
  289. if (!iter->status().ok()) {
  290. s = iter->status();
  291. delete iter;
  292. return s;
  293. } else {
  294. delete iter;
  295. if (done) {
  296. return s;
  297. }
  298. }
  299. }
  300. }
  301. return Status::NotFound(Slice()); // Use an empty error message for speed
  302. }
  303. bool Version::UpdateStats(const GetStats& stats) {
  304. FileMetaData* f = stats.seek_file;
  305. if (f != NULL) {
  306. f->allowed_seeks--;
  307. if (f->allowed_seeks <= 0 && file_to_compact_ == NULL) {
  308. file_to_compact_ = f;
  309. file_to_compact_level_ = stats.seek_file_level;
  310. return true;
  311. }
  312. }
  313. return false;
  314. }
  315. void Version::Ref() {
  316. ++refs_;
  317. }
  318. void Version::Unref() {
  319. assert(this != &vset_->dummy_versions_);
  320. assert(refs_ >= 1);
  321. --refs_;
  322. if (refs_ == 0) {
  323. delete this;
  324. }
  325. }
  326. bool Version::OverlapInLevel(int level,
  327. const Slice& smallest_user_key,
  328. const Slice& largest_user_key) {
  329. return SomeFileOverlapsRange(vset_->icmp_, files_[level],
  330. smallest_user_key,
  331. largest_user_key);
  332. }
  333. std::string Version::DebugString() const {
  334. std::string r;
  335. for (int level = 0; level < config::kNumLevels; level++) {
  336. // E.g.,
  337. // --- level 1 ---
  338. // 17:123['a' .. 'd']
  339. // 20:43['e' .. 'g']
  340. r.append("--- level ");
  341. AppendNumberTo(&r, level);
  342. r.append(" ---\n");
  343. const std::vector<FileMetaData*>& files = files_[level];
  344. for (size_t i = 0; i < files.size(); i++) {
  345. r.push_back(' ');
  346. AppendNumberTo(&r, files[i]->number);
  347. r.push_back(':');
  348. AppendNumberTo(&r, files[i]->file_size);
  349. r.append("['");
  350. AppendEscapedStringTo(&r, files[i]->smallest.Encode());
  351. r.append("' .. '");
  352. AppendEscapedStringTo(&r, files[i]->largest.Encode());
  353. r.append("']\n");
  354. }
  355. }
  356. return r;
  357. }
  358. // A helper class so we can efficiently apply a whole sequence
  359. // of edits to a particular state without creating intermediate
  360. // Versions that contain full copies of the intermediate state.
  361. class VersionSet::Builder {
  362. private:
  363. // Helper to sort by v->files_[file_number].smallest
  364. struct BySmallestKey {
  365. const InternalKeyComparator* internal_comparator;
  366. bool operator()(FileMetaData* f1, FileMetaData* f2) const {
  367. int r = internal_comparator->Compare(f1->smallest, f2->smallest);
  368. if (r != 0) {
  369. return (r < 0);
  370. } else {
  371. // Break ties by file number
  372. return (f1->number < f2->number);
  373. }
  374. }
  375. };
  376. typedef std::set<FileMetaData*, BySmallestKey> FileSet;
  377. struct LevelState {
  378. std::set<uint64_t> deleted_files;
  379. FileSet* added_files;
  380. };
  381. VersionSet* vset_;
  382. Version* base_;
  383. LevelState levels_[config::kNumLevels];
  384. public:
  385. // Initialize a builder with the files from *base and other info from *vset
  386. Builder(VersionSet* vset, Version* base)
  387. : vset_(vset),
  388. base_(base) {
  389. base_->Ref();
  390. BySmallestKey cmp;
  391. cmp.internal_comparator = &vset_->icmp_;
  392. for (int level = 0; level < config::kNumLevels; level++) {
  393. levels_[level].added_files = new FileSet(cmp);
  394. }
  395. }
  396. ~Builder() {
  397. for (int level = 0; level < config::kNumLevels; level++) {
  398. const FileSet* added = levels_[level].added_files;
  399. std::vector<FileMetaData*> to_unref;
  400. to_unref.reserve(added->size());
  401. for (FileSet::const_iterator it = added->begin();
  402. it != added->end(); ++it) {
  403. to_unref.push_back(*it);
  404. }
  405. delete added;
  406. for (uint32_t i = 0; i < to_unref.size(); i++) {
  407. FileMetaData* f = to_unref[i];
  408. f->refs--;
  409. if (f->refs <= 0) {
  410. delete f;
  411. }
  412. }
  413. }
  414. base_->Unref();
  415. }
  416. // Apply all of the edits in *edit to the current state.
  417. void Apply(VersionEdit* edit) {
  418. // Update compaction pointers
  419. for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
  420. const int level = edit->compact_pointers_[i].first;
  421. vset_->compact_pointer_[level] =
  422. edit->compact_pointers_[i].second.Encode().ToString();
  423. }
  424. // Delete files
  425. const VersionEdit::DeletedFileSet& del = edit->deleted_files_;
  426. for (VersionEdit::DeletedFileSet::const_iterator iter = del.begin();
  427. iter != del.end();
  428. ++iter) {
  429. const int level = iter->first;
  430. const uint64_t number = iter->second;
  431. levels_[level].deleted_files.insert(number);
  432. }
  433. // Add new files
  434. for (size_t i = 0; i < edit->new_files_.size(); i++) {
  435. const int level = edit->new_files_[i].first;
  436. FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
  437. f->refs = 1;
  438. // We arrange to automatically compact this file after
  439. // a certain number of seeks. Let's assume:
  440. // (1) One seek costs 10ms
  441. // (2) Writing or reading 1MB costs 10ms (100MB/s)
  442. // (3) A compaction of 1MB does 25MB of IO:
  443. // 1MB read from this level
  444. // 10-12MB read from next level (boundaries may be misaligned)
  445. // 10-12MB written to next level
  446. // This implies that 25 seeks cost the same as the compaction
  447. // of 1MB of data. I.e., one seek costs approximately the
  448. // same as the compaction of 40KB of data. We are a little
  449. // conservative and allow approximately one seek for every 16KB
  450. // of data before triggering a compaction.
  451. f->allowed_seeks = (f->file_size / 16384);
  452. if (f->allowed_seeks < 100) f->allowed_seeks = 100;
  453. levels_[level].deleted_files.erase(f->number);
  454. levels_[level].added_files->insert(f);
  455. }
  456. }
  457. // Save the current state in *v.
  458. void SaveTo(Version* v) {
  459. BySmallestKey cmp;
  460. cmp.internal_comparator = &vset_->icmp_;
  461. for (int level = 0; level < config::kNumLevels; level++) {
  462. // Merge the set of added files with the set of pre-existing files.
  463. // Drop any deleted files. Store the result in *v.
  464. const std::vector<FileMetaData*>& base_files = base_->files_[level];
  465. std::vector<FileMetaData*>::const_iterator base_iter = base_files.begin();
  466. std::vector<FileMetaData*>::const_iterator base_end = base_files.end();
  467. const FileSet* added = levels_[level].added_files;
  468. v->files_[level].reserve(base_files.size() + added->size());
  469. for (FileSet::const_iterator added_iter = added->begin();
  470. added_iter != added->end();
  471. ++added_iter) {
  472. // Add all smaller files listed in base_
  473. for (std::vector<FileMetaData*>::const_iterator bpos
  474. = std::upper_bound(base_iter, base_end, *added_iter, cmp);
  475. base_iter != bpos;
  476. ++base_iter) {
  477. MaybeAddFile(v, level, *base_iter);
  478. }
  479. MaybeAddFile(v, level, *added_iter);
  480. }
  481. // Add remaining base files
  482. for (; base_iter != base_end; ++base_iter) {
  483. MaybeAddFile(v, level, *base_iter);
  484. }
  485. #ifndef NDEBUG
  486. // Make sure there is no overlap in levels > 0
  487. if (level > 0) {
  488. for (uint32_t i = 1; i < v->files_[level].size(); i++) {
  489. const InternalKey& prev_end = v->files_[level][i-1]->largest;
  490. const InternalKey& this_begin = v->files_[level][i]->smallest;
  491. if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
  492. fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
  493. EscapeString(prev_end.Encode()).c_str(),
  494. EscapeString(this_begin.Encode()).c_str());
  495. abort();
  496. }
  497. }
  498. }
  499. #endif
  500. }
  501. }
  502. void MaybeAddFile(Version* v, int level, FileMetaData* f) {
  503. if (levels_[level].deleted_files.count(f->number) > 0) {
  504. // File is deleted: do nothing
  505. } else {
  506. std::vector<FileMetaData*>* files = &v->files_[level];
  507. if (level > 0 && !files->empty()) {
  508. // Must not overlap
  509. assert(vset_->icmp_.Compare((*files)[files->size()-1]->largest,
  510. f->smallest) < 0);
  511. }
  512. f->refs++;
  513. files->push_back(f);
  514. }
  515. }
  516. };
  517. VersionSet::VersionSet(const std::string& dbname,
  518. const Options* options,
  519. TableCache* table_cache,
  520. const InternalKeyComparator* cmp)
  521. : env_(options->env),
  522. dbname_(dbname),
  523. options_(options),
  524. table_cache_(table_cache),
  525. icmp_(*cmp),
  526. next_file_number_(2),
  527. manifest_file_number_(0), // Filled by Recover()
  528. last_sequence_(0),
  529. log_number_(0),
  530. prev_log_number_(0),
  531. descriptor_file_(NULL),
  532. descriptor_log_(NULL),
  533. dummy_versions_(this),
  534. current_(NULL) {
  535. AppendVersion(new Version(this));
  536. }
  537. VersionSet::~VersionSet() {
  538. current_->Unref();
  539. assert(dummy_versions_.next_ == &dummy_versions_); // List must be empty
  540. delete descriptor_log_;
  541. delete descriptor_file_;
  542. }
  543. void VersionSet::AppendVersion(Version* v) {
  544. // Make "v" current
  545. assert(v->refs_ == 0);
  546. assert(v != current_);
  547. if (current_ != NULL) {
  548. current_->Unref();
  549. }
  550. current_ = v;
  551. v->Ref();
  552. // Append to linked list
  553. v->prev_ = dummy_versions_.prev_;
  554. v->next_ = &dummy_versions_;
  555. v->prev_->next_ = v;
  556. v->next_->prev_ = v;
  557. }
  558. Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) {
  559. if (edit->has_log_number_) {
  560. assert(edit->log_number_ >= log_number_);
  561. assert(edit->log_number_ < next_file_number_);
  562. } else {
  563. edit->SetLogNumber(log_number_);
  564. }
  565. if (!edit->has_prev_log_number_) {
  566. edit->SetPrevLogNumber(prev_log_number_);
  567. }
  568. edit->SetNextFile(next_file_number_);
  569. edit->SetLastSequence(last_sequence_);
  570. Version* v = new Version(this);
  571. {
  572. Builder builder(this, current_);
  573. builder.Apply(edit);
  574. builder.SaveTo(v);
  575. }
  576. Finalize(v);
  577. // Initialize new descriptor log file if necessary by creating
  578. // a temporary file that contains a snapshot of the current version.
  579. std::string new_manifest_file;
  580. Status s;
  581. if (descriptor_log_ == NULL) {
  582. // No reason to unlock *mu here since we only hit this path in the
  583. // first call to LogAndApply (when opening the database).
  584. assert(descriptor_file_ == NULL);
  585. new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
  586. edit->SetNextFile(next_file_number_);
  587. s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
  588. if (s.ok()) {
  589. descriptor_log_ = new log::Writer(descriptor_file_);
  590. s = WriteSnapshot(descriptor_log_);
  591. }
  592. }
  593. // Unlock during expensive MANIFEST log write
  594. {
  595. mu->Unlock();
  596. // Write new record to MANIFEST log
  597. if (s.ok()) {
  598. std::string record;
  599. edit->EncodeTo(&record);
  600. s = descriptor_log_->AddRecord(record);
  601. if (s.ok()) {
  602. s = descriptor_file_->Sync();
  603. }
  604. }
  605. // If we just created a new descriptor file, install it by writing a
  606. // new CURRENT file that points to it.
  607. if (s.ok() && !new_manifest_file.empty()) {
  608. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  609. }
  610. mu->Lock();
  611. }
  612. // Install the new version
  613. if (s.ok()) {
  614. AppendVersion(v);
  615. log_number_ = edit->log_number_;
  616. prev_log_number_ = edit->prev_log_number_;
  617. } else {
  618. delete v;
  619. if (!new_manifest_file.empty()) {
  620. delete descriptor_log_;
  621. delete descriptor_file_;
  622. descriptor_log_ = NULL;
  623. descriptor_file_ = NULL;
  624. env_->DeleteFile(new_manifest_file);
  625. }
  626. }
  627. return s;
  628. }
  629. Status VersionSet::Recover() {
  630. struct LogReporter : public log::Reader::Reporter {
  631. Status* status;
  632. virtual void Corruption(size_t bytes, const Status& s) {
  633. if (this->status->ok()) *this->status = s;
  634. }
  635. };
  636. // Read "CURRENT" file, which contains a pointer to the current manifest file
  637. std::string current;
  638. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  639. if (!s.ok()) {
  640. return s;
  641. }
  642. if (current.empty() || current[current.size()-1] != '\n') {
  643. return Status::Corruption("CURRENT file does not end with newline");
  644. }
  645. current.resize(current.size() - 1);
  646. std::string dscname = dbname_ + "/" + current;
  647. SequentialFile* file;
  648. s = env_->NewSequentialFile(dscname, &file);
  649. if (!s.ok()) {
  650. return s;
  651. }
  652. bool have_log_number = false;
  653. bool have_prev_log_number = false;
  654. bool have_next_file = false;
  655. bool have_last_sequence = false;
  656. uint64_t next_file = 0;
  657. uint64_t last_sequence = 0;
  658. uint64_t log_number = 0;
  659. uint64_t prev_log_number = 0;
  660. Builder builder(this, current_);
  661. {
  662. LogReporter reporter;
  663. reporter.status = &s;
  664. log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/);
  665. Slice record;
  666. std::string scratch;
  667. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  668. VersionEdit edit;
  669. s = edit.DecodeFrom(record);
  670. if (s.ok()) {
  671. if (edit.has_comparator_ &&
  672. edit.comparator_ != icmp_.user_comparator()->Name()) {
  673. s = Status::InvalidArgument(
  674. edit.comparator_ + "does not match existing comparator ",
  675. icmp_.user_comparator()->Name());
  676. }
  677. }
  678. if (s.ok()) {
  679. builder.Apply(&edit);
  680. }
  681. if (edit.has_log_number_) {
  682. log_number = edit.log_number_;
  683. have_log_number = true;
  684. }
  685. if (edit.has_prev_log_number_) {
  686. prev_log_number = edit.prev_log_number_;
  687. have_prev_log_number = true;
  688. }
  689. if (edit.has_next_file_number_) {
  690. next_file = edit.next_file_number_;
  691. have_next_file = true;
  692. }
  693. if (edit.has_last_sequence_) {
  694. last_sequence = edit.last_sequence_;
  695. have_last_sequence = true;
  696. }
  697. }
  698. }
  699. delete file;
  700. file = NULL;
  701. if (s.ok()) {
  702. if (!have_next_file) {
  703. s = Status::Corruption("no meta-nextfile entry in descriptor");
  704. } else if (!have_log_number) {
  705. s = Status::Corruption("no meta-lognumber entry in descriptor");
  706. } else if (!have_last_sequence) {
  707. s = Status::Corruption("no last-sequence-number entry in descriptor");
  708. }
  709. if (!have_prev_log_number) {
  710. prev_log_number = 0;
  711. }
  712. MarkFileNumberUsed(prev_log_number);
  713. MarkFileNumberUsed(log_number);
  714. }
  715. if (s.ok()) {
  716. Version* v = new Version(this);
  717. builder.SaveTo(v);
  718. // Install recovered version
  719. Finalize(v);
  720. AppendVersion(v);
  721. manifest_file_number_ = next_file;
  722. next_file_number_ = next_file + 1;
  723. last_sequence_ = last_sequence;
  724. log_number_ = log_number;
  725. prev_log_number_ = prev_log_number;
  726. }
  727. return s;
  728. }
  729. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  730. if (next_file_number_ <= number) {
  731. next_file_number_ = number + 1;
  732. }
  733. }
  734. static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
  735. int64_t sum = 0;
  736. for (size_t i = 0; i < files.size(); i++) {
  737. sum += files[i]->file_size;
  738. }
  739. return sum;
  740. }
  741. void VersionSet::Finalize(Version* v) {
  742. // Precomputed best level for next compaction
  743. int best_level = -1;
  744. double best_score = -1;
  745. for (int level = 0; level < config::kNumLevels-1; level++) {
  746. double score;
  747. if (level == 0) {
  748. // We treat level-0 specially by bounding the number of files
  749. // instead of number of bytes for two reasons:
  750. //
  751. // (1) With larger write-buffer sizes, it is nice not to do too
  752. // many level-0 compactions.
  753. //
  754. // (2) The files in level-0 are merged on every read and
  755. // therefore we wish to avoid too many files when the individual
  756. // file size is small (perhaps because of a small write-buffer
  757. // setting, or very high compression ratios, or lots of
  758. // overwrites/deletions).
  759. score = v->files_[level].size() /
  760. static_cast<double>(config::kL0_CompactionTrigger);
  761. } else {
  762. // Compute the ratio of current size to size limit.
  763. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  764. score = static_cast<double>(level_bytes) / MaxBytesForLevel(level);
  765. }
  766. if (score > best_score) {
  767. best_level = level;
  768. best_score = score;
  769. }
  770. }
  771. v->compaction_level_ = best_level;
  772. v->compaction_score_ = best_score;
  773. }
  774. Status VersionSet::WriteSnapshot(log::Writer* log) {
  775. // TODO: Break up into multiple records to reduce memory usage on recovery?
  776. // Save metadata
  777. VersionEdit edit;
  778. edit.SetComparatorName(icmp_.user_comparator()->Name());
  779. // Save compaction pointers
  780. for (int level = 0; level < config::kNumLevels; level++) {
  781. if (!compact_pointer_[level].empty()) {
  782. InternalKey key;
  783. key.DecodeFrom(compact_pointer_[level]);
  784. edit.SetCompactPointer(level, key);
  785. }
  786. }
  787. // Save files
  788. for (int level = 0; level < config::kNumLevels; level++) {
  789. const std::vector<FileMetaData*>& files = current_->files_[level];
  790. for (size_t i = 0; i < files.size(); i++) {
  791. const FileMetaData* f = files[i];
  792. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  793. }
  794. }
  795. std::string record;
  796. edit.EncodeTo(&record);
  797. return log->AddRecord(record);
  798. }
  799. int VersionSet::NumLevelFiles(int level) const {
  800. assert(level >= 0);
  801. assert(level < config::kNumLevels);
  802. return current_->files_[level].size();
  803. }
  804. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  805. // Update code if kNumLevels changes
  806. assert(config::kNumLevels == 7);
  807. snprintf(scratch->buffer, sizeof(scratch->buffer),
  808. "files[ %d %d %d %d %d %d %d ]",
  809. int(current_->files_[0].size()),
  810. int(current_->files_[1].size()),
  811. int(current_->files_[2].size()),
  812. int(current_->files_[3].size()),
  813. int(current_->files_[4].size()),
  814. int(current_->files_[5].size()),
  815. int(current_->files_[6].size()));
  816. return scratch->buffer;
  817. }
  818. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  819. uint64_t result = 0;
  820. for (int level = 0; level < config::kNumLevels; level++) {
  821. const std::vector<FileMetaData*>& files = v->files_[level];
  822. for (size_t i = 0; i < files.size(); i++) {
  823. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  824. // Entire file is before "ikey", so just add the file size
  825. result += files[i]->file_size;
  826. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  827. // Entire file is after "ikey", so ignore
  828. if (level > 0) {
  829. // Files other than level 0 are sorted by meta->smallest, so
  830. // no further files in this level will contain data for
  831. // "ikey".
  832. break;
  833. }
  834. } else {
  835. // "ikey" falls in the range for this table. Add the
  836. // approximate offset of "ikey" within the table.
  837. Table* tableptr;
  838. Iterator* iter = table_cache_->NewIterator(
  839. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  840. if (tableptr != NULL) {
  841. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  842. }
  843. delete iter;
  844. }
  845. }
  846. }
  847. return result;
  848. }
  849. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  850. for (Version* v = dummy_versions_.next_;
  851. v != &dummy_versions_;
  852. v = v->next_) {
  853. for (int level = 0; level < config::kNumLevels; level++) {
  854. const std::vector<FileMetaData*>& files = v->files_[level];
  855. for (size_t i = 0; i < files.size(); i++) {
  856. live->insert(files[i]->number);
  857. }
  858. }
  859. }
  860. }
  861. int64_t VersionSet::NumLevelBytes(int level) const {
  862. assert(level >= 0);
  863. assert(level < config::kNumLevels);
  864. return TotalFileSize(current_->files_[level]);
  865. }
  866. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  867. int64_t result = 0;
  868. std::vector<FileMetaData*> overlaps;
  869. for (int level = 1; level < config::kNumLevels - 1; level++) {
  870. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  871. const FileMetaData* f = current_->files_[level][i];
  872. GetOverlappingInputs(level+1, f->smallest, f->largest, &overlaps);
  873. const int64_t sum = TotalFileSize(overlaps);
  874. if (sum > result) {
  875. result = sum;
  876. }
  877. }
  878. }
  879. return result;
  880. }
  881. // Store in "*inputs" all files in "level" that overlap [begin,end]
  882. void VersionSet::GetOverlappingInputs(
  883. int level,
  884. const InternalKey& begin,
  885. const InternalKey& end,
  886. std::vector<FileMetaData*>* inputs) {
  887. inputs->clear();
  888. Slice user_begin = begin.user_key();
  889. Slice user_end = end.user_key();
  890. const Comparator* user_cmp = icmp_.user_comparator();
  891. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  892. FileMetaData* f = current_->files_[level][i];
  893. if (user_cmp->Compare(f->largest.user_key(), user_begin) < 0 ||
  894. user_cmp->Compare(f->smallest.user_key(), user_end) > 0) {
  895. // Either completely before or after range; skip it
  896. } else {
  897. inputs->push_back(f);
  898. }
  899. }
  900. }
  901. // Stores the minimal range that covers all entries in inputs in
  902. // *smallest, *largest.
  903. // REQUIRES: inputs is not empty
  904. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  905. InternalKey* smallest,
  906. InternalKey* largest) {
  907. assert(!inputs.empty());
  908. smallest->Clear();
  909. largest->Clear();
  910. for (size_t i = 0; i < inputs.size(); i++) {
  911. FileMetaData* f = inputs[i];
  912. if (i == 0) {
  913. *smallest = f->smallest;
  914. *largest = f->largest;
  915. } else {
  916. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  917. *smallest = f->smallest;
  918. }
  919. if (icmp_.Compare(f->largest, *largest) > 0) {
  920. *largest = f->largest;
  921. }
  922. }
  923. }
  924. }
  925. // Stores the minimal range that covers all entries in inputs1 and inputs2
  926. // in *smallest, *largest.
  927. // REQUIRES: inputs is not empty
  928. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  929. const std::vector<FileMetaData*>& inputs2,
  930. InternalKey* smallest,
  931. InternalKey* largest) {
  932. std::vector<FileMetaData*> all = inputs1;
  933. all.insert(all.end(), inputs2.begin(), inputs2.end());
  934. GetRange(all, smallest, largest);
  935. }
  936. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  937. ReadOptions options;
  938. options.verify_checksums = options_->paranoid_checks;
  939. options.fill_cache = false;
  940. // Level-0 files have to be merged together. For other levels,
  941. // we will make a concatenating iterator per level.
  942. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  943. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  944. Iterator** list = new Iterator*[space];
  945. int num = 0;
  946. for (int which = 0; which < 2; which++) {
  947. if (!c->inputs_[which].empty()) {
  948. if (c->level() + which == 0) {
  949. const std::vector<FileMetaData*>& files = c->inputs_[which];
  950. for (size_t i = 0; i < files.size(); i++) {
  951. list[num++] = table_cache_->NewIterator(
  952. options, files[i]->number, files[i]->file_size);
  953. }
  954. } else {
  955. // Create concatenating iterator for the files from this level
  956. list[num++] = NewTwoLevelIterator(
  957. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  958. &GetFileIterator, table_cache_, options);
  959. }
  960. }
  961. }
  962. assert(num <= space);
  963. Iterator* result = NewMergingIterator(&icmp_, list, num);
  964. delete[] list;
  965. return result;
  966. }
  967. Compaction* VersionSet::PickCompaction() {
  968. Compaction* c;
  969. int level;
  970. // We prefer compactions triggered by too much data in a level over
  971. // the compactions triggered by seeks.
  972. const bool size_compaction = (current_->compaction_score_ >= 1);
  973. const bool seek_compaction = (current_->file_to_compact_ != NULL);
  974. if (size_compaction) {
  975. level = current_->compaction_level_;
  976. assert(level >= 0);
  977. assert(level+1 < config::kNumLevels);
  978. c = new Compaction(level);
  979. // Pick the first file that comes after compact_pointer_[level]
  980. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  981. FileMetaData* f = current_->files_[level][i];
  982. if (compact_pointer_[level].empty() ||
  983. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  984. c->inputs_[0].push_back(f);
  985. break;
  986. }
  987. }
  988. if (c->inputs_[0].empty()) {
  989. // Wrap-around to the beginning of the key space
  990. c->inputs_[0].push_back(current_->files_[level][0]);
  991. }
  992. } else if (seek_compaction) {
  993. level = current_->file_to_compact_level_;
  994. c = new Compaction(level);
  995. c->inputs_[0].push_back(current_->file_to_compact_);
  996. } else {
  997. return NULL;
  998. }
  999. c->input_version_ = current_;
  1000. c->input_version_->Ref();
  1001. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1002. if (level == 0) {
  1003. InternalKey smallest, largest;
  1004. GetRange(c->inputs_[0], &smallest, &largest);
  1005. // Note that the next call will discard the file we placed in
  1006. // c->inputs_[0] earlier and replace it with an overlapping set
  1007. // which will include the picked file.
  1008. GetOverlappingInputs(0, smallest, largest, &c->inputs_[0]);
  1009. assert(!c->inputs_[0].empty());
  1010. }
  1011. SetupOtherInputs(c);
  1012. return c;
  1013. }
  1014. void VersionSet::SetupOtherInputs(Compaction* c) {
  1015. const int level = c->level();
  1016. InternalKey smallest, largest;
  1017. GetRange(c->inputs_[0], &smallest, &largest);
  1018. GetOverlappingInputs(level+1, smallest, largest, &c->inputs_[1]);
  1019. // Get entire range covered by compaction
  1020. InternalKey all_start, all_limit;
  1021. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1022. // See if we can grow the number of inputs in "level" without
  1023. // changing the number of "level+1" files we pick up.
  1024. if (!c->inputs_[1].empty()) {
  1025. std::vector<FileMetaData*> expanded0;
  1026. GetOverlappingInputs(level, all_start, all_limit, &expanded0);
  1027. if (expanded0.size() > c->inputs_[0].size()) {
  1028. InternalKey new_start, new_limit;
  1029. GetRange(expanded0, &new_start, &new_limit);
  1030. std::vector<FileMetaData*> expanded1;
  1031. GetOverlappingInputs(level+1, new_start, new_limit, &expanded1);
  1032. if (expanded1.size() == c->inputs_[1].size()) {
  1033. Log(options_->info_log,
  1034. "Expanding@%d %d+%d to %d+%d\n",
  1035. level,
  1036. int(c->inputs_[0].size()),
  1037. int(c->inputs_[1].size()),
  1038. int(expanded0.size()),
  1039. int(expanded1.size()));
  1040. smallest = new_start;
  1041. largest = new_limit;
  1042. c->inputs_[0] = expanded0;
  1043. c->inputs_[1] = expanded1;
  1044. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1045. }
  1046. }
  1047. }
  1048. // Compute the set of grandparent files that overlap this compaction
  1049. // (parent == level+1; grandparent == level+2)
  1050. if (level + 2 < config::kNumLevels) {
  1051. GetOverlappingInputs(level + 2, all_start, all_limit, &c->grandparents_);
  1052. }
  1053. if (false) {
  1054. Log(options_->info_log, "Compacting %d '%s' .. '%s'",
  1055. level,
  1056. EscapeString(smallest.Encode()).c_str(),
  1057. EscapeString(largest.Encode()).c_str());
  1058. }
  1059. // Update the place where we will do the next compaction for this level.
  1060. // We update this immediately instead of waiting for the VersionEdit
  1061. // to be applied so that if the compaction fails, we will try a different
  1062. // key range next time.
  1063. compact_pointer_[level] = largest.Encode().ToString();
  1064. c->edit_.SetCompactPointer(level, largest);
  1065. }
  1066. Compaction* VersionSet::CompactRange(
  1067. int level,
  1068. const InternalKey& begin,
  1069. const InternalKey& end) {
  1070. std::vector<FileMetaData*> inputs;
  1071. GetOverlappingInputs(level, begin, end, &inputs);
  1072. if (inputs.empty()) {
  1073. return NULL;
  1074. }
  1075. Compaction* c = new Compaction(level);
  1076. c->input_version_ = current_;
  1077. c->input_version_->Ref();
  1078. c->inputs_[0] = inputs;
  1079. SetupOtherInputs(c);
  1080. return c;
  1081. }
  1082. Compaction::Compaction(int level)
  1083. : level_(level),
  1084. max_output_file_size_(MaxFileSizeForLevel(level)),
  1085. input_version_(NULL),
  1086. grandparent_index_(0),
  1087. seen_key_(false),
  1088. overlapped_bytes_(0) {
  1089. for (int i = 0; i < config::kNumLevels; i++) {
  1090. level_ptrs_[i] = 0;
  1091. }
  1092. }
  1093. Compaction::~Compaction() {
  1094. if (input_version_ != NULL) {
  1095. input_version_->Unref();
  1096. }
  1097. }
  1098. bool Compaction::IsTrivialMove() const {
  1099. // Avoid a move if there is lots of overlapping grandparent data.
  1100. // Otherwise, the move could create a parent file that will require
  1101. // a very expensive merge later on.
  1102. return (num_input_files(0) == 1 &&
  1103. num_input_files(1) == 0 &&
  1104. TotalFileSize(grandparents_) <= kMaxGrandParentOverlapBytes);
  1105. }
  1106. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1107. for (int which = 0; which < 2; which++) {
  1108. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1109. edit->DeleteFile(level_ + which, inputs_[which][i]->number);
  1110. }
  1111. }
  1112. }
  1113. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1114. // Maybe use binary search to find right entry instead of linear search?
  1115. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1116. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1117. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1118. for (; level_ptrs_[lvl] < files.size(); ) {
  1119. FileMetaData* f = files[level_ptrs_[lvl]];
  1120. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1121. // We've advanced far enough
  1122. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1123. // Key falls in this file's range, so definitely not base level
  1124. return false;
  1125. }
  1126. break;
  1127. }
  1128. level_ptrs_[lvl]++;
  1129. }
  1130. }
  1131. return true;
  1132. }
  1133. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1134. // Scan to find earliest grandparent file that contains key.
  1135. const InternalKeyComparator* icmp = &input_version_->vset_->icmp_;
  1136. while (grandparent_index_ < grandparents_.size() &&
  1137. icmp->Compare(internal_key,
  1138. grandparents_[grandparent_index_]->largest.Encode()) > 0) {
  1139. if (seen_key_) {
  1140. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1141. }
  1142. grandparent_index_++;
  1143. }
  1144. seen_key_ = true;
  1145. if (overlapped_bytes_ > kMaxGrandParentOverlapBytes) {
  1146. // Too much overlap for current output; start new output
  1147. overlapped_bytes_ = 0;
  1148. return true;
  1149. } else {
  1150. return false;
  1151. }
  1152. }
  1153. void Compaction::ReleaseInputs() {
  1154. if (input_version_ != NULL) {
  1155. input_version_->Unref();
  1156. input_version_ = NULL;
  1157. }
  1158. }
  1159. }