GeezerVison is showing github.com — fix(lockutil): use kernel-held advisory locks (#950) · Twigpine/zero@6fe0d1e
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: internal/cron/lock.go +9-66Lines changed: 9 additions & 66 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5,31 +5,23 @@ import ( | 5 | 5 | "fmt" | 6 | 6 | "os" | 7 | 7 | "path/filepath" | 8 | | - "sync/atomic" | 9 | 8 | "time" | 10 | 9 |
| 11 | 10 | "github.com/Gitlawb/zero/internal/lockutil" | 12 | 11 | ) | 13 | 12 |
| 14 | 13 | // Cross-process lock tuning. The lock is held only for a single metadata | 15 | | -// read-modify-write (milliseconds), never across a job's exec, so the timeout is | 16 | | -// generous and the stale threshold sits far above any real hold. | | 14 | +// read-modify-write (milliseconds), never across a job's exec, so the timeout | | 15 | +// is generous relative to any real hold. | 17 | 16 | const ( | 18 | 17 | cronLockTimeout = 10 * time.Second | 19 | | - cronLockStaleAfter = 60 * time.Second | 20 | 18 | cronLockRetryDelay = 20 * time.Millisecond | 21 | 19 | ) | 22 | 20 |
| 23 | | -var cronLockSeq atomic.Uint64 | 24 | | - | 25 | | -// lockJob takes a cross-process exclusive lock for one job by O_EXCL-creating a | 26 | | -// sibling "<id>.lock" file next to the job directory (so Remove's RemoveAll of | 27 | | -// the job dir never deletes a live lock). It serializes the read-modify-write of | 28 | | -// a job's metadata across concurrent schedulers and commands. The lock file is | 29 | | -// removed on release; a stale lock from a crashed holder (older than | 30 | | -// cronLockStaleAfter) is reclaimed. Wall-clock time.Now is used deliberately | 31 | | -// (not the injectable Store.now) so lock timing never depends on a frozen test | 32 | | -// clock and the stale check compares against real file mtimes. | | 21 | +// lockJob takes a cross-process advisory lock for one job on a stable sibling | | 22 | +// "<id>.lock" file next to the job directory. It serializes the read-modify-write | | 23 | +// of a job's metadata across concurrent schedulers and commands. The kernel | | 24 | +// releases the lock when a holder exits; the file is never renamed or removed. | 33 | 25 | func (s *Store) lockJob(id string) (func(), error) { | 34 | 26 | if !validID(id) { | 35 | 27 | return nil, fmt.Errorf("invalid cron job id %q", id) | @@ -38,64 +30,15 @@ func (s *Store) lockJob(id string) (func(), error) { | 38 | 30 | if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil { | 39 | 31 | return nil, err | 40 | 32 | } | 41 | | - token := fmt.Sprintf("%d-%d-%d", os.Getpid(), time.Now().UnixNano(), cronLockSeq.Add(1)) | 42 | 33 | deadline := time.Now().Add(cronLockTimeout) | 43 | 34 | for { | 44 | | - f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) | | 35 | + lock, err := lockutil.TryAcquireFileLock(lockPath) | 45 | 36 | if err == nil { | 46 | | - // A partial write would leave a lock file without our token, so the | 47 | | - // releaser could never delete it — stranding the lock. Fail closed. | 48 | | - if _, werr := f.WriteString(token); werr != nil { | 49 | | - _ = f.Close() | 50 | | - _ = lockutil.RemoveLockFile(lockPath) | 51 | | - return nil, fmt.Errorf("cron: write job lock: %w", werr) | 52 | | - } | 53 | | - if cerr := f.Close(); cerr != nil { | 54 | | - _ = lockutil.RemoveLockFile(lockPath) | 55 | | - return nil, fmt.Errorf("cron: close job lock: %w", cerr) | 56 | | - } | 57 | | - var released bool | 58 | | - return func() { | 59 | | - if released { | 60 | | - return | 61 | | - } | 62 | | - released = true | 63 | | - if data, rerr := os.ReadFile(lockPath); rerr == nil && string(data) == token { | 64 | | - _ = lockutil.RemoveLockFile(lockPath) | 65 | | - } | 66 | | - }, nil | | 37 | + return func() { _ = lock.Release() }, nil | 67 | 38 | } | 68 | | - // On Windows a concurrent holder's os.Remove leaves the lock file in a | 69 | | - // "delete pending" state, so an O_EXCL create races it with | 70 | | - // ERROR_ACCESS_DENIED (os.ErrPermission) rather than ErrExist. Treat that | 71 | | - // as contention and retry, exactly like ErrExist — otherwise the lock | 72 | | - // spuriously fails under concurrency on Windows. | 73 | | - if !errors.Is(err, os.ErrExist) && !errors.Is(err, os.ErrPermission) { | | 39 | + if !errors.Is(err, lockutil.ErrLockHeld) { | 74 | 40 | return nil, fmt.Errorf("cron: acquire job lock: %w", err) | 75 | 41 | } | 76 | | - // Reclaim a stale lock left by a crashed holder — atomically (H3). A blind | 77 | | - // Remove lets two racers both "reclaim" and recreate, so both hold the lock; | 78 | | - // reclaimStaleLock renames the file aside (only one rename of a given file | 79 | | - // wins) and restores it if it turns out fresh, so a live lock is never deleted | 80 | | - // out from under its holder. | 81 | | - if info, statErr := os.Stat(lockPath); statErr == nil && time.Since(info.ModTime()) > cronLockStaleAfter { | 82 | | - cleared, rerr := lockutil.ReclaimStaleLock(lockPath, token, func(reclaimedPath string) bool { | 83 | | - info, err := os.Stat(reclaimedPath) | 84 | | - return err == nil && time.Since(info.ModTime()) <= cronLockStaleAfter | 85 | | - }) | 86 | | - if rerr != nil { | 87 | | - // Reclaim hit a hard failure: the rename aside failed outright, or a | 88 | | - // live holder's lock could not be put back (the lock path may be | 89 | | - // missing, so re-acquiring would break mutual exclusion). Fail closed | 90 | | - // instead of spinning to the deadline. | 91 | | - return nil, fmt.Errorf("cron: reclaim stale job lock: %w", rerr) | 92 | | - } | 93 | | - if cleared { | 94 | | - continue // cleared a genuinely stale lock; retry the O_EXCL create now | 95 | | - } | 96 | | - // Lost the reclaim race (or it was actually fresh) — fall through to the | 97 | | - // bounded wait instead of hot-spinning on a reclaim that never wins (L13). | 98 | | - } | 99 | 42 | if !time.Now().Before(deadline) { | 100 | 43 | return nil, fmt.Errorf("cron: timed out acquiring job lock for %q", id) | 101 | 44 | } | |
Collapse file Copy file name to clipboardExpand all lines: internal/cron/mutate_test.go +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -64,7 +64,7 @@ func TestMutateRemovedJobReturnsNotFound(t *testing.T) { | 64 | 64 | if !errors.Is(err, ErrJobNotFound) { | 65 | 65 | t.Fatalf("Mutate on removed job = %v, want ErrJobNotFound", err) | 66 | 66 | } | 67 | | - // And the lock file left no litter / did not resurrect the job dir. | | 67 | + // The stable advisory-lock file does not resurrect the removed job dir. | 68 | 68 | if _, gerr := store.Get(job.ID); !errors.Is(gerr, ErrJobNotFound) { | 69 | 69 | t.Fatalf("job should remain removed, Get = %v", gerr) | 70 | 70 | } | |
Collapse file Copy file name to clipboardExpand all lines: internal/daemon/lock.go +35-67Lines changed: 35 additions & 67 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,107 +3,60 @@ package daemon | 3 | 3 | import ( | 4 | 4 | "errors" | 5 | 5 | "fmt" | 6 | | - "io/fs" | 7 | 6 | "os" | 8 | 7 | "strconv" | 9 | 8 | "strings" | 10 | | - "sync/atomic" | 11 | 9 |
| 12 | 10 | "github.com/Gitlawb/zero/internal/lockutil" | 13 | 11 | ) | 14 | 12 |
| 15 | | -// Single-instance lock. Mirrors reference-daemon-code-agent-js/supervisor.js's | 16 | | -// lock file: a PID file created with O_EXCL. A second start fails; a STALE lock | 17 | | -// left by a dead daemon (the recorded PID is no longer alive) is reclaimed so the | 18 | | -// daemon recovers from an unclean shutdown without manual cleanup. | | 13 | +// Single-instance lock. The stable PID file carries a kernel advisory lock for | | 14 | +// the daemon's full lifetime. Process exit releases the lock automatically, so | | 15 | +// stale metadata needs no rename/remove recovery protocol. | 19 | 16 |
| 20 | 17 | // ErrAlreadyRunning is returned when a live daemon already holds the lock. | 21 | 18 | var ErrAlreadyRunning = errors.New("daemon: another instance is already running") | 22 | 19 |
| 23 | 20 | // fileLock is an acquired single-instance lock. | 24 | 21 | type fileLock struct { | 25 | | - path string | | 22 | + lock *lockutil.FileLock | 26 | 23 | } | 27 | 24 |
| 28 | 25 | // processAlive reports whether pid is a live process. Implemented per-platform | 29 | 26 | // (lock_posix.go / lock_windows.go). It is a package var so tests can stub it. | 30 | 27 | var processAlive = osProcessAlive | 31 | 28 |
| 32 | | -// acquireLock takes the single-instance lock at path, reclaiming a stale lock | 33 | | -// whose recorded PID is dead. isAlive overrides the liveness check (tests pass a | 34 | | -// stub); nil uses the real processAlive. | | 29 | +// acquireLock takes the single-instance advisory lock at path. isAlive is used | | 30 | +// only to enrich a contention error with the current holder's PID; the kernel | | 31 | +// lock, not PID metadata, is authoritative. | 35 | 32 | func acquireLock(path string, isAlive func(pid int) bool) (*fileLock, error) { | 36 | 33 | if isAlive == nil { | 37 | 34 | isAlive = processAlive | 38 | 35 | } | 39 | | - // At most two passes: create, or detect-stale-then-retry once. | 40 | | - for attempt := 0; attempt < 2; attempt++ { | 41 | | - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) | 42 | | - if err == nil { | 43 | | - // A failed PID write would leave a malformed lock file that another | 44 | | - // process reads as stale (unparsable PID) and wrongly reclaims, breaking | 45 | | - // the single-instance guarantee — so on write failure, remove it and fail. | 46 | | - if _, werr := fmt.Fprintf(f, "%d\n", os.Getpid()); werr != nil { | 47 | | - _ = f.Close() | 48 | | - _ = lockutil.RemoveLockFile(path) | 49 | | - return nil, werr | 50 | | - } | 51 | | - if cerr := f.Close(); cerr != nil { | 52 | | - _ = lockutil.RemoveLockFile(path) | 53 | | - return nil, cerr | 54 | | - } | 55 | | - return &fileLock{path: path}, nil | 56 | | - } | 57 | | - if !errors.Is(err, fs.ErrExist) && !errors.Is(err, os.ErrPermission) { | | 36 | + lock, err := lockutil.TryAcquireFileLock(path) | | 37 | + if err != nil { | | 38 | + if !errors.Is(err, lockutil.ErrLockHeld) { | 58 | 39 | return nil, err | 59 | 40 | } | 60 | 41 | pid, perr := readPidFile(path) | 61 | 42 | if perr == nil && pid > 0 && isAlive(pid) { | 62 | 43 | return nil, fmt.Errorf("%w (pid %d)", ErrAlreadyRunning, pid) | 63 | 44 | } | 64 | | - // Stale lock (dead PID or unreadable) — reclaim it atomically, then retry the | 65 | | - // O_EXCL create. A blind Remove here races: two daemons starting at once could | 66 | | - // both read the stale PID, both Remove, and then one Removes the OTHER's | 67 | | - // freshly-created lock — leaving both "holding" the single-instance lock. | 68 | | - // reclaimStaleLock renames the file aside so only one racer wins the rename, | 69 | | - // and restores it if a live holder reacquired in the gap (D6). | 70 | | - if _, rerr := reclaimStaleLock(path, isAlive); rerr != nil { | 71 | | - // Reclaim hit a hard failure: the rename aside failed outright, or a | 72 | | - // live holder's lock could not be put back (the lock path may be | 73 | | - // missing, so re-acquiring would break the single-instance guarantee). | 74 | | - // Fail closed instead of spinning to the deadline. | 75 | | - return nil, fmt.Errorf("daemon: reclaim stale lock: %w", rerr) | 76 | | - } | | 45 | + return nil, ErrAlreadyRunning | 77 | 46 | } | 78 | | - return nil, ErrAlreadyRunning | 79 | | -} | 80 | | - | 81 | | -// daemonLockSeq makes each reclaim attempt's sidelined filename unique per process. | 82 | | -var daemonLockSeq atomic.Uint64 | 83 | | - | 84 | | -// reclaimStaleLock atomically reclaims a single-instance lock whose recorded | 85 | | -// PID is dead, via lockutil.ReclaimStaleLock: the lock file is renamed aside | 86 | | -// (only one racer can win the rename) and stolen only if the moved file's PID | 87 | | -// is still dead; a holder that reacquired the lock in the gap between the | 88 | | -// stale check and the rename carries a LIVE pid and is restored rather than | 89 | | -// stolen. Returns true only when a genuinely stale lock was removed. A | 90 | | -// non-nil error means the caller must fail closed instead of re-acquiring | 91 | | -// (see lockutil.ReclaimStaleLock). | 92 | | -func reclaimStaleLock(path string, isAlive func(pid int) bool) (bool, error) { | 93 | | - suffix := fmt.Sprintf("%d-%d", os.Getpid(), daemonLockSeq.Add(1)) | 94 | | - return lockutil.ReclaimStaleLock(path, suffix, func(reclaimedPath string) bool { | 95 | | - pid, err := readPidFile(reclaimedPath) | 96 | | - return err == nil && pid > 0 && isAlive(pid) | 97 | | - }) | | 47 | + if err := lock.WriteMetadata([]byte(fmt.Sprintf("%d\n", os.Getpid()))); err != nil { | | 48 | + return nil, errors.Join(err, lock.Release()) | | 49 | + } | | 50 | + return &fileLock{lock: lock}, nil | 98 | 51 | } | 99 | 52 |
| 100 | | -// release removes the lock file. Safe to call once. An already-missing lock | 101 | | -// file is not an error (lockutil.RemoveLockFile swallows it on every platform). | | 53 | +// release drops the kernel lock and closes its handle. The stable PID file is | | 54 | +// deliberately retained so contenders always address the same inode. | 102 | 55 | func (l *fileLock) release() error { | 103 | | - if l == nil || l.path == "" { | | 56 | + if l == nil || l.lock == nil { | 104 | 57 | return nil | 105 | 58 | } | 106 | | - return lockutil.RemoveLockFile(l.path) | | 59 | + return l.lock.Release() | 107 | 60 | } | 108 | 61 |
| 109 | 62 | // readPidFile reads and parses the PID recorded in a lock file. | @@ -112,5 +65,20 @@ func readPidFile(path string) (int, error) { | 112 | 65 | if err != nil { | 113 | 66 | return 0, err | 114 | 67 | } | 115 | | - return strconv.Atoi(strings.TrimSpace(string(data))) | | 68 | + metadata := strings.TrimSpace(string(data)) | | 69 | + if pid, err := strconv.Atoi(metadata); err == nil { | | 70 | + return pid, nil | | 71 | + } | | 72 | + pidText, sequenceText, ok := strings.Cut(metadata, "-") | | 73 | + if !ok || pidText == "" || sequenceText == "" || strings.Contains(sequenceText, "-") { | | 74 | + return 0, fmt.Errorf("daemon: parse lock PID metadata %q", metadata) | | 75 | + } | | 76 | + if _, err := strconv.ParseUint(sequenceText, 10, 64); err != nil { | | 77 | + return 0, fmt.Errorf("daemon: parse lock holder sequence: %w", err) | | 78 | + } | | 79 | + pid, err := strconv.Atoi(pidText) | | 80 | + if err != nil { | | 81 | + return 0, fmt.Errorf("daemon: parse lock PID: %w", err) | | 82 | + } | | 83 | + return pid, nil | 116 | 84 | } |
Collapse file Copy file name to clipboardExpand all lines: internal/daemon/lock_test.go +54-42Lines changed: 54 additions & 42 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -32,27 +32,48 @@ func TestLockSingleInstance(t *testing.T) { | 32 | 32 | _ = l2.release() | 33 | 33 | } | 34 | 34 |
| 35 | | -func TestLockStaleRecovery(t *testing.T) { | | 35 | +// A PID liveness probe is diagnostic only. Even if it reports the recorded PID | | 36 | +// dead, a contended kernel lock proves that the holder is active and must win. | | 37 | +// The old rename-aside protocol trusted this stale observation and admitted a | | 38 | +// second daemon while the first one was still inside its critical section. | | 39 | +func TestLockDoesNotOverrideKernelHolderWithStalePIDProbe(t *testing.T) { | 36 | 40 | path := filepath.Join(t.TempDir(), "daemon.lock") | 37 | | - // Simulate a stale lock from a crashed daemon: a PID file whose process is | 38 | | - // dead. | | 41 | + first, err := acquireLock(path, func(int) bool { return true }) | | 42 | + if err != nil { | | 43 | + t.Fatalf("first acquireLock: %v", err) | | 44 | + } | | 45 | + defer first.release() | | 46 | + | | 47 | + second, err := acquireLock(path, func(int) bool { return false }) | | 48 | + if second != nil { | | 49 | + _ = second.release() | | 50 | + } | | 51 | + if !errors.Is(err, ErrAlreadyRunning) { | | 52 | + t.Fatalf("contended acquire with stale PID probe = %v, want ErrAlreadyRunning", err) | | 53 | + } | | 54 | +} | | 55 | + | | 56 | +func TestLockIgnoresStaleMetadataWhenKernelLockIsFree(t *testing.T) { | | 57 | + path := filepath.Join(t.TempDir(), "daemon.lock") | | 58 | + // A crashed daemon may leave PID metadata behind, but its kernel lock is | | 59 | + // released automatically, so the next daemon can acquire without moving it. | 39 | 60 | if err := os.WriteFile(path, []byte("4242\n"), 0o600); err != nil { | 40 | 61 | t.Fatalf("write stale lock: %v", err) | 41 | 62 | } | 42 | 63 | dead := func(int) bool { return false } | 43 | 64 | l, err := acquireLock(path, dead) | 44 | 65 | if err != nil { | 45 | | - t.Fatalf("stale-lock recovery failed: %v", err) | | 66 | + t.Fatalf("acquire over stale metadata: %v", err) | 46 | 67 | } | 47 | 68 | // The lock now records OUR pid, not the stale one. | 48 | 69 | data, _ := os.ReadFile(path) | 49 | 70 | if strings.TrimSpace(string(data)) != strconv.Itoa(os.Getpid()) { | 50 | | - t.Fatalf("reclaimed lock pid = %q, want %d", strings.TrimSpace(string(data)), os.Getpid()) | | 71 | + t.Fatalf("lock pid = %q, want %d", strings.TrimSpace(string(data)), os.Getpid()) | 51 | 72 | } | 52 | 73 | _ = l.release() | 53 | 74 | } | 54 | 75 |
| 55 | | -func TestLockReleaseRemovesFile(t *testing.T) { | | 76 | +func TestLockReleaseKeepsStableFile(t *testing.T) { | 56 | 77 | path := filepath.Join(t.TempDir(), "daemon.lock") | 57 | 78 | l, err := acquireLock(path, func(int) bool { return true }) | 58 | 79 | if err != nil { | @@ -61,46 +82,37 @@ func TestLockReleaseRemovesFile(t *testing.T) { | 61 | 82 | if err := l.release(); err != nil { | 62 | 83 | t.Fatalf("release: %v", err) | 63 | 84 | } | 64 | | - if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { | 65 | | - t.Fatalf("lock file still present after release: %v", err) | | 85 | + if _, err := os.Stat(path); err != nil { | | 86 | + t.Fatalf("release removed stable lock file: %v", err) | 66 | 87 | } | 67 | 88 | } | 68 | 89 |
| 69 | | -func TestReclaimStaleLockRemovesDeadHolder(t *testing.T) { | | 90 | +func TestReadPidFileMetadataFormats(t *testing.T) { | 70 | 91 | path := filepath.Join(t.TempDir(), "daemon.lock") | 71 | | - if err := os.WriteFile(path, []byte("4242\n"), 0o600); err != nil { | 72 | | - t.Fatalf("write stale lock: %v", err) | 73 | | - } | 74 | | - if ok, err := reclaimStaleLock(path, func(int) bool { return false }); err != nil || !ok { | 75 | | - t.Fatalf("reclaimStaleLock must report a genuinely stale (dead-PID) lock reclaimed (ok=%v err=%v)", ok, err) | 76 | | - } | 77 | | - if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { | 78 | | - t.Fatalf("a reclaimed stale lock must be removed, stat = %v", err) | 79 | | - } | 80 | | -} | 81 | | - | 82 | | -func TestReclaimStaleLockRestoresLiveHolder(t *testing.T) { | 83 | | - // If a holder reacquires the lock in the gap between the stale check and the | 84 | | - // rename, the moved file carries a LIVE pid; reclaim must restore it untouched | 85 | | - // rather than steal it — otherwise two daemons both "hold" the lock (D6). | 86 | | - path := filepath.Join(t.TempDir(), "daemon.lock") | 87 | | - if err := os.WriteFile(path, []byte("4242\n"), 0o600); err != nil { | 88 | | - t.Fatalf("write lock: %v", err) | 89 | | - } | 90 | | - if ok, err := reclaimStaleLock(path, func(int) bool { return true }); err != nil || ok { | 91 | | - t.Fatalf("reclaimStaleLock must NOT report a live-PID lock reclaimed (ok=%v err=%v)", ok, err) | 92 | | - } | 93 | | - data, err := os.ReadFile(path) | 94 | | - if err != nil { | 95 | | - t.Fatalf("live lock must be restored in place, read = %v", err) | 96 | | - } | 97 | | - if strings.TrimSpace(string(data)) != "4242" { | 98 | | - t.Fatalf("restored lock content = %q, want %q (unchanged)", strings.TrimSpace(string(data)), "4242") | 99 | | - } | 100 | | - // No sidelined ".stale" leftovers. | 101 | | - matches, _ := filepath.Glob(path + ".stale.*") | 102 | | - if len(matches) != 0 { | 103 | | - t.Fatalf("reclaim left sidelined files: %v", matches) | | 92 | + for _, test := range []struct { | | 93 | + name string | | 94 | + metadata string | | 95 | + wantPID int | | 96 | + wantErr bool | | 97 | + }{ | | 98 | + {name: "legacy PID", metadata: "4242\n", wantPID: 4242}, | | 99 | + {name: "PID and holder sequence", metadata: "4242-7\n", wantPID: 4242}, | | 100 | + {name: "missing sequence", metadata: "4242-", wantErr: true}, | | 101 | + {name: "non-numeric sequence", metadata: "4242-next", wantErr: true}, | | 102 | + {name: "extra component", metadata: "4242-7-8", wantErr: true}, | | 103 | + } { | | 104 | + t.Run(test.name, func(t *testing.T) { | | 105 | + if err := os.WriteFile(path, []byte(test.metadata), 0o600); err != nil { | | 106 | + t.Fatal(err) | | 107 | + } | | 108 | + got, err := readPidFile(path) | | 109 | + if (err != nil) != test.wantErr { | | 110 | + t.Fatalf("readPidFile() error = %v, wantErr %v", err, test.wantErr) | | 111 | + } | | 112 | + if !test.wantErr && got != test.wantPID { | | 113 | + t.Fatalf("readPidFile() = %d, want %d", got, test.wantPID) | | 114 | + } | | 115 | + }) | 104 | 116 | } | 105 | 117 | } | 106 | 118 |
| |
|