package badger
import (
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
"github.com/dgraph-io/badger/v4/y"
)
type directoryLockGuard struct {
f *os .File
path string
readOnly bool
}
func acquireDirectoryLock(dirPath string , pidFileName string , readOnly bool ) (
*directoryLockGuard , error ) {
absPidFilePath , err := filepath .Abs (filepath .Join (dirPath , pidFileName ))
if err != nil {
return nil , y .Wrapf (err , "cannot get absolute path for pid lock file" )
}
f , err := os .Open (dirPath )
if err != nil {
return nil , y .Wrapf (err , "cannot open directory %q" , dirPath )
}
opts := unix .LOCK_EX | unix .LOCK_NB
if readOnly {
opts = unix .LOCK_SH | unix .LOCK_NB
}
err = unix .Flock (int (f .Fd ()), opts )
if err != nil {
f .Close ()
return nil , y .Wrapf (err ,
"Cannot acquire directory lock on %q. Another process is using this Badger database." ,
dirPath )
}
if !readOnly {
err = os .WriteFile (absPidFilePath , []byte (fmt .Sprintf ("%d\n" , os .Getpid ())), 0666 )
if err != nil {
f .Close ()
return nil , y .Wrapf (err ,
"Cannot write pid file %q" , absPidFilePath )
}
}
return &directoryLockGuard {f , absPidFilePath , readOnly }, nil
}
func (guard *directoryLockGuard ) release () error {
var err error
if !guard .readOnly {
err = os .Remove (guard .path )
}
if closeErr := guard .f .Close (); err == nil {
err = closeErr
}
guard .path = ""
guard .f = nil
return err
}
func openDir(path string ) (*os .File , error ) { return os .Open (path ) }
func syncDir(dir string ) error {
f , err := openDir (dir )
if err != nil {
return y .Wrapf (err , "While opening directory: %s." , dir )
}
err = f .Sync ()
closeErr := f .Close ()
if err != nil {
return y .Wrapf (err , "While syncing directory: %s." , dir )
}
return y .Wrapf (closeErr , "While closing directory: %s." , dir )
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .