作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

306 lines
9.9 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. //
  5. // The representation of a DBImpl consists of a set of Versions. The
  6. // newest version is called "current". Older versions may be kept
  7. // around to provide a consistent view to live iterators.
  8. //
  9. // Each Version keeps track of a set of Table files per level. The
  10. // entire set of versions is maintained in a VersionSet.
  11. //
  12. // Version,VersionSet are thread-compatible, but require external
  13. // synchronization on all accesses.
  14. #ifndef STORAGE_LEVELDB_DB_VERSION_SET_H_
  15. #define STORAGE_LEVELDB_DB_VERSION_SET_H_
  16. #include <map>
  17. #include <set>
  18. #include <vector>
  19. #include "db/dbformat.h"
  20. #include "db/version_edit.h"
  21. #include "port/port.h"
  22. namespace leveldb {
  23. namespace log { class Writer; }
  24. class Compaction;
  25. class Iterator;
  26. class MemTable;
  27. class TableBuilder;
  28. class TableCache;
  29. class Version;
  30. class VersionSet;
  31. class WritableFile;
  32. class Version {
  33. public:
  34. // Append to *iters a sequence of iterators that will
  35. // yield the contents of this Version when merged together.
  36. // REQUIRES: This version has been saved (see VersionSet::SaveTo)
  37. void AddIterators(const ReadOptions&, std::vector<Iterator*>* iters);
  38. // Reference count management (so Versions do not disappear out from
  39. // under live iterators)
  40. void Ref();
  41. void Unref();
  42. // Return a human readable string that describes this version's contents.
  43. std::string DebugString() const;
  44. private:
  45. friend class Compaction;
  46. friend class VersionSet;
  47. class LevelFileNumIterator;
  48. Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;
  49. VersionSet* vset_; // VersionSet to which this Version belongs
  50. Version* next_; // Next version in linked list
  51. Version* prev_; // Previous version in linked list
  52. int refs_; // Number of live refs to this version
  53. // List of files per level
  54. std::vector<FileMetaData*> files_[config::kNumLevels];
  55. // Level that should be compacted next and its compaction score.
  56. // Score < 1 means compaction is not strictly needed. These fields
  57. // are initialized by Finalize().
  58. double compaction_score_;
  59. int compaction_level_;
  60. explicit Version(VersionSet* vset)
  61. : vset_(vset), next_(this), prev_(this), refs_(0),
  62. compaction_score_(-1),
  63. compaction_level_(-1) {
  64. }
  65. ~Version();
  66. // No copying allowed
  67. Version(const Version&);
  68. void operator=(const Version&);
  69. };
  70. class VersionSet {
  71. public:
  72. VersionSet(const std::string& dbname,
  73. const Options* options,
  74. TableCache* table_cache,
  75. const InternalKeyComparator*);
  76. ~VersionSet();
  77. // Apply *edit to the current version to form a new descriptor that
  78. // is both saved to persistent state and installed as the new
  79. // current version.
  80. Status LogAndApply(VersionEdit* edit);
  81. // Recover the last saved descriptor from persistent storage.
  82. Status Recover();
  83. // Save current contents to *log
  84. Status WriteSnapshot(log::Writer* log);
  85. // Return the current version.
  86. Version* current() const { return current_; }
  87. // Return the current manifest file number
  88. uint64_t ManifestFileNumber() const { return manifest_file_number_; }
  89. // Allocate and return a new file number
  90. uint64_t NewFileNumber() { return next_file_number_++; }
  91. // Return the number of Table files at the specified level.
  92. int NumLevelFiles(int level) const;
  93. // Return the combined file size of all files at the specified level.
  94. int64_t NumLevelBytes(int level) const;
  95. // Return the last sequence number.
  96. uint64_t LastSequence() const { return last_sequence_; }
  97. // Set the last sequence number to s.
  98. void SetLastSequence(uint64_t s) {
  99. assert(s >= last_sequence_);
  100. last_sequence_ = s;
  101. }
  102. // Return the current log file number.
  103. uint64_t LogNumber() const { return log_number_; }
  104. // Return the log file number for the log file that is currently
  105. // being compacted, or zero if there is no such log file.
  106. uint64_t PrevLogNumber() const { return prev_log_number_; }
  107. // Pick level and inputs for a new compaction.
  108. // Returns NULL if there is no compaction to be done.
  109. // Otherwise returns a pointer to a heap-allocated object that
  110. // describes the compaction. Caller should delete the result.
  111. Compaction* PickCompaction();
  112. // Return a compaction object for compacting the range [begin,end] in
  113. // the specified level. Returns NULL if there is nothing in that
  114. // level that overlaps the specified range. Caller should delete
  115. // the result.
  116. Compaction* CompactRange(
  117. int level,
  118. const InternalKey& begin,
  119. const InternalKey& end);
  120. // Return the maximum overlapping data (in bytes) at next level for any
  121. // file at a level >= 1.
  122. int64_t MaxNextLevelOverlappingBytes();
  123. // Create an iterator that reads over the compaction inputs for "*c".
  124. // The caller should delete the iterator when no longer needed.
  125. Iterator* MakeInputIterator(Compaction* c);
  126. // Returns true iff some level needs a compaction.
  127. bool NeedsCompaction() const { return current_->compaction_score_ >= 1; }
  128. // Add all files listed in any live version to *live.
  129. // May also mutate some internal state.
  130. void AddLiveFiles(std::set<uint64_t>* live);
  131. // Return the approximate offset in the database of the data for
  132. // "key" as of version "v".
  133. uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
  134. // Return a human-readable short (single-line) summary of the number
  135. // of files per level. Uses *scratch as backing store.
  136. struct LevelSummaryStorage {
  137. char buffer[100];
  138. };
  139. const char* LevelSummary(LevelSummaryStorage* scratch) const;
  140. private:
  141. class Builder;
  142. friend class Compaction;
  143. friend class Version;
  144. void Finalize(Version* v);
  145. void GetOverlappingInputs(
  146. int level,
  147. const InternalKey& begin,
  148. const InternalKey& end,
  149. std::vector<FileMetaData*>* inputs);
  150. void GetRange(const std::vector<FileMetaData*>& inputs,
  151. InternalKey* smallest,
  152. InternalKey* largest);
  153. void GetRange2(const std::vector<FileMetaData*>& inputs1,
  154. const std::vector<FileMetaData*>& inputs2,
  155. InternalKey* smallest,
  156. InternalKey* largest);
  157. void SetupOtherInputs(Compaction* c);
  158. void AppendVersion(Version* v);
  159. Env* const env_;
  160. const std::string dbname_;
  161. const Options* const options_;
  162. TableCache* const table_cache_;
  163. const InternalKeyComparator icmp_;
  164. uint64_t next_file_number_;
  165. uint64_t manifest_file_number_;
  166. uint64_t last_sequence_;
  167. uint64_t log_number_;
  168. uint64_t prev_log_number_; // 0 or backing store for memtable being compacted
  169. // Opened lazily
  170. WritableFile* descriptor_file_;
  171. log::Writer* descriptor_log_;
  172. Version dummy_versions_; // Head of circular doubly-linked list of versions.
  173. Version* current_; // == dummy_versions_.prev_
  174. // Per-level key at which the next compaction at that level should start.
  175. // Either an empty string, or a valid InternalKey.
  176. std::string compact_pointer_[config::kNumLevels];
  177. // No copying allowed
  178. VersionSet(const VersionSet&);
  179. void operator=(const VersionSet&);
  180. };
  181. // A Compaction encapsulates information about a compaction.
  182. class Compaction {
  183. public:
  184. ~Compaction();
  185. // Return the level that is being compacted. Inputs from "level"
  186. // and "level+1" will be merged to produce a set of "level+1" files.
  187. int level() const { return level_; }
  188. // Return the object that holds the edits to the descriptor done
  189. // by this compaction.
  190. VersionEdit* edit() { return &edit_; }
  191. // "which" must be either 0 or 1
  192. int num_input_files(int which) const { return inputs_[which].size(); }
  193. // Return the ith input file at "level()+which" ("which" must be 0 or 1).
  194. FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
  195. // Maximum size of files to build during this compaction.
  196. uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
  197. // Is this a trivial compaction that can be implemented by just
  198. // moving a single input file to the next level (no merging or splitting)
  199. bool IsTrivialMove() const;
  200. // Add all inputs to this compaction as delete operations to *edit.
  201. void AddInputDeletions(VersionEdit* edit);
  202. // Returns true if the information we have available guarantees that
  203. // the compaction is producing data in "level+1" for which no data exists
  204. // in levels greater than "level+1".
  205. bool IsBaseLevelForKey(const Slice& user_key);
  206. // Returns true iff we should stop building the current output
  207. // before processing "internal_key".
  208. bool ShouldStopBefore(const Slice& internal_key);
  209. // Release the input version for the compaction, once the compaction
  210. // is successful.
  211. void ReleaseInputs();
  212. private:
  213. friend class Version;
  214. friend class VersionSet;
  215. explicit Compaction(int level);
  216. int level_;
  217. uint64_t max_output_file_size_;
  218. Version* input_version_;
  219. VersionEdit edit_;
  220. // Each compaction reads inputs from "level_" and "level_+1"
  221. std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
  222. // State used to check for number of of overlapping grandparent files
  223. // (parent == level_ + 1, grandparent == level_ + 2)
  224. std::vector<FileMetaData*> grandparents_;
  225. size_t grandparent_index_; // Index in grandparent_starts_
  226. bool seen_key_; // Some output key has been seen
  227. int64_t overlapped_bytes_; // Bytes of overlap between current output
  228. // and grandparent files
  229. // State for implementing IsBaseLevelForKey
  230. // level_ptrs_ holds indices into input_version_->levels_: our state
  231. // is that we are positioned at one of the file ranges for each
  232. // higher level than the ones involved in this compaction (i.e. for
  233. // all L >= level_ + 2).
  234. size_t level_ptrs_[config::kNumLevels];
  235. };
  236. }
  237. #endif // STORAGE_LEVELDB_DB_VERSION_SET_H_