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.

1027 lines
31 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. static double MaxBytesForLevel(int level) {
  24. // Note: the result for level zero is not really used since we set
  25. // the level-0 compaction threshold based on number of files.
  26. double result = 10 * 1048576.0; // Result for both level-0 and level-1
  27. while (level > 1) {
  28. result *= 10;
  29. level--;
  30. }
  31. return result;
  32. }
  33. static uint64_t MaxFileSizeForLevel(int level) {
  34. return kTargetFileSize; // We could vary per level to reduce number of files?
  35. }
  36. namespace {
  37. std::string IntSetToString(const std::set<uint64_t>& s) {
  38. std::string result = "{";
  39. for (std::set<uint64_t>::const_iterator it = s.begin();
  40. it != s.end();
  41. ++it) {
  42. result += (result.size() > 1) ? "," : "";
  43. result += NumberToString(*it);
  44. }
  45. result += "}";
  46. return result;
  47. }
  48. }
  49. Version::~Version() {
  50. assert(refs_ == 0);
  51. for (int level = 0; level < config::kNumLevels; level++) {
  52. for (size_t i = 0; i < files_[level].size(); i++) {
  53. FileMetaData* f = files_[level][i];
  54. assert(f->refs >= 0);
  55. f->refs--;
  56. if (f->refs <= 0) {
  57. delete f;
  58. }
  59. }
  60. }
  61. delete cleanup_mem_;
  62. }
  63. // An internal iterator. For a given version/level pair, yields
  64. // information about the files in the level. For a given entry, key()
  65. // is the largest key that occurs in the file, and value() is an
  66. // 16-byte value containing the file number and file size, both
  67. // encoded using EncodeFixed64.
  68. class Version::LevelFileNumIterator : public Iterator {
  69. public:
  70. LevelFileNumIterator(const Version* version,
  71. const std::vector<FileMetaData*>* flist)
  72. : icmp_(version->vset_->icmp_.user_comparator()),
  73. flist_(flist),
  74. index_(flist->size()) { // Marks as invalid
  75. }
  76. virtual bool Valid() const {
  77. return index_ < flist_->size();
  78. }
  79. virtual void Seek(const Slice& target) {
  80. uint32_t left = 0;
  81. uint32_t right = flist_->size() - 1;
  82. while (left < right) {
  83. uint32_t mid = (left + right) / 2;
  84. int cmp = icmp_.Compare((*flist_)[mid]->largest.Encode(), target);
  85. if (cmp < 0) {
  86. // Key at "mid.largest" is < than "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. index_ = left;
  96. }
  97. virtual void SeekToFirst() { index_ = 0; }
  98. virtual void SeekToLast() {
  99. index_ = flist_->empty() ? 0 : flist_->size() - 1;
  100. }
  101. virtual void Next() {
  102. assert(Valid());
  103. index_++;
  104. }
  105. virtual void Prev() {
  106. assert(Valid());
  107. if (index_ == 0) {
  108. index_ = flist_->size(); // Marks as invalid
  109. } else {
  110. index_--;
  111. }
  112. }
  113. Slice key() const {
  114. assert(Valid());
  115. return (*flist_)[index_]->largest.Encode();
  116. }
  117. Slice value() const {
  118. assert(Valid());
  119. EncodeFixed64(value_buf_, (*flist_)[index_]->number);
  120. EncodeFixed64(value_buf_+8, (*flist_)[index_]->file_size);
  121. return Slice(value_buf_, sizeof(value_buf_));
  122. }
  123. virtual Status status() const { return Status::OK(); }
  124. private:
  125. const InternalKeyComparator icmp_;
  126. const std::vector<FileMetaData*>* const flist_;
  127. uint32_t index_;
  128. // Backing store for value(). Holds the file number and size.
  129. mutable char value_buf_[16];
  130. };
  131. static Iterator* GetFileIterator(void* arg,
  132. const ReadOptions& options,
  133. const Slice& file_value) {
  134. TableCache* cache = reinterpret_cast<TableCache*>(arg);
  135. if (file_value.size() != 16) {
  136. return NewErrorIterator(
  137. Status::Corruption("FileReader invoked with unexpected value"));
  138. } else {
  139. return cache->NewIterator(options,
  140. DecodeFixed64(file_value.data()),
  141. DecodeFixed64(file_value.data() + 8));
  142. }
  143. }
  144. Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
  145. int level) const {
  146. return NewTwoLevelIterator(
  147. new LevelFileNumIterator(this, &files_[level]),
  148. &GetFileIterator, vset_->table_cache_, options);
  149. }
  150. void Version::AddIterators(const ReadOptions& options,
  151. std::vector<Iterator*>* iters) {
  152. // Merge all level zero files together since they may overlap
  153. for (size_t i = 0; i < files_[0].size(); i++) {
  154. iters->push_back(
  155. vset_->table_cache_->NewIterator(
  156. options, files_[0][i]->number, files_[0][i]->file_size));
  157. }
  158. // For levels > 0, we can use a concatenating iterator that sequentially
  159. // walks through the non-overlapping files in the level, opening them
  160. // lazily.
  161. for (int level = 1; level < config::kNumLevels; level++) {
  162. if (!files_[level].empty()) {
  163. iters->push_back(NewConcatenatingIterator(options, level));
  164. }
  165. }
  166. }
  167. void Version::Ref() {
  168. ++refs_;
  169. }
  170. void Version::Unref() {
  171. assert(refs_ >= 1);
  172. --refs_;
  173. if (refs_ == 0) {
  174. vset_->MaybeDeleteOldVersions();
  175. // TODO: try to delete obsolete files
  176. }
  177. }
  178. std::string Version::DebugString() const {
  179. std::string r;
  180. for (int level = 0; level < config::kNumLevels; level++) {
  181. // E.g., level 1: 17:123['a' .. 'd'] 20:43['e' .. 'g']
  182. r.append("level ");
  183. AppendNumberTo(&r, level);
  184. r.push_back(':');
  185. const std::vector<FileMetaData*>& files = files_[level];
  186. for (size_t i = 0; i < files.size(); i++) {
  187. r.push_back(' ');
  188. AppendNumberTo(&r, files[i]->number);
  189. r.push_back(':');
  190. AppendNumberTo(&r, files[i]->file_size);
  191. r.append("['");
  192. AppendEscapedStringTo(&r, files[i]->smallest.Encode());
  193. r.append("' .. '");
  194. AppendEscapedStringTo(&r, files[i]->largest.Encode());
  195. r.append("']");
  196. }
  197. r.push_back('\n');
  198. }
  199. return r;
  200. }
  201. // A helper class so we can efficiently apply a whole sequence
  202. // of edits to a particular state without creating intermediate
  203. // Versions that contain full copies of the intermediate state.
  204. class VersionSet::Builder {
  205. private:
  206. typedef std::map<uint64_t, FileMetaData*> FileMap;
  207. VersionSet* vset_;
  208. FileMap files_[config::kNumLevels];
  209. public:
  210. // Initialize a builder with the files from *base and other info from *vset
  211. Builder(VersionSet* vset, Version* base)
  212. : vset_(vset) {
  213. for (int level = 0; level < config::kNumLevels; level++) {
  214. const std::vector<FileMetaData*>& files = base->files_[level];
  215. for (size_t i = 0; i < files.size(); i++) {
  216. FileMetaData* f = files[i];
  217. f->refs++;
  218. files_[level].insert(std::make_pair(f->number, f));
  219. }
  220. }
  221. }
  222. ~Builder() {
  223. for (int level = 0; level < config::kNumLevels; level++) {
  224. const FileMap& fmap = files_[level];
  225. for (FileMap::const_iterator iter = fmap.begin();
  226. iter != fmap.end();
  227. ++iter) {
  228. FileMetaData* f = iter->second;
  229. f->refs--;
  230. if (f->refs <= 0) {
  231. delete f;
  232. }
  233. }
  234. }
  235. }
  236. // Apply all of the edits in *edit to the current state.
  237. void Apply(VersionEdit* edit) {
  238. // Update compaction pointers
  239. for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
  240. const int level = edit->compact_pointers_[i].first;
  241. vset_->compact_pointer_[level] =
  242. edit->compact_pointers_[i].second.Encode().ToString();
  243. }
  244. // Delete files
  245. const VersionEdit::DeletedFileSet& del = edit->deleted_files_;
  246. for (VersionEdit::DeletedFileSet::const_iterator iter = del.begin();
  247. iter != del.end();
  248. ++iter) {
  249. const int level = iter->first;
  250. const uint64_t number = iter->second;
  251. FileMap::iterator fiter = files_[level].find(number);
  252. assert(fiter != files_[level].end()); // Sanity check for debug mode
  253. if (fiter != files_[level].end()) {
  254. FileMetaData* f = fiter->second;
  255. f->refs--;
  256. if (f->refs <= 0) {
  257. delete f;
  258. }
  259. files_[level].erase(fiter);
  260. }
  261. }
  262. // Add new files
  263. for (size_t i = 0; i < edit->new_files_.size(); i++) {
  264. const int level = edit->new_files_[i].first;
  265. FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
  266. f->refs = 1;
  267. assert(files_[level].count(f->number) == 0);
  268. files_[level].insert(std::make_pair(f->number, f));
  269. }
  270. }
  271. // Save the current state in *v.
  272. void SaveTo(Version* v) {
  273. for (int level = 0; level < config::kNumLevels; level++) {
  274. const FileMap& fmap = files_[level];
  275. for (FileMap::const_iterator iter = fmap.begin();
  276. iter != fmap.end();
  277. ++iter) {
  278. FileMetaData* f = iter->second;
  279. f->refs++;
  280. v->files_[level].push_back(f);
  281. }
  282. }
  283. }
  284. };
  285. VersionSet::VersionSet(const std::string& dbname,
  286. const Options* options,
  287. TableCache* table_cache,
  288. const InternalKeyComparator* cmp)
  289. : env_(options->env),
  290. dbname_(dbname),
  291. options_(options),
  292. table_cache_(table_cache),
  293. icmp_(*cmp),
  294. next_file_number_(2),
  295. manifest_file_number_(0), // Filled by Recover()
  296. last_sequence_(0),
  297. log_number_(0),
  298. prev_log_number_(0),
  299. descriptor_file_(NULL),
  300. descriptor_log_(NULL),
  301. current_(new Version(this)),
  302. oldest_(current_) {
  303. }
  304. VersionSet::~VersionSet() {
  305. for (Version* v = oldest_; v != NULL; ) {
  306. Version* next = v->next_;
  307. assert(v->refs_ == 0);
  308. delete v;
  309. v = next;
  310. }
  311. delete descriptor_log_;
  312. delete descriptor_file_;
  313. }
  314. Status VersionSet::LogAndApply(VersionEdit* edit, MemTable* cleanup_mem) {
  315. if (edit->has_log_number_) {
  316. assert(edit->log_number_ >= log_number_);
  317. assert(edit->log_number_ < next_file_number_);
  318. } else {
  319. edit->SetLogNumber(log_number_);
  320. }
  321. if (!edit->has_prev_log_number_) {
  322. edit->SetPrevLogNumber(prev_log_number_);
  323. }
  324. edit->SetNextFile(next_file_number_);
  325. edit->SetLastSequence(last_sequence_);
  326. Version* v = new Version(this);
  327. {
  328. Builder builder(this, current_);
  329. builder.Apply(edit);
  330. builder.SaveTo(v);
  331. }
  332. std::string new_manifest_file;
  333. Status s = Finalize(v);
  334. // Initialize new descriptor log file if necessary by creating
  335. // a temporary file that contains a snapshot of the current version.
  336. if (s.ok()) {
  337. if (descriptor_log_ == NULL) {
  338. assert(descriptor_file_ == NULL);
  339. new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
  340. edit->SetNextFile(next_file_number_);
  341. s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
  342. if (s.ok()) {
  343. descriptor_log_ = new log::Writer(descriptor_file_);
  344. s = WriteSnapshot(descriptor_log_);
  345. }
  346. }
  347. }
  348. // Write new record to MANIFEST log
  349. if (s.ok()) {
  350. std::string record;
  351. edit->EncodeTo(&record);
  352. s = descriptor_log_->AddRecord(record);
  353. if (s.ok()) {
  354. s = descriptor_file_->Sync();
  355. }
  356. }
  357. // If we just created a new descriptor file, install it by writing a
  358. // new CURRENT file that points to it.
  359. if (s.ok() && !new_manifest_file.empty()) {
  360. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  361. }
  362. // Install the new version
  363. if (s.ok()) {
  364. assert(current_->next_ == NULL);
  365. assert(current_->cleanup_mem_ == NULL);
  366. current_->cleanup_mem_ = cleanup_mem;
  367. v->next_ = NULL;
  368. current_->next_ = v;
  369. current_ = v;
  370. log_number_ = edit->log_number_;
  371. prev_log_number_ = edit->prev_log_number_;
  372. } else {
  373. delete v;
  374. if (!new_manifest_file.empty()) {
  375. delete descriptor_log_;
  376. delete descriptor_file_;
  377. descriptor_log_ = NULL;
  378. descriptor_file_ = NULL;
  379. env_->DeleteFile(new_manifest_file);
  380. }
  381. }
  382. return s;
  383. }
  384. Status VersionSet::Recover() {
  385. struct LogReporter : public log::Reader::Reporter {
  386. Status* status;
  387. virtual void Corruption(size_t bytes, const Status& s) {
  388. if (this->status->ok()) *this->status = s;
  389. }
  390. };
  391. // Read "CURRENT" file, which contains a pointer to the current manifest file
  392. std::string current;
  393. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  394. if (!s.ok()) {
  395. return s;
  396. }
  397. if (current.empty() || current[current.size()-1] != '\n') {
  398. return Status::Corruption("CURRENT file does not end with newline");
  399. }
  400. current.resize(current.size() - 1);
  401. std::string dscname = dbname_ + "/" + current;
  402. SequentialFile* file;
  403. s = env_->NewSequentialFile(dscname, &file);
  404. if (!s.ok()) {
  405. return s;
  406. }
  407. bool have_log_number = false;
  408. bool have_prev_log_number = false;
  409. bool have_next_file = false;
  410. bool have_last_sequence = false;
  411. uint64_t next_file = 0;
  412. uint64_t last_sequence = 0;
  413. uint64_t log_number = 0;
  414. uint64_t prev_log_number = 0;
  415. Builder builder(this, current_);
  416. {
  417. LogReporter reporter;
  418. reporter.status = &s;
  419. log::Reader reader(file, &reporter, true/*checksum*/);
  420. Slice record;
  421. std::string scratch;
  422. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  423. VersionEdit edit;
  424. s = edit.DecodeFrom(record);
  425. if (s.ok()) {
  426. if (edit.has_comparator_ &&
  427. edit.comparator_ != icmp_.user_comparator()->Name()) {
  428. s = Status::InvalidArgument(
  429. edit.comparator_ + "does not match existing comparator ",
  430. icmp_.user_comparator()->Name());
  431. }
  432. }
  433. if (s.ok()) {
  434. builder.Apply(&edit);
  435. }
  436. if (edit.has_log_number_) {
  437. log_number = edit.log_number_;
  438. have_log_number = true;
  439. }
  440. if (edit.has_prev_log_number_) {
  441. prev_log_number = edit.prev_log_number_;
  442. have_prev_log_number = true;
  443. }
  444. if (edit.has_next_file_number_) {
  445. next_file = edit.next_file_number_;
  446. have_next_file = true;
  447. }
  448. if (edit.has_last_sequence_) {
  449. last_sequence = edit.last_sequence_;
  450. have_last_sequence = true;
  451. }
  452. }
  453. }
  454. delete file;
  455. file = NULL;
  456. if (s.ok()) {
  457. if (!have_next_file) {
  458. s = Status::Corruption("no meta-nextfile entry in descriptor");
  459. } else if (!have_log_number) {
  460. s = Status::Corruption("no meta-lognumber entry in descriptor");
  461. } else if (!have_last_sequence) {
  462. s = Status::Corruption("no last-sequence-number entry in descriptor");
  463. }
  464. if (!have_prev_log_number) {
  465. prev_log_number = 0;
  466. }
  467. }
  468. if (s.ok()) {
  469. Version* v = new Version(this);
  470. builder.SaveTo(v);
  471. s = Finalize(v);
  472. if (!s.ok()) {
  473. delete v;
  474. } else {
  475. // Install recovered version
  476. v->next_ = NULL;
  477. current_->next_ = v;
  478. current_ = v;
  479. manifest_file_number_ = next_file;
  480. next_file_number_ = next_file + 1;
  481. last_sequence_ = last_sequence;
  482. log_number_ = log_number;
  483. prev_log_number_ = prev_log_number;
  484. }
  485. }
  486. return s;
  487. }
  488. static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
  489. int64_t sum = 0;
  490. for (size_t i = 0; i < files.size(); i++) {
  491. sum += files[i]->file_size;
  492. }
  493. return sum;
  494. }
  495. Status VersionSet::Finalize(Version* v) {
  496. // Precomputed best level for next compaction
  497. int best_level = -1;
  498. double best_score = -1;
  499. Status s;
  500. for (int level = 0; s.ok() && level < config::kNumLevels-1; level++) {
  501. s = SortLevel(v, level);
  502. double score;
  503. if (level == 0) {
  504. // We treat level-0 specially by bounding the number of files
  505. // instead of number of bytes for two reasons:
  506. //
  507. // (1) With larger write-buffer sizes, it is nice not to do too
  508. // many level-0 compactions.
  509. //
  510. // (2) The files in level-0 are merged on every read and
  511. // therefore we wish to avoid too many files when the individual
  512. // file size is small (perhaps because of a small write-buffer
  513. // setting, or very high compression ratios, or lots of
  514. // overwrites/deletions).
  515. score = v->files_[level].size() / 4.0;
  516. } else {
  517. // Compute the ratio of current size to size limit.
  518. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  519. score = static_cast<double>(level_bytes) / MaxBytesForLevel(level);
  520. }
  521. if (score > best_score) {
  522. best_level = level;
  523. best_score = score;
  524. }
  525. }
  526. v->compaction_level_ = best_level;
  527. v->compaction_score_ = best_score;
  528. return s;
  529. }
  530. Status VersionSet::WriteSnapshot(log::Writer* log) {
  531. // TODO: Break up into multiple records to reduce memory usage on recovery?
  532. // Save metadata
  533. VersionEdit edit;
  534. edit.SetComparatorName(icmp_.user_comparator()->Name());
  535. // Save compaction pointers
  536. for (int level = 0; level < config::kNumLevels; level++) {
  537. if (!compact_pointer_[level].empty()) {
  538. InternalKey key;
  539. key.DecodeFrom(compact_pointer_[level]);
  540. edit.SetCompactPointer(level, key);
  541. }
  542. }
  543. // Save files
  544. for (int level = 0; level < config::kNumLevels; level++) {
  545. const std::vector<FileMetaData*>& files = current_->files_[level];
  546. for (size_t i = 0; i < files.size(); i++) {
  547. const FileMetaData* f = files[i];
  548. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  549. }
  550. }
  551. std::string record;
  552. edit.EncodeTo(&record);
  553. return log->AddRecord(record);
  554. }
  555. // Helper to sort by tables_[file_number].smallest
  556. struct VersionSet::BySmallestKey {
  557. const InternalKeyComparator* internal_comparator;
  558. bool operator()(FileMetaData* f1, FileMetaData* f2) const {
  559. return internal_comparator->Compare(f1->smallest, f2->smallest) < 0;
  560. }
  561. };
  562. Status VersionSet::SortLevel(Version* v, uint64_t level) {
  563. Status result;
  564. BySmallestKey cmp;
  565. cmp.internal_comparator = &icmp_;
  566. std::sort(v->files_[level].begin(), v->files_[level].end(), cmp);
  567. if (result.ok() && level > 0) {
  568. // There should be no overlap
  569. for (size_t i = 1; i < v->files_[level].size(); i++) {
  570. const InternalKey& prev_end = v->files_[level][i-1]->largest;
  571. const InternalKey& this_begin = v->files_[level][i]->smallest;
  572. if (icmp_.Compare(prev_end, this_begin) >= 0) {
  573. result = Status::Corruption(
  574. "overlapping ranges in same level",
  575. (EscapeString(prev_end.Encode()) + " vs. " +
  576. EscapeString(this_begin.Encode())));
  577. break;
  578. }
  579. }
  580. }
  581. return result;
  582. }
  583. int VersionSet::NumLevelFiles(int level) const {
  584. assert(level >= 0);
  585. assert(level < config::kNumLevels);
  586. return current_->files_[level].size();
  587. }
  588. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  589. uint64_t result = 0;
  590. for (int level = 0; level < config::kNumLevels; level++) {
  591. const std::vector<FileMetaData*>& files = v->files_[level];
  592. for (size_t i = 0; i < files.size(); i++) {
  593. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  594. // Entire file is before "ikey", so just add the file size
  595. result += files[i]->file_size;
  596. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  597. // Entire file is after "ikey", so ignore
  598. if (level > 0) {
  599. // Files other than level 0 are sorted by meta->smallest, so
  600. // no further files in this level will contain data for
  601. // "ikey".
  602. break;
  603. }
  604. } else {
  605. // "ikey" falls in the range for this table. Add the
  606. // approximate offset of "ikey" within the table.
  607. Table* tableptr;
  608. Iterator* iter = table_cache_->NewIterator(
  609. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  610. if (tableptr != NULL) {
  611. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  612. }
  613. delete iter;
  614. }
  615. }
  616. }
  617. return result;
  618. }
  619. void VersionSet::MaybeDeleteOldVersions() {
  620. // Note: it is important to delete versions in order since a newer
  621. // version with zero refs may be holding a pointer to a memtable
  622. // that is used by somebody who has a ref on an older version.
  623. while (oldest_ != current_ && oldest_->refs_ == 0) {
  624. Version* next = oldest_->next_;
  625. delete oldest_;
  626. oldest_ = next;
  627. }
  628. }
  629. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  630. for (Version* v = oldest_; v != NULL; v = v->next_) {
  631. for (int level = 0; level < config::kNumLevels; level++) {
  632. const std::vector<FileMetaData*>& files = v->files_[level];
  633. for (size_t i = 0; i < files.size(); i++) {
  634. live->insert(files[i]->number);
  635. }
  636. }
  637. }
  638. }
  639. int64_t VersionSet::NumLevelBytes(int level) const {
  640. assert(level >= 0);
  641. assert(level < config::kNumLevels);
  642. return TotalFileSize(current_->files_[level]);
  643. }
  644. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  645. int64_t result = 0;
  646. std::vector<FileMetaData*> overlaps;
  647. for (int level = 0; level < config::kNumLevels - 1; level++) {
  648. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  649. const FileMetaData* f = current_->files_[level][i];
  650. GetOverlappingInputs(level+1, f->smallest, f->largest, &overlaps);
  651. const int64_t sum = TotalFileSize(overlaps);
  652. if (sum > result) {
  653. result = sum;
  654. }
  655. }
  656. }
  657. return result;
  658. }
  659. // Store in "*inputs" all files in "level" that overlap [begin,end]
  660. void VersionSet::GetOverlappingInputs(
  661. int level,
  662. const InternalKey& begin,
  663. const InternalKey& end,
  664. std::vector<FileMetaData*>* inputs) {
  665. inputs->clear();
  666. Slice user_begin = begin.user_key();
  667. Slice user_end = end.user_key();
  668. const Comparator* user_cmp = icmp_.user_comparator();
  669. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  670. FileMetaData* f = current_->files_[level][i];
  671. if (user_cmp->Compare(f->largest.user_key(), user_begin) < 0 ||
  672. user_cmp->Compare(f->smallest.user_key(), user_end) > 0) {
  673. // Either completely before or after range; skip it
  674. } else {
  675. inputs->push_back(f);
  676. }
  677. }
  678. }
  679. // Stores the minimal range that covers all entries in inputs in
  680. // *smallest, *largest.
  681. // REQUIRES: inputs is not empty
  682. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  683. InternalKey* smallest,
  684. InternalKey* largest) {
  685. assert(!inputs.empty());
  686. smallest->Clear();
  687. largest->Clear();
  688. for (size_t i = 0; i < inputs.size(); i++) {
  689. FileMetaData* f = inputs[i];
  690. if (i == 0) {
  691. *smallest = f->smallest;
  692. *largest = f->largest;
  693. } else {
  694. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  695. *smallest = f->smallest;
  696. }
  697. if (icmp_.Compare(f->largest, *largest) > 0) {
  698. *largest = f->largest;
  699. }
  700. }
  701. }
  702. }
  703. // Stores the minimal range that covers all entries in inputs1 and inputs2
  704. // in *smallest, *largest.
  705. // REQUIRES: inputs is not empty
  706. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  707. const std::vector<FileMetaData*>& inputs2,
  708. InternalKey* smallest,
  709. InternalKey* largest) {
  710. std::vector<FileMetaData*> all = inputs1;
  711. all.insert(all.end(), inputs2.begin(), inputs2.end());
  712. GetRange(all, smallest, largest);
  713. }
  714. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  715. ReadOptions options;
  716. options.verify_checksums = options_->paranoid_checks;
  717. options.fill_cache = false;
  718. // Level-0 files have to be merged together. For other levels,
  719. // we will make a concatenating iterator per level.
  720. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  721. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  722. Iterator** list = new Iterator*[space];
  723. int num = 0;
  724. for (int which = 0; which < 2; which++) {
  725. if (!c->inputs_[which].empty()) {
  726. if (c->level() + which == 0) {
  727. const std::vector<FileMetaData*>& files = c->inputs_[which];
  728. for (size_t i = 0; i < files.size(); i++) {
  729. list[num++] = table_cache_->NewIterator(
  730. options, files[i]->number, files[i]->file_size);
  731. }
  732. } else {
  733. // Create concatenating iterator for the files from this level
  734. list[num++] = NewTwoLevelIterator(
  735. new Version::LevelFileNumIterator(
  736. c->input_version_, &c->inputs_[which]),
  737. &GetFileIterator, table_cache_, options);
  738. }
  739. }
  740. }
  741. assert(num <= space);
  742. Iterator* result = NewMergingIterator(&icmp_, list, num);
  743. delete[] list;
  744. return result;
  745. }
  746. Compaction* VersionSet::PickCompaction() {
  747. if (!NeedsCompaction()) {
  748. return NULL;
  749. }
  750. const int level = current_->compaction_level_;
  751. assert(level >= 0);
  752. assert(level+1 < config::kNumLevels);
  753. Compaction* c = new Compaction(level);
  754. c->input_version_ = current_;
  755. c->input_version_->Ref();
  756. // Pick the first file that comes after compact_pointer_[level]
  757. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  758. FileMetaData* f = current_->files_[level][i];
  759. if (compact_pointer_[level].empty() ||
  760. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  761. c->inputs_[0].push_back(f);
  762. break;
  763. }
  764. }
  765. if (c->inputs_[0].empty()) {
  766. // Wrap-around to the beginning of the key space
  767. c->inputs_[0].push_back(current_->files_[level][0]);
  768. }
  769. // Files in level 0 may overlap each other, so pick up all overlapping ones
  770. if (level == 0) {
  771. InternalKey smallest, largest;
  772. GetRange(c->inputs_[0], &smallest, &largest);
  773. // Note that the next call will discard the file we placed in
  774. // c->inputs_[0] earlier and replace it with an overlapping set
  775. // which will include the picked file.
  776. GetOverlappingInputs(0, smallest, largest, &c->inputs_[0]);
  777. assert(!c->inputs_[0].empty());
  778. }
  779. SetupOtherInputs(c);
  780. return c;
  781. }
  782. void VersionSet::SetupOtherInputs(Compaction* c) {
  783. const int level = c->level();
  784. InternalKey smallest, largest;
  785. GetRange(c->inputs_[0], &smallest, &largest);
  786. GetOverlappingInputs(level+1, smallest, largest, &c->inputs_[1]);
  787. // Get entire range covered by compaction
  788. InternalKey all_start, all_limit;
  789. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  790. // See if we can grow the number of inputs in "level" without
  791. // changing the number of "level+1" files we pick up.
  792. if (!c->inputs_[1].empty()) {
  793. std::vector<FileMetaData*> expanded0;
  794. GetOverlappingInputs(level, all_start, all_limit, &expanded0);
  795. if (expanded0.size() > c->inputs_[0].size()) {
  796. InternalKey new_start, new_limit;
  797. GetRange(expanded0, &new_start, &new_limit);
  798. std::vector<FileMetaData*> expanded1;
  799. GetOverlappingInputs(level+1, new_start, new_limit, &expanded1);
  800. if (expanded1.size() == c->inputs_[1].size()) {
  801. Log(env_, options_->info_log,
  802. "Expanding@%d %d+%d to %d+%d\n",
  803. level,
  804. int(c->inputs_[0].size()),
  805. int(c->inputs_[1].size()),
  806. int(expanded0.size()),
  807. int(expanded1.size()));
  808. smallest = new_start;
  809. largest = new_limit;
  810. c->inputs_[0] = expanded0;
  811. c->inputs_[1] = expanded1;
  812. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  813. }
  814. }
  815. }
  816. // Compute the set of grandparent files that overlap this compaction
  817. // (parent == level+1; grandparent == level+2)
  818. if (level + 2 < config::kNumLevels) {
  819. GetOverlappingInputs(level + 2, all_start, all_limit, &c->grandparents_);
  820. }
  821. if (false) {
  822. Log(env_, options_->info_log, "Compacting %d '%s' .. '%s'",
  823. level,
  824. EscapeString(smallest.Encode()).c_str(),
  825. EscapeString(largest.Encode()).c_str());
  826. }
  827. // Update the place where we will do the next compaction for this level.
  828. // We update this immediately instead of waiting for the VersionEdit
  829. // to be applied so that if the compaction fails, we will try a different
  830. // key range next time.
  831. compact_pointer_[level] = largest.Encode().ToString();
  832. c->edit_.SetCompactPointer(level, largest);
  833. }
  834. Compaction* VersionSet::CompactRange(
  835. int level,
  836. const InternalKey& begin,
  837. const InternalKey& end) {
  838. std::vector<FileMetaData*> inputs;
  839. GetOverlappingInputs(level, begin, end, &inputs);
  840. if (inputs.empty()) {
  841. return NULL;
  842. }
  843. Compaction* c = new Compaction(level);
  844. c->input_version_ = current_;
  845. c->input_version_->Ref();
  846. c->inputs_[0] = inputs;
  847. SetupOtherInputs(c);
  848. return c;
  849. }
  850. Compaction::Compaction(int level)
  851. : level_(level),
  852. max_output_file_size_(MaxFileSizeForLevel(level)),
  853. input_version_(NULL),
  854. grandparent_index_(0),
  855. seen_key_(false),
  856. overlapped_bytes_(0) {
  857. for (int i = 0; i < config::kNumLevels; i++) {
  858. level_ptrs_[i] = 0;
  859. }
  860. }
  861. Compaction::~Compaction() {
  862. if (input_version_ != NULL) {
  863. input_version_->Unref();
  864. }
  865. }
  866. bool Compaction::IsTrivialMove() const {
  867. // Avoid a move if there is lots of overlapping grandparent data.
  868. // Otherwise, the move could create a parent file that will require
  869. // a very expensive merge later on.
  870. return (num_input_files(0) == 1 &&
  871. num_input_files(1) == 0 &&
  872. TotalFileSize(grandparents_) <= kMaxGrandParentOverlapBytes);
  873. }
  874. void Compaction::AddInputDeletions(VersionEdit* edit) {
  875. for (int which = 0; which < 2; which++) {
  876. for (size_t i = 0; i < inputs_[which].size(); i++) {
  877. edit->DeleteFile(level_ + which, inputs_[which][i]->number);
  878. }
  879. }
  880. }
  881. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  882. // Maybe use binary search to find right entry instead of linear search?
  883. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  884. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  885. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  886. for (; level_ptrs_[lvl] < files.size(); ) {
  887. FileMetaData* f = files[level_ptrs_[lvl]];
  888. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  889. // We've advanced far enough
  890. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  891. // Key falls in this file's range, so definitely not base level
  892. return false;
  893. }
  894. break;
  895. }
  896. level_ptrs_[lvl]++;
  897. }
  898. }
  899. return true;
  900. }
  901. bool Compaction::ShouldStopBefore(const InternalKey& key) {
  902. // Scan to find earliest grandparent file that contains key.
  903. const InternalKeyComparator* icmp = &input_version_->vset_->icmp_;
  904. while (grandparent_index_ < grandparents_.size() &&
  905. icmp->Compare(key, grandparents_[grandparent_index_]->largest) > 0) {
  906. if (seen_key_) {
  907. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  908. }
  909. grandparent_index_++;
  910. }
  911. seen_key_ = true;
  912. if (overlapped_bytes_ > kMaxGrandParentOverlapBytes) {
  913. // Too much overlap for current output; start new output
  914. overlapped_bytes_ = 0;
  915. return true;
  916. } else {
  917. return false;
  918. }
  919. }
  920. void Compaction::ReleaseInputs() {
  921. if (input_version_ != NULL) {
  922. input_version_->Unref();
  923. input_version_ = NULL;
  924. }
  925. }
  926. }