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.

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