Download this file
| 1 | package proc |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "syscall" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // Lock is held by one holder at a time: across this process's |
| 12 | // goroutines (a channel) and the runner's processes (an flock on Path; |
| 13 | // "" keeps it within this process). |
| 14 | type Lock struct { |
| 15 | ch chan struct{} |
| 16 | path string |
| 17 | f *os.File |
| 18 | } |
| 19 | |
| 20 | // NewLock is a lock on path. |
| 21 | func NewLock(path string) *Lock { return &Lock{ch: make(chan struct{}, 1), path: path} } |
| 22 | |
| 23 | // Acquire waits for the lock until ctx ends. |
| 24 | func (l *Lock) Acquire(ctx context.Context) error { |
| 25 | select { |
| 26 | case l.ch <- struct{}{}: |
| 27 | case <-ctx.Done(): |
| 28 | return ctx.Err() |
| 29 | } |
| 30 | if l.path == "" { |
| 31 | return nil |
| 32 | } |
| 33 | f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600) |
| 34 | if err != nil { |
| 35 | <-l.ch |
| 36 | return err |
| 37 | } |
| 38 | for { |
| 39 | err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| 40 | if err == nil { |
| 41 | l.f = f |
| 42 | return nil |
| 43 | } |
| 44 | if !errors.Is(err, syscall.EWOULDBLOCK) { |
| 45 | f.Close() |
| 46 | <-l.ch |
| 47 | return err |
| 48 | } |
| 49 | select { |
| 50 | case <-ctx.Done(): |
| 51 | f.Close() |
| 52 | <-l.ch |
| 53 | return ctx.Err() |
| 54 | case <-time.After(250 * time.Millisecond): |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // TryAcquire takes the lock only if it is free now. |
| 60 | func (l *Lock) TryAcquire() bool { |
| 61 | select { |
| 62 | case l.ch <- struct{}{}: |
| 63 | default: |
| 64 | return false |
| 65 | } |
| 66 | if l.path == "" { |
| 67 | return true |
| 68 | } |
| 69 | f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600) |
| 70 | if err == nil { |
| 71 | if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil { |
| 72 | l.f = f |
| 73 | return true |
| 74 | } |
| 75 | f.Close() |
| 76 | } |
| 77 | <-l.ch |
| 78 | return false |
| 79 | } |
| 80 | |
| 81 | // Release gives the lock back. |
| 82 | func (l *Lock) Release() { |
| 83 | if l.f != nil { |
| 84 | _ = syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN) |
| 85 | l.f.Close() |
| 86 | l.f = nil |
| 87 | } |
| 88 | <-l.ch |
| 89 | } |
| 90 | |