LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

394 řádky
14 KiB

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