GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(lockutil): use kernel-held advisory locks (#950) · Twigpine/zero@6fe0d1e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal
    • cron
      • lock.go
      • mutate_test.go
    • daemon
      • lock.go
      • lock_test.go
      • server_test.go
    • hooks
      • lock.go
    • lockutil
      • lockutil.go
      • lockutil_other.go
      • lockutil_test.go
      • lockutil_windows.go
      • lockutil_windows_test.go
      • reclaim.go
      • reclaim_other_test.go
      • reclaim_test.go
      • reclaim_windows_test.go
    • oauth
      • lock.go
    • swarm
      • lock_other.go
      • lock_redirect_other_test.go
      • lock_redirect_windows_test.go
      • lock_windows.go
      • mailbox.go
      • mailbox_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/cron/lock.go‎

Copy file name to clipboardExpand all lines: internal/cron/lock.go
+9-66Lines changed: 9 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,23 @@ import (
55
"fmt"
66
"os"
77
"path/filepath"
8-
"sync/atomic"
98
"time"
109

1110
"github.com/Gitlawb/zero/internal/lockutil"
1211
)
1312

1413
// 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.
1716
const (
1817
cronLockTimeout = 10 * time.Second
19-
cronLockStaleAfter = 60 * time.Second
2018
cronLockRetryDelay = 20 * time.Millisecond
2119
)
2220

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.
3325
func (s *Store) lockJob(id string) (func(), error) {
3426
if !validID(id) {
3527
return nil, fmt.Errorf("invalid cron job id %q", id)
@@ -38,64 +30,15 @@ func (s *Store) lockJob(id string) (func(), error) {
3830
if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
3931
return nil, err
4032
}
41-
token := fmt.Sprintf("%d-%d-%d", os.Getpid(), time.Now().UnixNano(), cronLockSeq.Add(1))
4233
deadline := time.Now().Add(cronLockTimeout)
4334
for {
44-
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
35+
lock, err := lockutil.TryAcquireFileLock(lockPath)
4536
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
6738
}
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) {
7440
return nil, fmt.Errorf("cron: acquire job lock: %w", err)
7541
}
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-
}
9942
if !time.Now().Before(deadline) {
10043
return nil, fmt.Errorf("cron: timed out acquiring job lock for %q", id)
10144
}
Collapse file

‎internal/cron/mutate_test.go‎

Copy file name to clipboardExpand all lines: internal/cron/mutate_test.go
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func TestMutateRemovedJobReturnsNotFound(t *testing.T) {
6464
if !errors.Is(err, ErrJobNotFound) {
6565
t.Fatalf("Mutate on removed job = %v, want ErrJobNotFound", err)
6666
}
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.
6868
if _, gerr := store.Get(job.ID); !errors.Is(gerr, ErrJobNotFound) {
6969
t.Fatalf("job should remain removed, Get = %v", gerr)
7070
}
Collapse file

‎internal/daemon/lock.go‎

Copy file name to clipboardExpand all lines: internal/daemon/lock.go
+35-67Lines changed: 35 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,107 +3,60 @@ package daemon
33
import (
44
"errors"
55
"fmt"
6-
"io/fs"
76
"os"
87
"strconv"
98
"strings"
10-
"sync/atomic"
119

1210
"github.com/Gitlawb/zero/internal/lockutil"
1311
)
1412

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.
1916

2017
// ErrAlreadyRunning is returned when a live daemon already holds the lock.
2118
var ErrAlreadyRunning = errors.New("daemon: another instance is already running")
2219

2320
// fileLock is an acquired single-instance lock.
2421
type fileLock struct {
25-
path string
22+
lock *lockutil.FileLock
2623
}
2724

2825
// processAlive reports whether pid is a live process. Implemented per-platform
2926
// (lock_posix.go / lock_windows.go). It is a package var so tests can stub it.
3027
var processAlive = osProcessAlive
3128

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.
3532
func acquireLock(path string, isAlive func(pid int) bool) (*fileLock, error) {
3633
if isAlive == nil {
3734
isAlive = processAlive
3835
}
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) {
5839
return nil, err
5940
}
6041
pid, perr := readPidFile(path)
6142
if perr == nil && pid > 0 && isAlive(pid) {
6243
return nil, fmt.Errorf("%w (pid %d)", ErrAlreadyRunning, pid)
6344
}
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
7746
}
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
9851
}
9952

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.
10255
func (l *fileLock) release() error {
103-
if l == nil || l.path == "" {
56+
if l == nil || l.lock == nil {
10457
return nil
10558
}
106-
return lockutil.RemoveLockFile(l.path)
59+
return l.lock.Release()
10760
}
10861

10962
// readPidFile reads and parses the PID recorded in a lock file.
@@ -112,5 +65,20 @@ func readPidFile(path string) (int, error) {
11265
if err != nil {
11366
return 0, err
11467
}
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
11684
}
Collapse file

‎internal/daemon/lock_test.go‎

Copy file name to clipboardExpand all lines: internal/daemon/lock_test.go
+54-42Lines changed: 54 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -32,27 +32,48 @@ func TestLockSingleInstance(t *testing.T) {
3232
_ = l2.release()
3333
}
3434

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) {
3640
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.
3960
if err := os.WriteFile(path, []byte("4242\n"), 0o600); err != nil {
4061
t.Fatalf("write stale lock: %v", err)
4162
}
4263
dead := func(int) bool { return false }
4364
l, err := acquireLock(path, dead)
4465
if err != nil {
45-
t.Fatalf("stale-lock recovery failed: %v", err)
66+
t.Fatalf("acquire over stale metadata: %v", err)
4667
}
4768
// The lock now records OUR pid, not the stale one.
4869
data, _ := os.ReadFile(path)
4970
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())
5172
}
5273
_ = l.release()
5374
}
5475

55-
func TestLockReleaseRemovesFile(t *testing.T) {
76+
func TestLockReleaseKeepsStableFile(t *testing.T) {
5677
path := filepath.Join(t.TempDir(), "daemon.lock")
5778
l, err := acquireLock(path, func(int) bool { return true })
5879
if err != nil {
@@ -61,46 +82,37 @@ func TestLockReleaseRemovesFile(t *testing.T) {
6182
if err := l.release(); err != nil {
6283
t.Fatalf("release: %v", err)
6384
}
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)
6687
}
6788
}
6889

69-
func TestReclaimStaleLockRemovesDeadHolder(t *testing.T) {
90+
func TestReadPidFileMetadataFormats(t *testing.T) {
7091
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+
})
104116
}
105117
}
106118

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.