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 : "bytes"
9 : "context"
10 : "encoding/binary"
11 : "fmt"
12 : "io"
13 : "math"
14 : "os"
15 : "slices"
16 : "sync/atomic"
17 : "time"
18 :
19 : "github.com/cockroachdb/errors"
20 : "github.com/cockroachdb/errors/oserror"
21 : "github.com/cockroachdb/pebble/batchrepr"
22 : "github.com/cockroachdb/pebble/internal/arenaskl"
23 : "github.com/cockroachdb/pebble/internal/base"
24 : "github.com/cockroachdb/pebble/internal/cache"
25 : "github.com/cockroachdb/pebble/internal/constants"
26 : "github.com/cockroachdb/pebble/internal/invariants"
27 : "github.com/cockroachdb/pebble/internal/manifest"
28 : "github.com/cockroachdb/pebble/internal/manual"
29 : "github.com/cockroachdb/pebble/objstorage"
30 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
31 : "github.com/cockroachdb/pebble/objstorage/remote"
32 : "github.com/cockroachdb/pebble/record"
33 : "github.com/cockroachdb/pebble/sstable"
34 : "github.com/cockroachdb/pebble/vfs"
35 : "github.com/cockroachdb/pebble/wal"
36 : "github.com/prometheus/client_golang/prometheus"
37 : )
38 :
39 : const (
40 : initialMemTableSize = 256 << 10 // 256 KB
41 :
42 : // The max batch size is limited by the uint32 offsets stored in
43 : // internal/batchskl.node, DeferredBatchOp, and flushableBatchEntry.
44 : //
45 : // We limit the size to MaxUint32 (just short of 4GB) so that the exclusive
46 : // end of an allocation fits in uint32.
47 : //
48 : // On 32-bit systems, slices are naturally limited to MaxInt (just short of
49 : // 2GB).
50 : maxBatchSize = constants.MaxUint32OrInt
51 :
52 : // The max memtable size is limited by the uint32 offsets stored in
53 : // internal/arenaskl.node, DeferredBatchOp, and flushableBatchEntry.
54 : //
55 : // We limit the size to MaxUint32 (just short of 4GB) so that the exclusive
56 : // end of an allocation fits in uint32.
57 : //
58 : // On 32-bit systems, slices are naturally limited to MaxInt (just short of
59 : // 2GB).
60 : maxMemTableSize = constants.MaxUint32OrInt
61 : )
62 :
63 : // TableCacheSize can be used to determine the table
64 : // cache size for a single db, given the maximum open
65 : // files which can be used by a table cache which is
66 : // only used by a single db.
67 1 : func TableCacheSize(maxOpenFiles int) int {
68 1 : tableCacheSize := maxOpenFiles - numNonTableCacheFiles
69 1 : if tableCacheSize < minTableCacheSize {
70 0 : tableCacheSize = minTableCacheSize
71 0 : }
72 1 : return tableCacheSize
73 : }
74 :
75 : // Open opens a DB whose files live in the given directory.
76 1 : func Open(dirname string, opts *Options) (db *DB, err error) {
77 1 : // Make a copy of the options so that we don't mutate the passed in options.
78 1 : opts = opts.Clone()
79 1 : opts = opts.EnsureDefaults()
80 1 : if err := opts.Validate(); err != nil {
81 0 : return nil, err
82 0 : }
83 1 : if opts.LoggerAndTracer == nil {
84 1 : opts.LoggerAndTracer = &base.LoggerWithNoopTracer{Logger: opts.Logger}
85 1 : } else {
86 1 : opts.Logger = opts.LoggerAndTracer
87 1 : }
88 :
89 : // In all error cases, we return db = nil; this is used by various
90 : // deferred cleanups.
91 :
92 : // Open the database and WAL directories first.
93 1 : walDirname, dataDir, err := prepareAndOpenDirs(dirname, opts)
94 1 : if err != nil {
95 1 : return nil, errors.Wrapf(err, "error opening database at %q", dirname)
96 1 : }
97 1 : defer func() {
98 1 : if db == nil {
99 1 : dataDir.Close()
100 1 : }
101 : }()
102 :
103 : // Lock the database directory.
104 1 : var fileLock *Lock
105 1 : if opts.Lock != nil {
106 1 : // The caller already acquired the database lock. Ensure that the
107 1 : // directory matches.
108 1 : if err := opts.Lock.pathMatches(dirname); err != nil {
109 0 : return nil, err
110 0 : }
111 1 : if err := opts.Lock.refForOpen(); err != nil {
112 1 : return nil, err
113 1 : }
114 1 : fileLock = opts.Lock
115 1 : } else {
116 1 : fileLock, err = LockDirectory(dirname, opts.FS)
117 1 : if err != nil {
118 1 : return nil, err
119 1 : }
120 : }
121 1 : defer func() {
122 1 : if db == nil {
123 1 : fileLock.Close()
124 1 : }
125 : }()
126 :
127 : // List the directory contents. This also happens to include WAL log files, if
128 : // they are in the same dir, but we will ignore those below. The provider is
129 : // also given this list, but it ignores non sstable files.
130 1 : ls, err := opts.FS.List(dirname)
131 1 : if err != nil {
132 1 : return nil, err
133 1 : }
134 :
135 : // Establish the format major version.
136 1 : formatVersion, formatVersionMarker, err := lookupFormatMajorVersion(opts.FS, dirname, ls)
137 1 : if err != nil {
138 1 : return nil, err
139 1 : }
140 1 : defer func() {
141 1 : if db == nil {
142 1 : formatVersionMarker.Close()
143 1 : }
144 : }()
145 :
146 1 : noFormatVersionMarker := formatVersion == FormatDefault
147 1 : if noFormatVersionMarker {
148 1 : // We will initialize the store at the minimum possible format, then upgrade
149 1 : // the format to the desired one. This helps test the format upgrade code.
150 1 : formatVersion = FormatMinSupported
151 1 : if opts.Experimental.CreateOnShared != remote.CreateOnSharedNone {
152 1 : formatVersion = FormatMinForSharedObjects
153 1 : }
154 : // There is no format version marker file. There are three cases:
155 : // - we are trying to open an existing store that was created at
156 : // FormatMostCompatible (the only one without a version marker file)
157 : // - we are creating a new store;
158 : // - we are retrying a failed creation.
159 : //
160 : // To error in the first case, we set ErrorIfNotPristine.
161 1 : opts.ErrorIfNotPristine = true
162 1 : defer func() {
163 1 : if err != nil && errors.Is(err, ErrDBNotPristine) {
164 0 : // We must be trying to open an existing store at FormatMostCompatible.
165 0 : // Correct the error in this case -we
166 0 : err = errors.Newf(
167 0 : "pebble: database %q written in format major version 1 which is no longer supported",
168 0 : dirname)
169 0 : }
170 : }()
171 1 : } else {
172 1 : if opts.Experimental.CreateOnShared != remote.CreateOnSharedNone && formatVersion < FormatMinForSharedObjects {
173 0 : return nil, errors.Newf(
174 0 : "pebble: database %q configured with shared objects but written in too old format major version %d",
175 0 : formatVersion)
176 0 : }
177 : }
178 :
179 : // Find the currently active manifest, if there is one.
180 1 : manifestMarker, manifestFileNum, manifestExists, err := findCurrentManifest(opts.FS, dirname, ls)
181 1 : if err != nil {
182 1 : return nil, errors.Wrapf(err, "pebble: database %q", dirname)
183 1 : }
184 1 : defer func() {
185 1 : if db == nil {
186 1 : manifestMarker.Close()
187 1 : }
188 : }()
189 :
190 : // Atomic markers may leave behind obsolete files if there's a crash
191 : // mid-update. Clean these up if we're not in read-only mode.
192 1 : if !opts.ReadOnly {
193 1 : if err := formatVersionMarker.RemoveObsolete(); err != nil {
194 0 : return nil, err
195 0 : }
196 1 : if err := manifestMarker.RemoveObsolete(); err != nil {
197 0 : return nil, err
198 0 : }
199 : }
200 :
201 1 : if opts.Cache == nil {
202 1 : opts.Cache = cache.New(cacheDefaultSize)
203 1 : } else {
204 1 : opts.Cache.Ref()
205 1 : }
206 :
207 1 : d := &DB{
208 1 : cacheID: opts.Cache.NewID(),
209 1 : dirname: dirname,
210 1 : opts: opts,
211 1 : cmp: opts.Comparer.Compare,
212 1 : equal: opts.Comparer.Equal,
213 1 : merge: opts.Merger.Merge,
214 1 : split: opts.Comparer.Split,
215 1 : abbreviatedKey: opts.Comparer.AbbreviatedKey,
216 1 : largeBatchThreshold: (opts.MemTableSize - uint64(memTableEmptySize)) / 2,
217 1 : fileLock: fileLock,
218 1 : dataDir: dataDir,
219 1 : closed: new(atomic.Value),
220 1 : closedCh: make(chan struct{}),
221 1 : }
222 1 : d.mu.versions = &versionSet{}
223 1 : d.diskAvailBytes.Store(math.MaxUint64)
224 1 :
225 1 : defer func() {
226 1 : // If an error or panic occurs during open, attempt to release the manually
227 1 : // allocated memory resources. Note that rather than look for an error, we
228 1 : // look for the return of a nil DB pointer.
229 1 : if r := recover(); db == nil {
230 1 : // Release our references to the Cache. Note that both the DB, and
231 1 : // tableCache have a reference. When we release the reference to
232 1 : // the tableCache, and if there are no other references to
233 1 : // the tableCache, then the tableCache will also release its
234 1 : // reference to the cache.
235 1 : opts.Cache.Unref()
236 1 :
237 1 : if d.tableCache != nil {
238 1 : _ = d.tableCache.close()
239 1 : }
240 :
241 1 : for _, mem := range d.mu.mem.queue {
242 1 : switch t := mem.flushable.(type) {
243 1 : case *memTable:
244 1 : manual.Free(t.arenaBuf)
245 1 : t.arenaBuf = nil
246 : }
247 : }
248 1 : if d.cleanupManager != nil {
249 1 : d.cleanupManager.Close()
250 1 : }
251 1 : if d.objProvider != nil {
252 1 : d.objProvider.Close()
253 1 : }
254 1 : if r != nil {
255 1 : panic(r)
256 : }
257 : }
258 : }()
259 :
260 1 : d.commit = newCommitPipeline(commitEnv{
261 1 : logSeqNum: &d.mu.versions.logSeqNum,
262 1 : visibleSeqNum: &d.mu.versions.visibleSeqNum,
263 1 : apply: d.commitApply,
264 1 : write: d.commitWrite,
265 1 : })
266 1 : d.mu.nextJobID = 1
267 1 : d.mu.mem.nextSize = opts.MemTableSize
268 1 : if d.mu.mem.nextSize > initialMemTableSize {
269 1 : d.mu.mem.nextSize = initialMemTableSize
270 1 : }
271 1 : d.mu.compact.cond.L = &d.mu.Mutex
272 1 : d.mu.compact.inProgress = make(map[*compaction]struct{})
273 1 : d.mu.compact.noOngoingFlushStartTime = time.Now()
274 1 : d.mu.snapshots.init()
275 1 : // logSeqNum is the next sequence number that will be assigned.
276 1 : // Start assigning sequence numbers from base.SeqNumStart to leave
277 1 : // room for reserved sequence numbers (see comments around
278 1 : // SeqNumStart).
279 1 : d.mu.versions.logSeqNum.Store(base.SeqNumStart)
280 1 : d.mu.formatVers.vers.Store(uint64(formatVersion))
281 1 : d.mu.formatVers.marker = formatVersionMarker
282 1 :
283 1 : d.timeNow = time.Now
284 1 : d.openedAt = d.timeNow()
285 1 :
286 1 : d.mu.Lock()
287 1 : defer d.mu.Unlock()
288 1 :
289 1 : jobID := d.newJobIDLocked()
290 1 :
291 1 : providerSettings := objstorageprovider.Settings{
292 1 : Logger: opts.Logger,
293 1 : FS: opts.FS,
294 1 : FSDirName: dirname,
295 1 : FSDirInitialListing: ls,
296 1 : FSCleaner: opts.Cleaner,
297 1 : NoSyncOnClose: opts.NoSyncOnClose,
298 1 : BytesPerSync: opts.BytesPerSync,
299 1 : }
300 1 : providerSettings.Local.ReadaheadConfig = opts.Local.ReadaheadConfig
301 1 : providerSettings.Remote.StorageFactory = opts.Experimental.RemoteStorage
302 1 : providerSettings.Remote.CreateOnShared = opts.Experimental.CreateOnShared
303 1 : providerSettings.Remote.CreateOnSharedLocator = opts.Experimental.CreateOnSharedLocator
304 1 : providerSettings.Remote.CacheSizeBytes = opts.Experimental.SecondaryCacheSizeBytes
305 1 :
306 1 : d.objProvider, err = objstorageprovider.Open(providerSettings)
307 1 : if err != nil {
308 1 : return nil, err
309 1 : }
310 :
311 1 : if !manifestExists {
312 1 : // DB does not exist.
313 1 : if d.opts.ErrorIfNotExists || d.opts.ReadOnly {
314 1 : return nil, errors.Wrapf(ErrDBDoesNotExist, "dirname=%q", dirname)
315 1 : }
316 :
317 : // Create the DB.
318 1 : if err := d.mu.versions.create(
319 1 : jobID, dirname, d.objProvider, opts, manifestMarker, d.FormatMajorVersion, &d.mu.Mutex); err != nil {
320 1 : return nil, err
321 1 : }
322 1 : } else {
323 1 : if opts.ErrorIfExists {
324 1 : return nil, errors.Wrapf(ErrDBAlreadyExists, "dirname=%q", dirname)
325 1 : }
326 : // Load the version set.
327 1 : if err := d.mu.versions.load(
328 1 : dirname, d.objProvider, opts, manifestFileNum, manifestMarker, d.FormatMajorVersion, &d.mu.Mutex); err != nil {
329 1 : return nil, err
330 1 : }
331 1 : if opts.ErrorIfNotPristine {
332 1 : liveFileNums := make(map[base.DiskFileNum]struct{})
333 1 : d.mu.versions.addLiveFileNums(liveFileNums)
334 1 : if len(liveFileNums) != 0 {
335 1 : return nil, errors.Wrapf(ErrDBNotPristine, "dirname=%q", dirname)
336 1 : }
337 : }
338 : }
339 :
340 : // In read-only mode, we replay directly into the mutable memtable but never
341 : // flush it. We need to delay creation of the memtable until we know the
342 : // sequence number of the first batch that will be inserted.
343 1 : if !d.opts.ReadOnly {
344 1 : var entry *flushableEntry
345 1 : d.mu.mem.mutable, entry = d.newMemTable(0 /* logNum */, d.mu.versions.logSeqNum.Load(), 0 /* minSize */)
346 1 : d.mu.mem.queue = append(d.mu.mem.queue, entry)
347 1 : }
348 :
349 1 : d.mu.log.metrics.fsyncLatency = prometheus.NewHistogram(prometheus.HistogramOpts{
350 1 : Buckets: FsyncLatencyBuckets,
351 1 : })
352 1 : walOpts := wal.Options{
353 1 : Primary: wal.Dir{FS: opts.FS, Dirname: walDirname},
354 1 : Secondary: wal.Dir{},
355 1 : MinUnflushedWALNum: wal.NumWAL(d.mu.versions.minUnflushedLogNum),
356 1 : MaxNumRecyclableLogs: opts.MemTableStopWritesThreshold + 1,
357 1 : NoSyncOnClose: opts.NoSyncOnClose,
358 1 : BytesPerSync: opts.WALBytesPerSync,
359 1 : PreallocateSize: d.walPreallocateSize,
360 1 : MinSyncInterval: opts.WALMinSyncInterval,
361 1 : FsyncLatency: d.mu.log.metrics.fsyncLatency,
362 1 : QueueSemChan: d.commit.logSyncQSem,
363 1 : Logger: opts.Logger,
364 1 : EventListener: walEventListenerAdaptor{l: opts.EventListener},
365 1 : }
366 1 : if opts.WALFailover != nil {
367 1 : walOpts.Secondary = opts.WALFailover.Secondary
368 1 : walOpts.FailoverOptions = opts.WALFailover.FailoverOptions
369 1 : walOpts.FailoverWriteAndSyncLatency = prometheus.NewHistogram(prometheus.HistogramOpts{
370 1 : Buckets: FsyncLatencyBuckets,
371 1 : })
372 1 : }
373 1 : walDirs := append(walOpts.Dirs(), opts.WALRecoveryDirs...)
374 1 : wals, err := wal.Scan(walDirs...)
375 1 : if err != nil {
376 1 : return nil, err
377 1 : }
378 1 : walManager, err := wal.Init(walOpts, wals)
379 1 : if err != nil {
380 1 : return nil, err
381 1 : }
382 1 : defer func() {
383 1 : if db == nil {
384 1 : walManager.Close()
385 1 : }
386 : }()
387 :
388 1 : d.mu.log.manager = walManager
389 1 :
390 1 : d.cleanupManager = openCleanupManager(opts, d.objProvider, d.onObsoleteTableDelete, d.getDeletionPacerInfo)
391 1 :
392 1 : if manifestExists && !opts.DisableConsistencyCheck {
393 1 : curVersion := d.mu.versions.currentVersion()
394 1 : if err := checkConsistency(curVersion, dirname, d.objProvider); err != nil {
395 1 : return nil, err
396 1 : }
397 : }
398 :
399 1 : tableCacheSize := TableCacheSize(opts.MaxOpenFiles)
400 1 : d.tableCache = newTableCacheContainer(
401 1 : opts.TableCache, d.cacheID, d.objProvider, d.opts, tableCacheSize,
402 1 : &sstable.CategoryStatsCollector{})
403 1 : d.newIters = d.tableCache.newIters
404 1 : d.tableNewRangeKeyIter = tableNewRangeKeyIter(context.TODO(), d.newIters)
405 1 :
406 1 : var previousOptionsFileNum base.DiskFileNum
407 1 : var previousOptionsFilename string
408 1 : for _, filename := range ls {
409 1 : ft, fn, ok := base.ParseFilename(opts.FS, filename)
410 1 : if !ok {
411 1 : continue
412 : }
413 :
414 : // Don't reuse any obsolete file numbers to avoid modifying an
415 : // ingested sstable's original external file.
416 1 : d.mu.versions.markFileNumUsed(fn)
417 1 :
418 1 : switch ft {
419 0 : case fileTypeLog:
420 : // Ignore.
421 1 : case fileTypeOptions:
422 1 : if previousOptionsFileNum < fn {
423 1 : previousOptionsFileNum = fn
424 1 : previousOptionsFilename = filename
425 1 : }
426 1 : case fileTypeTemp, fileTypeOldTemp:
427 1 : if !d.opts.ReadOnly {
428 1 : // Some codepaths write to a temporary file and then
429 1 : // rename it to its final location when complete. A
430 1 : // temp file is leftover if a process exits before the
431 1 : // rename. Remove it.
432 1 : err := opts.FS.Remove(opts.FS.PathJoin(dirname, filename))
433 1 : if err != nil {
434 0 : return nil, err
435 0 : }
436 : }
437 : }
438 : }
439 1 : if n := len(wals); n > 0 {
440 1 : // Don't reuse any obsolete file numbers to avoid modifying an
441 1 : // ingested sstable's original external file.
442 1 : d.mu.versions.markFileNumUsed(base.DiskFileNum(wals[n-1].Num))
443 1 : }
444 :
445 : // Ratchet d.mu.versions.nextFileNum ahead of all known objects in the
446 : // objProvider. This avoids FileNum collisions with obsolete sstables.
447 1 : objects := d.objProvider.List()
448 1 : for _, obj := range objects {
449 1 : d.mu.versions.markFileNumUsed(obj.DiskFileNum)
450 1 : }
451 :
452 : // Validate the most-recent OPTIONS file, if there is one.
453 1 : if previousOptionsFilename != "" {
454 1 : path := opts.FS.PathJoin(dirname, previousOptionsFilename)
455 1 : previousOptions, err := readOptionsFile(opts, path)
456 1 : if err != nil {
457 0 : return nil, err
458 0 : }
459 1 : if err := opts.CheckCompatibility(previousOptions); err != nil {
460 1 : return nil, err
461 1 : }
462 : }
463 :
464 : // Replay any newer log files than the ones named in the manifest.
465 1 : var replayWALs wal.Logs
466 1 : for i, w := range wals {
467 1 : if base.DiskFileNum(w.Num) >= d.mu.versions.minUnflushedLogNum {
468 1 : replayWALs = wals[i:]
469 1 : break
470 : }
471 : }
472 1 : var ve versionEdit
473 1 : var toFlush flushableList
474 1 : for i, lf := range replayWALs {
475 1 : // WALs other than the last one would have been closed cleanly.
476 1 : //
477 1 : // Note: we used to never require strict WAL tails when reading from older
478 1 : // versions: RocksDB 6.2.1 and the version of Pebble included in CockroachDB
479 1 : // 20.1 do not guarantee that closed WALs end cleanly. But the earliest
480 1 : // compatible Pebble format is newer and guarantees a clean EOF.
481 1 : strictWALTail := i < len(replayWALs)-1
482 1 : flush, maxSeqNum, err := d.replayWAL(jobID, &ve, lf, strictWALTail)
483 1 : if err != nil {
484 1 : return nil, err
485 1 : }
486 1 : toFlush = append(toFlush, flush...)
487 1 : if d.mu.versions.logSeqNum.Load() < maxSeqNum {
488 1 : d.mu.versions.logSeqNum.Store(maxSeqNum)
489 1 : }
490 : }
491 1 : d.mu.versions.visibleSeqNum.Store(d.mu.versions.logSeqNum.Load())
492 1 :
493 1 : if !d.opts.ReadOnly {
494 1 : // Create an empty .log file.
495 1 : newLogNum := d.mu.versions.getNextDiskFileNum()
496 1 :
497 1 : // This logic is slightly different than RocksDB's. Specifically, RocksDB
498 1 : // sets MinUnflushedLogNum to max-recovered-log-num + 1. We set it to the
499 1 : // newLogNum. There should be no difference in using either value.
500 1 : ve.MinUnflushedLogNum = newLogNum
501 1 :
502 1 : // Create the manifest with the updated MinUnflushedLogNum before
503 1 : // creating the new log file. If we created the log file first, a
504 1 : // crash before the manifest is synced could leave two WALs with
505 1 : // unclean tails.
506 1 : d.mu.versions.logLock()
507 1 : if err := d.mu.versions.logAndApply(jobID, &ve, newFileMetrics(ve.NewFiles), false /* forceRotation */, func() []compactionInfo {
508 1 : return nil
509 1 : }); err != nil {
510 0 : return nil, err
511 0 : }
512 :
513 1 : for _, entry := range toFlush {
514 1 : entry.readerUnrefLocked(true)
515 1 : }
516 :
517 1 : d.mu.log.writer, err = d.mu.log.manager.Create(wal.NumWAL(newLogNum), int(jobID))
518 1 : if err != nil {
519 1 : return nil, err
520 1 : }
521 :
522 : // This isn't strictly necessary as we don't use the log number for
523 : // memtables being flushed, only for the next unflushed memtable.
524 1 : d.mu.mem.queue[len(d.mu.mem.queue)-1].logNum = newLogNum
525 : }
526 1 : d.updateReadStateLocked(d.opts.DebugCheck)
527 1 :
528 1 : if !d.opts.ReadOnly {
529 1 : // If the Options specify a format major version higher than the
530 1 : // loaded database's, upgrade it. If this is a new database, this
531 1 : // code path also performs an initial upgrade from the starting
532 1 : // implicit MinSupported version.
533 1 : //
534 1 : // We ratchet the version this far into Open so that migrations have a read
535 1 : // state available. Note that this also results in creating/updating the
536 1 : // format version marker file.
537 1 : if opts.FormatMajorVersion > d.FormatMajorVersion() {
538 1 : if err := d.ratchetFormatMajorVersionLocked(opts.FormatMajorVersion); err != nil {
539 0 : return nil, err
540 0 : }
541 1 : } else if noFormatVersionMarker {
542 1 : // We are creating a new store. Create the format version marker file.
543 1 : if err := d.writeFormatVersionMarker(d.FormatMajorVersion()); err != nil {
544 1 : return nil, err
545 1 : }
546 : }
547 :
548 : // Write the current options to disk.
549 1 : d.optionsFileNum = d.mu.versions.getNextDiskFileNum()
550 1 : tmpPath := base.MakeFilepath(opts.FS, dirname, fileTypeTemp, d.optionsFileNum)
551 1 : optionsPath := base.MakeFilepath(opts.FS, dirname, fileTypeOptions, d.optionsFileNum)
552 1 :
553 1 : // Write them to a temporary file first, in case we crash before
554 1 : // we're done. A corrupt options file prevents opening the
555 1 : // database.
556 1 : optionsFile, err := opts.FS.Create(tmpPath, vfs.WriteCategoryUnspecified)
557 1 : if err != nil {
558 1 : return nil, err
559 1 : }
560 1 : serializedOpts := []byte(opts.String())
561 1 : if _, err := optionsFile.Write(serializedOpts); err != nil {
562 1 : return nil, errors.CombineErrors(err, optionsFile.Close())
563 1 : }
564 1 : d.optionsFileSize = uint64(len(serializedOpts))
565 1 : if err := optionsFile.Sync(); err != nil {
566 1 : return nil, errors.CombineErrors(err, optionsFile.Close())
567 1 : }
568 1 : if err := optionsFile.Close(); err != nil {
569 0 : return nil, err
570 0 : }
571 : // Atomically rename to the OPTIONS-XXXXXX path. This rename is
572 : // guaranteed to be atomic because the destination path does not
573 : // exist.
574 1 : if err := opts.FS.Rename(tmpPath, optionsPath); err != nil {
575 1 : return nil, err
576 1 : }
577 1 : if err := d.dataDir.Sync(); err != nil {
578 1 : return nil, err
579 1 : }
580 : }
581 :
582 1 : if !d.opts.ReadOnly {
583 1 : d.scanObsoleteFiles(ls)
584 1 : d.deleteObsoleteFiles(jobID)
585 1 : }
586 : // Else, nothing is obsolete.
587 :
588 1 : d.mu.tableStats.cond.L = &d.mu.Mutex
589 1 : d.mu.tableValidation.cond.L = &d.mu.Mutex
590 1 : if !d.opts.ReadOnly {
591 1 : d.maybeCollectTableStatsLocked()
592 1 : }
593 1 : d.calculateDiskAvailableBytes()
594 1 :
595 1 : d.maybeScheduleFlush()
596 1 : d.maybeScheduleCompaction()
597 1 :
598 1 : // Note: this is a no-op if invariants are disabled or race is enabled.
599 1 : //
600 1 : // Setting a finalizer on *DB causes *DB to never be reclaimed and the
601 1 : // finalizer to never be run. The problem is due to this limitation of
602 1 : // finalizers mention in the SetFinalizer docs:
603 1 : //
604 1 : // If a cyclic structure includes a block with a finalizer, that cycle is
605 1 : // not guaranteed to be garbage collected and the finalizer is not
606 1 : // guaranteed to run, because there is no ordering that respects the
607 1 : // dependencies.
608 1 : //
609 1 : // DB has cycles with several of its internal structures: readState,
610 1 : // newIters, tableCache, versions, etc. Each of this individually cause a
611 1 : // cycle and prevent the finalizer from being run. But we can workaround this
612 1 : // finializer limitation by setting a finalizer on another object that is
613 1 : // tied to the lifetime of DB: the DB.closed atomic.Value.
614 1 : dPtr := fmt.Sprintf("%p", d)
615 1 : invariants.SetFinalizer(d.closed, func(obj interface{}) {
616 0 : v := obj.(*atomic.Value)
617 0 : if err := v.Load(); err == nil {
618 0 : fmt.Fprintf(os.Stderr, "%s: unreferenced DB not closed\n", dPtr)
619 0 : os.Exit(1)
620 0 : }
621 : })
622 :
623 1 : return d, nil
624 : }
625 :
626 : // prepareAndOpenDirs opens the directories for the store (and creates them if
627 : // necessary).
628 : //
629 : // Returns an error if ReadOnly is set and the directories don't exist.
630 : func prepareAndOpenDirs(
631 : dirname string, opts *Options,
632 1 : ) (walDirname string, dataDir vfs.File, err error) {
633 1 : walDirname = opts.WALDir
634 1 : if opts.WALDir == "" {
635 1 : walDirname = dirname
636 1 : }
637 :
638 : // Create directories if needed.
639 1 : if !opts.ReadOnly {
640 1 : f, err := mkdirAllAndSyncParents(opts.FS, dirname)
641 1 : if err != nil {
642 1 : return "", nil, err
643 1 : }
644 1 : f.Close()
645 1 : if walDirname != dirname {
646 1 : f, err := mkdirAllAndSyncParents(opts.FS, walDirname)
647 1 : if err != nil {
648 0 : return "", nil, err
649 0 : }
650 1 : f.Close()
651 : }
652 1 : if opts.WALFailover != nil {
653 1 : secondary := opts.WALFailover.Secondary
654 1 : f, err := mkdirAllAndSyncParents(secondary.FS, secondary.Dirname)
655 1 : if err != nil {
656 0 : return "", nil, err
657 0 : }
658 1 : f.Close()
659 : }
660 : }
661 :
662 1 : dataDir, err = opts.FS.OpenDir(dirname)
663 1 : if err != nil {
664 1 : if opts.ReadOnly && oserror.IsNotExist(err) {
665 1 : return "", nil, errors.Errorf("pebble: database %q does not exist", dirname)
666 1 : }
667 1 : return "", nil, err
668 : }
669 1 : if opts.ReadOnly && walDirname != dirname {
670 1 : // Check that the wal dir exists.
671 1 : walDir, err := opts.FS.OpenDir(walDirname)
672 1 : if err != nil {
673 1 : dataDir.Close()
674 1 : return "", nil, err
675 1 : }
676 0 : walDir.Close()
677 : }
678 :
679 1 : return walDirname, dataDir, nil
680 : }
681 :
682 : // GetVersion returns the engine version string from the latest options
683 : // file present in dir. Used to check what Pebble or RocksDB version was last
684 : // used to write to the database stored in this directory. An empty string is
685 : // returned if no valid OPTIONS file with a version key was found.
686 1 : func GetVersion(dir string, fs vfs.FS) (string, error) {
687 1 : ls, err := fs.List(dir)
688 1 : if err != nil {
689 0 : return "", err
690 0 : }
691 1 : var version string
692 1 : lastOptionsSeen := base.DiskFileNum(0)
693 1 : for _, filename := range ls {
694 1 : ft, fn, ok := base.ParseFilename(fs, filename)
695 1 : if !ok {
696 1 : continue
697 : }
698 1 : switch ft {
699 1 : case fileTypeOptions:
700 1 : // If this file has a higher number than the last options file
701 1 : // processed, reset version. This is because rocksdb often
702 1 : // writes multiple options files without deleting previous ones.
703 1 : // Otherwise, skip parsing this options file.
704 1 : if fn > lastOptionsSeen {
705 1 : version = ""
706 1 : lastOptionsSeen = fn
707 1 : } else {
708 0 : continue
709 : }
710 1 : f, err := fs.Open(fs.PathJoin(dir, filename))
711 1 : if err != nil {
712 0 : return "", err
713 0 : }
714 1 : data, err := io.ReadAll(f)
715 1 : f.Close()
716 1 :
717 1 : if err != nil {
718 0 : return "", err
719 0 : }
720 1 : err = parseOptions(string(data), func(section, key, value string) error {
721 1 : switch {
722 1 : case section == "Version":
723 1 : switch key {
724 1 : case "pebble_version":
725 1 : version = value
726 1 : case "rocksdb_version":
727 1 : version = fmt.Sprintf("rocksdb v%s", value)
728 : }
729 : }
730 1 : return nil
731 : })
732 1 : if err != nil {
733 0 : return "", err
734 0 : }
735 : }
736 : }
737 1 : return version, nil
738 : }
739 :
740 : // replayWAL replays the edits in the specified WAL. If the DB is in read
741 : // only mode, then the WALs are replayed into memtables and not flushed. If
742 : // the DB is not in read only mode, then the contents of the WAL are
743 : // guaranteed to be flushed. Note that this flushing is very important for
744 : // guaranteeing durability: the application may have had a number of pending
745 : // fsyncs to the WAL before the process crashed, and those fsyncs may not have
746 : // happened but the corresponding data may now be readable from the WAL (while
747 : // sitting in write-back caches in the kernel or the storage device). By
748 : // reading the WAL (including the non-fsynced data) and then flushing all
749 : // these changes (flush does fsyncs), we are able to guarantee that the
750 : // initial state of the DB is durable.
751 : //
752 : // The toFlush return value is a list of flushables associated with the WAL
753 : // being replayed which will be flushed. Once the version edit has been applied
754 : // to the manifest, it is up to the caller of replayWAL to unreference the
755 : // toFlush flushables returned by replayWAL.
756 : //
757 : // d.mu must be held when calling this, but the mutex may be dropped and
758 : // re-acquired during the course of this method.
759 : func (d *DB) replayWAL(
760 : jobID JobID, ve *versionEdit, ll wal.LogicalLog, strictWALTail bool,
761 1 : ) (toFlush flushableList, maxSeqNum base.SeqNum, err error) {
762 1 : rr := ll.OpenForRead()
763 1 : defer rr.Close()
764 1 : var (
765 1 : b Batch
766 1 : buf bytes.Buffer
767 1 : mem *memTable
768 1 : entry *flushableEntry
769 1 : offset int64 // byte offset in rr
770 1 : lastFlushOffset int64
771 1 : keysReplayed int64 // number of keys replayed
772 1 : batchesReplayed int64 // number of batches replayed
773 1 : )
774 1 :
775 1 : // TODO(jackson): This function is interspersed with panics, in addition to
776 1 : // corruption error propagation. Audit them to ensure we're truly only
777 1 : // panicking where the error points to Pebble bug and not user or
778 1 : // hardware-induced corruption.
779 1 :
780 1 : if d.opts.ReadOnly {
781 1 : // In read-only mode, we replay directly into the mutable memtable which will
782 1 : // never be flushed.
783 1 : mem = d.mu.mem.mutable
784 1 : if mem != nil {
785 1 : entry = d.mu.mem.queue[len(d.mu.mem.queue)-1]
786 1 : }
787 : }
788 :
789 : // Flushes the current memtable, if not nil.
790 1 : flushMem := func() {
791 1 : if mem == nil {
792 1 : return
793 1 : }
794 1 : var logSize uint64
795 1 : if offset >= lastFlushOffset {
796 1 : logSize = uint64(offset - lastFlushOffset)
797 1 : }
798 : // Else, this was the initial memtable in the read-only case which must have
799 : // been empty, but we need to flush it since we don't want to add to it later.
800 1 : lastFlushOffset = offset
801 1 : entry.logSize = logSize
802 1 : if !d.opts.ReadOnly {
803 1 : toFlush = append(toFlush, entry)
804 1 : }
805 1 : mem, entry = nil, nil
806 : }
807 : // Creates a new memtable if there is no current memtable.
808 1 : ensureMem := func(seqNum base.SeqNum) {
809 1 : if mem != nil {
810 1 : return
811 1 : }
812 1 : mem, entry = d.newMemTable(base.DiskFileNum(ll.Num), seqNum, 0 /* minSize */)
813 1 : if d.opts.ReadOnly {
814 1 : d.mu.mem.mutable = mem
815 1 : d.mu.mem.queue = append(d.mu.mem.queue, entry)
816 1 : }
817 : }
818 :
819 : // updateVE is used to update ve with information about new files created
820 : // during the flush of any flushable not of type ingestedFlushable. For the
821 : // flushable of type ingestedFlushable we use custom handling below.
822 1 : updateVE := func() error {
823 1 : // TODO(bananabrick): See if we can use the actual base level here,
824 1 : // instead of using 1.
825 1 : c, err := newFlush(d.opts, d.mu.versions.currentVersion(),
826 1 : 1 /* base level */, toFlush, d.timeNow())
827 1 : if err != nil {
828 0 : return err
829 0 : }
830 1 : newVE, _, err := d.runCompaction(jobID, c)
831 1 : if err != nil {
832 0 : return errors.Wrapf(err, "running compaction during WAL replay")
833 0 : }
834 1 : ve.NewFiles = append(ve.NewFiles, newVE.NewFiles...)
835 1 : return nil
836 : }
837 1 : defer func() {
838 1 : if err != nil {
839 1 : err = errors.WithDetailf(err, "replaying wal %d, offset %d", ll.Num, offset)
840 1 : }
841 : }()
842 :
843 1 : for {
844 1 : r, offset, err := rr.NextRecord()
845 1 : if err == nil {
846 1 : _, err = io.Copy(&buf, r)
847 1 : }
848 1 : if err != nil {
849 1 : // It is common to encounter a zeroed or invalid chunk due to WAL
850 1 : // preallocation and WAL recycling. We need to distinguish these
851 1 : // errors from EOF in order to recognize that the record was
852 1 : // truncated and to avoid replaying subsequent WALs, but want
853 1 : // to otherwise treat them like EOF.
854 1 : if err == io.EOF {
855 1 : break
856 1 : } else if record.IsInvalidRecord(err) && !strictWALTail {
857 1 : break
858 : }
859 1 : return nil, 0, errors.Wrap(err, "pebble: error when replaying WAL")
860 : }
861 :
862 1 : if buf.Len() < batchrepr.HeaderLen {
863 0 : return nil, 0, base.CorruptionErrorf("pebble: corrupt wal %s (offset %s)",
864 0 : errors.Safe(base.DiskFileNum(ll.Num)), offset)
865 0 : }
866 :
867 1 : if d.opts.ErrorIfNotPristine {
868 1 : return nil, 0, errors.WithDetailf(ErrDBNotPristine, "location: %q", d.dirname)
869 1 : }
870 :
871 : // Specify Batch.db so that Batch.SetRepr will compute Batch.memTableSize
872 : // which is used below.
873 1 : b = Batch{}
874 1 : b.db = d
875 1 : b.SetRepr(buf.Bytes())
876 1 : seqNum := b.SeqNum()
877 1 : maxSeqNum = seqNum + base.SeqNum(b.Count())
878 1 : keysReplayed += int64(b.Count())
879 1 : batchesReplayed++
880 1 : {
881 1 : br := b.Reader()
882 1 : if kind, encodedFileNum, _, ok, err := br.Next(); err != nil {
883 0 : return nil, 0, err
884 1 : } else if ok && kind == InternalKeyKindIngestSST {
885 1 : fileNums := make([]base.DiskFileNum, 0, b.Count())
886 1 : addFileNum := func(encodedFileNum []byte) {
887 1 : fileNum, n := binary.Uvarint(encodedFileNum)
888 1 : if n <= 0 {
889 0 : panic("pebble: ingest sstable file num is invalid.")
890 : }
891 1 : fileNums = append(fileNums, base.DiskFileNum(fileNum))
892 : }
893 1 : addFileNum(encodedFileNum)
894 1 :
895 1 : for i := 1; i < int(b.Count()); i++ {
896 1 : kind, encodedFileNum, _, ok, err := br.Next()
897 1 : if err != nil {
898 0 : return nil, 0, err
899 0 : }
900 1 : if kind != InternalKeyKindIngestSST {
901 0 : panic("pebble: invalid batch key kind.")
902 : }
903 1 : if !ok {
904 0 : panic("pebble: invalid batch count.")
905 : }
906 1 : addFileNum(encodedFileNum)
907 : }
908 :
909 1 : if _, _, _, ok, err := br.Next(); err != nil {
910 0 : return nil, 0, err
911 1 : } else if ok {
912 0 : panic("pebble: invalid number of entries in batch.")
913 : }
914 :
915 1 : meta := make([]*fileMetadata, len(fileNums))
916 1 : for i, n := range fileNums {
917 1 : var readable objstorage.Readable
918 1 : objMeta, err := d.objProvider.Lookup(fileTypeTable, n)
919 1 : if err != nil {
920 0 : return nil, 0, errors.Wrap(err, "pebble: error when looking up ingested SSTs")
921 0 : }
922 1 : if objMeta.IsRemote() {
923 0 : readable, err = d.objProvider.OpenForReading(context.TODO(), fileTypeTable, n, objstorage.OpenOptions{MustExist: true})
924 0 : if err != nil {
925 0 : return nil, 0, errors.Wrap(err, "pebble: error when opening flushable ingest files")
926 0 : }
927 1 : } else {
928 1 : path := base.MakeFilepath(d.opts.FS, d.dirname, fileTypeTable, n)
929 1 : f, err := d.opts.FS.Open(path)
930 1 : if err != nil {
931 0 : return nil, 0, err
932 0 : }
933 :
934 1 : readable, err = sstable.NewSimpleReadable(f)
935 1 : if err != nil {
936 0 : return nil, 0, err
937 0 : }
938 : }
939 : // NB: ingestLoad1 will close readable.
940 1 : meta[i], err = ingestLoad1(d.opts, d.FormatMajorVersion(), readable, d.cacheID, base.PhysicalTableFileNum(n))
941 1 : if err != nil {
942 0 : return nil, 0, errors.Wrap(err, "pebble: error when loading flushable ingest files")
943 0 : }
944 : }
945 :
946 1 : if uint32(len(meta)) != b.Count() {
947 0 : panic("pebble: couldn't load all files in WAL entry.")
948 : }
949 :
950 1 : entry, err = d.newIngestedFlushableEntry(meta, seqNum, base.DiskFileNum(ll.Num), KeyRange{})
951 1 : if err != nil {
952 0 : return nil, 0, err
953 0 : }
954 :
955 1 : if d.opts.ReadOnly {
956 1 : d.mu.mem.queue = append(d.mu.mem.queue, entry)
957 1 : // We added the IngestSST flushable to the queue. But there
958 1 : // must be at least one WAL entry waiting to be replayed. We
959 1 : // have to ensure this newer WAL entry isn't replayed into
960 1 : // the current value of d.mu.mem.mutable because the current
961 1 : // mutable memtable exists before this flushable entry in
962 1 : // the memtable queue. To ensure this, we just need to unset
963 1 : // d.mu.mem.mutable. When a newer WAL is replayed, we will
964 1 : // set d.mu.mem.mutable to a newer value.
965 1 : d.mu.mem.mutable = nil
966 1 : } else {
967 1 : toFlush = append(toFlush, entry)
968 1 : // During WAL replay, the lsm only has L0, hence, the
969 1 : // baseLevel is 1. For the sake of simplicity, we place the
970 1 : // ingested files in L0 here, instead of finding their
971 1 : // target levels. This is a simplification for the sake of
972 1 : // simpler code. It is expected that WAL replay should be
973 1 : // rare, and that flushables of type ingestedFlushable
974 1 : // should also be rare. So, placing the ingested files in L0
975 1 : // is alright.
976 1 : //
977 1 : // TODO(bananabrick): Maybe refactor this function to allow
978 1 : // us to easily place ingested files in levels as low as
979 1 : // possible during WAL replay. It would require breaking up
980 1 : // the application of ve to the manifest into chunks and is
981 1 : // not pretty w/o a refactor to this function and how it's
982 1 : // used.
983 1 : c, err := newFlush(
984 1 : d.opts, d.mu.versions.currentVersion(),
985 1 : 1, /* base level */
986 1 : []*flushableEntry{entry},
987 1 : d.timeNow(),
988 1 : )
989 1 : if err != nil {
990 0 : return nil, 0, err
991 0 : }
992 1 : for _, file := range c.flushing[0].flushable.(*ingestedFlushable).files {
993 1 : ve.NewFiles = append(ve.NewFiles, newFileEntry{Level: 0, Meta: file.FileMetadata})
994 1 : }
995 : }
996 1 : return toFlush, maxSeqNum, nil
997 : }
998 : }
999 :
1000 1 : if b.memTableSize >= uint64(d.largeBatchThreshold) {
1001 1 : flushMem()
1002 1 : // Make a copy of the data slice since it is currently owned by buf and will
1003 1 : // be reused in the next iteration.
1004 1 : b.data = slices.Clone(b.data)
1005 1 : b.flushable, err = newFlushableBatch(&b, d.opts.Comparer)
1006 1 : if err != nil {
1007 0 : return nil, 0, err
1008 0 : }
1009 1 : entry := d.newFlushableEntry(b.flushable, base.DiskFileNum(ll.Num), b.SeqNum())
1010 1 : // Disable memory accounting by adding a reader ref that will never be
1011 1 : // removed.
1012 1 : entry.readerRefs.Add(1)
1013 1 : if d.opts.ReadOnly {
1014 1 : d.mu.mem.queue = append(d.mu.mem.queue, entry)
1015 1 : // We added the flushable batch to the flushable to the queue.
1016 1 : // But there must be at least one WAL entry waiting to be
1017 1 : // replayed. We have to ensure this newer WAL entry isn't
1018 1 : // replayed into the current value of d.mu.mem.mutable because
1019 1 : // the current mutable memtable exists before this flushable
1020 1 : // entry in the memtable queue. To ensure this, we just need to
1021 1 : // unset d.mu.mem.mutable. When a newer WAL is replayed, we will
1022 1 : // set d.mu.mem.mutable to a newer value.
1023 1 : d.mu.mem.mutable = nil
1024 1 : } else {
1025 1 : toFlush = append(toFlush, entry)
1026 1 : }
1027 1 : } else {
1028 1 : ensureMem(seqNum)
1029 1 : if err = mem.prepare(&b); err != nil && err != arenaskl.ErrArenaFull {
1030 0 : return nil, 0, err
1031 0 : }
1032 : // We loop since DB.newMemTable() slowly grows the size of allocated memtables, so the
1033 : // batch may not initially fit, but will eventually fit (since it is smaller than
1034 : // largeBatchThreshold).
1035 1 : for err == arenaskl.ErrArenaFull {
1036 1 : flushMem()
1037 1 : ensureMem(seqNum)
1038 1 : err = mem.prepare(&b)
1039 1 : if err != nil && err != arenaskl.ErrArenaFull {
1040 0 : return nil, 0, err
1041 0 : }
1042 : }
1043 1 : if err = mem.apply(&b, seqNum); err != nil {
1044 0 : return nil, 0, err
1045 0 : }
1046 1 : mem.writerUnref()
1047 : }
1048 1 : buf.Reset()
1049 : }
1050 :
1051 1 : d.opts.Logger.Infof("[JOB %d] WAL %s stopped reading at offset: %d; replayed %d keys in %d batches",
1052 1 : jobID, base.DiskFileNum(ll.Num).String(), offset, keysReplayed, batchesReplayed)
1053 1 : flushMem()
1054 1 :
1055 1 : // mem is nil here.
1056 1 : if !d.opts.ReadOnly && batchesReplayed > 0 {
1057 1 : err = updateVE()
1058 1 : if err != nil {
1059 0 : return nil, 0, err
1060 0 : }
1061 : }
1062 1 : return toFlush, maxSeqNum, err
1063 : }
1064 :
1065 1 : func readOptionsFile(opts *Options, path string) (string, error) {
1066 1 : f, err := opts.FS.Open(path)
1067 1 : if err != nil {
1068 0 : return "", err
1069 0 : }
1070 1 : defer f.Close()
1071 1 :
1072 1 : data, err := io.ReadAll(f)
1073 1 : if err != nil {
1074 0 : return "", err
1075 0 : }
1076 1 : return string(data), nil
1077 : }
1078 :
1079 : // DBDesc briefly describes high-level state about a database.
1080 : type DBDesc struct {
1081 : // Exists is true if an existing database was found.
1082 : Exists bool
1083 : // FormatMajorVersion indicates the database's current format
1084 : // version.
1085 : FormatMajorVersion FormatMajorVersion
1086 : // ManifestFilename is the filename of the current active manifest,
1087 : // if the database exists.
1088 : ManifestFilename string
1089 : // OptionsFilename is the filename of the most recent OPTIONS file, if it
1090 : // exists.
1091 : OptionsFilename string
1092 : }
1093 :
1094 : // String implements fmt.Stringer.
1095 1 : func (d *DBDesc) String() string {
1096 1 : if !d.Exists {
1097 1 : return "uninitialized"
1098 1 : }
1099 1 : var buf bytes.Buffer
1100 1 : fmt.Fprintf(&buf, "initialized at format major version %s\n", d.FormatMajorVersion)
1101 1 : fmt.Fprintf(&buf, "manifest: %s\n", d.ManifestFilename)
1102 1 : fmt.Fprintf(&buf, "options: %s", d.OptionsFilename)
1103 1 : return buf.String()
1104 : }
1105 :
1106 : // Peek looks for an existing database in dirname on the provided FS. It
1107 : // returns a brief description of the database. Peek is read-only and
1108 : // does not open the database
1109 1 : func Peek(dirname string, fs vfs.FS) (*DBDesc, error) {
1110 1 : ls, err := fs.List(dirname)
1111 1 : if err != nil {
1112 1 : return nil, err
1113 1 : }
1114 :
1115 1 : vers, versMarker, err := lookupFormatMajorVersion(fs, dirname, ls)
1116 1 : if err != nil {
1117 0 : return nil, err
1118 0 : }
1119 : // TODO(jackson): Immediately closing the marker is clunky. Add a
1120 : // PeekMarker variant that avoids opening the directory.
1121 1 : if err := versMarker.Close(); err != nil {
1122 0 : return nil, err
1123 0 : }
1124 :
1125 : // Find the currently active manifest, if there is one.
1126 1 : manifestMarker, manifestFileNum, exists, err := findCurrentManifest(fs, dirname, ls)
1127 1 : if err != nil {
1128 0 : return nil, err
1129 0 : }
1130 : // TODO(jackson): Immediately closing the marker is clunky. Add a
1131 : // PeekMarker variant that avoids opening the directory.
1132 1 : if err := manifestMarker.Close(); err != nil {
1133 0 : return nil, err
1134 0 : }
1135 :
1136 1 : desc := &DBDesc{
1137 1 : Exists: exists,
1138 1 : FormatMajorVersion: vers,
1139 1 : }
1140 1 :
1141 1 : // Find the OPTIONS file with the highest file number within the list of
1142 1 : // directory entries.
1143 1 : var previousOptionsFileNum base.DiskFileNum
1144 1 : for _, filename := range ls {
1145 1 : ft, fn, ok := base.ParseFilename(fs, filename)
1146 1 : if !ok || ft != fileTypeOptions || fn < previousOptionsFileNum {
1147 1 : continue
1148 : }
1149 1 : previousOptionsFileNum = fn
1150 1 : desc.OptionsFilename = fs.PathJoin(dirname, filename)
1151 : }
1152 :
1153 1 : if exists {
1154 1 : desc.ManifestFilename = base.MakeFilepath(fs, dirname, fileTypeManifest, manifestFileNum)
1155 1 : }
1156 1 : return desc, nil
1157 : }
1158 :
1159 : // LockDirectory acquires the database directory lock in the named directory,
1160 : // preventing another process from opening the database. LockDirectory returns a
1161 : // handle to the held lock that may be passed to Open through Options.Lock to
1162 : // subsequently open the database, skipping lock acquistion during Open.
1163 : //
1164 : // LockDirectory may be used to expand the critical section protected by the
1165 : // database lock to include setup before the call to Open.
1166 1 : func LockDirectory(dirname string, fs vfs.FS) (*Lock, error) {
1167 1 : fileLock, err := fs.Lock(base.MakeFilepath(fs, dirname, fileTypeLock, base.DiskFileNum(0)))
1168 1 : if err != nil {
1169 1 : return nil, err
1170 1 : }
1171 1 : l := &Lock{dirname: dirname, fileLock: fileLock}
1172 1 : l.refs.Store(1)
1173 1 : invariants.SetFinalizer(l, func(obj interface{}) {
1174 1 : if refs := obj.(*Lock).refs.Load(); refs > 0 {
1175 0 : panic(errors.AssertionFailedf("lock for %q finalized with %d refs", dirname, refs))
1176 : }
1177 : })
1178 1 : return l, nil
1179 : }
1180 :
1181 : // Lock represents a file lock on a directory. It may be passed to Open through
1182 : // Options.Lock to elide lock aquisition during Open.
1183 : type Lock struct {
1184 : dirname string
1185 : fileLock io.Closer
1186 : // refs is a count of the number of handles on the lock. refs must be 0, 1
1187 : // or 2.
1188 : //
1189 : // When acquired by the client and passed to Open, refs = 1 and the Open
1190 : // call increments it to 2. When the database is closed, it's decremented to
1191 : // 1. Finally when the original caller, calls Close on the Lock, it's
1192 : // drecemented to zero and the underlying file lock is released.
1193 : //
1194 : // When Open acquires the file lock, refs remains at 1 until the database is
1195 : // closed.
1196 : refs atomic.Int32
1197 : }
1198 :
1199 1 : func (l *Lock) refForOpen() error {
1200 1 : // During Open, when a user passed in a lock, the reference count must be
1201 1 : // exactly 1. If it's zero, the lock is no longer held and is invalid. If
1202 1 : // it's 2, the lock is already in use by another database within the
1203 1 : // process.
1204 1 : if !l.refs.CompareAndSwap(1, 2) {
1205 1 : return errors.Errorf("pebble: unexpected Lock reference count; is the lock already in use?")
1206 1 : }
1207 1 : return nil
1208 : }
1209 :
1210 : // Close releases the lock, permitting another process to lock and open the
1211 : // database. Close must not be called until after a database using the Lock has
1212 : // been closed.
1213 1 : func (l *Lock) Close() error {
1214 1 : if l.refs.Add(-1) > 0 {
1215 1 : return nil
1216 1 : }
1217 1 : defer func() { l.fileLock = nil }()
1218 1 : return l.fileLock.Close()
1219 : }
1220 :
1221 1 : func (l *Lock) pathMatches(dirname string) error {
1222 1 : if dirname == l.dirname {
1223 1 : return nil
1224 1 : }
1225 : // Check for relative paths, symlinks, etc. This isn't ideal because we're
1226 : // circumventing the vfs.FS interface here.
1227 : //
1228 : // TODO(jackson): We could add support for retrieving file inodes through Stat
1229 : // calls in the VFS interface on platforms where it's available and use that
1230 : // to differentiate.
1231 1 : dirStat, err1 := os.Stat(dirname)
1232 1 : lockDirStat, err2 := os.Stat(l.dirname)
1233 1 : if err1 == nil && err2 == nil && os.SameFile(dirStat, lockDirStat) {
1234 1 : return nil
1235 1 : }
1236 0 : return errors.Join(
1237 0 : errors.Newf("pebble: opts.Lock acquired in %q not %q", l.dirname, dirname),
1238 0 : err1, err2)
1239 : }
1240 :
1241 : // ErrDBDoesNotExist is generated when ErrorIfNotExists is set and the database
1242 : // does not exist.
1243 : //
1244 : // Note that errors can be wrapped with more details; use errors.Is().
1245 : var ErrDBDoesNotExist = errors.New("pebble: database does not exist")
1246 :
1247 : // ErrDBAlreadyExists is generated when ErrorIfExists is set and the database
1248 : // already exists.
1249 : //
1250 : // Note that errors can be wrapped with more details; use errors.Is().
1251 : var ErrDBAlreadyExists = errors.New("pebble: database already exists")
1252 :
1253 : // ErrDBNotPristine is generated when ErrorIfNotPristine is set and the database
1254 : // already exists and is not pristine.
1255 : //
1256 : // Note that errors can be wrapped with more details; use errors.Is().
1257 : var ErrDBNotPristine = errors.New("pebble: database already exists and is not pristine")
1258 :
1259 : // IsCorruptionError returns true if the given error indicates database
1260 : // corruption.
1261 1 : func IsCorruptionError(err error) bool {
1262 1 : return errors.Is(err, base.ErrCorruption)
1263 1 : }
1264 :
1265 1 : func checkConsistency(v *manifest.Version, dirname string, objProvider objstorage.Provider) error {
1266 1 : var errs []error
1267 1 : dedup := make(map[base.DiskFileNum]struct{})
1268 1 : for level, files := range v.Levels {
1269 1 : iter := files.Iter()
1270 1 : for f := iter.First(); f != nil; f = iter.Next() {
1271 1 : backingState := f.FileBacking
1272 1 : if _, ok := dedup[backingState.DiskFileNum]; ok {
1273 1 : continue
1274 : }
1275 1 : dedup[backingState.DiskFileNum] = struct{}{}
1276 1 : fileNum := backingState.DiskFileNum
1277 1 : fileSize := backingState.Size
1278 1 : // We skip over remote objects; those are instead checked asynchronously
1279 1 : // by the table stats loading job.
1280 1 : meta, err := objProvider.Lookup(base.FileTypeTable, fileNum)
1281 1 : var size int64
1282 1 : if err == nil {
1283 1 : if meta.IsRemote() {
1284 1 : continue
1285 : }
1286 1 : size, err = objProvider.Size(meta)
1287 : }
1288 1 : if err != nil {
1289 1 : errs = append(errs, errors.Wrapf(err, "L%d: %s", errors.Safe(level), fileNum))
1290 1 : continue
1291 : }
1292 :
1293 1 : if size != int64(fileSize) {
1294 0 : errs = append(errs, errors.Errorf(
1295 0 : "L%d: %s: object size mismatch (%s): %d (disk) != %d (MANIFEST)",
1296 0 : errors.Safe(level), fileNum, objProvider.Path(meta),
1297 0 : errors.Safe(size), errors.Safe(fileSize)))
1298 0 : continue
1299 : }
1300 : }
1301 : }
1302 1 : return errors.Join(errs...)
1303 : }
1304 :
1305 : type walEventListenerAdaptor struct {
1306 : l *EventListener
1307 : }
1308 :
1309 1 : func (l walEventListenerAdaptor) LogCreated(ci wal.CreateInfo) {
1310 1 : // TODO(sumeer): extend WALCreateInfo for the failover case in case the path
1311 1 : // is insufficient to infer whether primary or secondary.
1312 1 : wci := WALCreateInfo{
1313 1 : JobID: ci.JobID,
1314 1 : Path: ci.Path,
1315 1 : FileNum: base.DiskFileNum(ci.Num),
1316 1 : RecycledFileNum: ci.RecycledFileNum,
1317 1 : Err: ci.Err,
1318 1 : }
1319 1 : l.l.WALCreated(wci)
1320 1 : }
|