| 1 | //go:build unix |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "syscall" |
| 11 | ) |
| 12 | |
| 13 | // lockState makes the state directory if it is missing and locks it for |
| 14 | // one pass, and returns what lets the lock go. The lock is flock's, on the |
| 15 | // directory's lock file. It is let go when the pass ends however it ends, |
| 16 | // since the kernel lets it go with the last descriptor of the file, and a |
| 17 | // second pass that asks for it while one holds it fails at once. |
| 18 | func lockState(dir string) (func(), error) { |
| 19 | if err := os.MkdirAll(dir, 0o700); err != nil { |
| 20 | return nil, err |
| 21 | } |
| 22 | path := filepath.Join(dir, lockFile) |
| 23 | f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 28 | f.Close() |
| 29 | if errors.Is(err, syscall.EWOULDBLOCK) { |
| 30 | return nil, fmt.Errorf("another pass is using the state directory %s: it holds the lock on %s until it ends", dir, path) |
| 31 | } |
| 32 | return nil, fmt.Errorf("could not lock the state directory %s: %w", dir, err) |
| 33 | } |
| 34 | return func() { f.Close() }, nil |
| 35 | } |