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.

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