MCPcopy
hub / github.com/netbirdio/netbird / Lock

Function Lock

proxy/internal/flock/flock_unix.go:29–58  ·  view source on GitHub ↗

Lock acquires an exclusive advisory lock on the given file path. It creates the lock file if it does not exist. The lock attempt respects context cancellation by using non-blocking flock with polling. The caller must call Unlock with the returned *os.File when done.

(ctx context.Context, path string)

Source from the content-addressed store, hash-verified

27// respects context cancellation by using non-blocking flock with polling.
28// The caller must call Unlock with the returned *os.File when done.
29func Lock(ctx context.Context, path string) (*os.File, error) {
30 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
31 if err != nil {
32 return nil, fmt.Errorf("open lock file %s: %w", path, err)
33 }
34
35 timer := time.NewTimer(retryInterval)
36 defer timer.Stop()
37
38 for {
39 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
40 return f, nil
41 } else if !errors.Is(err, syscall.EWOULDBLOCK) {
42 if cerr := f.Close(); cerr != nil {
43 log.Debugf("close lock file %s: %v", path, cerr)
44 }
45 return nil, fmt.Errorf("acquire lock on %s: %w", path, err)
46 }
47
48 select {
49 case <-ctx.Done():
50 if cerr := f.Close(); cerr != nil {
51 log.Debugf("close lock file %s: %v", path, cerr)
52 }
53 return nil, ctx.Err()
54 case <-timer.C:
55 timer.Reset(retryInterval)
56 }
57 }
58}
59
60// Unlock releases the lock and closes the file.
61func Unlock(f *os.File) error {

Callers 4

LockMethod · 0.92
TestLockUnlockFunction · 0.70
TestLockRespectsContextFunction · 0.70
TestLockBlocksFunction · 0.70

Calls 7

ErrorfMethod · 0.80
StopMethod · 0.65
CloseMethod · 0.65
DebugfMethod · 0.65
ResetMethod · 0.65
IsMethod · 0.45
DoneMethod · 0.45

Tested by 3

TestLockUnlockFunction · 0.56
TestLockRespectsContextFunction · 0.56
TestLockBlocksFunction · 0.56