Skip to content

Commit 09d1319

Browse files
author
dipto0321
committed
fix(platform): split lock.go into per-platform files
The monolithic internal/platform/lock.go used syscall.Flock, syscall.LOCK_EX, and syscall.LOCK_NB unconditionally, none of which exist in the syscall package on Windows. Cross-compiling for the windows-latest CI runner produced: internal\platform\lock.go:62:77: undefined: syscall.Flock internal\platform\lock.go:62:104: undefined: syscall.LOCK_EX internal\platform\lock.go:62:120: undefined: syscall.LOCK_NB internal\platform\lock.go:86:71: undefined: syscall.Flock internal\platform\lock.go:86:100: undefined: syscall.LOCK_UN Restructure into build-tagged files: - lock_unix.go (//go:build !windows) — keeps syscall.Flock + LOCK_EX / LOCK_NB / LOCK_UN. Same semantics as before. - lock_windows.go (//go:build windows) — uses kernel32 LockFileEx / UnlockFileEx via syscall.Syscall6 with the standard nargs-plus- trailing-zero pattern (mirrors syscall.setFilePointerEx in stdlib). ERROR_LOCK_VIOLATION is mapped to ErrAlreadyLocked so concurrent-run detection works identically on every OS. - lock_common.go — shared bytesTrimSpace + isSpace helpers, plus a focused unit test in lock_common_test.go. - registry_windows.go — fix the carry-over "return m, nil" typo from Phase 0 (should be m, true). Verified locally: GOOS=windows GOARCH=amd64 go build ./... # OK GOOS=windows GOARCH=arm64 go build ./... # OK GOOS=windows GOARCH=amd64 go vet ./... # clean go test ./... # 14 tests pass
1 parent 4f2258d commit 09d1319

6 files changed

Lines changed: 366 additions & 159 deletions

File tree

‎internal/detector/registry_windows.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func All() []Manager {
4848
func ByName(name string) (Manager, bool) {
4949
for _, m := range All() {
5050
if m.Name() == name {
51-
return m, nil
51+
return m, true
5252
}
5353
}
5454
return nil, false

‎internal/platform/lock.go‎

Lines changed: 0 additions & 158 deletions
This file was deleted.

‎internal/platform/lock_common.go‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package platform
2+
3+
import "path/filepath"
4+
5+
// bytesTrimSpace is a tiny helper to avoid importing bytes for one call.
6+
func bytesTrimSpace(b []byte) []byte {
7+
start, end := 0, len(b)
8+
for start < end && isSpace(b[start]) {
9+
start++
10+
}
11+
for end > start && isSpace(b[end-1]) {
12+
end--
13+
}
14+
return b[start:end]
15+
}
16+
17+
func isSpace(c byte) bool {
18+
return c == ' ' || c == '\t' || c == '\n' || c == '\r'
19+
}
20+
21+
// silenceGoUnused checks that filepath.Separator is referenced (used by
22+
// platform.go's filepath.Join calls). Keeping this comment + var alive
23+
// satisfies linters without affecting runtime behavior.
24+
var _ = filepath.Separator
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package platform
2+
3+
import (
4+
"bytes"
5+
"testing"
6+
)
7+
8+
// TestBytesTrimSpace is a parametric test for the trim helper shared by
9+
// the unix and windows lock implementations. Guards against accidental
10+
// regressions in whitespace handling — critical because lockfile contents
11+
// are integer-only and any leading newline would parse as zero.
12+
func TestBytesTrimSpace(t *testing.T) {
13+
cases := []struct {
14+
name string
15+
in []byte
16+
want []byte
17+
}{
18+
{"nil", nil, nil},
19+
{"empty", []byte{}, []byte{}},
20+
{"plain", []byte("12345"), []byte("12345")},
21+
{"leading spaces", []byte(" \t12345"), []byte("12345")},
22+
{"trailing newline", []byte("12345\n\r\n"), []byte("12345")},
23+
{"mixed", []byte("\t 12345 \n"), []byte("12345")},
24+
{"only whitespace", []byte(" \t\n"), []byte{}},
25+
}
26+
for _, tc := range cases {
27+
t.Run(tc.name, func(t *testing.T) {
28+
got := bytesTrimSpace(tc.in)
29+
if !bytes.Equal(got, tc.want) {
30+
t.Errorf("bytesTrimSpace(%q) = %q, want %q", tc.in, got, tc.want)
31+
}
32+
})
33+
}
34+
}

‎internal/platform/lock_unix.go‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
//go:build !windows
2+
3+
package platform
4+
5+
import (
6+
"errors"
7+
"fmt"
8+
"os"
9+
"strconv"
10+
"syscall"
11+
)
12+
13+
// LockFile is an advisory lock acquired by AcquireLock. Multiple processes
14+
// (e.g., two `nodeup upgrade` invocations) are prevented from mutating
15+
// the same Node installation concurrently.
16+
//
17+
// On linux/darwin we use the BSD flock(2) syscall: each process takes an
18+
// exclusive, non-blocking lock on the lock file; subsequent attempts return
19+
// ErrAlreadyLocked immediately.
20+
//
21+
// Lifecycle:
22+
//
23+
// lock, err := platform.AcquireLock()
24+
// if err != nil { ... }
25+
// defer lock.Release()
26+
type LockFile struct {
27+
path string
28+
f *os.File
29+
}
30+
31+
// ErrAlreadyLocked is returned when another nodeup process holds the lock.
32+
var ErrAlreadyLocked = errors.New("nodeup is already running")
33+
34+
// AcquireLock takes the nodeup lock at LockPath(). If another instance
35+
// already holds it, returns ErrAlreadyLocked wrapped with the PID of the
36+
// holder (read from the lock file contents). Stale lock files from dead
37+
// processes are removed first.
38+
func AcquireLock() (*LockFile, error) {
39+
lockPath, err := LockPath()
40+
if err != nil {
41+
return nil, err
42+
}
43+
44+
if existing, perr := readLockPID(lockPath); perr == nil {
45+
if !processAlive(existing) {
46+
_ = os.Remove(lockPath)
47+
} else {
48+
return nil, fmt.Errorf("%w: PID %d", ErrAlreadyLocked, existing)
49+
}
50+
}
51+
52+
f, err := os.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0o600)
53+
if err != nil {
54+
return nil, fmt.Errorf("create lock file: %w", err)
55+
}
56+
57+
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
58+
_ = f.Close()
59+
return nil, fmt.Errorf("%w (flock failed: %v)", ErrAlreadyLocked, err)
60+
}
61+
62+
if err := f.Truncate(0); err != nil {
63+
_ = f.Close()
64+
return nil, err
65+
}
66+
if _, err := f.WriteString(strconv.Itoa(os.Getpid())); err != nil {
67+
_ = f.Close()
68+
return nil, err
69+
}
70+
71+
return &LockFile{path: lockPath, f: f}, nil
72+
}
73+
74+
// Release unlocks and removes the lock file. Safe to call multiple times.
75+
func (l *LockFile) Release() error {
76+
if l == nil || l.f == nil {
77+
return nil
78+
}
79+
_ = syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
80+
cerr := l.f.Close()
81+
l.f = nil
82+
if rerr := os.Remove(l.path); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
83+
return rerr
84+
}
85+
return cerr
86+
}
87+
88+
// readLockPID reads the PID stored inside an existing lock file. Used to
89+
// detect and recover from locks left by crashed nodeup processes.
90+
func readLockPID(path string) (int, error) {
91+
b, err := os.ReadFile(path)
92+
if err != nil {
93+
return 0, err
94+
}
95+
pid, err := strconv.Atoi(string(bytesTrimSpace(b)))
96+
if err != nil {
97+
return 0, err
98+
}
99+
return pid, nil
100+
}
101+
102+
// processAlive sends signal 0 to pid and returns whether the process
103+
// accepted it. Signal 0 is the canonical "is this PID alive?" probe on
104+
// POSIX systems — it doesn't deliver anything but errors on ESRCH.
105+
func processAlive(pid int) bool {
106+
proc, err := os.FindProcess(pid)
107+
if err != nil {
108+
return false
109+
}
110+
if err := proc.Signal(syscall.Signal(0)); err == nil {
111+
return true
112+
}
113+
return false
114+
}

0 commit comments

Comments
 (0)