25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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