作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

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