LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
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.

1585 lines
51 KiB

1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "db/version_set.h"
  5. #include <algorithm>
  6. #include <cstdio>
  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 size_t TargetFileSize(const Options* options) {
  20. return options->max_file_size;
  21. }
  22. // Maximum bytes of overlaps in grandparent (i.e., level+2) before we
  23. // stop building a single file in a level->level+1 compaction.
  24. static int64_t MaxGrandParentOverlapBytes(const Options* options) {
  25. return 10 * TargetFileSize(options);
  26. }
  27. // Maximum number of bytes in all compacted files. We avoid expanding
  28. // the lower level file set of a compaction if it would make the
  29. // total compaction cover more than this many bytes.
  30. static int64_t ExpandedCompactionByteSizeLimit(const Options* options) {
  31. return 25 * TargetFileSize(options);
  32. }
  33. static double MaxBytesForLevel(const Options* options, int level) {
  34. // Note: the result for level zero is not really used since we set
  35. // the level-0 compaction threshold based on number of files.
  36. // Result for both level-0 and level-1
  37. double result = 10. * 1048576.0;
  38. while (level > 1) {
  39. result *= 10;
  40. level--;
  41. }
  42. return result;
  43. }
  44. static uint64_t MaxFileSizeForLevel(const Options* options, int level) {
  45. // We could vary per level to reduce number of files?
  46. return TargetFileSize(options);
  47. }
  48. static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
  49. int64_t sum = 0;
  50. for (size_t i = 0; i < files.size(); i++) {
  51. sum += files[i]->file_size;
  52. }
  53. return sum;
  54. }
  55. Version::~Version() {
  56. assert(refs_ == 0);
  57. // Remove from linked list
  58. prev_->next_ = next_;
  59. next_->prev_ = prev_;
  60. // Drop references to files
  61. for (int level = 0; level < config::kNumLevels; level++) {
  62. for (size_t i = 0; i < files_[level].size(); i++) {
  63. FileMetaData* f = files_[level][i];
  64. assert(f->refs > 0);
  65. f->refs--;
  66. if (f->refs <= 0) {
  67. delete f;
  68. }
  69. }
  70. }
  71. }
  72. int FindFile(const InternalKeyComparator& icmp,
  73. const std::vector<FileMetaData*>& files, const Slice& key) {
  74. uint32_t left = 0;
  75. uint32_t right = files.size();
  76. while (left < right) {
  77. uint32_t mid = (left + right) / 2;
  78. const FileMetaData* f = files[mid];
  79. if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) {
  80. // Key at "mid.largest" is < "target". Therefore all
  81. // files at or before "mid" are uninteresting.
  82. left = mid + 1;
  83. } else {
  84. // Key at "mid.largest" is >= "target". Therefore all files
  85. // after "mid" are uninteresting.
  86. right = mid;
  87. }
  88. }
  89. return right;
  90. }
  91. static bool AfterFile(const Comparator* ucmp, const Slice* user_key,
  92. const FileMetaData* f) {
  93. // null user_key occurs before all keys and is therefore never after *f
  94. return (user_key != nullptr &&
  95. ucmp->Compare(*user_key, f->largest.user_key()) > 0);
  96. }
  97. static bool BeforeFile(const Comparator* ucmp, const Slice* user_key,
  98. const FileMetaData* f) {
  99. // null user_key occurs after all keys and is therefore never before *f
  100. return (user_key != nullptr &&
  101. ucmp->Compare(*user_key, f->smallest.user_key()) < 0);
  102. }
  103. bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,
  104. bool disjoint_sorted_files,
  105. const std::vector<FileMetaData*>& files,
  106. const Slice* smallest_user_key,
  107. const Slice* largest_user_key) {
  108. const Comparator* ucmp = icmp.user_comparator();
  109. if (!disjoint_sorted_files) {
  110. // Need to check against all files
  111. for (size_t i = 0; i < files.size(); i++) {
  112. const FileMetaData* f = files[i];
  113. if (AfterFile(ucmp, smallest_user_key, f) ||
  114. BeforeFile(ucmp, largest_user_key, f)) {
  115. // No overlap
  116. } else {
  117. return true; // Overlap
  118. }
  119. }
  120. return false;
  121. }
  122. // Binary search over file list, 保证SSTable有序
  123. uint32_t index = 0;
  124. if (smallest_user_key != nullptr) {
  125. // Find the earliest possible internal key for smallest_user_key
  126. InternalKey small_key(*smallest_user_key, kMaxSequenceNumber,
  127. kValueTypeForSeek);
  128. index = FindFile(icmp, files, small_key.Encode());
  129. }
  130. if (index >= files.size()) {
  131. // beginning of range is after all files, so no overlap.
  132. return false;
  133. }
  134. return !BeforeFile(ucmp, largest_user_key, files[index]);
  135. }
  136. // An internal iterator. For a given version/level pair, yields
  137. // information about the files in the level. For a given entry, key()
  138. // is the largest key that occurs in the file, and value() is an
  139. // 16-byte value containing the file number and file size, both
  140. // encoded using EncodeFixed64.
  141. class Version::LevelFileNumIterator : public Iterator {
  142. public:
  143. LevelFileNumIterator(const InternalKeyComparator& icmp,
  144. const std::vector<FileMetaData*>* flist)
  145. : icmp_(icmp), flist_(flist), index_(flist->size()) { // Marks as invalid
  146. }
  147. bool Valid() const override { return index_ < flist_->size(); }
  148. void Seek(const Slice& target) override {
  149. index_ = FindFile(icmp_, *flist_, target);
  150. }
  151. void SeekToFirst() override { index_ = 0; }
  152. void SeekToLast() override {
  153. index_ = flist_->empty() ? 0 : flist_->size() - 1;
  154. }
  155. void Next() override {
  156. assert(Valid());
  157. index_++;
  158. }
  159. void Prev() override {
  160. assert(Valid());
  161. if (index_ == 0) {
  162. index_ = flist_->size(); // Marks as invalid
  163. } else {
  164. index_--;
  165. }
  166. }
  167. Slice key() const override {
  168. assert(Valid());
  169. return (*flist_)[index_]->largest.Encode();
  170. }
  171. Slice value() const override {
  172. assert(Valid());
  173. EncodeFixed64(value_buf_, (*flist_)[index_]->number);
  174. EncodeFixed64(value_buf_ + 8, (*flist_)[index_]->file_size);
  175. return Slice(value_buf_, sizeof(value_buf_));
  176. }
  177. Status status() const override { return Status::OK(); }
  178. private:
  179. const InternalKeyComparator icmp_;
  180. const std::vector<FileMetaData*>* const flist_;
  181. uint32_t index_;
  182. // Backing store for value(). Holds the file number and size.
  183. mutable char value_buf_[16];
  184. };
  185. static Iterator* GetFileIterator(void* arg, const ReadOptions& options,
  186. const Slice& file_value) {
  187. TableCache* cache = reinterpret_cast<TableCache*>(arg);
  188. if (file_value.size() != 16) {
  189. return NewErrorIterator(
  190. Status::Corruption("FileReader invoked with unexpected value"));
  191. } else {
  192. return cache->NewIterator(options, DecodeFixed64(file_value.data()),
  193. DecodeFixed64(file_value.data() + 8));
  194. }
  195. }
  196. Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
  197. int level) const {
  198. return NewTwoLevelIterator(
  199. new LevelFileNumIterator(vset_->icmp_, &files_[level]), &GetFileIterator,
  200. vset_->table_cache_, options);
  201. }
  202. void Version::AddIterators(const ReadOptions& options,
  203. std::vector<Iterator*>* iters) {
  204. // Merge all level zero files together since they may overlap
  205. for (size_t i = 0; i < files_[0].size(); i++) {
  206. iters->push_back(vset_->table_cache_->NewIterator(
  207. options, files_[0][i]->number, files_[0][i]->file_size));
  208. }
  209. // For levels > 0, we can use a concatenating iterator that sequentially
  210. // walks through the non-overlapping files in the level, opening them
  211. // lazily.
  212. for (int level = 1; level < config::kNumLevels; level++) {
  213. if (!files_[level].empty()) {
  214. iters->push_back(NewConcatenatingIterator(options, level));
  215. }
  216. }
  217. }
  218. // Callback from TableCache::Get()
  219. namespace {
  220. enum SaverState {
  221. kNotFound,
  222. kFound,
  223. kDeleted,
  224. kCorrupt,
  225. };
  226. struct Saver {
  227. SaverState state;
  228. const Comparator* ucmp;
  229. Slice user_key;
  230. std::string* value;
  231. };
  232. } // namespace
  233. static void SaveValue(void* arg, const Slice& ikey, const Slice& v) {
  234. Saver* s = reinterpret_cast<Saver*>(arg);
  235. ParsedInternalKey parsed_key;
  236. if (!ParseInternalKey(ikey, &parsed_key)) {
  237. s->state = kCorrupt;
  238. } else {
  239. if (s->ucmp->Compare(parsed_key.user_key, s->user_key) == 0) {
  240. s->state = (parsed_key.type == kTypeValue) ? kFound : kDeleted;
  241. if (s->state == kFound) {
  242. s->value->assign(v.data(), v.size());
  243. }
  244. }
  245. }
  246. }
  247. static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
  248. return a->number > b->number;
  249. }
  250. void Version::ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,
  251. bool (*func)(void*, int, FileMetaData*)) {
  252. const Comparator* ucmp = vset_->icmp_.user_comparator();
  253. // Search level-0 in order from newest to oldest.
  254. std::vector<FileMetaData*> tmp;
  255. tmp.reserve(files_[0].size());
  256. for (uint32_t i = 0; i < files_[0].size(); i++) {
  257. FileMetaData* f = files_[0][i];
  258. if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
  259. ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
  260. tmp.push_back(f);
  261. }
  262. }
  263. if (!tmp.empty()) {
  264. std::sort(tmp.begin(), tmp.end(), NewestFirst);
  265. for (uint32_t i = 0; i < tmp.size(); i++) {
  266. if (!(*func)(arg, 0, tmp[i])) {
  267. return;
  268. }
  269. }
  270. }
  271. // Search other levels.
  272. for (int level = 1; level < config::kNumLevels; level++) {
  273. size_t num_files = files_[level].size();
  274. if (num_files == 0) continue;
  275. // Binary search to find earliest index whose largest key >= internal_key.
  276. uint32_t index = FindFile(vset_->icmp_, files_[level], internal_key);
  277. if (index < num_files) {
  278. FileMetaData* f = files_[level][index];
  279. if (ucmp->Compare(user_key, f->smallest.user_key()) < 0) {
  280. // All of "f" is past any data for user_key
  281. } else {
  282. if (!(*func)(arg, level, f)) {
  283. return;
  284. }
  285. }
  286. }
  287. }
  288. }
  289. Status Version::Get(const ReadOptions& options, const LookupKey& k,
  290. std::string* value, GetStats* stats) {
  291. stats->seek_file = nullptr;
  292. stats->seek_file_level = -1;
  293. struct State {
  294. Saver saver;
  295. GetStats* stats;
  296. const ReadOptions* options;
  297. Slice ikey;
  298. FileMetaData* last_file_read;
  299. int last_file_read_level;
  300. VersionSet* vset;
  301. Status s;
  302. bool found;
  303. static bool Match(void* arg, int level, FileMetaData* f) {
  304. State* state = reinterpret_cast<State*>(arg);
  305. if (state->stats->seek_file == nullptr &&
  306. state->last_file_read != nullptr) {
  307. // We have had more than one seek for this read. Charge the 1st file.
  308. state->stats->seek_file = state->last_file_read;
  309. state->stats->seek_file_level = state->last_file_read_level;
  310. }
  311. state->last_file_read = f;
  312. state->last_file_read_level = level;
  313. if(state->stats->now_ts > f->newer_ts)return false;
  314. state->s = state->vset->table_cache_->Get(*state->options, f->number,
  315. f->file_size, state->ikey,
  316. &state->saver, SaveValue);
  317. if (!state->s.ok()) {
  318. state->found = true;
  319. return false;
  320. }
  321. switch (state->saver.state) {
  322. case kNotFound:
  323. return true; // Keep searching in other files
  324. case kFound:
  325. state->found = true;
  326. return false;
  327. case kDeleted:
  328. return false;
  329. case kCorrupt:
  330. state->s =
  331. Status::Corruption("corrupted key for ", state->saver.user_key);
  332. state->found = true;
  333. return false;
  334. }
  335. // Not reached. Added to avoid false compilation warnings of
  336. // "control reaches end of non-void function".
  337. return false;
  338. }
  339. };
  340. State state;
  341. state.found = false;
  342. state.stats = stats;
  343. state.last_file_read = nullptr;
  344. state.last_file_read_level = -1;
  345. state.options = &options;
  346. state.ikey = k.internal_key();
  347. state.vset = vset_;
  348. state.saver.state = kNotFound;
  349. state.saver.ucmp = vset_->icmp_.user_comparator();
  350. state.saver.user_key = k.user_key();
  351. state.saver.value = value;
  352. ForEachOverlapping(state.saver.user_key, state.ikey, &state, &State::Match);
  353. return state.found ? state.s : Status::NotFound(Slice());
  354. }
  355. bool Version::UpdateStats(const GetStats& stats) {
  356. FileMetaData* f = stats.seek_file;
  357. if (f != nullptr) {
  358. f->allowed_seeks--;
  359. if (f->allowed_seeks <= 0 && file_to_compact_ == nullptr) {
  360. file_to_compact_ = f;
  361. file_to_compact_level_ = stats.seek_file_level;
  362. return true;
  363. }
  364. }
  365. return false;
  366. }
  367. bool Version::UpdateStats(const GetStats& stats,bool is_expire) {
  368. FileMetaData* f = stats.seek_file;
  369. if (f != nullptr) {
  370. f->allowed_seeks--;
  371. if(is_expire)f->allowed_seeks--;
  372. if (f->allowed_seeks <= 0 && file_to_compact_ == nullptr) {
  373. file_to_compact_ = f;
  374. file_to_compact_level_ = stats.seek_file_level;
  375. return true;
  376. }
  377. }
  378. return false;
  379. }
  380. bool Version::RecordReadSample(Slice internal_key) {
  381. ParsedInternalKey ikey;
  382. if (!ParseInternalKey(internal_key, &ikey)) {
  383. return false;
  384. }
  385. struct State {
  386. GetStats stats; // Holds first matching file
  387. int matches;
  388. static bool Match(void* arg, int level, FileMetaData* f) {
  389. State* state = reinterpret_cast<State*>(arg);
  390. state->matches++;
  391. if (state->matches == 1) {
  392. // Remember first match.
  393. state->stats.seek_file = f;
  394. state->stats.seek_file_level = level;
  395. }
  396. // We can stop iterating once we have a second match.
  397. return state->matches < 2;
  398. }
  399. };
  400. State state;
  401. state.matches = 0;
  402. ForEachOverlapping(ikey.user_key, internal_key, &state, &State::Match);
  403. // Must have at least two matches since we want to merge across
  404. // files. But what if we have a single file that contains many
  405. // overwrites and deletions? Should we have another mechanism for
  406. // finding such files?
  407. if (state.matches >= 2) {
  408. // 1MB cost is about 1 seek (see comment in Builder::Apply).
  409. return UpdateStats(state.stats);
  410. }
  411. return false;
  412. }
  413. void Version::Ref() { ++refs_; }
  414. void Version::Unref() {
  415. assert(this != &vset_->dummy_versions_);
  416. assert(refs_ >= 1);
  417. --refs_;
  418. if (refs_ == 0) {
  419. delete this;
  420. }
  421. }
  422. //files_[level] 中存在至少一个文件的键范围与 [smallest_user_key, largest_user_key] 有重叠,那么 OverlapInLevel 就会返回 true。
  423. bool Version::OverlapInLevel(int level, const Slice* smallest_user_key,
  424. const Slice* largest_user_key) {
  425. return SomeFileOverlapsRange(vset_->icmp_, (level > 0), files_[level],
  426. smallest_user_key, largest_user_key);
  427. }
  428. int Version::PickLevelForMemTableOutput(const Slice& smallest_user_key,
  429. const Slice& largest_user_key) {
  430. int level = 0;
  431. if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) {//当与level0没有重叠时,直接选择压入其他层
  432. // Push to next level if there is no overlap in next level,
  433. // and the #bytes overlapping in the level after that are limited.
  434. InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
  435. InternalKey limit(largest_user_key, 0, static_cast<ValueType>(0));
  436. std::vector<FileMetaData*> overlaps;
  437. while (level < config::kMaxMemCompactLevel) {
  438. if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) {
  439. break;
  440. }
  441. if (level + 2 < config::kNumLevels) {
  442. // Check that file does not overlap too many grandparent bytes.
  443. GetOverlappingInputs(level + 2, &start, &limit, &overlaps);
  444. const int64_t sum = TotalFileSize(overlaps);
  445. if (sum > MaxGrandParentOverlapBytes(vset_->options_)) {
  446. break;
  447. }
  448. }
  449. level++;
  450. }
  451. }
  452. return level;
  453. }
  454. // Store in "*inputs" all files in "level" that overlap [begin,end]
  455. void Version::GetOverlappingInputs(int level, const InternalKey* begin,
  456. const InternalKey* end,
  457. std::vector<FileMetaData*>* inputs) {
  458. assert(level >= 0);
  459. assert(level < config::kNumLevels);
  460. inputs->clear();
  461. Slice user_begin, user_end;
  462. if (begin != nullptr) {
  463. user_begin = begin->user_key();
  464. }
  465. if (end != nullptr) {
  466. user_end = end->user_key();
  467. }
  468. const Comparator* user_cmp = vset_->icmp_.user_comparator();
  469. for (size_t i = 0; i < files_[level].size();) {
  470. FileMetaData* f = files_[level][i++];
  471. const Slice file_start = f->smallest.user_key();
  472. const Slice file_limit = f->largest.user_key();
  473. if (begin != nullptr && user_cmp->Compare(file_limit, user_begin) < 0) {
  474. // "f" is completely before specified range; skip it
  475. } else if (end != nullptr && user_cmp->Compare(file_start, user_end) > 0) {
  476. // "f" is completely after specified range; skip it
  477. } else {
  478. inputs->push_back(f);
  479. if (level == 0) {
  480. // Level-0 files may overlap each other. So check if the newly
  481. // added file has expanded the range. If so, restart search.
  482. if (begin != nullptr && user_cmp->Compare(file_start, user_begin) < 0) {
  483. user_begin = file_start;
  484. inputs->clear();
  485. i = 0;
  486. } else if (end != nullptr &&
  487. user_cmp->Compare(file_limit, user_end) > 0) {
  488. user_end = file_limit;
  489. inputs->clear();
  490. i = 0;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. std::string Version::DebugString() const {
  497. std::string r;
  498. for (int level = 0; level < config::kNumLevels; level++) {
  499. // E.g.,
  500. // --- level 1 ---
  501. // 17:123['a' .. 'd']
  502. // 20:43['e' .. 'g']
  503. r.append("--- level ");
  504. AppendNumberTo(&r, level);
  505. r.append(" ---\n");
  506. const std::vector<FileMetaData*>& files = files_[level];
  507. for (size_t i = 0; i < files.size(); i++) {
  508. r.push_back(' ');
  509. AppendNumberTo(&r, files[i]->number);
  510. r.push_back(':');
  511. AppendNumberTo(&r, files[i]->file_size);
  512. r.append("[");
  513. r.append(files[i]->smallest.DebugString());
  514. r.append(" .. ");
  515. r.append(files[i]->largest.DebugString());
  516. r.append("]\n");
  517. }
  518. }
  519. return r;
  520. }
  521. // A helper class so we can efficiently apply a whole sequence
  522. // of edits to a particular state without creating intermediate
  523. // Versions that contain full copies of the intermediate state.
  524. class VersionSet::Builder {
  525. private:
  526. // Helper to sort by v->files_[file_number].smallest
  527. struct BySmallestKey {
  528. const InternalKeyComparator* internal_comparator;
  529. bool operator()(FileMetaData* f1, FileMetaData* f2) const {
  530. int r = internal_comparator->Compare(f1->smallest, f2->smallest);
  531. if (r != 0) {
  532. return (r < 0);
  533. } else {
  534. // Break ties by file number
  535. return (f1->number < f2->number);
  536. }
  537. }
  538. };
  539. typedef std::set<FileMetaData*, BySmallestKey> FileSet;
  540. struct LevelState {
  541. std::set<uint64_t> deleted_files;
  542. FileSet* added_files;
  543. };
  544. VersionSet* vset_;
  545. Version* base_;
  546. LevelState levels_[config::kNumLevels];
  547. public:
  548. // Initialize a builder with the files from *base and other info from *vset
  549. Builder(VersionSet* vset, Version* base) : vset_(vset), base_(base) {
  550. base_->Ref();
  551. BySmallestKey cmp;
  552. cmp.internal_comparator = &vset_->icmp_;
  553. for (int level = 0; level < config::kNumLevels; level++) {
  554. levels_[level].added_files = new FileSet(cmp);
  555. }
  556. }
  557. ~Builder() {
  558. for (int level = 0; level < config::kNumLevels; level++) {
  559. const FileSet* added = levels_[level].added_files;
  560. std::vector<FileMetaData*> to_unref;
  561. to_unref.reserve(added->size());
  562. for (FileSet::const_iterator it = added->begin(); it != added->end();
  563. ++it) {
  564. to_unref.push_back(*it);
  565. }
  566. delete added;
  567. for (uint32_t i = 0; i < to_unref.size(); i++) {
  568. FileMetaData* f = to_unref[i];
  569. f->refs--;
  570. if (f->refs <= 0) {
  571. delete f;
  572. }
  573. }
  574. }
  575. base_->Unref();
  576. }
  577. // Apply all of the edits in *edit to the current state.
  578. void Apply(const VersionEdit* edit) {
  579. // Update compaction pointers
  580. for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
  581. const int level = edit->compact_pointers_[i].first;
  582. vset_->compact_pointer_[level] =
  583. edit->compact_pointers_[i].second.Encode().ToString();
  584. }
  585. // Delete files
  586. for (const auto& deleted_file_set_kvp : edit->deleted_files_) {
  587. const int level = deleted_file_set_kvp.first;
  588. const uint64_t number = deleted_file_set_kvp.second;
  589. levels_[level].deleted_files.insert(number);
  590. }
  591. // Add new files
  592. for (size_t i = 0; i < edit->new_files_.size(); i++) {
  593. const int level = edit->new_files_[i].first;
  594. FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
  595. f->refs = 1;
  596. // We arrange to automatically compact this file after
  597. // a certain number of seeks. Let's assume:
  598. // (1) One seek costs 10ms
  599. // (2) Writing or reading 1MB costs 10ms (100MB/s)
  600. // (3) A compaction of 1MB does 25MB of IO:
  601. // 1MB read from this level
  602. // 10-12MB read from next level (boundaries may be misaligned)
  603. // 10-12MB written to next level
  604. // This implies that 25 seeks cost the same as the compaction
  605. // of 1MB of data. I.e., one seek costs approximately the
  606. // same as the compaction of 40KB of data. We are a little
  607. // conservative and allow approximately one seek for every 16KB
  608. // of data before triggering a compaction.
  609. f->allowed_seeks = static_cast<int>((f->file_size / 16384U));
  610. if (f->allowed_seeks < 100) f->allowed_seeks = 100;
  611. levels_[level].deleted_files.erase(f->number);
  612. levels_[level].added_files->insert(f);//按照最小key排序
  613. }
  614. }
  615. // Save the current state in *v.
  616. void SaveTo(Version* v) {
  617. BySmallestKey cmp;
  618. cmp.internal_comparator = &vset_->icmp_;
  619. for (int level = 0; level < config::kNumLevels; level++) {
  620. // Merge the set of added files with the set of pre-existing files.
  621. // Drop any deleted files. Store the result in *v.
  622. const std::vector<FileMetaData*>& base_files = base_->files_[level];
  623. std::vector<FileMetaData*>::const_iterator base_iter = base_files.begin();
  624. std::vector<FileMetaData*>::const_iterator base_end = base_files.end();
  625. const FileSet* added_files = levels_[level].added_files;
  626. v->files_[level].reserve(base_files.size() + added_files->size());
  627. for (const auto& added_file : *added_files) {
  628. // Add all smaller files listed in base_
  629. for (std::vector<FileMetaData*>::const_iterator bpos =
  630. std::upper_bound(base_iter, base_end, added_file, cmp);
  631. base_iter != bpos; ++base_iter) {
  632. MaybeAddFile(v, level, *base_iter);
  633. }
  634. MaybeAddFile(v, level, added_file);
  635. }
  636. // Add remaining base files
  637. for (; base_iter != base_end; ++base_iter) {
  638. MaybeAddFile(v, level, *base_iter);
  639. }
  640. #ifndef NDEBUG
  641. // Make sure there is no overlap in levels > 0
  642. if (level > 0) {
  643. for (uint32_t i = 1; i < v->files_[level].size(); i++) {
  644. const InternalKey& prev_end = v->files_[level][i - 1]->largest;
  645. const InternalKey& this_begin = v->files_[level][i]->smallest;
  646. if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
  647. std::fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
  648. prev_end.DebugString().c_str(),
  649. this_begin.DebugString().c_str());
  650. std::abort();
  651. }
  652. }
  653. }
  654. #endif
  655. }
  656. }
  657. void MaybeAddFile(Version* v, int level, FileMetaData* f) {
  658. if (levels_[level].deleted_files.count(f->number) > 0) {
  659. // File is deleted: do nothing
  660. } else {
  661. std::vector<FileMetaData*>* files = &v->files_[level];
  662. if (level > 0 && !files->empty()) {
  663. // Must not overlap
  664. assert(vset_->icmp_.Compare((*files)[files->size() - 1]->largest,
  665. f->smallest) < 0);
  666. }
  667. f->refs++;
  668. files->push_back(f);
  669. }
  670. }
  671. };
  672. VersionSet::VersionSet(const std::string& dbname, const Options* options,
  673. TableCache* table_cache,
  674. const InternalKeyComparator* cmp)
  675. : env_(options->env),
  676. dbname_(dbname),
  677. options_(options),
  678. table_cache_(table_cache),
  679. icmp_(*cmp),
  680. next_file_number_(2),
  681. manifest_file_number_(0), // Filled by Recover()
  682. last_sequence_(0),
  683. log_number_(0),
  684. prev_log_number_(0),
  685. descriptor_file_(nullptr),
  686. descriptor_log_(nullptr),
  687. dummy_versions_(this),
  688. current_(nullptr) {
  689. AppendVersion(new Version(this));
  690. }
  691. VersionSet::~VersionSet() {
  692. current_->Unref();
  693. assert(dummy_versions_.next_ == &dummy_versions_); // List must be empty
  694. delete descriptor_log_;
  695. delete descriptor_file_;
  696. }
  697. void VersionSet::AppendVersion(Version* v) {
  698. // Make "v" current
  699. assert(v->refs_ == 0);
  700. assert(v != current_);
  701. if (current_ != nullptr) {
  702. current_->Unref();
  703. }
  704. current_ = v;
  705. v->Ref();
  706. // Append to linked list
  707. v->prev_ = dummy_versions_.prev_;
  708. v->next_ = &dummy_versions_;
  709. v->prev_->next_ = v;
  710. v->next_->prev_ = v;
  711. }
  712. Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) {
  713. if (edit->has_log_number_) {
  714. assert(edit->log_number_ >= log_number_);
  715. assert(edit->log_number_ < next_file_number_);
  716. } else {
  717. edit->SetLogNumber(log_number_);
  718. }
  719. if (!edit->has_prev_log_number_) {
  720. edit->SetPrevLogNumber(prev_log_number_);
  721. }
  722. edit->SetNextFile(next_file_number_);
  723. edit->SetLastSequence(last_sequence_);
  724. Version* v = new Version(this);
  725. {
  726. Builder builder(this, current_);
  727. builder.Apply(edit);
  728. builder.SaveTo(v);
  729. }
  730. Finalize(v);//对于每层compact打分
  731. // Initialize new descriptor log file if necessary by creating
  732. // a temporary file that contains a snapshot of the current version.
  733. std::string new_manifest_file;
  734. Status s;
  735. if (descriptor_log_ == nullptr) {
  736. // No reason to unlock *mu here since we only hit this path in the
  737. // first call to LogAndApply (when opening the database).
  738. assert(descriptor_file_ == nullptr);
  739. new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
  740. s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
  741. if (s.ok()) {
  742. descriptor_log_ = new log::Writer(descriptor_file_);
  743. s = WriteSnapshot(descriptor_log_);
  744. }
  745. }
  746. // Unlock during expensive MANIFEST log write
  747. {
  748. mu->Unlock();
  749. // Write new record to MANIFEST log
  750. if (s.ok()) {
  751. std::string record;
  752. edit->EncodeTo(&record);
  753. s = descriptor_log_->AddRecord(record);
  754. if (s.ok()) {
  755. s = descriptor_file_->Sync();
  756. }
  757. if (!s.ok()) {
  758. Log(options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str());
  759. }
  760. }
  761. // If we just created a new descriptor file, install it by writing a
  762. // new CURRENT file that points to it.
  763. if (s.ok() && !new_manifest_file.empty()) {
  764. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  765. }
  766. mu->Lock();
  767. }
  768. // Install the new version
  769. if (s.ok()) {
  770. AppendVersion(v);
  771. log_number_ = edit->log_number_;
  772. prev_log_number_ = edit->prev_log_number_;
  773. } else {
  774. delete v;
  775. if (!new_manifest_file.empty()) {
  776. delete descriptor_log_;
  777. delete descriptor_file_;
  778. descriptor_log_ = nullptr;
  779. descriptor_file_ = nullptr;
  780. env_->RemoveFile(new_manifest_file);
  781. }
  782. }
  783. return s;
  784. }
  785. Status VersionSet::Recover(bool* save_manifest) {
  786. struct LogReporter : public log::Reader::Reporter {
  787. Status* status;
  788. void Corruption(size_t bytes, const Status& s) override {
  789. if (this->status->ok()) *this->status = s;
  790. }
  791. };
  792. // Read "CURRENT" file, which contains a pointer to the current manifest file
  793. std::string current;
  794. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  795. if (!s.ok()) {
  796. return s;
  797. }
  798. if (current.empty() || current[current.size() - 1] != '\n') {
  799. return Status::Corruption("CURRENT file does not end with newline");
  800. }
  801. current.resize(current.size() - 1);
  802. std::string dscname = dbname_ + "/" + current;
  803. SequentialFile* file;
  804. s = env_->NewSequentialFile(dscname, &file);
  805. if (!s.ok()) {
  806. if (s.IsNotFound()) {
  807. return Status::Corruption("CURRENT points to a non-existent file",
  808. s.ToString());
  809. }
  810. return s;
  811. }
  812. bool have_log_number = false;
  813. bool have_prev_log_number = false;
  814. bool have_next_file = false;
  815. bool have_last_sequence = false;
  816. uint64_t next_file = 0;
  817. uint64_t last_sequence = 0;
  818. uint64_t log_number = 0;
  819. uint64_t prev_log_number = 0;
  820. Builder builder(this, current_);
  821. int read_records = 0;
  822. {
  823. LogReporter reporter;
  824. reporter.status = &s;
  825. log::Reader reader(file, &reporter, true /*checksum*/,
  826. 0 /*initial_offset*/);
  827. Slice record;
  828. std::string scratch;
  829. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  830. ++read_records;
  831. VersionEdit edit;
  832. s = edit.DecodeFrom(record);
  833. if (s.ok()) {
  834. if (edit.has_comparator_ &&
  835. edit.comparator_ != icmp_.user_comparator()->Name()) {
  836. s = Status::InvalidArgument(
  837. edit.comparator_ + " does not match existing comparator ",
  838. icmp_.user_comparator()->Name());
  839. }
  840. }
  841. if (s.ok()) {
  842. builder.Apply(&edit);
  843. }
  844. if (edit.has_log_number_) {
  845. log_number = edit.log_number_;
  846. have_log_number = true;
  847. }
  848. if (edit.has_prev_log_number_) {
  849. prev_log_number = edit.prev_log_number_;
  850. have_prev_log_number = true;
  851. }
  852. if (edit.has_next_file_number_) {
  853. next_file = edit.next_file_number_;
  854. have_next_file = true;
  855. }
  856. if (edit.has_last_sequence_) {
  857. last_sequence = edit.last_sequence_;
  858. have_last_sequence = true;
  859. }
  860. }
  861. }
  862. delete file;
  863. file = nullptr;
  864. if (s.ok()) {
  865. if (!have_next_file) {
  866. s = Status::Corruption("no meta-nextfile entry in descriptor");
  867. } else if (!have_log_number) {
  868. s = Status::Corruption("no meta-lognumber entry in descriptor");
  869. } else if (!have_last_sequence) {
  870. s = Status::Corruption("no last-sequence-number entry in descriptor");
  871. }
  872. if (!have_prev_log_number) {
  873. prev_log_number = 0;
  874. }
  875. MarkFileNumberUsed(prev_log_number);
  876. MarkFileNumberUsed(log_number);
  877. }
  878. if (s.ok()) {
  879. Version* v = new Version(this);
  880. builder.SaveTo(v);
  881. // Install recovered version
  882. Finalize(v);
  883. AppendVersion(v);
  884. manifest_file_number_ = next_file;
  885. next_file_number_ = next_file + 1;
  886. last_sequence_ = last_sequence;
  887. log_number_ = log_number;
  888. prev_log_number_ = prev_log_number;
  889. // See if we can reuse the existing MANIFEST file.
  890. if (ReuseManifest(dscname, current)) {
  891. // No need to save new manifest
  892. } else {
  893. *save_manifest = true;
  894. }
  895. } else {
  896. std::string error = s.ToString();
  897. Log(options_->info_log, "Error recovering version set with %d records: %s",
  898. read_records, error.c_str());
  899. }
  900. return s;
  901. }
  902. bool VersionSet::ReuseManifest(const std::string& dscname,
  903. const std::string& dscbase) {
  904. if (!options_->reuse_logs) {
  905. return false;
  906. }
  907. FileType manifest_type;
  908. uint64_t manifest_number;
  909. uint64_t manifest_size;
  910. if (!ParseFileName(dscbase, &manifest_number, &manifest_type) ||
  911. manifest_type != kDescriptorFile ||
  912. !env_->GetFileSize(dscname, &manifest_size).ok() ||
  913. // Make new compacted MANIFEST if old one is too big
  914. manifest_size >= TargetFileSize(options_)) {
  915. return false;
  916. }
  917. assert(descriptor_file_ == nullptr);
  918. assert(descriptor_log_ == nullptr);
  919. Status r = env_->NewAppendableFile(dscname, &descriptor_file_);
  920. if (!r.ok()) {
  921. Log(options_->info_log, "Reuse MANIFEST: %s\n", r.ToString().c_str());
  922. assert(descriptor_file_ == nullptr);
  923. return false;
  924. }
  925. Log(options_->info_log, "Reusing MANIFEST %s\n", dscname.c_str());
  926. descriptor_log_ = new log::Writer(descriptor_file_, manifest_size);
  927. manifest_file_number_ = manifest_number;
  928. return true;
  929. }
  930. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  931. if (next_file_number_ <= number) {
  932. next_file_number_ = number + 1;
  933. }
  934. }
  935. void VersionSet::Finalize(Version* v) {
  936. // Precomputed best level for next compaction
  937. int best_level = -1;
  938. double best_score = -1;
  939. for (int level = 0; level < config::kNumLevels - 1; level++) {
  940. double score;
  941. if (level == 0) {
  942. // We treat level-0 specially by bounding the number of files
  943. // instead of number of bytes for two reasons:
  944. //
  945. // (1) With larger write-buffer sizes, it is nice not to do too
  946. // many level-0 compactions.
  947. //
  948. // (2) The files in level-0 are merged on every read and
  949. // therefore we wish to avoid too many files when the individual
  950. // file size is small (perhaps because of a small write-buffer
  951. // setting, or very high compression ratios, or lots of
  952. // overwrites/deletions).
  953. score = v->files_[level].size() /
  954. static_cast<double>(config::kL0_CompactionTrigger);
  955. } else {
  956. // Compute the ratio of current size to size limit.
  957. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  958. score =
  959. static_cast<double>(level_bytes) / MaxBytesForLevel(options_, level);
  960. }
  961. if (score > best_score) {
  962. best_level = level;
  963. best_score = score;
  964. }
  965. }
  966. v->compaction_level_ = best_level;
  967. v->compaction_score_ = best_score;
  968. }
  969. Status VersionSet::WriteSnapshot(log::Writer* log) {
  970. // TODO: Break up into multiple records to reduce memory usage on recovery?
  971. // Save metadata
  972. VersionEdit edit;
  973. edit.SetComparatorName(icmp_.user_comparator()->Name());
  974. // Save compaction pointers
  975. for (int level = 0; level < config::kNumLevels; level++) {
  976. if (!compact_pointer_[level].empty()) {
  977. InternalKey key;
  978. key.DecodeFrom(compact_pointer_[level]);
  979. edit.SetCompactPointer(level, key);
  980. }
  981. }
  982. // Save files
  983. for (int level = 0; level < config::kNumLevels; level++) {
  984. const std::vector<FileMetaData*>& files = current_->files_[level];
  985. for (size_t i = 0; i < files.size(); i++) {
  986. const FileMetaData* f = files[i];
  987. //edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  988. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest,f->oldest_ts,f->newer_ts);
  989. }
  990. }
  991. std::string record;
  992. edit.EncodeTo(&record);
  993. return log->AddRecord(record);
  994. }
  995. int VersionSet::NumLevelFiles(int level) const {
  996. assert(level >= 0);
  997. assert(level < config::kNumLevels);
  998. return current_->files_[level].size();
  999. }
  1000. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  1001. // Update code if kNumLevels changes
  1002. static_assert(config::kNumLevels == 7, "");
  1003. std::snprintf(
  1004. scratch->buffer, sizeof(scratch->buffer), "files[ %d %d %d %d %d %d %d ]",
  1005. int(current_->files_[0].size()), int(current_->files_[1].size()),
  1006. int(current_->files_[2].size()), int(current_->files_[3].size()),
  1007. int(current_->files_[4].size()), int(current_->files_[5].size()),
  1008. int(current_->files_[6].size()));
  1009. return scratch->buffer;
  1010. }
  1011. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  1012. uint64_t result = 0;
  1013. for (int level = 0; level < config::kNumLevels; level++) {
  1014. const std::vector<FileMetaData*>& files = v->files_[level];
  1015. for (size_t i = 0; i < files.size(); i++) {
  1016. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  1017. // Entire file is before "ikey", so just add the file size
  1018. result += files[i]->file_size;
  1019. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  1020. // Entire file is after "ikey", so ignore
  1021. if (level > 0) {
  1022. // Files other than level 0 are sorted by meta->smallest, so
  1023. // no further files in this level will contain data for
  1024. // "ikey".
  1025. break;
  1026. }
  1027. } else {
  1028. // "ikey" falls in the range for this table. Add the
  1029. // approximate offset of "ikey" within the table.
  1030. Table* tableptr;
  1031. Iterator* iter = table_cache_->NewIterator(
  1032. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  1033. if (tableptr != nullptr) {
  1034. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  1035. }
  1036. delete iter;
  1037. }
  1038. }
  1039. }
  1040. return result;
  1041. }
  1042. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  1043. for (Version* v = dummy_versions_.next_; v != &dummy_versions_;
  1044. v = v->next_) {
  1045. for (int level = 0; level < config::kNumLevels; level++) {
  1046. const std::vector<FileMetaData*>& files = v->files_[level];
  1047. for (size_t i = 0; i < files.size(); i++) {
  1048. live->insert(files[i]->number);
  1049. }
  1050. }
  1051. }
  1052. }
  1053. int64_t VersionSet::NumLevelBytes(int level) const {
  1054. assert(level >= 0);
  1055. assert(level < config::kNumLevels);
  1056. return TotalFileSize(current_->files_[level]);
  1057. }
  1058. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  1059. int64_t result = 0;
  1060. std::vector<FileMetaData*> overlaps;
  1061. for (int level = 1; level < config::kNumLevels - 1; level++) {
  1062. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1063. const FileMetaData* f = current_->files_[level][i];
  1064. current_->GetOverlappingInputs(level + 1, &f->smallest, &f->largest,
  1065. &overlaps);
  1066. const int64_t sum = TotalFileSize(overlaps);
  1067. if (sum > result) {
  1068. result = sum;
  1069. }
  1070. }
  1071. }
  1072. return result;
  1073. }
  1074. // Stores the minimal range that covers all entries in inputs in
  1075. // *smallest, *largest.
  1076. // REQUIRES: inputs is not empty
  1077. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  1078. InternalKey* smallest, InternalKey* largest) {
  1079. assert(!inputs.empty());
  1080. smallest->Clear();
  1081. largest->Clear();
  1082. for (size_t i = 0; i < inputs.size(); i++) {
  1083. FileMetaData* f = inputs[i];
  1084. if (i == 0) {
  1085. *smallest = f->smallest;
  1086. *largest = f->largest;
  1087. } else {
  1088. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  1089. *smallest = f->smallest;
  1090. }
  1091. if (icmp_.Compare(f->largest, *largest) > 0) {
  1092. *largest = f->largest;
  1093. }
  1094. }
  1095. }
  1096. }
  1097. // Stores the minimal range that covers all entries in inputs1 and inputs2
  1098. // in *smallest, *largest.
  1099. // REQUIRES: inputs is not empty
  1100. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  1101. const std::vector<FileMetaData*>& inputs2,
  1102. InternalKey* smallest, InternalKey* largest) {
  1103. std::vector<FileMetaData*> all = inputs1;
  1104. all.insert(all.end(), inputs2.begin(), inputs2.end());
  1105. GetRange(all, smallest, largest);
  1106. }
  1107. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  1108. ReadOptions options;
  1109. options.verify_checksums = options_->paranoid_checks;
  1110. options.fill_cache = false;
  1111. // Level-0 files have to be merged together. For other levels,
  1112. // we will make a concatenating iterator per level.
  1113. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  1114. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  1115. Iterator** list = new Iterator*[space];
  1116. int num = 0;
  1117. for (int which = 0; which < 2; which++) {
  1118. if (!c->inputs_[which].empty()) {
  1119. if (c->level() + which == 0) {
  1120. const std::vector<FileMetaData*>& files = c->inputs_[which];
  1121. for (size_t i = 0; i < files.size(); i++) {
  1122. list[num++] = table_cache_->NewIterator(options, files[i]->number,
  1123. files[i]->file_size);
  1124. }
  1125. } else {
  1126. // Create concatenating iterator for the files from this level
  1127. list[num++] = NewTwoLevelIterator(
  1128. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  1129. &GetFileIterator, table_cache_, options);
  1130. }
  1131. }
  1132. }
  1133. assert(num <= space);
  1134. Iterator* result = NewMergingIterator(&icmp_, list, num);
  1135. delete[] list;
  1136. return result;
  1137. }
  1138. Compaction* VersionSet::PickCompaction() {
  1139. Compaction* c;
  1140. int level;
  1141. // We prefer compactions triggered by too much data in a level over
  1142. // the compactions triggered by seeks.
  1143. const bool size_compaction = (current_->compaction_score_ >= 1);
  1144. const bool seek_compaction = (current_->file_to_compact_ != nullptr);
  1145. if (size_compaction) {
  1146. level = current_->compaction_level_;
  1147. assert(level >= 0);
  1148. assert(level + 1 < config::kNumLevels);
  1149. c = new Compaction(options_, level);
  1150. // Pick the first file that comes after compact_pointer_[level]
  1151. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1152. FileMetaData* f = current_->files_[level][i];
  1153. if (compact_pointer_[level].empty() ||
  1154. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  1155. c->inputs_[0].push_back(f);
  1156. break;
  1157. }
  1158. }
  1159. if (c->inputs_[0].empty()) {
  1160. // Wrap-around to the beginning of the key space
  1161. c->inputs_[0].push_back(current_->files_[level][0]);
  1162. }
  1163. } else if (seek_compaction) {
  1164. level = current_->file_to_compact_level_;
  1165. c = new Compaction(options_, level);
  1166. c->inputs_[0].push_back(current_->file_to_compact_);
  1167. } else {
  1168. return nullptr;
  1169. }
  1170. c->input_version_ = current_;
  1171. c->input_version_->Ref();
  1172. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1173. if (level == 0) {
  1174. InternalKey smallest, largest;
  1175. GetRange(c->inputs_[0], &smallest, &largest);
  1176. // Note that the next call will discard the file we placed in
  1177. // c->inputs_[0] earlier and replace it with an overlapping set
  1178. // which will include the picked file.
  1179. current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]);
  1180. assert(!c->inputs_[0].empty());
  1181. }
  1182. SetupOtherInputs(c);
  1183. return c;
  1184. }
  1185. // Finds the largest key in a vector of files. Returns true if files is not
  1186. // empty.
  1187. bool FindLargestKey(const InternalKeyComparator& icmp,
  1188. const std::vector<FileMetaData*>& files,
  1189. InternalKey* largest_key) {
  1190. if (files.empty()) {
  1191. return false;
  1192. }
  1193. *largest_key = files[0]->largest;
  1194. for (size_t i = 1; i < files.size(); ++i) {
  1195. FileMetaData* f = files[i];
  1196. if (icmp.Compare(f->largest, *largest_key) > 0) {
  1197. *largest_key = f->largest;
  1198. }
  1199. }
  1200. return true;
  1201. }
  1202. // Finds minimum file b2=(l2, u2) in level file for which l2 > u1 and
  1203. // user_key(l2) = user_key(u1)
  1204. FileMetaData* FindSmallestBoundaryFile(
  1205. const InternalKeyComparator& icmp,
  1206. const std::vector<FileMetaData*>& level_files,
  1207. const InternalKey& largest_key) {
  1208. const Comparator* user_cmp = icmp.user_comparator();
  1209. FileMetaData* smallest_boundary_file = nullptr;
  1210. for (size_t i = 0; i < level_files.size(); ++i) {
  1211. FileMetaData* f = level_files[i];
  1212. if (icmp.Compare(f->smallest, largest_key) > 0 &&
  1213. user_cmp->Compare(f->smallest.user_key(), largest_key.user_key()) ==
  1214. 0) {
  1215. if (smallest_boundary_file == nullptr ||
  1216. icmp.Compare(f->smallest, smallest_boundary_file->smallest) < 0) {
  1217. smallest_boundary_file = f;
  1218. }
  1219. }
  1220. }
  1221. return smallest_boundary_file;
  1222. }
  1223. // Extracts the largest file b1 from |compaction_files| and then searches for a
  1224. // b2 in |level_files| for which user_key(u1) = user_key(l2). If it finds such a
  1225. // file b2 (known as a boundary file) it adds it to |compaction_files| and then
  1226. // searches again using this new upper bound.
  1227. //
  1228. // If there are two blocks, b1=(l1, u1) and b2=(l2, u2) and
  1229. // user_key(u1) = user_key(l2), and if we compact b1 but not b2 then a
  1230. // subsequent get operation will yield an incorrect result because it will
  1231. // return the record from b2 in level i rather than from b1 because it searches
  1232. // level by level for records matching the supplied user key.
  1233. //
  1234. // parameters:
  1235. // in level_files: List of files to search for boundary files.
  1236. // in/out compaction_files: List of files to extend by adding boundary files.
  1237. void AddBoundaryInputs(const InternalKeyComparator& icmp,
  1238. const std::vector<FileMetaData*>& level_files,
  1239. std::vector<FileMetaData*>* compaction_files) {
  1240. InternalKey largest_key;
  1241. // Quick return if compaction_files is empty.
  1242. if (!FindLargestKey(icmp, *compaction_files, &largest_key)) {
  1243. return;
  1244. }
  1245. bool continue_searching = true;
  1246. while (continue_searching) {
  1247. FileMetaData* smallest_boundary_file =
  1248. FindSmallestBoundaryFile(icmp, level_files, largest_key);
  1249. // If a boundary file was found advance largest_key, otherwise we're done.
  1250. if (smallest_boundary_file != NULL) {
  1251. compaction_files->push_back(smallest_boundary_file);
  1252. largest_key = smallest_boundary_file->largest;
  1253. } else {
  1254. continue_searching = false;
  1255. }
  1256. }
  1257. }
  1258. void VersionSet::SetupOtherInputs(Compaction* c) {
  1259. const int level = c->level();
  1260. InternalKey smallest, largest;
  1261. AddBoundaryInputs(icmp_, current_->files_[level], &c->inputs_[0]);//增加边界值,userkey相等的情况
  1262. GetRange(c->inputs_[0], &smallest, &largest);
  1263. current_->GetOverlappingInputs(level + 1, &smallest, &largest,
  1264. &c->inputs_[1]);
  1265. AddBoundaryInputs(icmp_, current_->files_[level + 1], &c->inputs_[1]);
  1266. // Get entire range covered by compaction
  1267. InternalKey all_start, all_limit;
  1268. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1269. // See if we can grow the number of inputs in "level" without
  1270. // changing the number of "level+1" files we pick up.
  1271. if (!c->inputs_[1].empty()) {
  1272. std::vector<FileMetaData*> expanded0;
  1273. current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0);
  1274. AddBoundaryInputs(icmp_, current_->files_[level], &expanded0);
  1275. const int64_t inputs0_size = TotalFileSize(c->inputs_[0]);
  1276. const int64_t inputs1_size = TotalFileSize(c->inputs_[1]);
  1277. const int64_t expanded0_size = TotalFileSize(expanded0);
  1278. if (expanded0.size() > c->inputs_[0].size() &&
  1279. inputs1_size + expanded0_size <
  1280. ExpandedCompactionByteSizeLimit(options_)) {
  1281. InternalKey new_start, new_limit;
  1282. GetRange(expanded0, &new_start, &new_limit);
  1283. std::vector<FileMetaData*> expanded1;
  1284. current_->GetOverlappingInputs(level + 1, &new_start, &new_limit,
  1285. &expanded1);
  1286. AddBoundaryInputs(icmp_, current_->files_[level + 1], &expanded1);
  1287. if (expanded1.size() == c->inputs_[1].size()) {
  1288. Log(options_->info_log,
  1289. "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n",
  1290. level, int(c->inputs_[0].size()), int(c->inputs_[1].size()),
  1291. long(inputs0_size), long(inputs1_size), int(expanded0.size()),
  1292. int(expanded1.size()), long(expanded0_size), long(inputs1_size));
  1293. smallest = new_start;
  1294. largest = new_limit;
  1295. c->inputs_[0] = expanded0;
  1296. c->inputs_[1] = expanded1;
  1297. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1298. }
  1299. }
  1300. }
  1301. // Compute the set of grandparent files that overlap this compaction
  1302. // (parent == level+1; grandparent == level+2)
  1303. if (level + 2 < config::kNumLevels) {
  1304. current_->GetOverlappingInputs(level + 2, &all_start, &all_limit,
  1305. &c->grandparents_);
  1306. }
  1307. // Update the place where we will do the next compaction for this level.
  1308. // We update this immediately instead of waiting for the VersionEdit
  1309. // to be applied so that if the compaction fails, we will try a different
  1310. // key range next time.
  1311. compact_pointer_[level] = largest.Encode().ToString();
  1312. c->edit_.SetCompactPointer(level, largest);
  1313. }
  1314. //得到基于当前level的所涉及的需要compact的文件,(level0可能会涉及到level1等)
  1315. Compaction* VersionSet::CompactRange(int level, const InternalKey* begin,
  1316. const InternalKey* end) {
  1317. std::vector<FileMetaData*> inputs;
  1318. current_->GetOverlappingInputs(level, begin, end, &inputs);//得到一层的input
  1319. if (inputs.empty()) {
  1320. return nullptr;
  1321. }
  1322. // Avoid compacting too much in one shot in case the range is large.
  1323. // But we cannot do this for level-0 since level-0 files can overlap
  1324. // and we must not pick one file and drop another older file if the
  1325. // two files overlap.
  1326. if (level > 0) {
  1327. const uint64_t limit = MaxFileSizeForLevel(options_, level);
  1328. uint64_t total = 0;
  1329. for (size_t i = 0; i < inputs.size(); i++) {
  1330. uint64_t s = inputs[i]->file_size;
  1331. total += s;
  1332. if (total >= limit) {
  1333. inputs.resize(i + 1);
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. Compaction* c = new Compaction(options_, level);
  1339. c->input_version_ = current_;
  1340. c->input_version_->Ref();
  1341. c->inputs_[0] = inputs;
  1342. SetupOtherInputs(c);
  1343. return c;
  1344. }
  1345. Compaction::Compaction(const Options* options, int level)
  1346. : level_(level),
  1347. max_output_file_size_(MaxFileSizeForLevel(options, level)),
  1348. input_version_(nullptr),
  1349. grandparent_index_(0),
  1350. seen_key_(false),
  1351. overlapped_bytes_(0) {
  1352. for (int i = 0; i < config::kNumLevels; i++) {
  1353. level_ptrs_[i] = 0;
  1354. }
  1355. }
  1356. Compaction::~Compaction() {
  1357. if (input_version_ != nullptr) {
  1358. input_version_->Unref();
  1359. }
  1360. }
  1361. bool Compaction::IsTrivialMove() const {
  1362. const VersionSet* vset = input_version_->vset_;
  1363. // Avoid a move if there is lots of overlapping grandparent data.
  1364. // Otherwise, the move could create a parent file that will require
  1365. // a very expensive merge later on.
  1366. return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
  1367. TotalFileSize(grandparents_) <=
  1368. MaxGrandParentOverlapBytes(vset->options_));
  1369. }
  1370. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1371. for (int which = 0; which < 2; which++) {
  1372. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1373. edit->RemoveFile(level_ + which, inputs_[which][i]->number);
  1374. }
  1375. }
  1376. }
  1377. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1378. // Maybe use binary search to find right entry instead of linear search?
  1379. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1380. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1381. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1382. while (level_ptrs_[lvl] < files.size()) {
  1383. FileMetaData* f = files[level_ptrs_[lvl]];
  1384. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1385. // We've advanced far enough
  1386. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1387. // Key falls in this file's range, so definitely not base level
  1388. return false;
  1389. }
  1390. break;
  1391. }
  1392. level_ptrs_[lvl]++;
  1393. }
  1394. }
  1395. return true;
  1396. }
  1397. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1398. const VersionSet* vset = input_version_->vset_;
  1399. // Scan to find earliest grandparent file that contains key.
  1400. const InternalKeyComparator* icmp = &vset->icmp_;
  1401. while (grandparent_index_ < grandparents_.size() &&
  1402. icmp->Compare(internal_key,
  1403. grandparents_[grandparent_index_]->largest.Encode()) >
  1404. 0) {
  1405. if (seen_key_) {
  1406. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1407. }
  1408. grandparent_index_++;
  1409. }
  1410. seen_key_ = true;
  1411. if (overlapped_bytes_ > MaxGrandParentOverlapBytes(vset->options_)) {
  1412. // Too much overlap for current output; start new output
  1413. overlapped_bytes_ = 0;
  1414. return true;
  1415. } else {
  1416. return false;
  1417. }
  1418. }
  1419. void Compaction::ReleaseInputs() {
  1420. if (input_version_ != nullptr) {
  1421. input_version_->Unref();
  1422. input_version_ = nullptr;
  1423. }
  1424. }
  1425. } // namespace leveldb