devbox/cmd/devbox-hub/lock_unix.go
shoemoney f51e69839a
Some checks are pending
CI / vet-build-test (push) Waiting to run
fix(hub): flock gc against backup so a sweep can't strand a backup mid-copy 🔒💾
`backup` does VACUUM INTO (DB snapshot) then copies the blob tree; a concurrent
gc sweep could delete a blob the snapshot references between those steps,
producing a backup that's internally inconsistent — a dangling ref you'd only
discover on restore. Now gc sweeps (the --gc-every ticker AND `gc`) and `backup`
take an exclusive flock on <data>/.lock, so they can't overlap. Dry-run gc skips
the lock (read-only, must not block a long backup). unix flock (auto-released on
crash); no-op stub on non-unix (the hub ships linux/darwin).

Test: TestDataLockMutualExclusion. Cross-builds clean for windows + linux/arm64.
2026-06-30 17:27:00 -05:00

32 lines
907 B
Go

//go:build unix
package main
import (
"os"
"path/filepath"
"syscall"
)
// dataLock takes an exclusive advisory lock on <data>/.lock so the gc sweep and
// `backup` can never run at the same time — otherwise gc could delete a blob
// mid-backup, leaving the backup's DB referencing a blob its copy missed. flock
// is released automatically if the process dies, so a crash can't wedge it.
// Returns a release func; call it (idempotent enough) when the critical section ends.
func dataLock(data string) (func(), error) {
if err := os.MkdirAll(data, 0o700); err != nil {
return nil, err
}
f, err := os.OpenFile(filepath.Join(data, ".lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
f.Close()
return nil, err
}
return func() {
syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
f.Close()
}, nil
}