No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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