10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
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.

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