小组成员:10215300402-朱维清 & 10222140408 谷杰
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1532 строки
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. if (s.IsNotFound()) {
  842. return Status::Corruption(
  843. "CURRENT points to a non-existent file", s.ToString());
  844. }
  845. return s;
  846. }
  847. bool have_log_number = false;
  848. bool have_prev_log_number = false;
  849. bool have_next_file = false;
  850. bool have_last_sequence = false;
  851. uint64_t next_file = 0;
  852. uint64_t last_sequence = 0;
  853. uint64_t log_number = 0;
  854. uint64_t prev_log_number = 0;
  855. Builder builder(this, current_);
  856. {
  857. LogReporter reporter;
  858. reporter.status = &s;
  859. log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/);
  860. Slice record;
  861. std::string scratch;
  862. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  863. VersionEdit edit;
  864. s = edit.DecodeFrom(record);
  865. if (s.ok()) {
  866. if (edit.has_comparator_ &&
  867. edit.comparator_ != icmp_.user_comparator()->Name()) {
  868. s = Status::InvalidArgument(
  869. edit.comparator_ + " does not match existing comparator ",
  870. icmp_.user_comparator()->Name());
  871. }
  872. }
  873. if (s.ok()) {
  874. builder.Apply(&edit);
  875. }
  876. if (edit.has_log_number_) {
  877. log_number = edit.log_number_;
  878. have_log_number = true;
  879. }
  880. if (edit.has_prev_log_number_) {
  881. prev_log_number = edit.prev_log_number_;
  882. have_prev_log_number = true;
  883. }
  884. if (edit.has_next_file_number_) {
  885. next_file = edit.next_file_number_;
  886. have_next_file = true;
  887. }
  888. if (edit.has_last_sequence_) {
  889. last_sequence = edit.last_sequence_;
  890. have_last_sequence = true;
  891. }
  892. }
  893. }
  894. delete file;
  895. file = NULL;
  896. if (s.ok()) {
  897. if (!have_next_file) {
  898. s = Status::Corruption("no meta-nextfile entry in descriptor");
  899. } else if (!have_log_number) {
  900. s = Status::Corruption("no meta-lognumber entry in descriptor");
  901. } else if (!have_last_sequence) {
  902. s = Status::Corruption("no last-sequence-number entry in descriptor");
  903. }
  904. if (!have_prev_log_number) {
  905. prev_log_number = 0;
  906. }
  907. MarkFileNumberUsed(prev_log_number);
  908. MarkFileNumberUsed(log_number);
  909. }
  910. if (s.ok()) {
  911. Version* v = new Version(this);
  912. builder.SaveTo(v);
  913. // Install recovered version
  914. Finalize(v);
  915. AppendVersion(v);
  916. manifest_file_number_ = next_file;
  917. next_file_number_ = next_file + 1;
  918. last_sequence_ = last_sequence;
  919. log_number_ = log_number;
  920. prev_log_number_ = prev_log_number;
  921. // See if we can reuse the existing MANIFEST file.
  922. if (ReuseManifest(dscname, current)) {
  923. // No need to save new manifest
  924. } else {
  925. *save_manifest = true;
  926. }
  927. }
  928. return s;
  929. }
  930. bool VersionSet::ReuseManifest(const std::string& dscname,
  931. const std::string& dscbase) {
  932. if (!options_->reuse_logs) {
  933. return false;
  934. }
  935. FileType manifest_type;
  936. uint64_t manifest_number;
  937. uint64_t manifest_size;
  938. if (!ParseFileName(dscbase, &manifest_number, &manifest_type) ||
  939. manifest_type != kDescriptorFile ||
  940. !env_->GetFileSize(dscname, &manifest_size).ok() ||
  941. // Make new compacted MANIFEST if old one is too big
  942. manifest_size >= TargetFileSize(options_)) {
  943. return false;
  944. }
  945. assert(descriptor_file_ == NULL);
  946. assert(descriptor_log_ == NULL);
  947. Status r = env_->NewAppendableFile(dscname, &descriptor_file_);
  948. if (!r.ok()) {
  949. Log(options_->info_log, "Reuse MANIFEST: %s\n", r.ToString().c_str());
  950. assert(descriptor_file_ == NULL);
  951. return false;
  952. }
  953. Log(options_->info_log, "Reusing MANIFEST %s\n", dscname.c_str());
  954. descriptor_log_ = new log::Writer(descriptor_file_, manifest_size);
  955. manifest_file_number_ = manifest_number;
  956. return true;
  957. }
  958. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  959. if (next_file_number_ <= number) {
  960. next_file_number_ = number + 1;
  961. }
  962. }
  963. void VersionSet::Finalize(Version* v) {
  964. // Precomputed best level for next compaction
  965. int best_level = -1;
  966. double best_score = -1;
  967. for (int level = 0; level < config::kNumLevels-1; level++) {
  968. double score;
  969. if (level == 0) {
  970. // We treat level-0 specially by bounding the number of files
  971. // instead of number of bytes for two reasons:
  972. //
  973. // (1) With larger write-buffer sizes, it is nice not to do too
  974. // many level-0 compactions.
  975. //
  976. // (2) The files in level-0 are merged on every read and
  977. // therefore we wish to avoid too many files when the individual
  978. // file size is small (perhaps because of a small write-buffer
  979. // setting, or very high compression ratios, or lots of
  980. // overwrites/deletions).
  981. score = v->files_[level].size() /
  982. static_cast<double>(config::kL0_CompactionTrigger);
  983. } else {
  984. // Compute the ratio of current size to size limit.
  985. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  986. score =
  987. static_cast<double>(level_bytes) / MaxBytesForLevel(options_, level);
  988. }
  989. if (score > best_score) {
  990. best_level = level;
  991. best_score = score;
  992. }
  993. }
  994. v->compaction_level_ = best_level;
  995. v->compaction_score_ = best_score;
  996. }
  997. Status VersionSet::WriteSnapshot(log::Writer* log) {
  998. // TODO: Break up into multiple records to reduce memory usage on recovery?
  999. // Save metadata
  1000. VersionEdit edit;
  1001. edit.SetComparatorName(icmp_.user_comparator()->Name());
  1002. // Save compaction pointers
  1003. for (int level = 0; level < config::kNumLevels; level++) {
  1004. if (!compact_pointer_[level].empty()) {
  1005. InternalKey key;
  1006. key.DecodeFrom(compact_pointer_[level]);
  1007. edit.SetCompactPointer(level, key);
  1008. }
  1009. }
  1010. // Save files
  1011. for (int level = 0; level < config::kNumLevels; level++) {
  1012. const std::vector<FileMetaData*>& files = current_->files_[level];
  1013. for (size_t i = 0; i < files.size(); i++) {
  1014. const FileMetaData* f = files[i];
  1015. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  1016. }
  1017. }
  1018. std::string record;
  1019. edit.EncodeTo(&record);
  1020. return log->AddRecord(record);
  1021. }
  1022. int VersionSet::NumLevelFiles(int level) const {
  1023. assert(level >= 0);
  1024. assert(level < config::kNumLevels);
  1025. return current_->files_[level].size();
  1026. }
  1027. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  1028. // Update code if kNumLevels changes
  1029. assert(config::kNumLevels == 7);
  1030. snprintf(scratch->buffer, sizeof(scratch->buffer),
  1031. "files[ %d %d %d %d %d %d %d ]",
  1032. int(current_->files_[0].size()),
  1033. int(current_->files_[1].size()),
  1034. int(current_->files_[2].size()),
  1035. int(current_->files_[3].size()),
  1036. int(current_->files_[4].size()),
  1037. int(current_->files_[5].size()),
  1038. int(current_->files_[6].size()));
  1039. return scratch->buffer;
  1040. }
  1041. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  1042. uint64_t result = 0;
  1043. for (int level = 0; level < config::kNumLevels; level++) {
  1044. const std::vector<FileMetaData*>& files = v->files_[level];
  1045. for (size_t i = 0; i < files.size(); i++) {
  1046. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  1047. // Entire file is before "ikey", so just add the file size
  1048. result += files[i]->file_size;
  1049. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  1050. // Entire file is after "ikey", so ignore
  1051. if (level > 0) {
  1052. // Files other than level 0 are sorted by meta->smallest, so
  1053. // no further files in this level will contain data for
  1054. // "ikey".
  1055. break;
  1056. }
  1057. } else {
  1058. // "ikey" falls in the range for this table. Add the
  1059. // approximate offset of "ikey" within the table.
  1060. Table* tableptr;
  1061. Iterator* iter = table_cache_->NewIterator(
  1062. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  1063. if (tableptr != NULL) {
  1064. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  1065. }
  1066. delete iter;
  1067. }
  1068. }
  1069. }
  1070. return result;
  1071. }
  1072. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  1073. for (Version* v = dummy_versions_.next_;
  1074. v != &dummy_versions_;
  1075. v = v->next_) {
  1076. for (int level = 0; level < config::kNumLevels; level++) {
  1077. const std::vector<FileMetaData*>& files = v->files_[level];
  1078. for (size_t i = 0; i < files.size(); i++) {
  1079. live->insert(files[i]->number);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. int64_t VersionSet::NumLevelBytes(int level) const {
  1085. assert(level >= 0);
  1086. assert(level < config::kNumLevels);
  1087. return TotalFileSize(current_->files_[level]);
  1088. }
  1089. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  1090. int64_t result = 0;
  1091. std::vector<FileMetaData*> overlaps;
  1092. for (int level = 1; level < config::kNumLevels - 1; level++) {
  1093. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1094. const FileMetaData* f = current_->files_[level][i];
  1095. current_->GetOverlappingInputs(level+1, &f->smallest, &f->largest,
  1096. &overlaps);
  1097. const int64_t sum = TotalFileSize(overlaps);
  1098. if (sum > result) {
  1099. result = sum;
  1100. }
  1101. }
  1102. }
  1103. return result;
  1104. }
  1105. // Stores the minimal range that covers all entries in inputs in
  1106. // *smallest, *largest.
  1107. // REQUIRES: inputs is not empty
  1108. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  1109. InternalKey* smallest,
  1110. InternalKey* largest) {
  1111. assert(!inputs.empty());
  1112. smallest->Clear();
  1113. largest->Clear();
  1114. for (size_t i = 0; i < inputs.size(); i++) {
  1115. FileMetaData* f = inputs[i];
  1116. if (i == 0) {
  1117. *smallest = f->smallest;
  1118. *largest = f->largest;
  1119. } else {
  1120. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  1121. *smallest = f->smallest;
  1122. }
  1123. if (icmp_.Compare(f->largest, *largest) > 0) {
  1124. *largest = f->largest;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. // Stores the minimal range that covers all entries in inputs1 and inputs2
  1130. // in *smallest, *largest.
  1131. // REQUIRES: inputs is not empty
  1132. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  1133. const std::vector<FileMetaData*>& inputs2,
  1134. InternalKey* smallest,
  1135. InternalKey* largest) {
  1136. std::vector<FileMetaData*> all = inputs1;
  1137. all.insert(all.end(), inputs2.begin(), inputs2.end());
  1138. GetRange(all, smallest, largest);
  1139. }
  1140. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  1141. ReadOptions options;
  1142. options.verify_checksums = options_->paranoid_checks;
  1143. options.fill_cache = false;
  1144. // Level-0 files have to be merged together. For other levels,
  1145. // we will make a concatenating iterator per level.
  1146. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  1147. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  1148. Iterator** list = new Iterator*[space];
  1149. int num = 0;
  1150. for (int which = 0; which < 2; which++) {
  1151. if (!c->inputs_[which].empty()) {
  1152. if (c->level() + which == 0) {
  1153. const std::vector<FileMetaData*>& files = c->inputs_[which];
  1154. for (size_t i = 0; i < files.size(); i++) {
  1155. list[num++] = table_cache_->NewIterator(
  1156. options, files[i]->number, files[i]->file_size);
  1157. }
  1158. } else {
  1159. // Create concatenating iterator for the files from this level
  1160. list[num++] = NewTwoLevelIterator(
  1161. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  1162. &GetFileIterator, table_cache_, options);
  1163. }
  1164. }
  1165. }
  1166. assert(num <= space);
  1167. Iterator* result = NewMergingIterator(&icmp_, list, num);
  1168. delete[] list;
  1169. return result;
  1170. }
  1171. Compaction* VersionSet::PickCompaction() {
  1172. Compaction* c;
  1173. int level;
  1174. // We prefer compactions triggered by too much data in a level over
  1175. // the compactions triggered by seeks.
  1176. const bool size_compaction = (current_->compaction_score_ >= 1);
  1177. const bool seek_compaction = (current_->file_to_compact_ != NULL);
  1178. if (size_compaction) {
  1179. level = current_->compaction_level_;
  1180. assert(level >= 0);
  1181. assert(level+1 < config::kNumLevels);
  1182. c = new Compaction(options_, level);
  1183. // Pick the first file that comes after compact_pointer_[level]
  1184. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1185. FileMetaData* f = current_->files_[level][i];
  1186. if (compact_pointer_[level].empty() ||
  1187. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  1188. c->inputs_[0].push_back(f);
  1189. break;
  1190. }
  1191. }
  1192. if (c->inputs_[0].empty()) {
  1193. // Wrap-around to the beginning of the key space
  1194. c->inputs_[0].push_back(current_->files_[level][0]);
  1195. }
  1196. } else if (seek_compaction) {
  1197. level = current_->file_to_compact_level_;
  1198. c = new Compaction(options_, level);
  1199. c->inputs_[0].push_back(current_->file_to_compact_);
  1200. } else {
  1201. return NULL;
  1202. }
  1203. c->input_version_ = current_;
  1204. c->input_version_->Ref();
  1205. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1206. if (level == 0) {
  1207. InternalKey smallest, largest;
  1208. GetRange(c->inputs_[0], &smallest, &largest);
  1209. // Note that the next call will discard the file we placed in
  1210. // c->inputs_[0] earlier and replace it with an overlapping set
  1211. // which will include the picked file.
  1212. current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]);
  1213. assert(!c->inputs_[0].empty());
  1214. }
  1215. SetupOtherInputs(c);
  1216. return c;
  1217. }
  1218. void VersionSet::SetupOtherInputs(Compaction* c) {
  1219. const int level = c->level();
  1220. InternalKey smallest, largest;
  1221. GetRange(c->inputs_[0], &smallest, &largest);
  1222. current_->GetOverlappingInputs(level+1, &smallest, &largest, &c->inputs_[1]);
  1223. // Get entire range covered by compaction
  1224. InternalKey all_start, all_limit;
  1225. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1226. // See if we can grow the number of inputs in "level" without
  1227. // changing the number of "level+1" files we pick up.
  1228. if (!c->inputs_[1].empty()) {
  1229. std::vector<FileMetaData*> expanded0;
  1230. current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0);
  1231. const int64_t inputs0_size = TotalFileSize(c->inputs_[0]);
  1232. const int64_t inputs1_size = TotalFileSize(c->inputs_[1]);
  1233. const int64_t expanded0_size = TotalFileSize(expanded0);
  1234. if (expanded0.size() > c->inputs_[0].size() &&
  1235. inputs1_size + expanded0_size <
  1236. ExpandedCompactionByteSizeLimit(options_)) {
  1237. InternalKey new_start, new_limit;
  1238. GetRange(expanded0, &new_start, &new_limit);
  1239. std::vector<FileMetaData*> expanded1;
  1240. current_->GetOverlappingInputs(level+1, &new_start, &new_limit,
  1241. &expanded1);
  1242. if (expanded1.size() == c->inputs_[1].size()) {
  1243. Log(options_->info_log,
  1244. "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n",
  1245. level,
  1246. int(c->inputs_[0].size()),
  1247. int(c->inputs_[1].size()),
  1248. long(inputs0_size), long(inputs1_size),
  1249. int(expanded0.size()),
  1250. int(expanded1.size()),
  1251. long(expanded0_size), long(inputs1_size));
  1252. smallest = new_start;
  1253. largest = new_limit;
  1254. c->inputs_[0] = expanded0;
  1255. c->inputs_[1] = expanded1;
  1256. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1257. }
  1258. }
  1259. }
  1260. // Compute the set of grandparent files that overlap this compaction
  1261. // (parent == level+1; grandparent == level+2)
  1262. if (level + 2 < config::kNumLevels) {
  1263. current_->GetOverlappingInputs(level + 2, &all_start, &all_limit,
  1264. &c->grandparents_);
  1265. }
  1266. // Update the place where we will do the next compaction for this level.
  1267. // We update this immediately instead of waiting for the VersionEdit
  1268. // to be applied so that if the compaction fails, we will try a different
  1269. // key range next time.
  1270. compact_pointer_[level] = largest.Encode().ToString();
  1271. c->edit_.SetCompactPointer(level, largest);
  1272. }
  1273. Compaction* VersionSet::CompactRange(
  1274. int level,
  1275. const InternalKey* begin,
  1276. const InternalKey* end) {
  1277. std::vector<FileMetaData*> inputs;
  1278. current_->GetOverlappingInputs(level, begin, end, &inputs);
  1279. if (inputs.empty()) {
  1280. return NULL;
  1281. }
  1282. // Avoid compacting too much in one shot in case the range is large.
  1283. // But we cannot do this for level-0 since level-0 files can overlap
  1284. // and we must not pick one file and drop another older file if the
  1285. // two files overlap.
  1286. if (level > 0) {
  1287. const uint64_t limit = MaxFileSizeForLevel(options_, level);
  1288. uint64_t total = 0;
  1289. for (size_t i = 0; i < inputs.size(); i++) {
  1290. uint64_t s = inputs[i]->file_size;
  1291. total += s;
  1292. if (total >= limit) {
  1293. inputs.resize(i + 1);
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. Compaction* c = new Compaction(options_, level);
  1299. c->input_version_ = current_;
  1300. c->input_version_->Ref();
  1301. c->inputs_[0] = inputs;
  1302. SetupOtherInputs(c);
  1303. return c;
  1304. }
  1305. Compaction::Compaction(const Options* options, int level)
  1306. : level_(level),
  1307. max_output_file_size_(MaxFileSizeForLevel(options, level)),
  1308. input_version_(NULL),
  1309. grandparent_index_(0),
  1310. seen_key_(false),
  1311. overlapped_bytes_(0) {
  1312. for (int i = 0; i < config::kNumLevels; i++) {
  1313. level_ptrs_[i] = 0;
  1314. }
  1315. }
  1316. Compaction::~Compaction() {
  1317. if (input_version_ != NULL) {
  1318. input_version_->Unref();
  1319. }
  1320. }
  1321. bool Compaction::IsTrivialMove() const {
  1322. const VersionSet* vset = input_version_->vset_;
  1323. // Avoid a move if there is lots of overlapping grandparent data.
  1324. // Otherwise, the move could create a parent file that will require
  1325. // a very expensive merge later on.
  1326. return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
  1327. TotalFileSize(grandparents_) <=
  1328. MaxGrandParentOverlapBytes(vset->options_));
  1329. }
  1330. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1331. for (int which = 0; which < 2; which++) {
  1332. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1333. edit->DeleteFile(level_ + which, inputs_[which][i]->number);
  1334. }
  1335. }
  1336. }
  1337. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1338. // Maybe use binary search to find right entry instead of linear search?
  1339. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1340. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1341. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1342. for (; level_ptrs_[lvl] < files.size(); ) {
  1343. FileMetaData* f = files[level_ptrs_[lvl]];
  1344. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1345. // We've advanced far enough
  1346. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1347. // Key falls in this file's range, so definitely not base level
  1348. return false;
  1349. }
  1350. break;
  1351. }
  1352. level_ptrs_[lvl]++;
  1353. }
  1354. }
  1355. return true;
  1356. }
  1357. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1358. const VersionSet* vset = input_version_->vset_;
  1359. // Scan to find earliest grandparent file that contains key.
  1360. const InternalKeyComparator* icmp = &vset->icmp_;
  1361. while (grandparent_index_ < grandparents_.size() &&
  1362. icmp->Compare(internal_key,
  1363. grandparents_[grandparent_index_]->largest.Encode()) > 0) {
  1364. if (seen_key_) {
  1365. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1366. }
  1367. grandparent_index_++;
  1368. }
  1369. seen_key_ = true;
  1370. if (overlapped_bytes_ > MaxGrandParentOverlapBytes(vset->options_)) {
  1371. // Too much overlap for current output; start new output
  1372. overlapped_bytes_ = 0;
  1373. return true;
  1374. } else {
  1375. return false;
  1376. }
  1377. }
  1378. void Compaction::ReleaseInputs() {
  1379. if (input_version_ != NULL) {
  1380. input_version_->Unref();
  1381. input_version_ = NULL;
  1382. }
  1383. }
  1384. } // namespace leveldb