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