blob: 61c4c99a08636344fff7369be294e6f5c39c6597 [file] [log] [blame]
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +00001// 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
15#ifndef STORAGE_LEVELDB_DB_VERSION_SET_H_
16#define STORAGE_LEVELDB_DB_VERSION_SET_H_
17
18#include <map>
19#include <set>
20#include <vector>
21#include "db/dbformat.h"
22#include "db/version_edit.h"
23#include "port/port.h"
24
25namespace leveldb {
26
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000027namespace log { class Writer; }
28
29class Compaction;
30class Iterator;
31class MemTable;
32class TableBuilder;
33class TableCache;
34class Version;
35class VersionSet;
36class WritableFile;
37
gabor@google.comccf0fcd2011-06-22 02:36:45 +000038// Return the smallest index i such that files[i]->largest >= key.
39// Return files.size() if there is no such file.
40// REQUIRES: "files" contains a sorted list of non-overlapping files.
41extern int FindFile(const InternalKeyComparator& icmp,
42 const std::vector<FileMetaData*>& files,
43 const Slice& key);
44
gabor@google.com6699c7e2011-07-15 00:20:57 +000045// Returns true iff some file in "files" overlaps the user key range
Gabor Cselle299cced2011-10-05 16:30:28 -070046// [*smallest,*largest].
47// smallest==NULL represents a key smaller than all keys in the DB.
48// largest==NULL represents a key largest than all keys in the DB.
49// REQUIRES: If disjoint_sorted_files, files[] contains disjoint ranges
50// in sorted order.
gabor@google.comccf0fcd2011-06-22 02:36:45 +000051extern bool SomeFileOverlapsRange(
52 const InternalKeyComparator& icmp,
Gabor Cselle299cced2011-10-05 16:30:28 -070053 bool disjoint_sorted_files,
gabor@google.comccf0fcd2011-06-22 02:36:45 +000054 const std::vector<FileMetaData*>& files,
Gabor Cselle299cced2011-10-05 16:30:28 -070055 const Slice* smallest_user_key,
56 const Slice* largest_user_key);
gabor@google.comccf0fcd2011-06-22 02:36:45 +000057
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000058class Version {
59 public:
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
gabor@google.comccf0fcd2011-06-22 02:36:45 +000065 // Lookup the value for key. If found, store it in *val and
66 // return OK. Else return a non-OK status. Fills *stats.
67 // REQUIRES: lock is not held
68 struct GetStats {
69 FileMetaData* seek_file;
70 int seek_file_level;
71 };
72 Status Get(const ReadOptions&, const LookupKey& key, std::string* val,
73 GetStats* stats);
74
75 // Adds "stats" into the current state. Returns true if a new
76 // compaction may need to be triggered, false otherwise.
77 // REQUIRES: lock is held
78 bool UpdateStats(const GetStats& stats);
79
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000080 // Reference count management (so Versions do not disappear out from
81 // under live iterators)
82 void Ref();
83 void Unref();
84
Gabor Cselle299cced2011-10-05 16:30:28 -070085 void GetOverlappingInputs(
86 int level,
87 const InternalKey* begin, // NULL means before all keys
88 const InternalKey* end, // NULL means after all keys
89 std::vector<FileMetaData*>* inputs);
90
gabor@google.comccf0fcd2011-06-22 02:36:45 +000091 // Returns true iff some file in the specified level overlaps
Gabor Cselle299cced2011-10-05 16:30:28 -070092 // some part of [*smallest_user_key,*largest_user_key].
93 // smallest_user_key==NULL represents a key smaller than all keys in the DB.
94 // largest_user_key==NULL represents a key largest than all keys in the DB.
gabor@google.comccf0fcd2011-06-22 02:36:45 +000095 bool OverlapInLevel(int level,
Gabor Cselle299cced2011-10-05 16:30:28 -070096 const Slice* smallest_user_key,
97 const Slice* largest_user_key);
98
99 // Return the level at which we should place a new memtable compaction
100 // result that covers the range [smallest_user_key,largest_user_key].
101 int PickLevelForMemTableOutput(const Slice& smallest_user_key,
102 const Slice& largest_user_key);
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000103
104 int NumFiles(int level) const { return files_[level].size(); }
105
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000106 // Return a human readable string that describes this version's contents.
107 std::string DebugString() const;
108
109 private:
110 friend class Compaction;
111 friend class VersionSet;
112
113 class LevelFileNumIterator;
114 Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;
115
116 VersionSet* vset_; // VersionSet to which this Version belongs
117 Version* next_; // Next version in linked list
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000118 Version* prev_; // Previous version in linked list
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000119 int refs_; // Number of live refs to this version
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000120
121 // List of files per level
122 std::vector<FileMetaData*> files_[config::kNumLevels];
123
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000124 // Next file to compact based on seek stats.
125 FileMetaData* file_to_compact_;
126 int file_to_compact_level_;
127
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000128 // Level that should be compacted next and its compaction score.
129 // Score < 1 means compaction is not strictly needed. These fields
130 // are initialized by Finalize().
131 double compaction_score_;
132 int compaction_level_;
133
134 explicit Version(VersionSet* vset)
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000135 : vset_(vset), next_(this), prev_(this), refs_(0),
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000136 file_to_compact_(NULL),
137 file_to_compact_level_(-1),
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000138 compaction_score_(-1),
139 compaction_level_(-1) {
140 }
141
142 ~Version();
143
144 // No copying allowed
145 Version(const Version&);
146 void operator=(const Version&);
147};
148
149class VersionSet {
150 public:
151 VersionSet(const std::string& dbname,
152 const Options* options,
153 TableCache* table_cache,
154 const InternalKeyComparator*);
155 ~VersionSet();
156
157 // Apply *edit to the current version to form a new descriptor that
158 // is both saved to persistent state and installed as the new
gabor@google.com72630232011-09-01 19:08:02 +0000159 // current version. Will release *mu while actually writing to the file.
160 // REQUIRES: *mu is held on entry.
161 // REQUIRES: no other thread concurrently calls LogAndApply()
162 Status LogAndApply(VersionEdit* edit, port::Mutex* mu);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000163
164 // Recover the last saved descriptor from persistent storage.
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000165 Status Recover();
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000166
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000167 // Return the current version.
168 Version* current() const { return current_; }
169
170 // Return the current manifest file number
171 uint64_t ManifestFileNumber() const { return manifest_file_number_; }
172
173 // Allocate and return a new file number
174 uint64_t NewFileNumber() { return next_file_number_++; }
175
Sanjay Ghemawat075a35a2012-05-30 09:45:46 -0700176 // Arrange to reuse "file_number" unless a newer file number has
177 // already been allocated.
178 // REQUIRES: "file_number" was returned by a call to NewFileNumber().
179 void ReuseFileNumber(uint64_t file_number) {
180 if (next_file_number_ == file_number + 1) {
181 next_file_number_ = file_number;
182 }
183 }
184
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000185 // Return the number of Table files at the specified level.
186 int NumLevelFiles(int level) const;
187
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000188 // Return the combined file size of all files at the specified level.
189 int64_t NumLevelBytes(int level) const;
190
191 // Return the last sequence number.
192 uint64_t LastSequence() const { return last_sequence_; }
193
194 // Set the last sequence number to s.
195 void SetLastSequence(uint64_t s) {
196 assert(s >= last_sequence_);
197 last_sequence_ = s;
198 }
199
gabor@google.com72630232011-09-01 19:08:02 +0000200 // Mark the specified file number as used.
201 void MarkFileNumberUsed(uint64_t number);
202
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000203 // Return the current log file number.
204 uint64_t LogNumber() const { return log_number_; }
205
206 // Return the log file number for the log file that is currently
207 // being compacted, or zero if there is no such log file.
208 uint64_t PrevLogNumber() const { return prev_log_number_; }
209
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000210 // Pick level and inputs for a new compaction.
211 // Returns NULL if there is no compaction to be done.
212 // Otherwise returns a pointer to a heap-allocated object that
213 // describes the compaction. Caller should delete the result.
214 Compaction* PickCompaction();
215
216 // Return a compaction object for compacting the range [begin,end] in
217 // the specified level. Returns NULL if there is nothing in that
218 // level that overlaps the specified range. Caller should delete
219 // the result.
220 Compaction* CompactRange(
221 int level,
Gabor Cselle299cced2011-10-05 16:30:28 -0700222 const InternalKey* begin,
223 const InternalKey* end);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000224
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000225 // Return the maximum overlapping data (in bytes) at next level for any
226 // file at a level >= 1.
jorlow@chromium.org8303bb12011-03-22 23:24:02 +0000227 int64_t MaxNextLevelOverlappingBytes();
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000228
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000229 // Create an iterator that reads over the compaction inputs for "*c".
230 // The caller should delete the iterator when no longer needed.
231 Iterator* MakeInputIterator(Compaction* c);
232
233 // Returns true iff some level needs a compaction.
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000234 bool NeedsCompaction() const {
235 Version* v = current_;
236 return (v->compaction_score_ >= 1) || (v->file_to_compact_ != NULL);
237 }
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000238
239 // Add all files listed in any live version to *live.
240 // May also mutate some internal state.
241 void AddLiveFiles(std::set<uint64_t>* live);
242
243 // Return the approximate offset in the database of the data for
244 // "key" as of version "v".
245 uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
246
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000247 // Return a human-readable short (single-line) summary of the number
248 // of files per level. Uses *scratch as backing store.
249 struct LevelSummaryStorage {
250 char buffer[100];
251 };
252 const char* LevelSummary(LevelSummaryStorage* scratch) const;
253
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000254 private:
255 class Builder;
256
257 friend class Compaction;
258 friend class Version;
259
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000260 void Finalize(Version* v);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000261
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000262 void GetRange(const std::vector<FileMetaData*>& inputs,
263 InternalKey* smallest,
264 InternalKey* largest);
265
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000266 void GetRange2(const std::vector<FileMetaData*>& inputs1,
267 const std::vector<FileMetaData*>& inputs2,
268 InternalKey* smallest,
269 InternalKey* largest);
270
271 void SetupOtherInputs(Compaction* c);
272
gabor@google.com72630232011-09-01 19:08:02 +0000273 // Save current contents to *log
274 Status WriteSnapshot(log::Writer* log);
275
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000276 void AppendVersion(Version* v);
277
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000278 Env* const env_;
279 const std::string dbname_;
280 const Options* const options_;
281 TableCache* const table_cache_;
282 const InternalKeyComparator icmp_;
283 uint64_t next_file_number_;
284 uint64_t manifest_file_number_;
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000285 uint64_t last_sequence_;
286 uint64_t log_number_;
287 uint64_t prev_log_number_; // 0 or backing store for memtable being compacted
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000288
289 // Opened lazily
290 WritableFile* descriptor_file_;
291 log::Writer* descriptor_log_;
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000292 Version dummy_versions_; // Head of circular doubly-linked list of versions.
293 Version* current_; // == dummy_versions_.prev_
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000294
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000295 // Per-level key at which the next compaction at that level should start.
296 // Either an empty string, or a valid InternalKey.
297 std::string compact_pointer_[config::kNumLevels];
298
299 // No copying allowed
300 VersionSet(const VersionSet&);
301 void operator=(const VersionSet&);
302};
303
304// A Compaction encapsulates information about a compaction.
305class Compaction {
306 public:
307 ~Compaction();
308
309 // Return the level that is being compacted. Inputs from "level"
310 // and "level+1" will be merged to produce a set of "level+1" files.
311 int level() const { return level_; }
312
313 // Return the object that holds the edits to the descriptor done
314 // by this compaction.
315 VersionEdit* edit() { return &edit_; }
316
317 // "which" must be either 0 or 1
318 int num_input_files(int which) const { return inputs_[which].size(); }
319
320 // Return the ith input file at "level()+which" ("which" must be 0 or 1).
321 FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
322
323 // Maximum size of files to build during this compaction.
324 uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
325
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000326 // Is this a trivial compaction that can be implemented by just
327 // moving a single input file to the next level (no merging or splitting)
328 bool IsTrivialMove() const;
329
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000330 // Add all inputs to this compaction as delete operations to *edit.
331 void AddInputDeletions(VersionEdit* edit);
332
333 // Returns true if the information we have available guarantees that
334 // the compaction is producing data in "level+1" for which no data exists
335 // in levels greater than "level+1".
336 bool IsBaseLevelForKey(const Slice& user_key);
337
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000338 // Returns true iff we should stop building the current output
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000339 // before processing "internal_key".
340 bool ShouldStopBefore(const Slice& internal_key);
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000341
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000342 // Release the input version for the compaction, once the compaction
343 // is successful.
344 void ReleaseInputs();
345
346 private:
347 friend class Version;
348 friend class VersionSet;
349
350 explicit Compaction(int level);
351
352 int level_;
353 uint64_t max_output_file_size_;
354 Version* input_version_;
355 VersionEdit edit_;
356
357 // Each compaction reads inputs from "level_" and "level_+1"
358 std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
359
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000360 // State used to check for number of of overlapping grandparent files
361 // (parent == level_ + 1, grandparent == level_ + 2)
362 std::vector<FileMetaData*> grandparents_;
dgrogan@chromium.orgba6dac02011-04-20 22:48:11 +0000363 size_t grandparent_index_; // Index in grandparent_starts_
jorlow@chromium.org8303bb12011-03-22 23:24:02 +0000364 bool seen_key_; // Some output key has been seen
365 int64_t overlapped_bytes_; // Bytes of overlap between current output
366 // and grandparent files
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000367
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000368 // State for implementing IsBaseLevelForKey
369
370 // level_ptrs_ holds indices into input_version_->levels_: our state
371 // is that we are positioned at one of the file ranges for each
372 // higher level than the ones involved in this compaction (i.e. for
373 // all L >= level_ + 2).
dgrogan@chromium.orgba6dac02011-04-20 22:48:11 +0000374 size_t level_ptrs_[config::kNumLevels];
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000375};
376
Hans Wennborg36a5f8e2011-10-31 17:22:06 +0000377} // namespace leveldb
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000378
379#endif // STORAGE_LEVELDB_DB_VERSION_SET_H_