小组成员:10215300402-朱维清 & 10222140408 谷杰
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.

1438 satır
45 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. if (!s.ok()) {
  719. Log(options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str());
  720. if (ManifestContains(record)) {
  721. Log(options_->info_log,
  722. "MANIFEST contains log record despite error; advancing to new "
  723. "version to prevent mismatch between in-memory and logged state");
  724. s = Status::OK();
  725. }
  726. }
  727. }
  728. // If we just created a new descriptor file, install it by writing a
  729. // new CURRENT file that points to it.
  730. if (s.ok() && !new_manifest_file.empty()) {
  731. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  732. // No need to double-check MANIFEST in case of error since it
  733. // will be discarded below.
  734. }
  735. mu->Lock();
  736. }
  737. // Install the new version
  738. if (s.ok()) {
  739. AppendVersion(v);
  740. log_number_ = edit->log_number_;
  741. prev_log_number_ = edit->prev_log_number_;
  742. } else {
  743. delete v;
  744. if (!new_manifest_file.empty()) {
  745. delete descriptor_log_;
  746. delete descriptor_file_;
  747. descriptor_log_ = NULL;
  748. descriptor_file_ = NULL;
  749. env_->DeleteFile(new_manifest_file);
  750. }
  751. }
  752. return s;
  753. }
  754. Status VersionSet::Recover() {
  755. struct LogReporter : public log::Reader::Reporter {
  756. Status* status;
  757. virtual void Corruption(size_t bytes, const Status& s) {
  758. if (this->status->ok()) *this->status = s;
  759. }
  760. };
  761. // Read "CURRENT" file, which contains a pointer to the current manifest file
  762. std::string current;
  763. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  764. if (!s.ok()) {
  765. return s;
  766. }
  767. if (current.empty() || current[current.size()-1] != '\n') {
  768. return Status::Corruption("CURRENT file does not end with newline");
  769. }
  770. current.resize(current.size() - 1);
  771. std::string dscname = dbname_ + "/" + current;
  772. SequentialFile* file;
  773. s = env_->NewSequentialFile(dscname, &file);
  774. if (!s.ok()) {
  775. return s;
  776. }
  777. bool have_log_number = false;
  778. bool have_prev_log_number = false;
  779. bool have_next_file = false;
  780. bool have_last_sequence = false;
  781. uint64_t next_file = 0;
  782. uint64_t last_sequence = 0;
  783. uint64_t log_number = 0;
  784. uint64_t prev_log_number = 0;
  785. Builder builder(this, current_);
  786. {
  787. LogReporter reporter;
  788. reporter.status = &s;
  789. log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/);
  790. Slice record;
  791. std::string scratch;
  792. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  793. VersionEdit edit;
  794. s = edit.DecodeFrom(record);
  795. if (s.ok()) {
  796. if (edit.has_comparator_ &&
  797. edit.comparator_ != icmp_.user_comparator()->Name()) {
  798. s = Status::InvalidArgument(
  799. edit.comparator_ + " does not match existing comparator ",
  800. icmp_.user_comparator()->Name());
  801. }
  802. }
  803. if (s.ok()) {
  804. builder.Apply(&edit);
  805. }
  806. if (edit.has_log_number_) {
  807. log_number = edit.log_number_;
  808. have_log_number = true;
  809. }
  810. if (edit.has_prev_log_number_) {
  811. prev_log_number = edit.prev_log_number_;
  812. have_prev_log_number = true;
  813. }
  814. if (edit.has_next_file_number_) {
  815. next_file = edit.next_file_number_;
  816. have_next_file = true;
  817. }
  818. if (edit.has_last_sequence_) {
  819. last_sequence = edit.last_sequence_;
  820. have_last_sequence = true;
  821. }
  822. }
  823. }
  824. delete file;
  825. file = NULL;
  826. if (s.ok()) {
  827. if (!have_next_file) {
  828. s = Status::Corruption("no meta-nextfile entry in descriptor");
  829. } else if (!have_log_number) {
  830. s = Status::Corruption("no meta-lognumber entry in descriptor");
  831. } else if (!have_last_sequence) {
  832. s = Status::Corruption("no last-sequence-number entry in descriptor");
  833. }
  834. if (!have_prev_log_number) {
  835. prev_log_number = 0;
  836. }
  837. MarkFileNumberUsed(prev_log_number);
  838. MarkFileNumberUsed(log_number);
  839. }
  840. if (s.ok()) {
  841. Version* v = new Version(this);
  842. builder.SaveTo(v);
  843. // Install recovered version
  844. Finalize(v);
  845. AppendVersion(v);
  846. manifest_file_number_ = next_file;
  847. next_file_number_ = next_file + 1;
  848. last_sequence_ = last_sequence;
  849. log_number_ = log_number;
  850. prev_log_number_ = prev_log_number;
  851. }
  852. return s;
  853. }
  854. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  855. if (next_file_number_ <= number) {
  856. next_file_number_ = number + 1;
  857. }
  858. }
  859. void VersionSet::Finalize(Version* v) {
  860. // Precomputed best level for next compaction
  861. int best_level = -1;
  862. double best_score = -1;
  863. for (int level = 0; level < config::kNumLevels-1; level++) {
  864. double score;
  865. if (level == 0) {
  866. // We treat level-0 specially by bounding the number of files
  867. // instead of number of bytes for two reasons:
  868. //
  869. // (1) With larger write-buffer sizes, it is nice not to do too
  870. // many level-0 compactions.
  871. //
  872. // (2) The files in level-0 are merged on every read and
  873. // therefore we wish to avoid too many files when the individual
  874. // file size is small (perhaps because of a small write-buffer
  875. // setting, or very high compression ratios, or lots of
  876. // overwrites/deletions).
  877. score = v->files_[level].size() /
  878. static_cast<double>(config::kL0_CompactionTrigger);
  879. } else {
  880. // Compute the ratio of current size to size limit.
  881. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  882. score = static_cast<double>(level_bytes) / MaxBytesForLevel(level);
  883. }
  884. if (score > best_score) {
  885. best_level = level;
  886. best_score = score;
  887. }
  888. }
  889. v->compaction_level_ = best_level;
  890. v->compaction_score_ = best_score;
  891. }
  892. Status VersionSet::WriteSnapshot(log::Writer* log) {
  893. // TODO: Break up into multiple records to reduce memory usage on recovery?
  894. // Save metadata
  895. VersionEdit edit;
  896. edit.SetComparatorName(icmp_.user_comparator()->Name());
  897. // Save compaction pointers
  898. for (int level = 0; level < config::kNumLevels; level++) {
  899. if (!compact_pointer_[level].empty()) {
  900. InternalKey key;
  901. key.DecodeFrom(compact_pointer_[level]);
  902. edit.SetCompactPointer(level, key);
  903. }
  904. }
  905. // Save files
  906. for (int level = 0; level < config::kNumLevels; level++) {
  907. const std::vector<FileMetaData*>& files = current_->files_[level];
  908. for (size_t i = 0; i < files.size(); i++) {
  909. const FileMetaData* f = files[i];
  910. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  911. }
  912. }
  913. std::string record;
  914. edit.EncodeTo(&record);
  915. return log->AddRecord(record);
  916. }
  917. int VersionSet::NumLevelFiles(int level) const {
  918. assert(level >= 0);
  919. assert(level < config::kNumLevels);
  920. return current_->files_[level].size();
  921. }
  922. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  923. // Update code if kNumLevels changes
  924. assert(config::kNumLevels == 7);
  925. snprintf(scratch->buffer, sizeof(scratch->buffer),
  926. "files[ %d %d %d %d %d %d %d ]",
  927. int(current_->files_[0].size()),
  928. int(current_->files_[1].size()),
  929. int(current_->files_[2].size()),
  930. int(current_->files_[3].size()),
  931. int(current_->files_[4].size()),
  932. int(current_->files_[5].size()),
  933. int(current_->files_[6].size()));
  934. return scratch->buffer;
  935. }
  936. // Return true iff the manifest contains the specified record.
  937. bool VersionSet::ManifestContains(const std::string& record) const {
  938. std::string fname = DescriptorFileName(dbname_, manifest_file_number_);
  939. Log(options_->info_log, "ManifestContains: checking %s\n", fname.c_str());
  940. SequentialFile* file = NULL;
  941. Status s = env_->NewSequentialFile(fname, &file);
  942. if (!s.ok()) {
  943. Log(options_->info_log, "ManifestContains: %s\n", s.ToString().c_str());
  944. return false;
  945. }
  946. log::Reader reader(file, NULL, true/*checksum*/, 0);
  947. Slice r;
  948. std::string scratch;
  949. bool result = false;
  950. while (reader.ReadRecord(&r, &scratch)) {
  951. if (r == Slice(record)) {
  952. result = true;
  953. break;
  954. }
  955. }
  956. delete file;
  957. Log(options_->info_log, "ManifestContains: result = %d\n", result ? 1 : 0);
  958. return result;
  959. }
  960. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  961. uint64_t result = 0;
  962. for (int level = 0; level < config::kNumLevels; level++) {
  963. const std::vector<FileMetaData*>& files = v->files_[level];
  964. for (size_t i = 0; i < files.size(); i++) {
  965. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  966. // Entire file is before "ikey", so just add the file size
  967. result += files[i]->file_size;
  968. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  969. // Entire file is after "ikey", so ignore
  970. if (level > 0) {
  971. // Files other than level 0 are sorted by meta->smallest, so
  972. // no further files in this level will contain data for
  973. // "ikey".
  974. break;
  975. }
  976. } else {
  977. // "ikey" falls in the range for this table. Add the
  978. // approximate offset of "ikey" within the table.
  979. Table* tableptr;
  980. Iterator* iter = table_cache_->NewIterator(
  981. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  982. if (tableptr != NULL) {
  983. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  984. }
  985. delete iter;
  986. }
  987. }
  988. }
  989. return result;
  990. }
  991. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  992. for (Version* v = dummy_versions_.next_;
  993. v != &dummy_versions_;
  994. v = v->next_) {
  995. for (int level = 0; level < config::kNumLevels; level++) {
  996. const std::vector<FileMetaData*>& files = v->files_[level];
  997. for (size_t i = 0; i < files.size(); i++) {
  998. live->insert(files[i]->number);
  999. }
  1000. }
  1001. }
  1002. }
  1003. int64_t VersionSet::NumLevelBytes(int level) const {
  1004. assert(level >= 0);
  1005. assert(level < config::kNumLevels);
  1006. return TotalFileSize(current_->files_[level]);
  1007. }
  1008. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  1009. int64_t result = 0;
  1010. std::vector<FileMetaData*> overlaps;
  1011. for (int level = 1; level < config::kNumLevels - 1; level++) {
  1012. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1013. const FileMetaData* f = current_->files_[level][i];
  1014. current_->GetOverlappingInputs(level+1, &f->smallest, &f->largest,
  1015. &overlaps);
  1016. const int64_t sum = TotalFileSize(overlaps);
  1017. if (sum > result) {
  1018. result = sum;
  1019. }
  1020. }
  1021. }
  1022. return result;
  1023. }
  1024. // Stores the minimal range that covers all entries in inputs in
  1025. // *smallest, *largest.
  1026. // REQUIRES: inputs is not empty
  1027. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  1028. InternalKey* smallest,
  1029. InternalKey* largest) {
  1030. assert(!inputs.empty());
  1031. smallest->Clear();
  1032. largest->Clear();
  1033. for (size_t i = 0; i < inputs.size(); i++) {
  1034. FileMetaData* f = inputs[i];
  1035. if (i == 0) {
  1036. *smallest = f->smallest;
  1037. *largest = f->largest;
  1038. } else {
  1039. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  1040. *smallest = f->smallest;
  1041. }
  1042. if (icmp_.Compare(f->largest, *largest) > 0) {
  1043. *largest = f->largest;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. // Stores the minimal range that covers all entries in inputs1 and inputs2
  1049. // in *smallest, *largest.
  1050. // REQUIRES: inputs is not empty
  1051. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  1052. const std::vector<FileMetaData*>& inputs2,
  1053. InternalKey* smallest,
  1054. InternalKey* largest) {
  1055. std::vector<FileMetaData*> all = inputs1;
  1056. all.insert(all.end(), inputs2.begin(), inputs2.end());
  1057. GetRange(all, smallest, largest);
  1058. }
  1059. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  1060. ReadOptions options;
  1061. options.verify_checksums = options_->paranoid_checks;
  1062. options.fill_cache = false;
  1063. // Level-0 files have to be merged together. For other levels,
  1064. // we will make a concatenating iterator per level.
  1065. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  1066. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  1067. Iterator** list = new Iterator*[space];
  1068. int num = 0;
  1069. for (int which = 0; which < 2; which++) {
  1070. if (!c->inputs_[which].empty()) {
  1071. if (c->level() + which == 0) {
  1072. const std::vector<FileMetaData*>& files = c->inputs_[which];
  1073. for (size_t i = 0; i < files.size(); i++) {
  1074. list[num++] = table_cache_->NewIterator(
  1075. options, files[i]->number, files[i]->file_size);
  1076. }
  1077. } else {
  1078. // Create concatenating iterator for the files from this level
  1079. list[num++] = NewTwoLevelIterator(
  1080. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  1081. &GetFileIterator, table_cache_, options);
  1082. }
  1083. }
  1084. }
  1085. assert(num <= space);
  1086. Iterator* result = NewMergingIterator(&icmp_, list, num);
  1087. delete[] list;
  1088. return result;
  1089. }
  1090. Compaction* VersionSet::PickCompaction() {
  1091. Compaction* c;
  1092. int level;
  1093. // We prefer compactions triggered by too much data in a level over
  1094. // the compactions triggered by seeks.
  1095. const bool size_compaction = (current_->compaction_score_ >= 1);
  1096. const bool seek_compaction = (current_->file_to_compact_ != NULL);
  1097. if (size_compaction) {
  1098. level = current_->compaction_level_;
  1099. assert(level >= 0);
  1100. assert(level+1 < config::kNumLevels);
  1101. c = new Compaction(level);
  1102. // Pick the first file that comes after compact_pointer_[level]
  1103. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1104. FileMetaData* f = current_->files_[level][i];
  1105. if (compact_pointer_[level].empty() ||
  1106. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  1107. c->inputs_[0].push_back(f);
  1108. break;
  1109. }
  1110. }
  1111. if (c->inputs_[0].empty()) {
  1112. // Wrap-around to the beginning of the key space
  1113. c->inputs_[0].push_back(current_->files_[level][0]);
  1114. }
  1115. } else if (seek_compaction) {
  1116. level = current_->file_to_compact_level_;
  1117. c = new Compaction(level);
  1118. c->inputs_[0].push_back(current_->file_to_compact_);
  1119. } else {
  1120. return NULL;
  1121. }
  1122. c->input_version_ = current_;
  1123. c->input_version_->Ref();
  1124. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1125. if (level == 0) {
  1126. InternalKey smallest, largest;
  1127. GetRange(c->inputs_[0], &smallest, &largest);
  1128. // Note that the next call will discard the file we placed in
  1129. // c->inputs_[0] earlier and replace it with an overlapping set
  1130. // which will include the picked file.
  1131. current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]);
  1132. assert(!c->inputs_[0].empty());
  1133. }
  1134. SetupOtherInputs(c);
  1135. return c;
  1136. }
  1137. void VersionSet::SetupOtherInputs(Compaction* c) {
  1138. const int level = c->level();
  1139. InternalKey smallest, largest;
  1140. GetRange(c->inputs_[0], &smallest, &largest);
  1141. current_->GetOverlappingInputs(level+1, &smallest, &largest, &c->inputs_[1]);
  1142. // Get entire range covered by compaction
  1143. InternalKey all_start, all_limit;
  1144. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1145. // See if we can grow the number of inputs in "level" without
  1146. // changing the number of "level+1" files we pick up.
  1147. if (!c->inputs_[1].empty()) {
  1148. std::vector<FileMetaData*> expanded0;
  1149. current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0);
  1150. const int64_t inputs0_size = TotalFileSize(c->inputs_[0]);
  1151. const int64_t inputs1_size = TotalFileSize(c->inputs_[1]);
  1152. const int64_t expanded0_size = TotalFileSize(expanded0);
  1153. if (expanded0.size() > c->inputs_[0].size() &&
  1154. inputs1_size + expanded0_size < kExpandedCompactionByteSizeLimit) {
  1155. InternalKey new_start, new_limit;
  1156. GetRange(expanded0, &new_start, &new_limit);
  1157. std::vector<FileMetaData*> expanded1;
  1158. current_->GetOverlappingInputs(level+1, &new_start, &new_limit,
  1159. &expanded1);
  1160. if (expanded1.size() == c->inputs_[1].size()) {
  1161. Log(options_->info_log,
  1162. "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n",
  1163. level,
  1164. int(c->inputs_[0].size()),
  1165. int(c->inputs_[1].size()),
  1166. long(inputs0_size), long(inputs1_size),
  1167. int(expanded0.size()),
  1168. int(expanded1.size()),
  1169. long(expanded0_size), long(inputs1_size));
  1170. smallest = new_start;
  1171. largest = new_limit;
  1172. c->inputs_[0] = expanded0;
  1173. c->inputs_[1] = expanded1;
  1174. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1175. }
  1176. }
  1177. }
  1178. // Compute the set of grandparent files that overlap this compaction
  1179. // (parent == level+1; grandparent == level+2)
  1180. if (level + 2 < config::kNumLevels) {
  1181. current_->GetOverlappingInputs(level + 2, &all_start, &all_limit,
  1182. &c->grandparents_);
  1183. }
  1184. if (false) {
  1185. Log(options_->info_log, "Compacting %d '%s' .. '%s'",
  1186. level,
  1187. smallest.DebugString().c_str(),
  1188. largest.DebugString().c_str());
  1189. }
  1190. // Update the place where we will do the next compaction for this level.
  1191. // We update this immediately instead of waiting for the VersionEdit
  1192. // to be applied so that if the compaction fails, we will try a different
  1193. // key range next time.
  1194. compact_pointer_[level] = largest.Encode().ToString();
  1195. c->edit_.SetCompactPointer(level, largest);
  1196. }
  1197. Compaction* VersionSet::CompactRange(
  1198. int level,
  1199. const InternalKey* begin,
  1200. const InternalKey* end) {
  1201. std::vector<FileMetaData*> inputs;
  1202. current_->GetOverlappingInputs(level, begin, end, &inputs);
  1203. if (inputs.empty()) {
  1204. return NULL;
  1205. }
  1206. // Avoid compacting too much in one shot in case the range is large.
  1207. const uint64_t limit = MaxFileSizeForLevel(level);
  1208. uint64_t total = 0;
  1209. for (size_t i = 0; i < inputs.size(); i++) {
  1210. uint64_t s = inputs[i]->file_size;
  1211. total += s;
  1212. if (total >= limit) {
  1213. inputs.resize(i + 1);
  1214. break;
  1215. }
  1216. }
  1217. Compaction* c = new Compaction(level);
  1218. c->input_version_ = current_;
  1219. c->input_version_->Ref();
  1220. c->inputs_[0] = inputs;
  1221. SetupOtherInputs(c);
  1222. return c;
  1223. }
  1224. Compaction::Compaction(int level)
  1225. : level_(level),
  1226. max_output_file_size_(MaxFileSizeForLevel(level)),
  1227. input_version_(NULL),
  1228. grandparent_index_(0),
  1229. seen_key_(false),
  1230. overlapped_bytes_(0) {
  1231. for (int i = 0; i < config::kNumLevels; i++) {
  1232. level_ptrs_[i] = 0;
  1233. }
  1234. }
  1235. Compaction::~Compaction() {
  1236. if (input_version_ != NULL) {
  1237. input_version_->Unref();
  1238. }
  1239. }
  1240. bool Compaction::IsTrivialMove() const {
  1241. // Avoid a move if there is lots of overlapping grandparent data.
  1242. // Otherwise, the move could create a parent file that will require
  1243. // a very expensive merge later on.
  1244. return (num_input_files(0) == 1 &&
  1245. num_input_files(1) == 0 &&
  1246. TotalFileSize(grandparents_) <= kMaxGrandParentOverlapBytes);
  1247. }
  1248. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1249. for (int which = 0; which < 2; which++) {
  1250. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1251. edit->DeleteFile(level_ + which, inputs_[which][i]->number);
  1252. }
  1253. }
  1254. }
  1255. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1256. // Maybe use binary search to find right entry instead of linear search?
  1257. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1258. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1259. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1260. for (; level_ptrs_[lvl] < files.size(); ) {
  1261. FileMetaData* f = files[level_ptrs_[lvl]];
  1262. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1263. // We've advanced far enough
  1264. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1265. // Key falls in this file's range, so definitely not base level
  1266. return false;
  1267. }
  1268. break;
  1269. }
  1270. level_ptrs_[lvl]++;
  1271. }
  1272. }
  1273. return true;
  1274. }
  1275. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1276. // Scan to find earliest grandparent file that contains key.
  1277. const InternalKeyComparator* icmp = &input_version_->vset_->icmp_;
  1278. while (grandparent_index_ < grandparents_.size() &&
  1279. icmp->Compare(internal_key,
  1280. grandparents_[grandparent_index_]->largest.Encode()) > 0) {
  1281. if (seen_key_) {
  1282. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1283. }
  1284. grandparent_index_++;
  1285. }
  1286. seen_key_ = true;
  1287. if (overlapped_bytes_ > kMaxGrandParentOverlapBytes) {
  1288. // Too much overlap for current output; start new output
  1289. overlapped_bytes_ = 0;
  1290. return true;
  1291. } else {
  1292. return false;
  1293. }
  1294. }
  1295. void Compaction::ReleaseInputs() {
  1296. if (input_version_ != NULL) {
  1297. input_version_->Unref();
  1298. input_version_ = NULL;
  1299. }
  1300. }
  1301. } // namespace leveldb