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)
| 27 | // respects context cancellation by using non-blocking flock with polling. |
| 28 | // The caller must call Unlock with the returned *os.File when done. |
| 29 | func 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. |
| 61 | func Unlock(f *os.File) error { |