提供基本的ttl测试用例
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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