blob: 0beae4dd00aa3f0ea939871af6a17fa7c56d33d9 [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"
David Grogan946e5b52012-10-12 11:53:12 -070024#include "port/thread_annotations.h"
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000025
26namespace leveldb {
27
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000028namespace log { class Writer; }
29
30class Compaction;
31class Iterator;
32class MemTable;
33class TableBuilder;
34class TableCache;
35class Version;
36class VersionSet;
37class WritableFile;
38
gabor@google.comccf0fcd2011-06-22 02:36:45 +000039// Return the smallest index i such that files[i]->largest >= key.
40// Return files.size() if there is no such file.
41// REQUIRES: "files" contains a sorted list of non-overlapping files.
costanaece2062018-03-12 09:14:44 -070042int FindFile(const InternalKeyComparator& icmp,
43 const std::vector<FileMetaData*>& files,
44 const Slice& key);
gabor@google.comccf0fcd2011-06-22 02:36:45 +000045
gabor@google.com6699c7e2011-07-15 00:20:57 +000046// Returns true iff some file in "files" overlaps the user key range
Gabor Cselle299cced2011-10-05 16:30:28 -070047// [*smallest,*largest].
costan09217fd2018-04-10 16:18:06 -070048// smallest==nullptr represents a key smaller than all keys in the DB.
49// largest==nullptr represents a key largest than all keys in the DB.
Gabor Cselle299cced2011-10-05 16:30:28 -070050// REQUIRES: If disjoint_sorted_files, files[] contains disjoint ranges
51// in sorted order.
costanaece2062018-03-12 09:14:44 -070052bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,
53 bool disjoint_sorted_files,
54 const std::vector<FileMetaData*>& files,
55 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
David Grogan748539c2013-08-21 11:12:47 -070080 // Record a sample of bytes read at the specified internal key.
81 // Samples are taken approximately once every config::kReadBytesPeriod
82 // bytes. Returns true if a new compaction may need to be triggered.
83 // REQUIRES: lock is held
84 bool RecordReadSample(Slice key);
85
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000086 // Reference count management (so Versions do not disappear out from
87 // under live iterators)
88 void Ref();
89 void Unref();
90
Gabor Cselle299cced2011-10-05 16:30:28 -070091 void GetOverlappingInputs(
92 int level,
costan09217fd2018-04-10 16:18:06 -070093 const InternalKey* begin, // nullptr means before all keys
94 const InternalKey* end, // nullptr means after all keys
Gabor Cselle299cced2011-10-05 16:30:28 -070095 std::vector<FileMetaData*>* inputs);
96
gabor@google.comccf0fcd2011-06-22 02:36:45 +000097 // Returns true iff some file in the specified level overlaps
Gabor Cselle299cced2011-10-05 16:30:28 -070098 // some part of [*smallest_user_key,*largest_user_key].
costan09217fd2018-04-10 16:18:06 -070099 // smallest_user_key==nullptr represents a key smaller than all the DB's keys.
100 // largest_user_key==nullptr represents a key largest than all the DB's keys.
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000101 bool OverlapInLevel(int level,
Gabor Cselle299cced2011-10-05 16:30:28 -0700102 const Slice* smallest_user_key,
103 const Slice* largest_user_key);
104
105 // Return the level at which we should place a new memtable compaction
106 // result that covers the range [smallest_user_key,largest_user_key].
107 int PickLevelForMemTableOutput(const Slice& smallest_user_key,
108 const Slice& largest_user_key);
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000109
110 int NumFiles(int level) const { return files_[level].size(); }
111
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000112 // Return a human readable string that describes this version's contents.
113 std::string DebugString() const;
114
115 private:
116 friend class Compaction;
117 friend class VersionSet;
118
119 class LevelFileNumIterator;
120 Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;
121
David Grogan748539c2013-08-21 11:12:47 -0700122 // Call func(arg, level, f) for every file that overlaps user_key in
123 // order from newest to oldest. If an invocation of func returns
124 // false, makes no more calls.
125 //
126 // REQUIRES: user portion of internal_key == user_key.
127 void ForEachOverlapping(Slice user_key, Slice internal_key,
128 void* arg,
129 bool (*func)(void*, int, FileMetaData*));
130
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000131 VersionSet* vset_; // VersionSet to which this Version belongs
132 Version* next_; // Next version in linked list
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000133 Version* prev_; // Previous version in linked list
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000134 int refs_; // Number of live refs to this version
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000135
136 // List of files per level
137 std::vector<FileMetaData*> files_[config::kNumLevels];
138
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000139 // Next file to compact based on seek stats.
140 FileMetaData* file_to_compact_;
141 int file_to_compact_level_;
142
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000143 // Level that should be compacted next and its compaction score.
144 // Score < 1 means compaction is not strictly needed. These fields
145 // are initialized by Finalize().
146 double compaction_score_;
147 int compaction_level_;
148
149 explicit Version(VersionSet* vset)
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000150 : vset_(vset), next_(this), prev_(this), refs_(0),
costan09217fd2018-04-10 16:18:06 -0700151 file_to_compact_(nullptr),
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000152 file_to_compact_level_(-1),
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000153 compaction_score_(-1),
154 compaction_level_(-1) {
155 }
156
157 ~Version();
158
159 // No copying allowed
160 Version(const Version&);
161 void operator=(const Version&);
162};
163
164class VersionSet {
165 public:
166 VersionSet(const std::string& dbname,
167 const Options* options,
168 TableCache* table_cache,
169 const InternalKeyComparator*);
170 ~VersionSet();
171
172 // Apply *edit to the current version to form a new descriptor that
173 // is both saved to persistent state and installed as the new
gabor@google.com72630232011-09-01 19:08:02 +0000174 // current version. Will release *mu while actually writing to the file.
175 // REQUIRES: *mu is held on entry.
176 // REQUIRES: no other thread concurrently calls LogAndApply()
David Grogan946e5b52012-10-12 11:53:12 -0700177 Status LogAndApply(VersionEdit* edit, port::Mutex* mu)
178 EXCLUSIVE_LOCKS_REQUIRED(mu);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000179
180 // Recover the last saved descriptor from persistent storage.
Sanjay Ghemawatac1d69d2014-12-11 08:13:18 -0800181 Status Recover(bool *save_manifest);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000182
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000183 // Return the current version.
184 Version* current() const { return current_; }
185
186 // Return the current manifest file number
187 uint64_t ManifestFileNumber() const { return manifest_file_number_; }
188
189 // Allocate and return a new file number
190 uint64_t NewFileNumber() { return next_file_number_++; }
191
Sanjay Ghemawat075a35a2012-05-30 09:45:46 -0700192 // Arrange to reuse "file_number" unless a newer file number has
193 // already been allocated.
194 // REQUIRES: "file_number" was returned by a call to NewFileNumber().
195 void ReuseFileNumber(uint64_t file_number) {
196 if (next_file_number_ == file_number + 1) {
197 next_file_number_ = file_number;
198 }
199 }
200
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000201 // Return the number of Table files at the specified level.
202 int NumLevelFiles(int level) const;
203
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000204 // Return the combined file size of all files at the specified level.
205 int64_t NumLevelBytes(int level) const;
206
207 // Return the last sequence number.
208 uint64_t LastSequence() const { return last_sequence_; }
209
210 // Set the last sequence number to s.
211 void SetLastSequence(uint64_t s) {
212 assert(s >= last_sequence_);
213 last_sequence_ = s;
214 }
215
gabor@google.com72630232011-09-01 19:08:02 +0000216 // Mark the specified file number as used.
217 void MarkFileNumberUsed(uint64_t number);
218
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000219 // Return the current log file number.
220 uint64_t LogNumber() const { return log_number_; }
221
222 // Return the log file number for the log file that is currently
223 // being compacted, or zero if there is no such log file.
224 uint64_t PrevLogNumber() const { return prev_log_number_; }
225
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000226 // Pick level and inputs for a new compaction.
costan09217fd2018-04-10 16:18:06 -0700227 // Returns nullptr if there is no compaction to be done.
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000228 // Otherwise returns a pointer to a heap-allocated object that
229 // describes the compaction. Caller should delete the result.
230 Compaction* PickCompaction();
231
232 // Return a compaction object for compacting the range [begin,end] in
costan09217fd2018-04-10 16:18:06 -0700233 // the specified level. Returns nullptr if there is nothing in that
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000234 // level that overlaps the specified range. Caller should delete
235 // the result.
236 Compaction* CompactRange(
237 int level,
Gabor Cselle299cced2011-10-05 16:30:28 -0700238 const InternalKey* begin,
239 const InternalKey* end);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000240
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000241 // Return the maximum overlapping data (in bytes) at next level for any
242 // file at a level >= 1.
jorlow@chromium.org8303bb12011-03-22 23:24:02 +0000243 int64_t MaxNextLevelOverlappingBytes();
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000244
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000245 // Create an iterator that reads over the compaction inputs for "*c".
246 // The caller should delete the iterator when no longer needed.
247 Iterator* MakeInputIterator(Compaction* c);
248
249 // Returns true iff some level needs a compaction.
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000250 bool NeedsCompaction() const {
251 Version* v = current_;
costan09217fd2018-04-10 16:18:06 -0700252 return (v->compaction_score_ >= 1) || (v->file_to_compact_ != nullptr);
gabor@google.comccf0fcd2011-06-22 02:36:45 +0000253 }
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000254
255 // Add all files listed in any live version to *live.
256 // May also mutate some internal state.
257 void AddLiveFiles(std::set<uint64_t>* live);
258
259 // Return the approximate offset in the database of the data for
260 // "key" as of version "v".
261 uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
262
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000263 // Return a human-readable short (single-line) summary of the number
264 // of files per level. Uses *scratch as backing store.
265 struct LevelSummaryStorage {
266 char buffer[100];
267 };
268 const char* LevelSummary(LevelSummaryStorage* scratch) const;
269
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000270 private:
271 class Builder;
272
273 friend class Compaction;
274 friend class Version;
275
Sanjay Ghemawatac1d69d2014-12-11 08:13:18 -0800276 bool ReuseManifest(const std::string& dscname, const std::string& dscbase);
277
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000278 void Finalize(Version* v);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000279
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000280 void GetRange(const std::vector<FileMetaData*>& inputs,
281 InternalKey* smallest,
282 InternalKey* largest);
283
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000284 void GetRange2(const std::vector<FileMetaData*>& inputs1,
285 const std::vector<FileMetaData*>& inputs2,
286 InternalKey* smallest,
287 InternalKey* largest);
288
289 void SetupOtherInputs(Compaction* c);
290
gabor@google.com72630232011-09-01 19:08:02 +0000291 // Save current contents to *log
292 Status WriteSnapshot(log::Writer* log);
293
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000294 void AppendVersion(Version* v);
295
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000296 Env* const env_;
297 const std::string dbname_;
298 const Options* const options_;
299 TableCache* const table_cache_;
300 const InternalKeyComparator icmp_;
301 uint64_t next_file_number_;
302 uint64_t manifest_file_number_;
dgrogan@chromium.orgf779e7a2011-04-12 19:38:58 +0000303 uint64_t last_sequence_;
304 uint64_t log_number_;
305 uint64_t prev_log_number_; // 0 or backing store for memtable being compacted
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000306
307 // Opened lazily
308 WritableFile* descriptor_file_;
309 log::Writer* descriptor_log_;
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000310 Version dummy_versions_; // Head of circular doubly-linked list of versions.
311 Version* current_; // == dummy_versions_.prev_
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000312
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000313 // Per-level key at which the next compaction at that level should start.
314 // Either an empty string, or a valid InternalKey.
315 std::string compact_pointer_[config::kNumLevels];
316
317 // No copying allowed
318 VersionSet(const VersionSet&);
319 void operator=(const VersionSet&);
320};
321
322// A Compaction encapsulates information about a compaction.
323class Compaction {
324 public:
325 ~Compaction();
326
327 // Return the level that is being compacted. Inputs from "level"
328 // and "level+1" will be merged to produce a set of "level+1" files.
329 int level() const { return level_; }
330
331 // Return the object that holds the edits to the descriptor done
332 // by this compaction.
333 VersionEdit* edit() { return &edit_; }
334
335 // "which" must be either 0 or 1
336 int num_input_files(int which) const { return inputs_[which].size(); }
337
338 // Return the ith input file at "level()+which" ("which" must be 0 or 1).
339 FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
340
341 // Maximum size of files to build during this compaction.
342 uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
343
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000344 // Is this a trivial compaction that can be implemented by just
345 // moving a single input file to the next level (no merging or splitting)
346 bool IsTrivialMove() const;
347
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000348 // Add all inputs to this compaction as delete operations to *edit.
349 void AddInputDeletions(VersionEdit* edit);
350
351 // Returns true if the information we have available guarantees that
352 // the compaction is producing data in "level+1" for which no data exists
353 // in levels greater than "level+1".
354 bool IsBaseLevelForKey(const Slice& user_key);
355
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000356 // Returns true iff we should stop building the current output
dgrogan@chromium.orgda799092011-05-21 02:17:43 +0000357 // before processing "internal_key".
358 bool ShouldStopBefore(const Slice& internal_key);
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000359
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000360 // Release the input version for the compaction, once the compaction
361 // is successful.
362 void ReleaseInputs();
363
364 private:
365 friend class Version;
366 friend class VersionSet;
367
corradoa2fb0862016-09-27 04:50:38 -0700368 Compaction(const Options* options, int level);
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000369
370 int level_;
371 uint64_t max_output_file_size_;
372 Version* input_version_;
373 VersionEdit edit_;
374
375 // Each compaction reads inputs from "level_" and "level_+1"
376 std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
377
Chris Mumford71ed7c42019-04-11 12:25:12 -0700378 // State used to check for number of overlapping grandparent files
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000379 // (parent == level_ + 1, grandparent == level_ + 2)
380 std::vector<FileMetaData*> grandparents_;
dgrogan@chromium.orgba6dac02011-04-20 22:48:11 +0000381 size_t grandparent_index_; // Index in grandparent_starts_
jorlow@chromium.org8303bb12011-03-22 23:24:02 +0000382 bool seen_key_; // Some output key has been seen
383 int64_t overlapped_bytes_; // Bytes of overlap between current output
384 // and grandparent files
jorlow@chromium.org13b72af2011-03-22 18:32:49 +0000385
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000386 // State for implementing IsBaseLevelForKey
387
388 // level_ptrs_ holds indices into input_version_->levels_: our state
389 // is that we are positioned at one of the file ranges for each
390 // higher level than the ones involved in this compaction (i.e. for
391 // all L >= level_ + 2).
dgrogan@chromium.orgba6dac02011-04-20 22:48:11 +0000392 size_t level_ptrs_[config::kNumLevels];
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000393};
394
Hans Wennborg36a5f8e2011-10-31 17:22:06 +0000395} // namespace leveldb
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +0000396
397#endif // STORAGE_LEVELDB_DB_VERSION_SET_H_