diff --git a/db.go b/db.go index f7d8473e5..05a8a276c 100644 --- a/db.go +++ b/db.go @@ -234,33 +234,35 @@ func Open(opt Options) (db *DB, err error) { if err := createDirs(opt); err != nil { return nil, err } - dirLockGuard, err = acquireDirectoryLock(opt.Dir, lockFile, opt.ReadOnly) - if err != nil { - return nil, err - } - defer func() { - if dirLockGuard != nil { - _ = dirLockGuard.release() - } - }() - absDir, err := filepath.Abs(opt.Dir) - if err != nil { - return nil, err - } - absValueDir, err := filepath.Abs(opt.ValueDir) - if err != nil { - return nil, err - } - if absValueDir != absDir { - valueDirLockGuard, err = acquireDirectoryLock(opt.ValueDir, lockFile, opt.ReadOnly) + if !opt.BypassLockGuard { + dirLockGuard, err = acquireDirectoryLock(opt.Dir, lockFile, opt.ReadOnly) if err != nil { return nil, err } defer func() { - if valueDirLockGuard != nil { - _ = valueDirLockGuard.release() + if dirLockGuard != nil { + _ = dirLockGuard.release() } }() + absDir, err := filepath.Abs(opt.Dir) + if err != nil { + return nil, err + } + absValueDir, err := filepath.Abs(opt.ValueDir) + if err != nil { + return nil, err + } + if absValueDir != absDir { + valueDirLockGuard, err = acquireDirectoryLock(opt.ValueDir, lockFile, opt.ReadOnly) + if err != nil { + return nil, err + } + defer func() { + if valueDirLockGuard != nil { + _ = valueDirLockGuard.release() + } + }() + } } } diff --git a/options.go b/options.go index 0e3c60e3f..f11ce3f8c 100644 --- a/options.go +++ b/options.go @@ -84,6 +84,11 @@ type Options struct { EncryptionKey []byte // encryption key EncryptionKeyRotationDuration time.Duration // key rotation duration + // BypassLockGaurd will bypass the lock guard on badger. Bypassing lock + // guard can cause data corruption if multiple badger instances are using + // the same directory. Use this options with caution. + BypassLockGuard bool + // ChecksumVerificationMode decides when db should verify checksums for SSTable blocks. ChecksumVerificationMode options.ChecksumVerificationMode @@ -575,3 +580,16 @@ func (opt Options) WithZSTDCompressionLevel(cLevel int) Options { opt.ZSTDCompressionLevel = cLevel return opt } + +// WithBypassLockGuard returns a new Options value with BypassLockGuard +// set to the given value. +// +// When BypassLockGuard option is set, badger will not acquire a lock on the +// directory. This could lead to data corruption if multiple badger instances +// write to the same data directory. Use this option with caution. +// +// The default value of BypassLockGuard is false. +func (opt Options) WithBypassLockGuard(b bool) Options { + opt.BypassLockGuard = b + return opt +}