feat: add an option to open block device with exclusive flock The problem is the interaction of udevd and our code managing partition table: udevd might trigger `BLKRRPART` ioctl concurrently with our code which tries to sync partition table which leads to a mess. With `flock(LOCK_EX)` udevd skips `BLKRRPART` syscall. Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com> (cherry picked from commit b0375e4267fdc6108bd9ff7a5dc97b80cd924b1d)
diff --git a/blockdevice/blockdevice_linux.go b/blockdevice/blockdevice_linux.go index c3600d4..fd4e862 100644 --- a/blockdevice/blockdevice_linux.go +++ b/blockdevice/blockdevice_linux.go
@@ -63,6 +63,14 @@ } }() + if opts.ExclusiveLock { + if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + err = fmt.Errorf("error locking device %q: %w", devname, err) + + return nil, err + } + } + if opts.CreateGPT { var g *gpt.GPT
diff --git a/blockdevice/options.go b/blockdevice/options.go index 2ffc5fb..0a8cbca 100644 --- a/blockdevice/options.go +++ b/blockdevice/options.go
@@ -6,7 +6,8 @@ // Options is the functional options struct. type Options struct { - CreateGPT bool + CreateGPT bool + ExclusiveLock bool } // Option is the functional option func. @@ -19,6 +20,13 @@ } } +// WithExclusiveLock locks the blockdevice for exclusive access using flock(). +func WithExclusiveLock(o bool) Option { + return func(args *Options) { + args.ExclusiveLock = o + } +} + // NewDefaultOptions initializes a Options struct with default values. func NewDefaultOptions(setters ...Option) *Options { opts := &Options{