LCOV - code coverage report
Current view: top level - pebble - checkpoint.go (source / functions) Hit Total Coverage
Test: 2023-12-04 08:11Z 51fca96d - tests + meta.lcov Lines: 213 272 78.3 %
Date: 2023-12-04 08:13:13 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2019 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             :         "io"
       9             :         "os"
      10             : 
      11             :         "github.com/cockroachdb/errors/oserror"
      12             :         "github.com/cockroachdb/pebble/internal/base"
      13             :         "github.com/cockroachdb/pebble/record"
      14             :         "github.com/cockroachdb/pebble/vfs"
      15             :         "github.com/cockroachdb/pebble/vfs/atomicfs"
      16             : )
      17             : 
      18             : // checkpointOptions hold the optional parameters to construct checkpoint
      19             : // snapshots.
      20             : type checkpointOptions struct {
      21             :         // flushWAL set to true will force a flush and sync of the WAL prior to
      22             :         // checkpointing.
      23             :         flushWAL bool
      24             : 
      25             :         // If set, any SSTs that don't overlap with these spans are excluded from a checkpoint.
      26             :         restrictToSpans []CheckpointSpan
      27             : }
      28             : 
      29             : // CheckpointOption set optional parameters used by `DB.Checkpoint`.
      30             : type CheckpointOption func(*checkpointOptions)
      31             : 
      32             : // WithFlushedWAL enables flushing and syncing the WAL prior to constructing a
      33             : // checkpoint. This guarantees that any writes committed before calling
      34             : // DB.Checkpoint will be part of that checkpoint.
      35             : //
      36             : // Note that this setting can only be useful in cases when some writes are
      37             : // performed with Sync = false. Otherwise, the guarantee will already be met.
      38             : //
      39             : // Passing this option is functionally equivalent to calling
      40             : // DB.LogData(nil, Sync) right before DB.Checkpoint.
      41           1 : func WithFlushedWAL() CheckpointOption {
      42           1 :         return func(opt *checkpointOptions) {
      43           1 :                 opt.flushWAL = true
      44           1 :         }
      45             : }
      46             : 
      47             : // WithRestrictToSpans specifies spans of interest for the checkpoint. Any SSTs
      48             : // that don't overlap with any of these spans are excluded from the checkpoint.
      49             : //
      50             : // Note that the checkpoint can still surface keys outside of these spans (from
      51             : // the WAL and from SSTs that partially overlap with these spans). Moreover,
      52             : // these surface keys aren't necessarily "valid" in that they could have been
      53             : // modified but the SST containing the modification is excluded.
      54           2 : func WithRestrictToSpans(spans []CheckpointSpan) CheckpointOption {
      55           2 :         return func(opt *checkpointOptions) {
      56           2 :                 opt.restrictToSpans = spans
      57           2 :         }
      58             : }
      59             : 
      60             : // CheckpointSpan is a key range [Start, End) (inclusive on Start, exclusive on
      61             : // End) of interest for a checkpoint.
      62             : type CheckpointSpan struct {
      63             :         Start []byte
      64             :         End   []byte
      65             : }
      66             : 
      67             : // excludeFromCheckpoint returns true if an SST file should be excluded from the
      68             : // checkpoint because it does not overlap with the spans of interest
      69             : // (opt.restrictToSpans).
      70           2 : func excludeFromCheckpoint(f *fileMetadata, opt *checkpointOptions, cmp Compare) bool {
      71           2 :         if len(opt.restrictToSpans) == 0 {
      72           2 :                 // Option not set; don't exclude anything.
      73           2 :                 return false
      74           2 :         }
      75           2 :         for _, s := range opt.restrictToSpans {
      76           2 :                 if f.Overlaps(cmp, s.Start, s.End, true /* exclusiveEnd */) {
      77           2 :                         return false
      78           2 :                 }
      79             :         }
      80             :         // None of the restrictToSpans overlapped; we can exclude this file.
      81           2 :         return true
      82             : }
      83             : 
      84             : // mkdirAllAndSyncParents creates destDir and any of its missing parents.
      85             : // Those missing parents, as well as the closest existing ancestor, are synced.
      86             : // Returns a handle to the directory created at destDir.
      87           2 : func mkdirAllAndSyncParents(fs vfs.FS, destDir string) (vfs.File, error) {
      88           2 :         // Collect paths for all directories between destDir (excluded) and its
      89           2 :         // closest existing ancestor (included).
      90           2 :         var parentPaths []string
      91           2 :         foundExistingAncestor := false
      92           2 :         for parentPath := fs.PathDir(destDir); parentPath != "."; parentPath = fs.PathDir(parentPath) {
      93           2 :                 parentPaths = append(parentPaths, parentPath)
      94           2 :                 _, err := fs.Stat(parentPath)
      95           2 :                 if err == nil {
      96           2 :                         // Exit loop at the closest existing ancestor.
      97           2 :                         foundExistingAncestor = true
      98           2 :                         break
      99             :                 }
     100           2 :                 if !oserror.IsNotExist(err) {
     101           0 :                         return nil, err
     102           0 :                 }
     103             :         }
     104             :         // Handle empty filesystem edge case.
     105           2 :         if !foundExistingAncestor {
     106           1 :                 parentPaths = append(parentPaths, "")
     107           1 :         }
     108             :         // Create destDir and any of its missing parents.
     109           2 :         if err := fs.MkdirAll(destDir, 0755); err != nil {
     110           0 :                 return nil, err
     111           0 :         }
     112             :         // Sync all the parent directories up to the closest existing ancestor,
     113             :         // included.
     114           2 :         for _, parentPath := range parentPaths {
     115           2 :                 parentDir, err := fs.OpenDir(parentPath)
     116           2 :                 if err != nil {
     117           0 :                         return nil, err
     118           0 :                 }
     119           2 :                 err = parentDir.Sync()
     120           2 :                 if err != nil {
     121           0 :                         _ = parentDir.Close()
     122           0 :                         return nil, err
     123           0 :                 }
     124           2 :                 err = parentDir.Close()
     125           2 :                 if err != nil {
     126           0 :                         return nil, err
     127           0 :                 }
     128             :         }
     129           2 :         return fs.OpenDir(destDir)
     130             : }
     131             : 
     132             : // Checkpoint constructs a snapshot of the DB instance in the specified
     133             : // directory. The WAL, MANIFEST, OPTIONS, and sstables will be copied into the
     134             : // snapshot. Hard links will be used when possible. Beware of the significant
     135             : // space overhead for a checkpoint if hard links are disabled. Also beware that
     136             : // even if hard links are used, the space overhead for the checkpoint will
     137             : // increase over time as the DB performs compactions.
     138             : func (d *DB) Checkpoint(
     139             :         destDir string, opts ...CheckpointOption,
     140             : ) (
     141             :         ckErr error, /* used in deferred cleanup */
     142           2 : ) {
     143           2 :         opt := &checkpointOptions{}
     144           2 :         for _, fn := range opts {
     145           2 :                 fn(opt)
     146           2 :         }
     147             : 
     148           2 :         if _, err := d.opts.FS.Stat(destDir); !oserror.IsNotExist(err) {
     149           1 :                 if err == nil {
     150           1 :                         return &os.PathError{
     151           1 :                                 Op:   "checkpoint",
     152           1 :                                 Path: destDir,
     153           1 :                                 Err:  oserror.ErrExist,
     154           1 :                         }
     155           1 :                 }
     156           0 :                 return err
     157             :         }
     158             : 
     159           2 :         if opt.flushWAL && !d.opts.DisableWAL {
     160           1 :                 // Write an empty log-data record to flush and sync the WAL.
     161           1 :                 if err := d.LogData(nil /* data */, Sync); err != nil {
     162           0 :                         return err
     163           0 :                 }
     164             :         }
     165             : 
     166             :         // Disable file deletions.
     167           2 :         d.mu.Lock()
     168           2 :         d.disableFileDeletions()
     169           2 :         defer func() {
     170           2 :                 d.mu.Lock()
     171           2 :                 defer d.mu.Unlock()
     172           2 :                 d.enableFileDeletions()
     173           2 :         }()
     174             : 
     175             :         // TODO(peter): RocksDB provides the option to roll the manifest if the
     176             :         // MANIFEST size is too large. Should we do this too?
     177             : 
     178             :         // Lock the manifest before getting the current version. We need the
     179             :         // length of the manifest that we read to match the current version that
     180             :         // we read, otherwise we might copy a versionEdit not reflected in the
     181             :         // sstables we copy/link.
     182           2 :         d.mu.versions.logLock()
     183           2 :         // Get the unflushed log files, the current version, and the current manifest
     184           2 :         // file number.
     185           2 :         memQueue := d.mu.mem.queue
     186           2 :         current := d.mu.versions.currentVersion()
     187           2 :         formatVers := d.FormatMajorVersion()
     188           2 :         manifestFileNum := d.mu.versions.manifestFileNum
     189           2 :         manifestSize := d.mu.versions.manifest.Size()
     190           2 :         optionsFileNum := d.optionsFileNum
     191           2 :         virtualBackingFiles := make(map[base.DiskFileNum]struct{})
     192           2 :         for diskFileNum := range d.mu.versions.backingState.fileBackingMap {
     193           2 :                 virtualBackingFiles[diskFileNum] = struct{}{}
     194           2 :         }
     195             :         // Release the manifest and DB.mu so we don't block other operations on
     196             :         // the database.
     197           2 :         d.mu.versions.logUnlock()
     198           2 :         d.mu.Unlock()
     199           2 : 
     200           2 :         // Wrap the normal filesystem with one which wraps newly created files with
     201           2 :         // vfs.NewSyncingFile.
     202           2 :         fs := vfs.NewSyncingFS(d.opts.FS, vfs.SyncingFileOptions{
     203           2 :                 NoSyncOnClose: d.opts.NoSyncOnClose,
     204           2 :                 BytesPerSync:  d.opts.BytesPerSync,
     205           2 :         })
     206           2 : 
     207           2 :         // Create the dir and its parents (if necessary), and sync them.
     208           2 :         var dir vfs.File
     209           2 :         defer func() {
     210           2 :                 if dir != nil {
     211           0 :                         _ = dir.Close()
     212           0 :                 }
     213           2 :                 if ckErr != nil {
     214           0 :                         // Attempt to cleanup on error.
     215           0 :                         _ = fs.RemoveAll(destDir)
     216           0 :                 }
     217             :         }()
     218           2 :         dir, ckErr = mkdirAllAndSyncParents(fs, destDir)
     219           2 :         if ckErr != nil {
     220           0 :                 return ckErr
     221           0 :         }
     222             : 
     223           2 :         {
     224           2 :                 // Link or copy the OPTIONS.
     225           2 :                 srcPath := base.MakeFilepath(fs, d.dirname, fileTypeOptions, optionsFileNum)
     226           2 :                 destPath := fs.PathJoin(destDir, fs.PathBase(srcPath))
     227           2 :                 ckErr = vfs.LinkOrCopy(fs, srcPath, destPath)
     228           2 :                 if ckErr != nil {
     229           0 :                         return ckErr
     230           0 :                 }
     231             :         }
     232             : 
     233           2 :         {
     234           2 :                 // Set the format major version in the destination directory.
     235           2 :                 var versionMarker *atomicfs.Marker
     236           2 :                 versionMarker, _, ckErr = atomicfs.LocateMarker(fs, destDir, formatVersionMarkerName)
     237           2 :                 if ckErr != nil {
     238           0 :                         return ckErr
     239           0 :                 }
     240             : 
     241             :                 // We use the marker to encode the active format version in the
     242             :                 // marker filename. Unlike other uses of the atomic marker,
     243             :                 // there is no file with the filename `formatVers.String()` on
     244             :                 // the filesystem.
     245           2 :                 ckErr = versionMarker.Move(formatVers.String())
     246           2 :                 if ckErr != nil {
     247           0 :                         return ckErr
     248           0 :                 }
     249           2 :                 ckErr = versionMarker.Close()
     250           2 :                 if ckErr != nil {
     251           0 :                         return ckErr
     252           0 :                 }
     253             :         }
     254             : 
     255           2 :         var excludedFiles map[deletedFileEntry]*fileMetadata
     256           2 :         // Set of FileBacking.DiskFileNum which will be required by virtual sstables
     257           2 :         // in the checkpoint.
     258           2 :         requiredVirtualBackingFiles := make(map[base.DiskFileNum]struct{})
     259           2 :         // Link or copy the sstables.
     260           2 :         for l := range current.Levels {
     261           2 :                 iter := current.Levels[l].Iter()
     262           2 :                 for f := iter.First(); f != nil; f = iter.Next() {
     263           2 :                         if excludeFromCheckpoint(f, opt, d.cmp) {
     264           2 :                                 if excludedFiles == nil {
     265           2 :                                         excludedFiles = make(map[deletedFileEntry]*fileMetadata)
     266           2 :                                 }
     267           2 :                                 excludedFiles[deletedFileEntry{
     268           2 :                                         Level:   l,
     269           2 :                                         FileNum: f.FileNum,
     270           2 :                                 }] = f
     271           2 :                                 continue
     272             :                         }
     273             : 
     274           2 :                         fileBacking := f.FileBacking
     275           2 :                         if f.Virtual {
     276           2 :                                 if _, ok := requiredVirtualBackingFiles[fileBacking.DiskFileNum]; ok {
     277           2 :                                         continue
     278             :                                 }
     279           2 :                                 requiredVirtualBackingFiles[fileBacking.DiskFileNum] = struct{}{}
     280             :                         }
     281             : 
     282           2 :                         srcPath := base.MakeFilepath(fs, d.dirname, fileTypeTable, fileBacking.DiskFileNum)
     283           2 :                         destPath := fs.PathJoin(destDir, fs.PathBase(srcPath))
     284           2 :                         ckErr = vfs.LinkOrCopy(fs, srcPath, destPath)
     285           2 :                         if ckErr != nil {
     286           0 :                                 return ckErr
     287           0 :                         }
     288             :                 }
     289             :         }
     290             : 
     291           2 :         var removeBackingTables []base.DiskFileNum
     292           2 :         for diskFileNum := range virtualBackingFiles {
     293           2 :                 if _, ok := requiredVirtualBackingFiles[diskFileNum]; !ok {
     294           2 :                         // The backing sstable associated with fileNum is no longer
     295           2 :                         // required.
     296           2 :                         removeBackingTables = append(removeBackingTables, diskFileNum)
     297           2 :                 }
     298             :         }
     299             : 
     300           2 :         ckErr = d.writeCheckpointManifest(
     301           2 :                 fs, formatVers, destDir, dir, manifestFileNum, manifestSize,
     302           2 :                 excludedFiles, removeBackingTables,
     303           2 :         )
     304           2 :         if ckErr != nil {
     305           0 :                 return ckErr
     306           0 :         }
     307             : 
     308             :         // Copy the WAL files. We copy rather than link because WAL file recycling
     309             :         // will cause the WAL files to be reused which would invalidate the
     310             :         // checkpoint.
     311           2 :         for i := range memQueue {
     312           2 :                 logNum := memQueue[i].logNum
     313           2 :                 if logNum == 0 {
     314           1 :                         continue
     315             :                 }
     316           2 :                 srcPath := base.MakeFilepath(fs, d.walDirname, fileTypeLog, logNum)
     317           2 :                 destPath := fs.PathJoin(destDir, fs.PathBase(srcPath))
     318           2 :                 ckErr = vfs.Copy(fs, srcPath, destPath)
     319           2 :                 if ckErr != nil {
     320           0 :                         return ckErr
     321           0 :                 }
     322             :         }
     323             : 
     324             :         // Sync and close the checkpoint directory.
     325           2 :         ckErr = dir.Sync()
     326           2 :         if ckErr != nil {
     327           0 :                 return ckErr
     328           0 :         }
     329           2 :         ckErr = dir.Close()
     330           2 :         dir = nil
     331           2 :         return ckErr
     332             : }
     333             : 
     334             : func (d *DB) writeCheckpointManifest(
     335             :         fs vfs.FS,
     336             :         formatVers FormatMajorVersion,
     337             :         destDirPath string,
     338             :         destDir vfs.File,
     339             :         manifestFileNum base.DiskFileNum,
     340             :         manifestSize int64,
     341             :         excludedFiles map[deletedFileEntry]*fileMetadata,
     342             :         removeBackingTables []base.DiskFileNum,
     343           2 : ) error {
     344           2 :         // Copy the MANIFEST, and create a pointer to it. We copy rather
     345           2 :         // than link because additional version edits added to the
     346           2 :         // MANIFEST after we took our snapshot of the sstables will
     347           2 :         // reference sstables that aren't in our checkpoint. For a
     348           2 :         // similar reason, we need to limit how much of the MANIFEST we
     349           2 :         // copy.
     350           2 :         // If some files are excluded from the checkpoint, also append a block that
     351           2 :         // records those files as deleted.
     352           2 :         if err := func() error {
     353           2 :                 srcPath := base.MakeFilepath(fs, d.dirname, fileTypeManifest, manifestFileNum)
     354           2 :                 destPath := fs.PathJoin(destDirPath, fs.PathBase(srcPath))
     355           2 :                 src, err := fs.Open(srcPath, vfs.SequentialReadsOption)
     356           2 :                 if err != nil {
     357           0 :                         return err
     358           0 :                 }
     359           2 :                 defer src.Close()
     360           2 : 
     361           2 :                 dst, err := fs.Create(destPath)
     362           2 :                 if err != nil {
     363           0 :                         return err
     364           0 :                 }
     365           2 :                 defer dst.Close()
     366           2 : 
     367           2 :                 // Copy all existing records. We need to copy at the record level in case we
     368           2 :                 // need to append another record with the excluded files (we cannot simply
     369           2 :                 // append a record after a raw data copy; see
     370           2 :                 // https://github.com/cockroachdb/cockroach/issues/100935).
     371           2 :                 r := record.NewReader(&io.LimitedReader{R: src, N: manifestSize}, manifestFileNum)
     372           2 :                 w := record.NewWriter(dst)
     373           2 :                 for {
     374           2 :                         rr, err := r.Next()
     375           2 :                         if err != nil {
     376           2 :                                 if err == io.EOF {
     377           2 :                                         break
     378             :                                 }
     379           0 :                                 return err
     380             :                         }
     381             : 
     382           2 :                         rw, err := w.Next()
     383           2 :                         if err != nil {
     384           0 :                                 return err
     385           0 :                         }
     386           2 :                         if _, err := io.Copy(rw, rr); err != nil {
     387           0 :                                 return err
     388           0 :                         }
     389             :                 }
     390             : 
     391           2 :                 if len(excludedFiles) > 0 {
     392           2 :                         // Write out an additional VersionEdit that deletes the excluded SST files.
     393           2 :                         ve := versionEdit{
     394           2 :                                 DeletedFiles:         excludedFiles,
     395           2 :                                 RemovedBackingTables: removeBackingTables,
     396           2 :                         }
     397           2 : 
     398           2 :                         rw, err := w.Next()
     399           2 :                         if err != nil {
     400           0 :                                 return err
     401           0 :                         }
     402           2 :                         if err := ve.Encode(rw); err != nil {
     403           0 :                                 return err
     404           0 :                         }
     405             :                 }
     406           2 :                 if err := w.Close(); err != nil {
     407           0 :                         return err
     408           0 :                 }
     409           2 :                 return dst.Sync()
     410           0 :         }(); err != nil {
     411           0 :                 return err
     412           0 :         }
     413             : 
     414             :         // Recent format versions use an atomic marker for setting the
     415             :         // active manifest. Older versions use the CURRENT file. The
     416             :         // setCurrentFunc function will return a closure that will
     417             :         // take the appropriate action for the database's format
     418             :         // version.
     419           2 :         var manifestMarker *atomicfs.Marker
     420           2 :         manifestMarker, _, err := atomicfs.LocateMarker(fs, destDirPath, manifestMarkerName)
     421           2 :         if err != nil {
     422           0 :                 return err
     423           0 :         }
     424           2 :         if err := setCurrentFunc(formatVers, manifestMarker, fs, destDirPath, destDir)(manifestFileNum); err != nil {
     425           0 :                 return err
     426           0 :         }
     427           2 :         return manifestMarker.Close()
     428             : }

Generated by: LCOV version 1.14