作者: 韩晨旭 10225101440 李畅 10225102463
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.

1267 line
39 KiB

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