作者: 韩晨旭 10225101440 李畅 10225102463
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

317 linhas
11 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. // Grouping of constants. We may want to make some of these
  24. // parameters set via options.
  25. namespace config {
  26. static const int kNumLevels = 7;
  27. }
  28. namespace log { class Writer; }
  29. class Compaction;
  30. class Iterator;
  31. class MemTable;
  32. class TableBuilder;
  33. class TableCache;
  34. class Version;
  35. class VersionSet;
  36. class WritableFile;
  37. class Version {
  38. public:
  39. // Append to *iters a sequence of iterators that will
  40. // yield the contents of this Version when merged together.
  41. // REQUIRES: This version has been saved (see VersionSet::SaveTo)
  42. void AddIterators(const ReadOptions&, std::vector<Iterator*>* iters);
  43. // Reference count management (so Versions do not disappear out from
  44. // under live iterators)
  45. void Ref();
  46. void Unref();
  47. // Return a human readable string that describes this version's contents.
  48. std::string DebugString() const;
  49. private:
  50. friend class Compaction;
  51. friend class VersionSet;
  52. class LevelFileNumIterator;
  53. Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;
  54. VersionSet* vset_; // VersionSet to which this Version belongs
  55. Version* next_; // Next version in linked list
  56. int refs_; // Number of live refs to this version
  57. MemTable* cleanup_mem_; // NULL, or table to delete when version dropped
  58. // List of files per level
  59. std::vector<FileMetaData*> files_[config::kNumLevels];
  60. // Level that should be compacted next and its compaction score.
  61. // Score < 1 means compaction is not strictly needed. These fields
  62. // are initialized by Finalize().
  63. double compaction_score_;
  64. int compaction_level_;
  65. explicit Version(VersionSet* vset)
  66. : vset_(vset), next_(NULL), refs_(0),
  67. cleanup_mem_(NULL),
  68. compaction_score_(-1),
  69. compaction_level_(-1) {
  70. }
  71. ~Version();
  72. // No copying allowed
  73. Version(const Version&);
  74. void operator=(const Version&);
  75. };
  76. class VersionSet {
  77. public:
  78. VersionSet(const std::string& dbname,
  79. const Options* options,
  80. TableCache* table_cache,
  81. const InternalKeyComparator*);
  82. ~VersionSet();
  83. // Apply *edit to the current version to form a new descriptor that
  84. // is both saved to persistent state and installed as the new
  85. // current version. Iff Apply() returns OK, arrange to delete
  86. // cleanup_mem (if cleanup_mem != NULL) when it is no longer needed
  87. // by older versions.
  88. Status LogAndApply(VersionEdit* edit, MemTable* cleanup_mem);
  89. // Recover the last saved descriptor from persistent storage.
  90. Status Recover(uint64_t* log_number, SequenceNumber* last_sequence);
  91. // Save current contents to *log
  92. Status WriteSnapshot(log::Writer* log);
  93. // Return the current version.
  94. Version* current() const { return current_; }
  95. // Return the current manifest file number
  96. uint64_t ManifestFileNumber() const { return manifest_file_number_; }
  97. // Allocate and return a new file number
  98. uint64_t NewFileNumber() { return next_file_number_++; }
  99. // Return the number of Table files at the specified level.
  100. int NumLevelFiles(int level) const;
  101. // Pick level and inputs for a new compaction.
  102. // Returns NULL if there is no compaction to be done.
  103. // Otherwise returns a pointer to a heap-allocated object that
  104. // describes the compaction. Caller should delete the result.
  105. Compaction* PickCompaction();
  106. // Return a compaction object for compacting the range [begin,end] in
  107. // the specified level. Returns NULL if there is nothing in that
  108. // level that overlaps the specified range. Caller should delete
  109. // the result.
  110. Compaction* CompactRange(
  111. int level,
  112. const InternalKey& begin,
  113. const InternalKey& end);
  114. // Return the maximum overlapping data (in bytes) at next level for any
  115. // file at a level >= 1.
  116. int64_t MaxNextLevelOverlappingBytes();
  117. // Create an iterator that reads over the compaction inputs for "*c".
  118. // The caller should delete the iterator when no longer needed.
  119. Iterator* MakeInputIterator(Compaction* c);
  120. // Returns true iff some level needs a compaction.
  121. bool NeedsCompaction() const { return current_->compaction_score_ >= 1; }
  122. // Add all files listed in any live version to *live.
  123. // May also mutate some internal state.
  124. void AddLiveFiles(std::set<uint64_t>* live);
  125. // Return the approximate offset in the database of the data for
  126. // "key" as of version "v".
  127. uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
  128. // Register a reference to a large value with the specified
  129. // large_ref from the specified file number. Returns "true" if this
  130. // is the first recorded reference to the "large_ref" value in the
  131. // database, and false otherwise.
  132. bool RegisterLargeValueRef(const LargeValueRef& large_ref,
  133. uint64_t filenum,
  134. const InternalKey& internal_key);
  135. // Cleanup the large value reference state by eliminating any
  136. // references from files that are not includes in either "live_tables"
  137. // or "log_file".
  138. void CleanupLargeValueRefs(const std::set<uint64_t>& live_tables,
  139. uint64_t log_file_num);
  140. // Returns true if a large value with the given reference is live.
  141. bool LargeValueIsLive(const LargeValueRef& large_ref);
  142. private:
  143. class Builder;
  144. friend class Compaction;
  145. friend class Version;
  146. Status Finalize(Version* v);
  147. // Delete any old versions that are no longer needed.
  148. void MaybeDeleteOldVersions();
  149. struct BySmallestKey;
  150. Status SortLevel(Version* v, uint64_t level);
  151. void GetOverlappingInputs(
  152. int level,
  153. const InternalKey& begin,
  154. const InternalKey& end,
  155. std::vector<FileMetaData*>* inputs);
  156. void GetRange(const std::vector<FileMetaData*>& inputs,
  157. InternalKey* smallest,
  158. InternalKey* largest);
  159. void GetRange2(const std::vector<FileMetaData*>& inputs1,
  160. const std::vector<FileMetaData*>& inputs2,
  161. InternalKey* smallest,
  162. InternalKey* largest);
  163. void SetupOtherInputs(Compaction* c);
  164. Env* const env_;
  165. const std::string dbname_;
  166. const Options* const options_;
  167. TableCache* const table_cache_;
  168. const InternalKeyComparator icmp_;
  169. uint64_t next_file_number_;
  170. uint64_t manifest_file_number_;
  171. // Opened lazily
  172. WritableFile* descriptor_file_;
  173. log::Writer* descriptor_log_;
  174. // Versions are kept in a singly linked list that is never empty
  175. Version* current_; // Pointer to the last (newest) list entry
  176. Version* oldest_; // Pointer to the first (oldest) list entry
  177. // Map from large value reference to the set of <file numbers,internal_key>
  178. // values containing references to the value. We keep the
  179. // internal key as a std::string rather than as an InternalKey because
  180. // we want to be able to easily use a set.
  181. typedef std::set<std::pair<uint64_t, std::string> > LargeReferencesSet;
  182. typedef std::map<LargeValueRef, LargeReferencesSet> LargeValueMap;
  183. LargeValueMap large_value_refs_;
  184. // Per-level key at which the next compaction at that level should start.
  185. // Either an empty string, or a valid InternalKey.
  186. std::string compact_pointer_[config::kNumLevels];
  187. // No copying allowed
  188. VersionSet(const VersionSet&);
  189. void operator=(const VersionSet&);
  190. };
  191. // A Compaction encapsulates information about a compaction.
  192. class Compaction {
  193. public:
  194. ~Compaction();
  195. // Return the level that is being compacted. Inputs from "level"
  196. // and "level+1" will be merged to produce a set of "level+1" files.
  197. int level() const { return level_; }
  198. // Return the object that holds the edits to the descriptor done
  199. // by this compaction.
  200. VersionEdit* edit() { return &edit_; }
  201. // "which" must be either 0 or 1
  202. int num_input_files(int which) const { return inputs_[which].size(); }
  203. // Return the ith input file at "level()+which" ("which" must be 0 or 1).
  204. FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
  205. // Maximum size of files to build during this compaction.
  206. uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
  207. // Is this a trivial compaction that can be implemented by just
  208. // moving a single input file to the next level (no merging or splitting)
  209. bool IsTrivialMove() const;
  210. // Add all inputs to this compaction as delete operations to *edit.
  211. void AddInputDeletions(VersionEdit* edit);
  212. // Returns true if the information we have available guarantees that
  213. // the compaction is producing data in "level+1" for which no data exists
  214. // in levels greater than "level+1".
  215. bool IsBaseLevelForKey(const Slice& user_key);
  216. // Returns true iff we should stop building the current output
  217. // before processing "key".
  218. bool ShouldStopBefore(const InternalKey& key);
  219. // Release the input version for the compaction, once the compaction
  220. // is successful.
  221. void ReleaseInputs();
  222. private:
  223. friend class Version;
  224. friend class VersionSet;
  225. explicit Compaction(int level);
  226. int level_;
  227. uint64_t max_output_file_size_;
  228. Version* input_version_;
  229. VersionEdit edit_;
  230. // Each compaction reads inputs from "level_" and "level_+1"
  231. std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
  232. // State used to check for number of of overlapping grandparent files
  233. // (parent == level_ + 1, grandparent == level_ + 2)
  234. std::vector<FileMetaData*> grandparents_;
  235. int grandparent_index_; // Index in grandparent_starts_
  236. bool seen_key_; // Some output key has been seen
  237. int64_t overlapped_bytes_; // Bytes of overlap between current output
  238. // and grandparent files
  239. // State for implementing IsBaseLevelForKey
  240. // level_ptrs_ holds indices into input_version_->levels_: our state
  241. // is that we are positioned at one of the file ranges for each
  242. // higher level than the ones involved in this compaction (i.e. for
  243. // all L >= level_ + 2).
  244. int level_ptrs_[config::kNumLevels];
  245. };
  246. }
  247. #endif // STORAGE_LEVELDB_DB_VERSION_SET_H_