gunk-dev/the-valley

lock.go

source6a7605f70901main's published tip history
2.5 KiB
1package location
2
3import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 "syscall"
9)
10
11// ErrBusy is a lock another process holds.
12var ErrBusy = errors.New("held by another process")
13
14// BusyError is the lock file another process holds.
15type BusyError struct{ Path string }
16
17func (e *BusyError) Error() string { return e.Path + " is " + ErrBusy.Error() }
18func (e *BusyError) Is(target error) bool { return target == ErrBusy }
19
20// Lock is an exclusive flock held on each of a lock's files.
21type Lock struct{ files []*os.File }
22
23// TryLock locks each of paths in turn, without waiting, creating them and
24// their directories as needed. A path another process holds is a
25// BusyError, and releases what it took. Paths that are one file are locked
26// once. A lock that moves is the legacy path then the flow one: a build
27// that locks either alone excludes, and is excluded by, one that locks
28// both.
29func TryLock(paths ...string) (*Lock, error) { return lock(paths, false) }
30
31// WaitLock is TryLock waiting for each path in turn.
32func WaitLock(paths ...string) (*Lock, error) { return lock(paths, true) }
33
34func lock(paths []string, wait bool) (*Lock, error) {
35 l := &Lock{}
36 var held []os.FileInfo
37 for _, path := range paths {
38 f, fi, err := openLock(path)
39 if err != nil {
40 l.Release()
41 return nil, err
42 }
43 if sameAsAny(fi, held) {
44 // This description holds no lock, so closing it drops none.
45 f.Close()
46 continue
47 }
48 how := syscall.LOCK_EX
49 if !wait {
50 how |= syscall.LOCK_NB
51 }
52 if err := syscall.Flock(int(f.Fd()), how); err != nil {
53 f.Close()
54 l.Release()
55 if errors.Is(err, syscall.EWOULDBLOCK) {
56 return nil, &BusyError{Path: path}
57 }
58 return nil, fmt.Errorf("locking %s: %w", path, err)
59 }
60 l.files = append(l.files, f)
61 held = append(held, fi)
62 }
63 return l, nil
64}
65
66func openLock(path string) (*os.File, os.FileInfo, error) {
67 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
68 return nil, nil, err
69 }
70 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
71 if err != nil {
72 return nil, nil, err
73 }
74 fi, err := f.Stat()
75 if err != nil {
76 f.Close()
77 return nil, nil, err
78 }
79 return f, fi, nil
80}
81
82func sameAsAny(fi os.FileInfo, held []os.FileInfo) bool {
83 for _, h := range held {
84 if os.SameFile(fi, h) {
85 return true
86 }
87 }
88 return false
89}
90
91// Release drops the lock, last file first. Its files stay: another process
92// may hold or wait on them.
93func (l *Lock) Release() {
94 if l == nil {
95 return
96 }
97 for i := len(l.files) - 1; i >= 0; i-- {
98 l.files[i].Close() // close drops the flock
99 }
100 l.files = nil
101}