Skip to content

Commit

Permalink
feat: add support for retry-locking the blockdevice
Browse files Browse the repository at this point in the history
This allows to wait for others to unlock the blockdevice.

Signed-off-by: Andrey Smirnov <[email protected]>
  • Loading branch information
smira committed Aug 15, 2024
1 parent 114af20 commit 07f736f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
27 changes: 27 additions & 0 deletions block/device_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ package block

import (
"bytes"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"unsafe"

"golang.org/x/sys/unix"
Expand Down Expand Up @@ -280,6 +282,31 @@ func (d *Device) TryLock(exclusive bool) error {
return d.lock(exclusive, unix.LOCK_NB)
}

// RetryLock until the context deadline.
func (d *Device) RetryLock(ctx context.Context, exclusive bool) error {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()

for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := d.TryLock(exclusive); err == nil {
return nil
}
}
}
}

// RetryLockWithTimeout retries locking until the timeout.
func (d *Device) RetryLockWithTimeout(ctx context.Context, exclusive bool, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

return d.RetryLock(ctx, exclusive)
}

// Unlock releases any lock.
func (d *Device) Unlock() error {
for {
Expand Down
19 changes: 19 additions & 0 deletions block/device_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
package block_test

import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"

"github.com/freddierice/go-losetup/v2"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -204,6 +206,23 @@ func TestDevice(t *testing.T) {
require.NoError(t, devWhole2.Unlock())
})

t.Run("retry lock", func(t *testing.T) {
require.NoError(t, devWhole.Lock(true))

errCh := make(chan error)

go func() {
errCh <- devWhole2.RetryLockWithTimeout(context.Background(), true, 10*time.Second)
}()

time.Sleep(1 * time.Second)

require.NoError(t, devWhole.Unlock())

require.NoError(t, <-errCh)
require.NoError(t, devWhole2.Unlock())
})

t.Run("read only", func(t *testing.T) {
readOnly, err := devWhole.IsReadOnly()
require.NoError(t, err)
Expand Down

0 comments on commit 07f736f

Please sign in to comment.