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