小组成员:姚凯文(kevinyao0901),姜嘉琪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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