Files
w3cjandClaude Opus 5.5 2de3e31a6c fix(vm): devvm ports shows a status line as it restarts a running VM's forwarder, and every lock's wait is tested for its label
Lock waits:
- Tests record the label of each lock's wait that had none, the lock held
  as by another devvm and the wait ended by a cancel, a deadline failing
  one that shows nothing rather than hanging: git_lock_waiting
  (TestGitLockWaits; .git protection's Serial is gitSerial, so a test can
  reach it), packages_waiting and rebuilds_waiting (TestImageLocksWait),
  ubuntu_pin_waiting (TestPinOriginWaits), custom_secrets_waiting
  (TestYoursLockWaits) and forwarder_waiting (TestForwardsLockWaits).
- A test build's locks panic on a nil platform.Waiting
  (platform.CheckWaiting, which the root's run calls in every test build
  beside state.CheckLockOrder), so the CLI tests and e2e catch a nil wait
  the structure test can't see, such as a zero agentlogin.File's; a
  msg.Waiting given a nil status shows nothing and stays review only.
  msg.Waiting with no status gives a wait that shows nothing, never nil;
  platform.NoWait is the Waiting of a lock that never waits (the build
  port's record, which passed nil), and the status-lines rule holds it to
  statusSites as it does nil (TestCheckWaiting, TestWaiting, the rule's
  NoWait case).
- forbidigo refuses syscall.Flock and unix.Flock outside internal/platform,
  internal/proxy/rotate.go, the stubs and tests (testdata/lint, both).
- TestLockFileWaiting runs in a synctest bubble and checks the wait shows
  while held, not before (its counters under a mutex, which the race
  detector needs, as only the file's lock orders them).

Status lines:
- TestCommandStatusLines runs the setters too: devvm ports LIST and ports
  add, size --cpus, network open, allowlist, transparent off and on, learn
  and allow, git-protect off and on, ssh-agent off. It found devvm ports on
  a running VM starting its forwarder again (ssh and a command in the VM)
  with no status line; that step now shows ports_restarting.

The folder named twice:
- vm_folder_unreadable's why was the open's error, the folder's path in
  it; folderUnreadable gives the system's reason alone when the error is
  about the folder itself (TestUnreadableFolder checks the whole message).
- platform.OpenNoLinks and StatFolder return a link on the path as an
  fs.PathError about the folder too (ErrLinkOnPath still matches), so that
  case names it once as well (TestStatFolderUnique).

Docs: Contributing's CLI page (status lines) and structure page, the
codebase-standards guards; CHANGELOG (devvm ports' status line).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 17:04:29 -07:00

363 lines
10 KiB
Go

//go:build unix
package platform
import (
"bufio"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"sync"
"syscall"
"testing"
"testing/synctest"
"time"
)
// A file's lock is held by one at a time: another waits for it until its
// context ends, and gets it once it's let go.
func TestLockFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
unlock, err := LockFile(t.Context(), path, nil)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond)
defer cancel()
if _, err := LockFile(ctx, path, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("held twice: %v", err)
}
got := make(chan error, 1)
go func() {
u, err := LockFile(t.Context(), path, nil)
if err == nil {
u()
}
got <- err
}()
time.Sleep(100 * time.Millisecond)
unlock()
select {
case err := <-got:
if err != nil {
t.Errorf("once let go: %v", err)
}
case <-time.After(2 * time.Second):
t.Error("not got once let go")
}
if _, err := LockFile(t.Context(), filepath.Join(t.TempDir(), "no", "x.lock"), nil); err == nil {
t.Error("a lock in a missing folder: no error")
}
}
// A lock's waiting is called once, only when another holds the lock, and
// what it returned once the wait ends, with the lock got or given up; a
// free lock calls neither, shared or not.
func TestLockFileWaiting(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
var waitMu sync.Mutex
waits, ends := 0, 0
waiting := func() func() {
waitMu.Lock()
defer waitMu.Unlock()
waits++
return func() { waitMu.Lock(); ends++; waitMu.Unlock() }
}
unlock, err := LockFile(t.Context(), path, waiting)
if err != nil || waits != 0 || ends != 0 {
t.Fatalf("a free lock: %v, waits %d, ends %d", err, waits, ends)
}
for _, shared := range []bool{false, true} {
waits, ends = 0, 0
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
lock := LockFile
if shared {
lock = LockFileShared
}
if _, err := lock(ctx, path, waiting); !errors.Is(err, context.DeadlineExceeded) || waits != 1 || ends != 1 {
t.Errorf("held, shared %v: %v, waits %d, ends %d", shared, err, waits, ends)
}
cancel()
}
// Got once let go: the wait ends then, not before.
waits, ends = 0, 0
got := make(chan error, 1)
go func() {
u, err := LockFile(t.Context(), path, waiting)
if err == nil {
u()
}
got <- err
}()
synctest.Wait()
// Only the file's lock, which the race detector can't see, orders this read before the
// goroutine's end, so both go through waitMu.
waitMu.Lock()
w, e := waits, ends
waitMu.Unlock()
if w != 1 || e != 0 {
t.Errorf("waiting: waits %d, ends %d", w, e)
}
unlock()
if err := <-got; err != nil || ends != 1 {
t.Errorf("got once let go: %v, ends %d", err, ends)
}
waits = 0
shared, err := LockFileShared(t.Context(), path, waiting)
if err != nil || waits != 0 {
t.Errorf("a free shared lock: %v, waits %d", err, waits)
} else {
shared()
}
})
}
// A folder's lock is held by one at a time, as a file's is: another waits
// for it, showing its wait once, until its context ends, a deadline or a
// cancel, and gets it once it's let go. It's the lock a plain flock of the
// folder takes, as an older devvm's proxy takes it. A folder that isn't
// there isn't made.
func TestLockDir(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
unlock, err := LockDir(t.Context(), dir, nil)
if err != nil {
t.Fatal(err)
}
waits, ends := 0, 0
waiting := func() func() {
waits++
return func() { ends++ }
}
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
if _, err := LockDir(ctx, dir, waiting); !errors.Is(err, context.DeadlineExceeded) || waits != 1 || ends != 1 {
t.Errorf("held, to a deadline: %v, waits %d, ends %d", err, waits, ends)
}
cancel()
ctx, cancel = context.WithCancel(t.Context())
got := make(chan error, 1)
go func() {
_, err := LockDir(ctx, dir, nil)
got <- err
}()
synctest.Wait()
cancel()
if err := <-got; !errors.Is(err, context.Canceled) {
t.Errorf("held, cancelled: %v", err)
}
go func() {
u, err := LockDir(t.Context(), dir, nil)
if err == nil {
u()
}
got <- err
}()
synctest.Wait()
unlock()
if err := <-got; err != nil {
t.Errorf("once let go: %v", err)
}
d, err := os.Open(dir) //nolint:gosec // G304: the test's own temp folder
if err != nil {
t.Fatal(err)
}
defer func() { _ = d.Close() }()
if err := syscall.Flock(int(d.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
t.Fatal(err)
}
ctx, cancel = context.WithTimeout(t.Context(), time.Minute)
defer cancel()
if _, err := LockDir(ctx, dir, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("held by a plain flock: %v", err)
}
missing := filepath.Join(dir, "no")
if _, err := LockDir(t.Context(), missing, nil); !errors.Is(err, os.ErrNotExist) {
t.Errorf("a missing folder: %v", err)
}
if _, err := os.Stat(missing); err == nil {
t.Error("LockDir made the folder")
}
})
}
// Once CheckWaiting runs, as in a test build, a lock taken with a nil
// Waiting panics, a file's and a folder's, before it takes the lock; NoWait
// and a Waiting of a status line pass. Before it, nil passes, as in the
// tests' own locks.
func TestCheckWaiting(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "x.lock")
t.Cleanup(func() { waitingChecked.Store(false) })
panics := func(f func() (func(), error)) (p any) {
defer func() { p = recover() }()
if unlock, err := f(); err == nil {
unlock()
}
return nil
}
nilFile := func() (func(), error) { return LockFile(t.Context(), path, nil) }
if p := panics(nilFile); p != nil {
t.Errorf("unchecked, nil: %v", p)
}
CheckWaiting()
for name, f := range map[string]func() (func(), error){
"a file's": nilFile,
"a shared": func() (func(), error) { return LockFileShared(t.Context(), path, nil) },
"a folder's": func() (func(), error) { return LockDir(t.Context(), dir, nil) },
} {
if p := panics(f); p == nil {
t.Errorf("checked, %s with nil: no panic", name)
}
}
shown := func() func() { return func() {} }
for name, w := range map[string]Waiting{"NoWait": NoWait, "a status line": shown} {
if p := panics(func() (func(), error) { return LockFile(t.Context(), path, w) }); p != nil {
t.Errorf("checked, %s: %v", name, p)
}
}
}
// A holder may remove the lock file before it lets go: one waiting for
// the removed file takes the lock on the new one, so two never hold it.
func TestLockFileRemoved(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
unlock, err := LockFile(t.Context(), path, nil)
if err != nil {
t.Fatal(err)
}
got := make(chan func(), 1)
go func() {
u, err := LockFile(t.Context(), path, nil)
if err != nil {
t.Error(err)
}
got <- u
}()
time.Sleep(100 * time.Millisecond) // it has opened the file, and waits
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
unlock()
u := <-got
if _, ok, err := TryLockFile(path); ok || err != nil {
t.Errorf("tried while the waiter holds the new file: ok %v, %v", ok, err)
}
u()
}
// LockHeld tells an exclusive lock another holds, and takes none.
func TestLockHeld(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
if held, err := LockHeld(path); held || err != nil {
t.Errorf("no file: %v, %v", held, err)
}
if _, err := os.Stat(path); err == nil {
t.Error("LockHeld made the file")
}
unlock, err := LockFile(t.Context(), path, nil)
if err != nil {
t.Fatal(err)
}
if held, err := LockHeld(path); !held || err != nil {
t.Errorf("held: %v, %v", held, err)
}
unlock()
if held, err := LockHeld(path); held || err != nil {
t.Errorf("let go: %v, %v", held, err)
}
if unlock, ok, err := TryLockFile(path); !ok || err != nil {
t.Errorf("after LockHeld: ok %v, %v", ok, err)
} else {
unlock()
}
}
// A shared lock is held by any number at once; TryLockFile doesn't get
// the lock while any holds it, and gets it once all let go, keeping
// shared ones out meanwhile.
func TestLockFileShared(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
one, err := LockFileShared(t.Context(), path, nil)
if err != nil {
t.Fatal(err)
}
two, err := LockFileShared(t.Context(), path, nil)
if err != nil {
t.Fatalf("a second shared lock: %v", err)
}
if _, ok, err := TryLockFile(path); ok || err != nil {
t.Errorf("tried while two held: ok %v, %v", ok, err)
}
one()
if _, ok, err := TryLockFile(path); ok || err != nil {
t.Errorf("tried while one held: ok %v, %v", ok, err)
}
two()
unlock, ok, err := TryLockFile(path)
if !ok || err != nil {
t.Fatalf("tried once let go: ok %v, %v", ok, err)
}
ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond)
defer cancel()
if _, err := LockFileShared(ctx, path, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("shared while tried: %v", err)
}
unlock()
if _, _, err := TryLockFile(filepath.Join(t.TempDir(), "no", "x.lock")); err == nil {
t.Error("a lock in a missing folder: no error")
}
}
// lockHelper is set in the environment of the test binary run as
// TestLockHolder: the lock file it holds.
const lockHelper = "DEVVM_TEST_LOCK_HOLDER"
// TestLockHolder is a process that holds a shared lock until it's killed,
// when run by TestLockFileKilled.
func TestLockHolder(t *testing.T) {
path := os.Getenv(lockHelper)
if path == "" {
t.Skip("run by TestLockFileKilled")
}
if _, err := LockFileShared(t.Context(), path, nil); err != nil {
t.Fatal(err)
}
if _, err := os.Stdout.WriteString("held\n"); err != nil { //nolint:forbidigo // the helper process tells its parent
t.Fatal(err)
}
time.Sleep(time.Minute)
}
// A process killed while holding a shared lock lets go of it.
func TestLockFileKilled(t *testing.T) {
path := filepath.Join(t.TempDir(), "x.lock")
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestLockHolder$") //nolint:gosec // the test binary itself
cmd.Env = append(os.Environ(), lockHelper+"="+path)
out, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
line, err := bufio.NewReader(out).ReadString('\n')
if err != nil || line != "held\n" {
t.Fatalf("helper: %q, %v", line, err)
}
if _, ok, _ := TryLockFile(path); ok {
t.Error("got while the helper held it")
}
if err := cmd.Process.Kill(); err != nil {
t.Fatal(err)
}
_ = cmd.Wait()
unlock, ok, err := TryLockFile(path)
if !ok || err != nil {
t.Fatalf("once the helper was killed: ok %v, %v", ok, err)
}
unlock()
}