選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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