Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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