Line data Source code
1 : // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "fmt"
9 : "io"
10 : "sync"
11 : "sync/atomic"
12 : "time"
13 :
14 : "github.com/cockroachdb/crlib/crtime"
15 : "github.com/cockroachdb/errors"
16 : "github.com/cockroachdb/pebble/internal/base"
17 : "github.com/cockroachdb/pebble/internal/invariants"
18 : "github.com/cockroachdb/pebble/internal/manifest"
19 : "github.com/cockroachdb/pebble/objstorage"
20 : "github.com/cockroachdb/pebble/record"
21 : "github.com/cockroachdb/pebble/vfs"
22 : "github.com/cockroachdb/pebble/vfs/atomicfs"
23 : )
24 :
25 : const numLevels = manifest.NumLevels
26 :
27 : const manifestMarkerName = `manifest`
28 :
29 : // versionSet manages a collection of immutable versions, and manages the
30 : // creation of a new version from the most recent version. A new version is
31 : // created from an existing version by applying a version edit which is just
32 : // like it sounds: a delta from the previous version. Version edits are logged
33 : // to the MANIFEST file, which is replayed at startup.
34 : type versionSet struct {
35 : // Next seqNum to use for WAL writes.
36 : logSeqNum base.AtomicSeqNum
37 :
38 : // The upper bound on sequence numbers that have been assigned so far. A
39 : // suffix of these sequence numbers may not have been written to a WAL. Both
40 : // logSeqNum and visibleSeqNum are atomically updated by the commitPipeline.
41 : // visibleSeqNum is <= logSeqNum.
42 : visibleSeqNum base.AtomicSeqNum
43 :
44 : // Number of bytes present in sstables being written by in-progress
45 : // compactions. This value will be zero if there are no in-progress
46 : // compactions. Updated and read atomically.
47 : atomicInProgressBytes atomic.Int64
48 :
49 : // Immutable fields.
50 : dirname string
51 : provider objstorage.Provider
52 : // Set to DB.mu.
53 : mu *sync.Mutex
54 : opts *Options
55 : fs vfs.FS
56 : cmp *base.Comparer
57 : // Dynamic base level allows the dynamic base level computation to be
58 : // disabled. Used by tests which want to create specific LSM structures.
59 : dynamicBaseLevel bool
60 :
61 : // Mutable fields.
62 : versions manifest.VersionList
63 : latest latestVersionState
64 : picker compactionPicker
65 : // curCompactionConcurrency is updated whenever picker is updated.
66 : // INVARIANT: >= 1.
67 : curCompactionConcurrency atomic.Int32
68 :
69 : // Not all metrics are kept here. See DB.Metrics().
70 : metrics Metrics
71 :
72 : // A pointer to versionSet.addObsoleteLocked. Avoids allocating a new closure
73 : // on the creation of every version.
74 : obsoleteFn func(manifest.ObsoleteFiles)
75 : // obsolete{Tables,Blobs,Manifests,Options} are sorted by file number ascending.
76 : obsoleteTables []obsoleteFile
77 : obsoleteBlobs []obsoleteFile
78 : obsoleteManifests []obsoleteFile
79 : obsoleteOptions []obsoleteFile
80 :
81 : // Zombie tables which have been removed from the current version but are
82 : // still referenced by an inuse iterator.
83 : zombieTables zombieObjects
84 : // Zombie blobs which have been removed from the current version but are
85 : // still referenced by an inuse iterator.
86 : zombieBlobs zombieObjects
87 :
88 : // minUnflushedLogNum is the smallest WAL log file number corresponding to
89 : // mutations that have not been flushed to an sstable.
90 : minUnflushedLogNum base.DiskFileNum
91 :
92 : // The next file number. A single counter is used to assign file
93 : // numbers for the WAL, MANIFEST, sstable, and OPTIONS files.
94 : nextFileNum atomic.Uint64
95 :
96 : // The current manifest file number.
97 : manifestFileNum base.DiskFileNum
98 : manifestMarker *atomicfs.Marker
99 :
100 : manifestFile vfs.File
101 : manifest *record.Writer
102 : getFormatMajorVersion func() FormatMajorVersion
103 :
104 : writing bool
105 : writerCond sync.Cond
106 : // State for deciding when to write a snapshot. Protected by mu.
107 : rotationHelper record.RotationHelper
108 :
109 : pickedCompactionCache pickedCompactionCache
110 : }
111 :
112 : // latestVersionState maintains mutable state describing only the most recent
113 : // version. Unlike a *Version, the state within this struct is updated as new
114 : // version edits are applied.
115 : type latestVersionState struct {
116 : l0Organizer *manifest.L0Organizer
117 : // blobFiles is the set of blob files referenced by the current version.
118 : // blobFiles is protected by the manifest logLock (not vs.mu).
119 : blobFiles manifest.CurrentBlobFileSet
120 : // virtualBackings contains information about the FileBackings which support
121 : // virtual sstables in the latest version. It is mainly used to determine when
122 : // a backing is no longer in use by the tables in the latest version; this is
123 : // not a trivial problem because compactions and other operations can happen
124 : // in parallel (and they can finish in unpredictable order).
125 : //
126 : // This mechanism is complementary to the backing Ref/Unref mechanism, which
127 : // determines when a backing is no longer used by *any* live version and can
128 : // be removed.
129 : //
130 : // In principle this should have been a copy-on-write structure, with each
131 : // Version having its own record of its virtual backings (similar to the
132 : // B-tree that holds the tables). However, in practice we only need it for the
133 : // latest version, so we use a simpler structure and store it in the
134 : // versionSet instead.
135 : //
136 : // virtualBackings is modified under DB.mu and the log lock. If it is accessed
137 : // under DB.mu and a version update is in progress, it reflects the state of
138 : // the next version.
139 : virtualBackings manifest.VirtualBackings
140 : }
141 :
142 : func (vs *versionSet) init(
143 : dirname string,
144 : provider objstorage.Provider,
145 : opts *Options,
146 : marker *atomicfs.Marker,
147 : getFMV func() FormatMajorVersion,
148 : mu *sync.Mutex,
149 1 : ) {
150 1 : vs.dirname = dirname
151 1 : vs.provider = provider
152 1 : vs.mu = mu
153 1 : vs.writerCond.L = mu
154 1 : vs.opts = opts
155 1 : vs.fs = opts.FS
156 1 : vs.cmp = opts.Comparer
157 1 : vs.dynamicBaseLevel = true
158 1 : vs.versions.Init(mu)
159 1 : vs.latest.l0Organizer = manifest.NewL0Organizer(opts.Comparer, opts.FlushSplitBytes)
160 1 : vs.latest.virtualBackings = manifest.MakeVirtualBackings()
161 1 : vs.obsoleteFn = vs.addObsoleteLocked
162 1 : vs.zombieTables = makeZombieObjects()
163 1 : vs.zombieBlobs = makeZombieObjects()
164 1 : vs.nextFileNum.Store(1)
165 1 : vs.manifestMarker = marker
166 1 : vs.getFormatMajorVersion = getFMV
167 1 : }
168 :
169 : // create creates a version set for a fresh DB.
170 : func (vs *versionSet) create(
171 : jobID JobID,
172 : dirname string,
173 : provider objstorage.Provider,
174 : opts *Options,
175 : marker *atomicfs.Marker,
176 : getFormatMajorVersion func() FormatMajorVersion,
177 : blobRewriteHeuristic manifest.BlobRewriteHeuristic,
178 : mu *sync.Mutex,
179 1 : ) error {
180 1 : vs.init(dirname, provider, opts, marker, getFormatMajorVersion, mu)
181 1 : vs.latest.blobFiles.Init(nil, blobRewriteHeuristic)
182 1 : emptyVersion := manifest.NewInitialVersion(opts.Comparer)
183 1 : vs.append(emptyVersion)
184 1 :
185 1 : vs.setCompactionPicker(
186 1 : newCompactionPickerByScore(emptyVersion, &vs.latest, vs.opts, nil))
187 1 : // Note that a "snapshot" version edit is written to the manifest when it is
188 1 : // created.
189 1 : vs.manifestFileNum = vs.getNextDiskFileNum()
190 1 : err := vs.createManifest(vs.dirname, vs.manifestFileNum, vs.minUnflushedLogNum, vs.nextFileNum.Load(), nil /* virtualBackings */)
191 1 : if err == nil {
192 1 : if err = vs.manifest.Flush(); err != nil {
193 0 : vs.opts.Logger.Fatalf("MANIFEST flush failed: %v", err)
194 0 : }
195 : }
196 1 : if err == nil {
197 1 : if err = vs.manifestFile.Sync(); err != nil {
198 0 : vs.opts.Logger.Fatalf("MANIFEST sync failed: %v", err)
199 0 : }
200 : }
201 1 : if err == nil {
202 1 : // NB: Move() is responsible for syncing the data directory.
203 1 : if err = vs.manifestMarker.Move(base.MakeFilename(base.FileTypeManifest, vs.manifestFileNum)); err != nil {
204 0 : vs.opts.Logger.Fatalf("MANIFEST set current failed: %v", err)
205 0 : }
206 : }
207 :
208 1 : vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
209 1 : JobID: int(jobID),
210 1 : Path: base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, vs.manifestFileNum),
211 1 : FileNum: vs.manifestFileNum,
212 1 : Err: err,
213 1 : })
214 1 : if err != nil {
215 0 : return err
216 0 : }
217 1 : return nil
218 : }
219 :
220 : // load loads the version set from the manifest file.
221 : func (vs *versionSet) load(
222 : dirname string,
223 : provider objstorage.Provider,
224 : opts *Options,
225 : manifestFileNum base.DiskFileNum,
226 : marker *atomicfs.Marker,
227 : getFormatMajorVersion func() FormatMajorVersion,
228 : blobRewriteHeuristic manifest.BlobRewriteHeuristic,
229 : mu *sync.Mutex,
230 1 : ) error {
231 1 : vs.init(dirname, provider, opts, marker, getFormatMajorVersion, mu)
232 1 :
233 1 : vs.manifestFileNum = manifestFileNum
234 1 : manifestPath := base.MakeFilepath(opts.FS, dirname, base.FileTypeManifest, vs.manifestFileNum)
235 1 : manifestFilename := opts.FS.PathBase(manifestPath)
236 1 :
237 1 : // Read the versionEdits in the manifest file.
238 1 : var bve manifest.BulkVersionEdit
239 1 : bve.AllAddedTables = make(map[base.TableNum]*manifest.TableMetadata)
240 1 : manifestFile, err := vs.fs.Open(manifestPath)
241 1 : if err != nil {
242 0 : return errors.Wrapf(err, "pebble: could not open manifest file %q for DB %q",
243 0 : errors.Safe(manifestFilename), dirname)
244 0 : }
245 1 : defer manifestFile.Close()
246 1 : rr := record.NewReader(manifestFile, 0 /* logNum */)
247 1 : for {
248 1 : r, err := rr.Next()
249 1 : if err == io.EOF || record.IsInvalidRecord(err) {
250 1 : break
251 : }
252 1 : if err != nil {
253 0 : return errors.Wrapf(err, "pebble: error when loading manifest file %q",
254 0 : errors.Safe(manifestFilename))
255 0 : }
256 1 : var ve manifest.VersionEdit
257 1 : err = ve.Decode(r)
258 1 : if err != nil {
259 0 : // Break instead of returning an error if the record is corrupted
260 0 : // or invalid.
261 0 : if err == io.EOF || record.IsInvalidRecord(err) {
262 0 : break
263 : }
264 0 : return err
265 : }
266 1 : if ve.ComparerName != "" {
267 1 : if ve.ComparerName != vs.cmp.Name {
268 0 : return errors.Errorf("pebble: manifest file %q for DB %q: "+
269 0 : "comparer name from file %q != comparer name from Options %q",
270 0 : errors.Safe(manifestFilename), dirname, errors.Safe(ve.ComparerName), errors.Safe(vs.cmp.Name))
271 0 : }
272 : }
273 1 : if err := bve.Accumulate(&ve); err != nil {
274 0 : return err
275 0 : }
276 1 : if ve.MinUnflushedLogNum != 0 {
277 1 : vs.minUnflushedLogNum = ve.MinUnflushedLogNum
278 1 : }
279 1 : if ve.NextFileNum != 0 {
280 1 : vs.nextFileNum.Store(ve.NextFileNum)
281 1 : }
282 1 : if ve.LastSeqNum != 0 {
283 1 : // logSeqNum is the _next_ sequence number that will be assigned,
284 1 : // while LastSeqNum is the last assigned sequence number. Note that
285 1 : // this behaviour mimics that in RocksDB; the first sequence number
286 1 : // assigned is one greater than the one present in the manifest
287 1 : // (assuming no WALs contain higher sequence numbers than the
288 1 : // manifest's LastSeqNum). Increment LastSeqNum by 1 to get the
289 1 : // next sequence number that will be assigned.
290 1 : //
291 1 : // If LastSeqNum is less than SeqNumStart, increase it to at least
292 1 : // SeqNumStart to leave ample room for reserved sequence numbers.
293 1 : if ve.LastSeqNum+1 < base.SeqNumStart {
294 0 : vs.logSeqNum.Store(base.SeqNumStart)
295 1 : } else {
296 1 : vs.logSeqNum.Store(ve.LastSeqNum + 1)
297 1 : }
298 : }
299 : }
300 : // We have already set vs.nextFileNum = 2 at the beginning of the
301 : // function and could have only updated it to some other non-zero value,
302 : // so it cannot be 0 here.
303 1 : if vs.minUnflushedLogNum == 0 {
304 1 : if vs.nextFileNum.Load() >= 2 {
305 1 : // We either have a freshly created DB, or a DB created by RocksDB
306 1 : // that has not had a single flushed SSTable yet. This is because
307 1 : // RocksDB bumps up nextFileNum in this case without bumping up
308 1 : // minUnflushedLogNum, even if WALs with non-zero file numbers are
309 1 : // present in the directory.
310 1 : } else {
311 0 : return base.CorruptionErrorf("pebble: malformed manifest file %q for DB %q",
312 0 : errors.Safe(manifestFilename), dirname)
313 0 : }
314 : }
315 1 : vs.markFileNumUsed(vs.minUnflushedLogNum)
316 1 :
317 1 : // Populate the virtual backings for virtual sstables since we have finished
318 1 : // version edit accumulation.
319 1 : for _, b := range bve.AddedFileBacking {
320 1 : vs.latest.virtualBackings.AddAndRef(b)
321 1 : }
322 :
323 1 : for _, addedLevel := range bve.AddedTables {
324 1 : for _, m := range addedLevel {
325 1 : if m.Virtual {
326 1 : vs.latest.virtualBackings.AddTable(m)
327 1 : }
328 : }
329 : }
330 :
331 1 : if invariants.Enabled {
332 1 : // There should be no deleted tables or backings, since we're starting from
333 1 : // an empty state.
334 1 : for _, deletedLevel := range bve.DeletedTables {
335 1 : if len(deletedLevel) != 0 {
336 0 : panic("deleted files after manifest replay")
337 : }
338 : }
339 1 : if len(bve.RemovedFileBacking) > 0 {
340 0 : panic("deleted backings after manifest replay")
341 : }
342 : }
343 :
344 1 : emptyVersion := manifest.NewInitialVersion(opts.Comparer)
345 1 : newVersion, err := bve.Apply(emptyVersion, opts.Experimental.ReadCompactionRate)
346 1 : if err != nil {
347 0 : return err
348 0 : }
349 1 : vs.latest.l0Organizer.PerformUpdate(vs.latest.l0Organizer.PrepareUpdate(&bve, newVersion), newVersion)
350 1 : vs.latest.l0Organizer.InitCompactingFileInfo(nil /* in-progress compactions */)
351 1 : vs.latest.blobFiles.Init(&bve, blobRewriteHeuristic)
352 1 : vs.append(newVersion)
353 1 :
354 1 : for i := range vs.metrics.Levels {
355 1 : l := &vs.metrics.Levels[i]
356 1 : l.TablesCount = int64(newVersion.Levels[i].Len())
357 1 : files := newVersion.Levels[i].Slice()
358 1 : l.TablesSize = int64(files.TableSizeSum())
359 1 : }
360 1 : for _, l := range newVersion.Levels {
361 1 : for f := range l.All() {
362 1 : if !f.Virtual {
363 1 : isLocal, localSize := sizeIfLocal(f.TableBacking, vs.provider)
364 1 : vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localSize)
365 1 : if isLocal {
366 1 : vs.metrics.Table.Local.LiveCount++
367 1 : }
368 : }
369 : }
370 : }
371 1 : vs.latest.virtualBackings.ForEach(func(backing *manifest.TableBacking) {
372 1 : isLocal, localSize := sizeIfLocal(backing, vs.provider)
373 1 : vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localSize)
374 1 : if isLocal {
375 1 : vs.metrics.Table.Local.LiveCount++
376 1 : }
377 : })
378 :
379 1 : vs.setCompactionPicker(newCompactionPickerByScore(newVersion, &vs.latest, vs.opts, nil))
380 1 : return nil
381 : }
382 :
383 1 : func (vs *versionSet) close() error {
384 1 : if vs.manifestFile != nil {
385 1 : if err := vs.manifestFile.Close(); err != nil {
386 0 : return err
387 0 : }
388 : }
389 1 : if vs.manifestMarker != nil {
390 1 : if err := vs.manifestMarker.Close(); err != nil {
391 0 : return err
392 0 : }
393 : }
394 1 : return nil
395 : }
396 :
397 : // logLock locks the manifest for writing. The lock must be released by
398 : // a call to logUnlock.
399 : //
400 : // DB.mu must be held when calling this method, but the mutex may be dropped and
401 : // re-acquired during the course of this method.
402 1 : func (vs *versionSet) logLock() {
403 1 : // Wait for any existing writing to the manifest to complete, then mark the
404 1 : // manifest as busy.
405 1 : for vs.writing {
406 1 : // Note: writerCond.L is DB.mu, so we unlock it while we wait.
407 1 : vs.writerCond.Wait()
408 1 : }
409 1 : vs.writing = true
410 : }
411 :
412 : // logUnlock releases the lock for manifest writing.
413 : //
414 : // DB.mu must be held when calling this method.
415 1 : func (vs *versionSet) logUnlock() {
416 1 : if !vs.writing {
417 0 : vs.opts.Logger.Fatalf("MANIFEST not locked for writing")
418 0 : }
419 1 : vs.writing = false
420 1 : vs.writerCond.Signal()
421 : }
422 :
423 1 : func (vs *versionSet) logUnlockAndInvalidatePickedCompactionCache() {
424 1 : vs.pickedCompactionCache.invalidate()
425 1 : vs.logUnlock()
426 1 : }
427 :
428 : // versionUpdate is returned by the function passed to UpdateVersionLocked.
429 : //
430 : // If VE is nil, there is no update to apply (but it is not an error).
431 : type versionUpdate struct {
432 : VE *manifest.VersionEdit
433 : JobID JobID
434 : Metrics levelMetricsDelta
435 : // InProgressCompactionFn is called while DB.mu is held after the I/O part of
436 : // the update was performed. It should return any compactions that are
437 : // in-progress (excluding than the one that is being applied).
438 : InProgressCompactionsFn func() []compactionInfo
439 : ForceManifestRotation bool
440 : }
441 :
442 : // UpdateVersionLocked is used to update the current version, returning the
443 : // duration of the manifest update. If the manifest update is unsuccessful, the
444 : // duration will be unset (0).
445 : //
446 : // DB.mu must be held. UpdateVersionLocked first waits for any other version
447 : // update to complete, releasing and reacquiring DB.mu.
448 : //
449 : // UpdateVersionLocked then calls updateFn which builds a versionUpdate, while
450 : // holding DB.mu. The updateFn can release and reacquire DB.mu (it should
451 : // attempt to do as much work as possible outside of the lock).
452 : //
453 : // UpdateVersionLocked fills in the following fields of the VersionEdit:
454 : // NextFileNum, LastSeqNum, RemovedBackingTables. The removed backing tables are
455 : // those backings that are no longer used (in the new version) after applying
456 : // the edit (as per vs.virtualBackings). Other than these fields, the
457 : // VersionEdit must be complete.
458 : //
459 : // New table backing references (TableBacking.Ref) are taken as part of applying
460 : // the version edit. The state of the virtual backings (vs.virtualBackings) is
461 : // updated before logging to the manifest and installing the latest version;
462 : // this is ok because any failure in those steps is fatal.
463 : //
464 : // If updateFn returns an error, no update is applied and that same error is returned.
465 : // If versionUpdate.VE is nil, the no update is applied (and no error is returned).
466 : func (vs *versionSet) UpdateVersionLocked(
467 : updateFn func() (versionUpdate, error),
468 1 : ) (time.Duration, error) {
469 1 : vs.logLock()
470 1 : defer vs.logUnlockAndInvalidatePickedCompactionCache()
471 1 :
472 1 : vu, err := updateFn()
473 1 : if err != nil || vu.VE == nil {
474 1 : return 0, err
475 1 : }
476 :
477 1 : if !vs.writing {
478 0 : vs.opts.Logger.Fatalf("MANIFEST not locked for writing")
479 0 : }
480 :
481 1 : updateManifestStart := crtime.NowMono()
482 1 : ve := vu.VE
483 1 : if ve.MinUnflushedLogNum != 0 {
484 1 : if ve.MinUnflushedLogNum < vs.minUnflushedLogNum ||
485 1 : vs.nextFileNum.Load() <= uint64(ve.MinUnflushedLogNum) {
486 0 : panic(fmt.Sprintf("pebble: inconsistent versionEdit minUnflushedLogNum %d",
487 0 : ve.MinUnflushedLogNum))
488 : }
489 : }
490 :
491 : // This is the next manifest filenum, but if the current file is too big we
492 : // will write this ve to the next file which means what ve encodes is the
493 : // current filenum and not the next one.
494 : //
495 : // TODO(sbhola): figure out why this is correct and update comment.
496 1 : ve.NextFileNum = vs.nextFileNum.Load()
497 1 :
498 1 : // LastSeqNum is set to the current upper bound on the assigned sequence
499 1 : // numbers. Note that this is exactly the behavior of RocksDB. LastSeqNum is
500 1 : // used to initialize versionSet.logSeqNum and versionSet.visibleSeqNum on
501 1 : // replay. It must be higher than or equal to any than any sequence number
502 1 : // written to an sstable, including sequence numbers in ingested files.
503 1 : // Note that LastSeqNum is not (and cannot be) the minimum unflushed sequence
504 1 : // number. This is fallout from ingestion which allows a sequence number X to
505 1 : // be assigned to an ingested sstable even though sequence number X-1 resides
506 1 : // in an unflushed memtable. logSeqNum is the _next_ sequence number that
507 1 : // will be assigned, so subtract that by 1 to get the upper bound on the
508 1 : // last assigned sequence number.
509 1 : logSeqNum := vs.logSeqNum.Load()
510 1 : ve.LastSeqNum = logSeqNum - 1
511 1 : if logSeqNum == 0 {
512 0 : // logSeqNum is initialized to 1 in Open() if there are no previous WAL
513 0 : // or manifest records, so this case should never happen.
514 0 : vs.opts.Logger.Fatalf("logSeqNum must be a positive integer: %d", logSeqNum)
515 0 : }
516 :
517 1 : currentVersion := vs.currentVersion()
518 1 : var newVersion *manifest.Version
519 1 :
520 1 : // Generate a new manifest if we don't currently have one, or forceRotation
521 1 : // is true, or the current one is too large.
522 1 : //
523 1 : // For largeness, we do not exclusively use MaxManifestFileSize size
524 1 : // threshold since we have had incidents where due to either large keys or
525 1 : // large numbers of files, each edit results in a snapshot + write of the
526 1 : // edit. This slows the system down since each flush or compaction is
527 1 : // writing a new manifest snapshot. The primary goal of the size-based
528 1 : // rollover logic is to ensure that when reopening a DB, the number of edits
529 1 : // that need to be replayed on top of the snapshot is "sane". Rolling over
530 1 : // to a new manifest after each edit is not relevant to that goal.
531 1 : //
532 1 : // Consider the following cases:
533 1 : // - The number of live files F in the DB is roughly stable: after writing
534 1 : // the snapshot (with F files), say we require that there be enough edits
535 1 : // such that the cumulative number of files in those edits, E, be greater
536 1 : // than F. This will ensure that the total amount of time in
537 1 : // UpdateVersionLocked that is spent in snapshot writing is ~50%.
538 1 : //
539 1 : // - The number of live files F in the DB is shrinking drastically, say from
540 1 : // F to F/10: This can happen for various reasons, like wide range
541 1 : // tombstones, or large numbers of smaller than usual files that are being
542 1 : // merged together into larger files. And say the new files generated
543 1 : // during this shrinkage is insignificant compared to F/10, and so for
544 1 : // this example we will assume it is effectively 0. After this shrinking,
545 1 : // E = 0.9F, and so if we used the previous snapshot file count, F, as the
546 1 : // threshold that needs to be exceeded, we will further delay the snapshot
547 1 : // writing. Which means on DB reopen we will need to replay 0.9F edits to
548 1 : // get to a version with 0.1F files. It would be better to create a new
549 1 : // snapshot when E exceeds the number of files in the current version.
550 1 : //
551 1 : // - The number of live files F in the DB is growing via perfect ingests
552 1 : // into L6: Say we wrote the snapshot when there were F files and now we
553 1 : // have 10F files, so E = 9F. We will further delay writing a new
554 1 : // snapshot. This case can be critiqued as contrived, but we consider it
555 1 : // nonetheless.
556 1 : //
557 1 : // The logic below uses the min of the last snapshot file count and the file
558 1 : // count in the current version.
559 1 : vs.rotationHelper.AddRecord(int64(len(ve.DeletedTables) + len(ve.NewTables)))
560 1 : sizeExceeded := vs.manifest.Size() >= vs.opts.MaxManifestFileSize
561 1 : requireRotation := vu.ForceManifestRotation || vs.manifest == nil
562 1 :
563 1 : var nextSnapshotFilecount int64
564 1 : for i := range vs.metrics.Levels {
565 1 : nextSnapshotFilecount += vs.metrics.Levels[i].TablesCount
566 1 : }
567 1 : if sizeExceeded && !requireRotation {
568 1 : requireRotation = vs.rotationHelper.ShouldRotate(nextSnapshotFilecount)
569 1 : }
570 1 : var newManifestFileNum base.DiskFileNum
571 1 : var prevManifestFileSize uint64
572 1 : var newManifestVirtualBackings []*manifest.TableBacking
573 1 : if requireRotation {
574 1 : newManifestFileNum = vs.getNextDiskFileNum()
575 1 : prevManifestFileSize = uint64(vs.manifest.Size())
576 1 :
577 1 : // We want the virtual backings *before* applying the version edit, because
578 1 : // the new manifest will contain the pre-apply version plus the last version
579 1 : // edit.
580 1 : newManifestVirtualBackings = vs.latest.virtualBackings.Backings()
581 1 : }
582 :
583 : // Grab certain values before releasing vs.mu, in case createManifest() needs
584 : // to be called.
585 1 : minUnflushedLogNum := vs.minUnflushedLogNum
586 1 : nextFileNum := vs.nextFileNum.Load()
587 1 :
588 1 : // Note: this call populates ve.RemovedBackingTables.
589 1 : zombieBackings, removedVirtualBackings, localTablesLiveDelta :=
590 1 : getZombieTablesAndUpdateVirtualBackings(ve, &vs.latest.virtualBackings, vs.provider)
591 1 :
592 1 : var l0Update manifest.L0PreparedUpdate
593 1 : if err := func() error {
594 1 : vs.mu.Unlock()
595 1 : defer vs.mu.Lock()
596 1 :
597 1 : if vs.getFormatMajorVersion() < FormatVirtualSSTables && len(ve.CreatedBackingTables) > 0 {
598 0 : return base.AssertionFailedf("MANIFEST cannot contain virtual sstable records due to format major version")
599 0 : }
600 :
601 : // Rotate the manifest if necessary. Rotating the manifest involves
602 : // creating a new file and writing an initial version edit containing a
603 : // snapshot of the current version. This initial version edit will
604 : // reflect the Version prior to the pending version edit (`ve`). Once
605 : // we've created the new manifest with the previous version state, we'll
606 : // append the version edit `ve` to the tail of the new manifest.
607 1 : if newManifestFileNum != 0 {
608 1 : if err := vs.createManifest(vs.dirname, newManifestFileNum, minUnflushedLogNum, nextFileNum, newManifestVirtualBackings); err != nil {
609 0 : vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
610 0 : JobID: int(vu.JobID),
611 0 : Path: base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, newManifestFileNum),
612 0 : FileNum: newManifestFileNum,
613 0 : Err: err,
614 0 : })
615 0 : return errors.Wrap(err, "MANIFEST create failed")
616 0 : }
617 : }
618 :
619 : // Call ApplyAndUpdateVersionEdit before accumulating the version edit.
620 : // If any blob files are no longer referenced, the version edit will be
621 : // updated to explicitly record the deletion of the blob files. This can
622 : // happen here because vs.blobFiles is protected by the manifest logLock
623 : // (NOT vs.mu). We only read or write vs.blobFiles while holding the
624 : // manifest lock.
625 1 : if err := vs.latest.blobFiles.ApplyAndUpdateVersionEdit(ve); err != nil {
626 0 : return errors.Wrap(err, "MANIFEST blob files apply and update failed")
627 0 : }
628 :
629 1 : var bulkEdit manifest.BulkVersionEdit
630 1 : err := bulkEdit.Accumulate(ve)
631 1 : if err != nil {
632 0 : return errors.Wrap(err, "MANIFEST accumulate failed")
633 0 : }
634 1 : newVersion, err = bulkEdit.Apply(currentVersion, vs.opts.Experimental.ReadCompactionRate)
635 1 : if err != nil {
636 0 : return errors.Wrap(err, "MANIFEST apply failed")
637 0 : }
638 1 : l0Update = vs.latest.l0Organizer.PrepareUpdate(&bulkEdit, newVersion)
639 1 :
640 1 : w, err := vs.manifest.Next()
641 1 : if err != nil {
642 0 : return errors.Wrap(err, "MANIFEST next record write failed")
643 0 : }
644 :
645 : // NB: Any error from this point on is considered fatal as we don't know if
646 : // the MANIFEST write occurred or not. Trying to determine that is
647 : // fraught. Instead we rely on the standard recovery mechanism run when a
648 : // database is open. In particular, that mechanism generates a new MANIFEST
649 : // and ensures it is synced.
650 1 : if err := ve.Encode(w); err != nil {
651 0 : return errors.Wrap(err, "MANIFEST write failed")
652 0 : }
653 1 : if err := vs.manifest.Flush(); err != nil {
654 0 : return errors.Wrap(err, "MANIFEST flush failed")
655 0 : }
656 1 : if err := vs.manifestFile.Sync(); err != nil {
657 0 : return errors.Wrap(err, "MANIFEST sync failed")
658 0 : }
659 1 : if newManifestFileNum != 0 {
660 1 : // NB: Move() is responsible for syncing the data directory.
661 1 : if err := vs.manifestMarker.Move(base.MakeFilename(base.FileTypeManifest, newManifestFileNum)); err != nil {
662 0 : return errors.Wrap(err, "MANIFEST set current failed")
663 0 : }
664 1 : vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
665 1 : JobID: int(vu.JobID),
666 1 : Path: base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, newManifestFileNum),
667 1 : FileNum: newManifestFileNum,
668 1 : })
669 : }
670 1 : return nil
671 0 : }(); err != nil {
672 0 : // Any error encountered during any of the operations in the previous
673 0 : // closure are considered fatal. Treating such errors as fatal is preferred
674 0 : // to attempting to unwind various file and b-tree reference counts, and
675 0 : // re-generating L0 sublevel metadata. This may change in the future, if
676 0 : // certain manifest / WAL operations become retryable. For more context, see
677 0 : // #1159 and #1792.
678 0 : vs.opts.Logger.Fatalf("%s", err)
679 0 : return 0, err
680 0 : }
681 :
682 1 : if requireRotation {
683 1 : // Successfully rotated.
684 1 : vs.rotationHelper.Rotate(nextSnapshotFilecount)
685 1 : }
686 : // Now that DB.mu is held again, initialize compacting file info in
687 : // L0Sublevels.
688 1 : inProgress := vu.InProgressCompactionsFn()
689 1 :
690 1 : zombieBlobs, localBlobLiveDelta := getZombieBlobFilesAndComputeLocalMetrics(ve, vs.provider)
691 1 : vs.latest.l0Organizer.PerformUpdate(l0Update, newVersion)
692 1 : vs.latest.l0Organizer.InitCompactingFileInfo(inProgressL0Compactions(inProgress))
693 1 :
694 1 : // Update the zombie objects sets first, as installation of the new version
695 1 : // will unref the previous version which could result in addObsoleteLocked
696 1 : // being called.
697 1 : for _, b := range zombieBackings {
698 1 : vs.zombieTables.Add(objectInfo{
699 1 : fileInfo: fileInfo{
700 1 : FileNum: b.backing.DiskFileNum,
701 1 : FileSize: b.backing.Size,
702 1 : },
703 1 : isLocal: b.isLocal,
704 1 : })
705 1 : }
706 1 : for _, zb := range zombieBlobs {
707 1 : vs.zombieBlobs.Add(zb)
708 1 : }
709 : // Unref the removed backings and report those that already became obsolete.
710 : // Note that the only case where we report obsolete tables here is when
711 : // VirtualBackings.Protect/Unprotect was used to keep a backing alive without
712 : // it being used in the current version.
713 1 : var obsoleteVirtualBackings manifest.ObsoleteFiles
714 1 : for _, b := range removedVirtualBackings {
715 1 : if b.backing.Unref() == 0 {
716 1 : obsoleteVirtualBackings.TableBackings = append(obsoleteVirtualBackings.TableBackings, b.backing)
717 1 : }
718 : }
719 1 : vs.addObsoleteLocked(obsoleteVirtualBackings)
720 1 :
721 1 : // Install the new version.
722 1 : vs.append(newVersion)
723 1 :
724 1 : if ve.MinUnflushedLogNum != 0 {
725 1 : vs.minUnflushedLogNum = ve.MinUnflushedLogNum
726 1 : }
727 1 : if newManifestFileNum != 0 {
728 1 : if vs.manifestFileNum != 0 {
729 1 : vs.obsoleteManifests = append(vs.obsoleteManifests, obsoleteFile{
730 1 : fileType: base.FileTypeManifest,
731 1 : fs: vs.fs,
732 1 : path: base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, vs.manifestFileNum),
733 1 : fileNum: vs.manifestFileNum,
734 1 : fileSize: prevManifestFileSize,
735 1 : isLocal: true,
736 1 : })
737 1 : }
738 1 : vs.manifestFileNum = newManifestFileNum
739 : }
740 :
741 1 : vs.metrics.updateLevelMetrics(vu.Metrics)
742 1 : for i := range vs.metrics.Levels {
743 1 : l := &vs.metrics.Levels[i]
744 1 : l.TablesCount = int64(newVersion.Levels[i].Len())
745 1 : l.VirtualTablesCount = newVersion.Levels[i].NumVirtual
746 1 : l.VirtualTablesSize = newVersion.Levels[i].VirtualTableSize
747 1 : l.TablesSize = int64(newVersion.Levels[i].TableSize())
748 1 : l.EstimatedReferencesSize = newVersion.Levels[i].EstimatedReferenceSize()
749 1 : l.Sublevels = 0
750 1 : if l.TablesCount > 0 {
751 1 : l.Sublevels = 1
752 1 : }
753 1 : if invariants.Enabled {
754 1 : levelFiles := newVersion.Levels[i].Slice()
755 1 : if size := int64(levelFiles.TableSizeSum()); l.TablesSize != size {
756 0 : vs.opts.Logger.Fatalf("versionSet metrics L%d Size = %d, actual size = %d", i, l.TablesSize, size)
757 0 : }
758 1 : refSize := uint64(0)
759 1 : for f := range levelFiles.All() {
760 1 : refSize += f.EstimatedReferenceSize()
761 1 : }
762 1 : if refSize != l.EstimatedReferencesSize {
763 0 : vs.opts.Logger.Fatalf("versionSet metrics L%d EstimatedReferencesSize = %d, recomputed size = %d", i, l.EstimatedReferencesSize, refSize)
764 0 : }
765 :
766 1 : if nVirtual := levelFiles.NumVirtual(); nVirtual != l.VirtualTablesCount {
767 0 : vs.opts.Logger.Fatalf(
768 0 : "versionSet metrics L%d NumVirtual = %d, actual NumVirtual = %d",
769 0 : i, l.VirtualTablesCount, nVirtual,
770 0 : )
771 0 : }
772 1 : if vSize := levelFiles.VirtualTableSizeSum(); vSize != l.VirtualTablesSize {
773 0 : vs.opts.Logger.Fatalf(
774 0 : "versionSet metrics L%d Virtual size = %d, actual size = %d",
775 0 : i, l.VirtualTablesSize, vSize,
776 0 : )
777 0 : }
778 : }
779 : }
780 1 : vs.metrics.Levels[0].Sublevels = int32(len(newVersion.L0SublevelFiles))
781 1 : vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localTablesLiveDelta.size)
782 1 : vs.metrics.Table.Local.LiveCount = uint64(int64(vs.metrics.Table.Local.LiveCount) + localTablesLiveDelta.count)
783 1 : vs.metrics.BlobFiles.Local.LiveSize = uint64(int64(vs.metrics.BlobFiles.Local.LiveSize) + localBlobLiveDelta.size)
784 1 : vs.metrics.BlobFiles.Local.LiveCount = uint64(int64(vs.metrics.BlobFiles.Local.LiveCount) + localBlobLiveDelta.count)
785 1 :
786 1 : vs.setCompactionPicker(newCompactionPickerByScore(newVersion, &vs.latest, vs.opts, inProgress))
787 1 : if !vs.dynamicBaseLevel {
788 0 : vs.picker.forceBaseLevel1()
789 0 : }
790 :
791 1 : return updateManifestStart.Elapsed(), nil
792 : }
793 :
794 1 : func (vs *versionSet) setCompactionPicker(picker *compactionPickerByScore) {
795 1 : vs.picker = picker
796 1 : vs.curCompactionConcurrency.Store(int32(picker.getCompactionConcurrency()))
797 1 : }
798 :
799 : type tableBackingInfo struct {
800 : backing *manifest.TableBacking
801 : isLocal bool
802 : }
803 :
804 : type fileMetricDelta struct {
805 : count int64
806 : size int64
807 : }
808 :
809 : // getZombieTablesAndUpdateVirtualBackings updates the virtual backings with the
810 : // changes in the versionEdit and populates ve.RemovedBackingTables.
811 : // Returns:
812 : // - zombieBackings: all backings (physical and virtual) that will no longer be
813 : // needed when we apply ve.
814 : // - removedVirtualBackings: the virtual backings that will be removed by the
815 : // VersionEdit and which must be Unref()ed by the caller. These backings
816 : // match ve.RemovedBackingTables.
817 : // - localLiveSizeDelta: the delta in local live bytes.
818 : func getZombieTablesAndUpdateVirtualBackings(
819 : ve *manifest.VersionEdit, virtualBackings *manifest.VirtualBackings, provider objstorage.Provider,
820 1 : ) (zombieBackings, removedVirtualBackings []tableBackingInfo, localLiveDelta fileMetricDelta) {
821 1 : // First, deal with the physical tables.
822 1 : //
823 1 : // A physical backing has become unused if it is in DeletedFiles but not in
824 1 : // NewFiles or CreatedBackingTables.
825 1 : //
826 1 : // Note that for the common case where there are very few elements, the map
827 1 : // will stay on the stack.
828 1 : stillUsed := make(map[base.DiskFileNum]struct{})
829 1 : for _, nf := range ve.NewTables {
830 1 : if !nf.Meta.Virtual {
831 1 : stillUsed[nf.Meta.TableBacking.DiskFileNum] = struct{}{}
832 1 : isLocal, localFileDelta := sizeIfLocal(nf.Meta.TableBacking, provider)
833 1 : localLiveDelta.size += localFileDelta
834 1 : if isLocal {
835 1 : localLiveDelta.count++
836 1 : }
837 : }
838 : }
839 1 : for _, b := range ve.CreatedBackingTables {
840 1 : stillUsed[b.DiskFileNum] = struct{}{}
841 1 : }
842 1 : for _, m := range ve.DeletedTables {
843 1 : if !m.Virtual {
844 1 : // NB: this deleted file may also be in NewFiles or
845 1 : // CreatedBackingTables, due to a file moving between levels, or
846 1 : // becoming virtualized. In which case there is no change due to this
847 1 : // file in the localLiveSizeDelta -- the subtraction below compensates
848 1 : // for the addition.
849 1 : isLocal, localFileDelta := sizeIfLocal(m.TableBacking, provider)
850 1 : localLiveDelta.size -= localFileDelta
851 1 : if isLocal {
852 1 : localLiveDelta.count--
853 1 : }
854 1 : if _, ok := stillUsed[m.TableBacking.DiskFileNum]; !ok {
855 1 : zombieBackings = append(zombieBackings, tableBackingInfo{
856 1 : backing: m.TableBacking,
857 1 : isLocal: isLocal,
858 1 : })
859 1 : }
860 : }
861 : }
862 :
863 : // Now deal with virtual tables.
864 : //
865 : // When a virtual table moves between levels we AddTable() then RemoveTable(),
866 : // which works out.
867 1 : for _, b := range ve.CreatedBackingTables {
868 1 : virtualBackings.AddAndRef(b)
869 1 : isLocal, localFileDelta := sizeIfLocal(b, provider)
870 1 : localLiveDelta.size += localFileDelta
871 1 : if isLocal {
872 1 : localLiveDelta.count++
873 1 : }
874 : }
875 1 : for _, nf := range ve.NewTables {
876 1 : if nf.Meta.Virtual {
877 1 : virtualBackings.AddTable(nf.Meta)
878 1 : }
879 : }
880 1 : for _, m := range ve.DeletedTables {
881 1 : if m.Virtual {
882 1 : virtualBackings.RemoveTable(m)
883 1 : }
884 : }
885 :
886 1 : if unused := virtualBackings.Unused(); len(unused) > 0 {
887 1 : // Virtual backings that are no longer used are zombies and are also added
888 1 : // to RemovedBackingTables (before the version edit is written to disk).
889 1 : ve.RemovedBackingTables = make([]base.DiskFileNum, len(unused))
890 1 : for i, b := range unused {
891 1 : isLocal, localFileDelta := sizeIfLocal(b, provider)
892 1 : localLiveDelta.size -= localFileDelta
893 1 : if isLocal {
894 1 : localLiveDelta.count--
895 1 : }
896 1 : ve.RemovedBackingTables[i] = b.DiskFileNum
897 1 : zombieBackings = append(zombieBackings, tableBackingInfo{
898 1 : backing: b,
899 1 : isLocal: isLocal,
900 1 : })
901 1 : virtualBackings.Remove(b.DiskFileNum)
902 : }
903 1 : removedVirtualBackings = zombieBackings[len(zombieBackings)-len(unused):]
904 : }
905 1 : return zombieBackings, removedVirtualBackings, localLiveDelta
906 : }
907 :
908 : // getZombieBlobFilesAndComputeLocalMetrics constructs objectInfos for all
909 : // zombie blob files, and computes the metric deltas for live files overall and
910 : // locally.
911 : func getZombieBlobFilesAndComputeLocalMetrics(
912 : ve *manifest.VersionEdit, provider objstorage.Provider,
913 1 : ) (zombieBlobFiles []objectInfo, localLiveDelta fileMetricDelta) {
914 1 : for _, b := range ve.NewBlobFiles {
915 1 : if objstorage.IsLocalBlobFile(provider, b.Physical.FileNum) {
916 1 : localLiveDelta.count++
917 1 : localLiveDelta.size += int64(b.Physical.Size)
918 1 : }
919 : }
920 1 : zombieBlobFiles = make([]objectInfo, 0, len(ve.DeletedBlobFiles))
921 1 : for _, physical := range ve.DeletedBlobFiles {
922 1 : isLocal := objstorage.IsLocalBlobFile(provider, physical.FileNum)
923 1 : if isLocal {
924 1 : localLiveDelta.count--
925 1 : localLiveDelta.size -= int64(physical.Size)
926 1 : }
927 1 : zombieBlobFiles = append(zombieBlobFiles, objectInfo{
928 1 : fileInfo: fileInfo{
929 1 : FileNum: physical.FileNum,
930 1 : FileSize: physical.Size,
931 1 : },
932 1 : isLocal: isLocal,
933 1 : })
934 : }
935 1 : return zombieBlobFiles, localLiveDelta
936 : }
937 :
938 : // sizeIfLocal returns backing.Size if the backing is a local file, else 0.
939 : func sizeIfLocal(
940 : backing *manifest.TableBacking, provider objstorage.Provider,
941 1 : ) (isLocal bool, localSize int64) {
942 1 : isLocal = objstorage.IsLocalTable(provider, backing.DiskFileNum)
943 1 : if isLocal {
944 1 : return true, int64(backing.Size)
945 1 : }
946 1 : return false, 0
947 : }
948 :
949 : func (vs *versionSet) incrementCompactions(
950 : kind compactionKind, extraLevels []*compactionLevel, bytesWritten int64, compactionErr error,
951 1 : ) {
952 1 : if kind == compactionKindFlush || kind == compactionKindIngestedFlushable {
953 1 : vs.metrics.Flush.Count++
954 1 : } else {
955 1 : vs.metrics.Compact.Count++
956 1 : if compactionErr != nil {
957 1 : if errors.Is(compactionErr, ErrCancelledCompaction) {
958 1 : vs.metrics.Compact.CancelledCount++
959 1 : vs.metrics.Compact.CancelledBytes += bytesWritten
960 1 : } else {
961 0 : vs.metrics.Compact.FailedCount++
962 0 : }
963 : }
964 : }
965 :
966 1 : switch kind {
967 1 : case compactionKindDefault:
968 1 : vs.metrics.Compact.DefaultCount++
969 :
970 1 : case compactionKindFlush, compactionKindIngestedFlushable:
971 :
972 1 : case compactionKindMove:
973 1 : vs.metrics.Compact.MoveCount++
974 :
975 1 : case compactionKindDeleteOnly:
976 1 : vs.metrics.Compact.DeleteOnlyCount++
977 :
978 1 : case compactionKindElisionOnly:
979 1 : vs.metrics.Compact.ElisionOnlyCount++
980 :
981 0 : case compactionKindRead:
982 0 : vs.metrics.Compact.ReadCount++
983 :
984 1 : case compactionKindTombstoneDensity:
985 1 : vs.metrics.Compact.TombstoneDensityCount++
986 :
987 1 : case compactionKindRewrite:
988 1 : vs.metrics.Compact.RewriteCount++
989 :
990 1 : case compactionKindCopy:
991 1 : vs.metrics.Compact.CopyCount++
992 :
993 1 : case compactionKindBlobFileRewrite:
994 1 : vs.metrics.Compact.BlobFileRewriteCount++
995 :
996 0 : default:
997 0 : if invariants.Enabled {
998 0 : panic("unhandled compaction kind")
999 : }
1000 :
1001 : }
1002 1 : if len(extraLevels) > 0 {
1003 1 : vs.metrics.Compact.MultiLevelCount++
1004 1 : }
1005 : }
1006 :
1007 1 : func (vs *versionSet) incrementCompactionBytes(numBytes int64) {
1008 1 : vs.atomicInProgressBytes.Add(numBytes)
1009 1 : }
1010 :
1011 : // createManifest creates a manifest file that contains a snapshot of vs.
1012 : func (vs *versionSet) createManifest(
1013 : dirname string,
1014 : fileNum, minUnflushedLogNum base.DiskFileNum,
1015 : nextFileNum uint64,
1016 : virtualBackings []*manifest.TableBacking,
1017 1 : ) (err error) {
1018 1 : var (
1019 1 : filename = base.MakeFilepath(vs.fs, dirname, base.FileTypeManifest, fileNum)
1020 1 : manifestFile vfs.File
1021 1 : manifestWriter *record.Writer
1022 1 : )
1023 1 : defer func() {
1024 1 : if manifestWriter != nil {
1025 0 : _ = manifestWriter.Close()
1026 0 : }
1027 1 : if manifestFile != nil {
1028 0 : _ = manifestFile.Close()
1029 0 : }
1030 1 : if err != nil {
1031 0 : _ = vs.fs.Remove(filename)
1032 0 : }
1033 : }()
1034 1 : manifestFile, err = vs.fs.Create(filename, "pebble-manifest")
1035 1 : if err != nil {
1036 0 : return err
1037 0 : }
1038 1 : manifestWriter = record.NewWriter(manifestFile)
1039 1 :
1040 1 : snapshot := manifest.VersionEdit{
1041 1 : ComparerName: vs.cmp.Name,
1042 1 : // When creating a version snapshot for an existing DB, this snapshot
1043 1 : // VersionEdit will be immediately followed by another VersionEdit
1044 1 : // (being written in UpdateVersionLocked()). That VersionEdit always
1045 1 : // contains a LastSeqNum, so we don't need to include that in the
1046 1 : // snapshot. But it does not necessarily include MinUnflushedLogNum,
1047 1 : // NextFileNum, so we initialize those using the corresponding fields in
1048 1 : // the versionSet (which came from the latest preceding VersionEdit that
1049 1 : // had those fields).
1050 1 : MinUnflushedLogNum: minUnflushedLogNum,
1051 1 : NextFileNum: nextFileNum,
1052 1 : CreatedBackingTables: virtualBackings,
1053 1 : NewBlobFiles: vs.latest.blobFiles.Metadatas(),
1054 1 : }
1055 1 :
1056 1 : // Add all extant sstables in the current version.
1057 1 : for level, levelMetadata := range vs.currentVersion().Levels {
1058 1 : for meta := range levelMetadata.All() {
1059 1 : snapshot.NewTables = append(snapshot.NewTables, manifest.NewTableEntry{
1060 1 : Level: level,
1061 1 : Meta: meta,
1062 1 : })
1063 1 : }
1064 : }
1065 :
1066 1 : w, err1 := manifestWriter.Next()
1067 1 : if err1 != nil {
1068 0 : return err1
1069 0 : }
1070 1 : if err := snapshot.Encode(w); err != nil {
1071 0 : return err
1072 0 : }
1073 :
1074 1 : if vs.manifest != nil {
1075 1 : if err := vs.manifest.Close(); err != nil {
1076 0 : return err
1077 0 : }
1078 1 : vs.manifest = nil
1079 : }
1080 1 : if vs.manifestFile != nil {
1081 1 : if err := vs.manifestFile.Close(); err != nil {
1082 0 : return err
1083 0 : }
1084 1 : vs.manifestFile = nil
1085 : }
1086 :
1087 1 : vs.manifest, manifestWriter = manifestWriter, nil
1088 1 : vs.manifestFile, manifestFile = manifestFile, nil
1089 1 : return nil
1090 : }
1091 :
1092 : // NB: This method is not safe for concurrent use. It is only safe
1093 : // to be called when concurrent changes to nextFileNum are not expected.
1094 1 : func (vs *versionSet) markFileNumUsed(fileNum base.DiskFileNum) {
1095 1 : if vs.nextFileNum.Load() <= uint64(fileNum) {
1096 1 : vs.nextFileNum.Store(uint64(fileNum + 1))
1097 1 : }
1098 : }
1099 :
1100 : // getNextTableNum returns a new table number.
1101 : //
1102 : // Can be called without the versionSet's mutex being held.
1103 1 : func (vs *versionSet) getNextTableNum() base.TableNum {
1104 1 : x := vs.nextFileNum.Add(1) - 1
1105 1 : return base.TableNum(x)
1106 1 : }
1107 :
1108 : // Can be called without the versionSet's mutex being held.
1109 1 : func (vs *versionSet) getNextDiskFileNum() base.DiskFileNum {
1110 1 : x := vs.nextFileNum.Add(1) - 1
1111 1 : return base.DiskFileNum(x)
1112 1 : }
1113 :
1114 1 : func (vs *versionSet) append(v *manifest.Version) {
1115 1 : if v.Refs() != 0 {
1116 0 : panic("pebble: version should be unreferenced")
1117 : }
1118 1 : if !vs.versions.Empty() {
1119 1 : vs.versions.Back().UnrefLocked()
1120 1 : }
1121 1 : v.Deleted = vs.obsoleteFn
1122 1 : v.Ref()
1123 1 : vs.versions.PushBack(v)
1124 1 : if invariants.Enabled {
1125 1 : // Verify that the virtualBackings contains all the backings referenced by
1126 1 : // the version.
1127 1 : for _, l := range v.Levels {
1128 1 : for f := range l.All() {
1129 1 : if f.Virtual {
1130 1 : if _, ok := vs.latest.virtualBackings.Get(f.TableBacking.DiskFileNum); !ok {
1131 0 : panic(fmt.Sprintf("%s is not in virtualBackings", f.TableBacking.DiskFileNum))
1132 : }
1133 : }
1134 : }
1135 : }
1136 : }
1137 : }
1138 :
1139 1 : func (vs *versionSet) currentVersion() *manifest.Version {
1140 1 : return vs.versions.Back()
1141 1 : }
1142 :
1143 1 : func (vs *versionSet) addLiveFileNums(m map[base.DiskFileNum]struct{}) {
1144 1 : current := vs.currentVersion()
1145 1 : for v := vs.versions.Front(); true; v = v.Next() {
1146 1 : for _, lm := range v.Levels {
1147 1 : for f := range lm.All() {
1148 1 : m[f.TableBacking.DiskFileNum] = struct{}{}
1149 1 : }
1150 : }
1151 1 : for bf := range v.BlobFiles.All() {
1152 1 : m[bf.Physical.FileNum] = struct{}{}
1153 1 : }
1154 1 : if v == current {
1155 1 : break
1156 : }
1157 : }
1158 : // virtualBackings contains backings that are referenced by some virtual
1159 : // tables in the latest version (which are handled above), and backings that
1160 : // are not but are still alive because of the protection mechanism (see
1161 : // manifset.VirtualBackings). This loop ensures the latter get added to the
1162 : // map.
1163 1 : vs.latest.virtualBackings.ForEach(func(b *manifest.TableBacking) {
1164 1 : m[b.DiskFileNum] = struct{}{}
1165 1 : })
1166 : }
1167 :
1168 : // addObsoleteLocked will add the fileInfo associated with obsolete backing
1169 : // sstables to the obsolete tables list.
1170 : //
1171 : // The file backings in the obsolete list must not appear more than once.
1172 : //
1173 : // DB.mu must be held when addObsoleteLocked is called.
1174 1 : func (vs *versionSet) addObsoleteLocked(obsolete manifest.ObsoleteFiles) {
1175 1 : if obsolete.Count() == 0 {
1176 1 : return
1177 1 : }
1178 :
1179 : // Note that the zombie objects transition from zombie *to* obsolete, and
1180 : // will no longer be considered zombie.
1181 :
1182 1 : newlyObsoleteTables := make([]obsoleteFile, len(obsolete.TableBackings))
1183 1 : for i, bs := range obsolete.TableBackings {
1184 1 : newlyObsoleteTables[i] = vs.zombieTables.Extract(bs.DiskFileNum).
1185 1 : asObsoleteFile(vs.fs, base.FileTypeTable, vs.dirname)
1186 1 : }
1187 1 : vs.obsoleteTables = mergeObsoleteFiles(vs.obsoleteTables, newlyObsoleteTables)
1188 1 :
1189 1 : newlyObsoleteBlobFiles := make([]obsoleteFile, len(obsolete.BlobFiles))
1190 1 : for i, bf := range obsolete.BlobFiles {
1191 1 : newlyObsoleteBlobFiles[i] = vs.zombieBlobs.Extract(bf.FileNum).
1192 1 : asObsoleteFile(vs.fs, base.FileTypeBlob, vs.dirname)
1193 1 : }
1194 1 : vs.obsoleteBlobs = mergeObsoleteFiles(vs.obsoleteBlobs, newlyObsoleteBlobFiles)
1195 1 : vs.updateObsoleteObjectMetricsLocked()
1196 : }
1197 :
1198 : // addObsolete will acquire DB.mu, so DB.mu must not be held when this is
1199 : // called.
1200 1 : func (vs *versionSet) addObsolete(obsolete manifest.ObsoleteFiles) {
1201 1 : vs.mu.Lock()
1202 1 : defer vs.mu.Unlock()
1203 1 : vs.addObsoleteLocked(obsolete)
1204 1 : }
1205 :
1206 1 : func (vs *versionSet) updateObsoleteObjectMetricsLocked() {
1207 1 : // TODO(jackson): Ideally we would update vs.fileDeletions.queuedStats to
1208 1 : // include the files on vs.obsolete{Tables,Blobs}, but there's subtlety in
1209 1 : // deduplicating the files before computing the stats. It might also be
1210 1 : // possible to refactor to remove the vs.obsolete{Tables,Blobs} intermediary
1211 1 : // step. Revisit this.
1212 1 : vs.metrics.Table.ObsoleteCount = int64(len(vs.obsoleteTables))
1213 1 : vs.metrics.Table.ObsoleteSize = 0
1214 1 : vs.metrics.Table.Local.ObsoleteSize = 0
1215 1 : vs.metrics.Table.Local.ObsoleteCount = 0
1216 1 : for _, fi := range vs.obsoleteTables {
1217 1 : vs.metrics.Table.ObsoleteSize += fi.fileSize
1218 1 : if fi.isLocal {
1219 1 : vs.metrics.Table.Local.ObsoleteSize += fi.fileSize
1220 1 : vs.metrics.Table.Local.ObsoleteCount++
1221 1 : }
1222 : }
1223 1 : vs.metrics.BlobFiles.ObsoleteCount = uint64(len(vs.obsoleteBlobs))
1224 1 : vs.metrics.BlobFiles.ObsoleteSize = 0
1225 1 : vs.metrics.BlobFiles.Local.ObsoleteSize = 0
1226 1 : vs.metrics.BlobFiles.Local.ObsoleteCount = 0
1227 1 : for _, fi := range vs.obsoleteBlobs {
1228 1 : vs.metrics.BlobFiles.ObsoleteSize += fi.fileSize
1229 1 : if fi.isLocal {
1230 1 : vs.metrics.BlobFiles.Local.ObsoleteSize += fi.fileSize
1231 1 : vs.metrics.BlobFiles.Local.ObsoleteCount++
1232 1 : }
1233 : }
1234 : }
1235 :
1236 : func findCurrentManifest(
1237 : fs vfs.FS, dirname string, ls []string,
1238 1 : ) (marker *atomicfs.Marker, manifestNum base.DiskFileNum, exists bool, err error) {
1239 1 : // Locating a marker should succeed even if the marker has never been placed.
1240 1 : var filename string
1241 1 : marker, filename, err = atomicfs.LocateMarkerInListing(fs, dirname, manifestMarkerName, ls)
1242 1 : if err != nil {
1243 0 : return nil, 0, false, err
1244 0 : }
1245 :
1246 1 : if filename == "" {
1247 1 : // The marker hasn't been set yet. This database doesn't exist.
1248 1 : return marker, 0, false, nil
1249 1 : }
1250 :
1251 1 : var ok bool
1252 1 : _, manifestNum, ok = base.ParseFilename(fs, filename)
1253 1 : if !ok {
1254 0 : return marker, 0, false, base.CorruptionErrorf("pebble: MANIFEST name %q is malformed", errors.Safe(filename))
1255 0 : }
1256 1 : return marker, manifestNum, true, nil
1257 : }
1258 :
1259 0 : func newFileMetrics(newFiles []manifest.NewTableEntry) levelMetricsDelta {
1260 0 : var m levelMetricsDelta
1261 0 : for _, nf := range newFiles {
1262 0 : lm := m[nf.Level]
1263 0 : if lm == nil {
1264 0 : lm = &LevelMetrics{}
1265 0 : m[nf.Level] = lm
1266 0 : }
1267 0 : lm.TablesCount++
1268 0 : lm.TablesSize += int64(nf.Meta.Size)
1269 0 : lm.EstimatedReferencesSize += nf.Meta.EstimatedReferenceSize()
1270 : }
1271 0 : return m
1272 : }
|