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.

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