作者: 韩晨旭 10225101440 李畅 10225102463
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
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 the user key range
  39. // [smallest,largest].
  40. extern bool SomeFileOverlapsRange(
  41. const InternalKeyComparator& icmp,
  42. const std::vector<FileMetaData*>& files,
  43. const Slice& smallest_user_key,
  44. const Slice& largest_user_key);
  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_user_key,largest_user_key].
  70. bool OverlapInLevel(int level,
  71. const Slice& smallest_user_key,
  72. const Slice& largest_user_key);
  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. Will release *mu while actually writing to the file.
  117. // REQUIRES: *mu is held on entry.
  118. // REQUIRES: no other thread concurrently calls LogAndApply()
  119. Status LogAndApply(VersionEdit* edit, port::Mutex* mu);
  120. // Recover the last saved descriptor from persistent storage.
  121. Status Recover();
  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. // Mark the specified file number as used.
  140. void MarkFileNumberUsed(uint64_t number);
  141. // Return the current log file number.
  142. uint64_t LogNumber() const { return log_number_; }
  143. // Return the log file number for the log file that is currently
  144. // being compacted, or zero if there is no such log file.
  145. uint64_t PrevLogNumber() const { return prev_log_number_; }
  146. // Pick level and inputs for a new compaction.
  147. // Returns NULL if there is no compaction to be done.
  148. // Otherwise returns a pointer to a heap-allocated object that
  149. // describes the compaction. Caller should delete the result.
  150. Compaction* PickCompaction();
  151. // Return a compaction object for compacting the range [begin,end] in
  152. // the specified level. Returns NULL if there is nothing in that
  153. // level that overlaps the specified range. Caller should delete
  154. // the result.
  155. Compaction* CompactRange(
  156. int level,
  157. const InternalKey& begin,
  158. const InternalKey& end);
  159. // Return the maximum overlapping data (in bytes) at next level for any
  160. // file at a level >= 1.
  161. int64_t MaxNextLevelOverlappingBytes();
  162. // Create an iterator that reads over the compaction inputs for "*c".
  163. // The caller should delete the iterator when no longer needed.
  164. Iterator* MakeInputIterator(Compaction* c);
  165. // Returns true iff some level needs a compaction.
  166. bool NeedsCompaction() const {
  167. Version* v = current_;
  168. return (v->compaction_score_ >= 1) || (v->file_to_compact_ != NULL);
  169. }
  170. // Add all files listed in any live version to *live.
  171. // May also mutate some internal state.
  172. void AddLiveFiles(std::set<uint64_t>* live);
  173. // Return the approximate offset in the database of the data for
  174. // "key" as of version "v".
  175. uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
  176. // Return a human-readable short (single-line) summary of the number
  177. // of files per level. Uses *scratch as backing store.
  178. struct LevelSummaryStorage {
  179. char buffer[100];
  180. };
  181. const char* LevelSummary(LevelSummaryStorage* scratch) const;
  182. private:
  183. class Builder;
  184. friend class Compaction;
  185. friend class Version;
  186. void Finalize(Version* v);
  187. void GetOverlappingInputs(
  188. int level,
  189. const InternalKey& begin,
  190. const InternalKey& end,
  191. std::vector<FileMetaData*>* inputs);
  192. void GetRange(const std::vector<FileMetaData*>& inputs,
  193. InternalKey* smallest,
  194. InternalKey* largest);
  195. void GetRange2(const std::vector<FileMetaData*>& inputs1,
  196. const std::vector<FileMetaData*>& inputs2,
  197. InternalKey* smallest,
  198. InternalKey* largest);
  199. void SetupOtherInputs(Compaction* c);
  200. // Save current contents to *log
  201. Status WriteSnapshot(log::Writer* log);
  202. void AppendVersion(Version* v);
  203. Env* const env_;
  204. const std::string dbname_;
  205. const Options* const options_;
  206. TableCache* const table_cache_;
  207. const InternalKeyComparator icmp_;
  208. uint64_t next_file_number_;
  209. uint64_t manifest_file_number_;
  210. uint64_t last_sequence_;
  211. uint64_t log_number_;
  212. uint64_t prev_log_number_; // 0 or backing store for memtable being compacted
  213. // Opened lazily
  214. WritableFile* descriptor_file_;
  215. log::Writer* descriptor_log_;
  216. Version dummy_versions_; // Head of circular doubly-linked list of versions.
  217. Version* current_; // == dummy_versions_.prev_
  218. // Per-level key at which the next compaction at that level should start.
  219. // Either an empty string, or a valid InternalKey.
  220. std::string compact_pointer_[config::kNumLevels];
  221. // No copying allowed
  222. VersionSet(const VersionSet&);
  223. void operator=(const VersionSet&);
  224. };
  225. // A Compaction encapsulates information about a compaction.
  226. class Compaction {
  227. public:
  228. ~Compaction();
  229. // Return the level that is being compacted. Inputs from "level"
  230. // and "level+1" will be merged to produce a set of "level+1" files.
  231. int level() const { return level_; }
  232. // Return the object that holds the edits to the descriptor done
  233. // by this compaction.
  234. VersionEdit* edit() { return &edit_; }
  235. // "which" must be either 0 or 1
  236. int num_input_files(int which) const { return inputs_[which].size(); }
  237. // Return the ith input file at "level()+which" ("which" must be 0 or 1).
  238. FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
  239. // Maximum size of files to build during this compaction.
  240. uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
  241. // Is this a trivial compaction that can be implemented by just
  242. // moving a single input file to the next level (no merging or splitting)
  243. bool IsTrivialMove() const;
  244. // Add all inputs to this compaction as delete operations to *edit.
  245. void AddInputDeletions(VersionEdit* edit);
  246. // Returns true if the information we have available guarantees that
  247. // the compaction is producing data in "level+1" for which no data exists
  248. // in levels greater than "level+1".
  249. bool IsBaseLevelForKey(const Slice& user_key);
  250. // Returns true iff we should stop building the current output
  251. // before processing "internal_key".
  252. bool ShouldStopBefore(const Slice& internal_key);
  253. // Release the input version for the compaction, once the compaction
  254. // is successful.
  255. void ReleaseInputs();
  256. private:
  257. friend class Version;
  258. friend class VersionSet;
  259. explicit Compaction(int level);
  260. int level_;
  261. uint64_t max_output_file_size_;
  262. Version* input_version_;
  263. VersionEdit edit_;
  264. // Each compaction reads inputs from "level_" and "level_+1"
  265. std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
  266. // State used to check for number of of overlapping grandparent files
  267. // (parent == level_ + 1, grandparent == level_ + 2)
  268. std::vector<FileMetaData*> grandparents_;
  269. size_t grandparent_index_; // Index in grandparent_starts_
  270. bool seen_key_; // Some output key has been seen
  271. int64_t overlapped_bytes_; // Bytes of overlap between current output
  272. // and grandparent files
  273. // State for implementing IsBaseLevelForKey
  274. // level_ptrs_ holds indices into input_version_->levels_: our state
  275. // is that we are positioned at one of the file ranges for each
  276. // higher level than the ones involved in this compaction (i.e. for
  277. // all L >= level_ + 2).
  278. size_t level_ptrs_[config::kNumLevels];
  279. };
  280. }
  281. #endif // STORAGE_LEVELDB_DB_VERSION_SET_H_