diff --git a/.agents/skills/codebase-standards/rules.md b/.agents/skills/codebase-standards/rules.md index a8a99b2f..9055aafb 100644 --- a/.agents/skills/codebase-standards/rules.md +++ b/.agents/skills/codebase-standards/rules.md @@ -54,7 +54,7 @@ These rules are written in [AGENTS.md](../../../AGENTS.md) and the [Contributing | Every message is in `locales/en.toml`, called through its generated function, with its doc link | [Messages](../../../docs/content/docs/contributing/cli.md#messages) | `TestGeneratedFileIsCurrent`, `TestEveryMessageRenders`, `TestEveryMessageIsUsed` and `TestDocLinks` | | Prose is never built with `fmt` | [Messages](../../../docs/content/docs/contributing/cli.md#messages) | review only | | Every question declares what answers it | [Questions](../../../docs/content/docs/contributing/cli.md#questions) | `TestQuestionsDeclareAnswers` | -| Slow work runs under a status line, a `Status` with a label message or a `LoggedCmd` step, and none spans work that takes the terminal | [Status lines](../../../docs/content/docs/contributing/cli.md#status-lines) | the structure test's `status-lines` (`statusSites`), a lock's wait included, `TestLaunchStatusLines` and `TestCommandStatusLines` for the backend's calls, `TestVMLockWaits` and `TestCheckLayoutWaits` for the state's locks, `TestSSHAddOffStatusLine` for `ssh-add`, and `TestMessagesClearTheStatusLine`, `TestQuestionsHoldTheStatusLine`, `TestSecretAndPickerHoldTheStatusLine`, `TestTerminalHoldsTheStatusLine` and `TestStatusLinesNest` for the UI, while a caller's status line that `statusSites` names, a backend's methods in a command the tests don't run, and a wait's label are review only | +| Slow work runs under a status line, a `Status` with a label message or a `LoggedCmd` step, and none spans work that takes the terminal | [Status lines](../../../docs/content/docs/contributing/cli.md#status-lines) | the structure test's `status-lines` (`statusSites`), a lock's wait included, a test build's panic on a `nil` `Waiting` (`platform.CheckWaiting`), forbidigo's `syscall.Flock` rule, `TestLaunchStatusLines` and `TestCommandStatusLines` for the backend's calls, `TestVMLockWaits` and `TestCheckLayoutWaits` for the state's locks, `TestSSHAddOffStatusLine` for `ssh-add`, and `TestMessagesClearTheStatusLine`, `TestQuestionsHoldTheStatusLine`, `TestSecretAndPickerHoldTheStatusLine`, `TestTerminalHoldsTheStatusLine` and `TestStatusLinesNest` for the UI, while a caller's status line that `statusSites` names, a backend's methods in a command the tests don't run, and a wait's label are review only | | Tests check which message and with what, never its wording | [Names mode](../../../docs/content/docs/contributing/cli.md#names-mode) | the CLI tests run in names mode unless a script turns it off, while a Go test is review only | | Messages follow the docs voice, only shorter | [the docs-voice skill's Messages](../docs-voice/SKILL.md#messages) | review only, with its `scan.sh` | diff --git a/.agents/skills/codebase-standards/standards.md b/.agents/skills/codebase-standards/standards.md index 2f6880c0..69b97387 100644 --- a/.agents/skills/codebase-standards/standards.md +++ b/.agents/skills/codebase-standards/standards.md @@ -159,7 +159,7 @@ im.Opencode = func(context.Context, ...string) ([]byte, error) { } ``` -**Guard:** the structure test's `status-lines` rule fails on a function that makes a host command, runs host git, walks a folder, looks up a volume, makes a request through `internal/fetch`, waits for a lock whose `platform.Waiting` is `nil`, which shows nothing while another devvm holds it, or runs a backend's command outside a step with no status line of its own, unless `statusSites` lists it with why, such as the caller's status line it runs under. `TestLaunchStatusLines` fails on a backend call that a launch makes with no status line showing, `TestCommandStatusLines` on one that the other commands on a VM make, `TestVMLockWaits` and `TestCheckLayoutWaits` on a wait for the state's locks with none, `TestSSHAddOffStatusLine` on an `ssh-add` under one, and `TestMessagesClearTheStatusLine`, `TestQuestionsHoldTheStatusLine`, `TestSecretAndPickerHoldTheStatusLine`, `TestTerminalHoldsTheStatusLine` and `TestStatusLinesNest` keep the status line off what devvm says and asks. That a caller's status line covers a listed call, a backend's methods in a command the tests don't run, and a wait's label are review only. +**Guard:** the structure test's `status-lines` rule fails on a function that makes a host command, runs host git, walks a folder, looks up a volume, makes a request through `internal/fetch`, waits for a lock whose `platform.Waiting` is `nil` or `platform.NoWait`, which show nothing while another devvm holds it, or runs a backend's command outside a step with no status line of its own, unless `statusSites` lists it with why, such as the caller's status line it runs under. A test build's locks panic on a `nil` `Waiting` at run time (`platform.CheckWaiting`), and forbidigo refuses a raw `syscall.Flock` outside `internal/platform`. `TestLaunchStatusLines` fails on a backend call that a launch makes with no status line showing, `TestCommandStatusLines` on one that the other commands on a VM make, its setters included, `TestVMLockWaits`, `TestCheckLayoutWaits` and each lock's own test, such as `TestGitLockWaits`, `TestImageLocksWait`, `TestPinOriginWaits`, `TestYoursLockWaits` and `TestForwardsLockWaits`, on a wait with no label or the wrong one, `TestSSHAddOffStatusLine` on an `ssh-add` under one, and `TestMessagesClearTheStatusLine`, `TestQuestionsHoldTheStatusLine`, `TestSecretAndPickerHoldTheStatusLine`, `TestTerminalHoldsTheStatusLine` and `TestStatusLinesNest` keep the status line off what devvm says and asks. That a caller's status line covers a listed call, a backend's methods in a command the tests don't run, and a wait's label are review only. ## Extend the owner, and wait for a third copy diff --git a/.golangci.yml b/.golangci.yml index 94c2b1db..71f0db67 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -145,6 +145,8 @@ linters: msg: change a file through what opened it (os.File's Chmod, Chown and Truncate, or an os.Root's methods), never by its path, which a VM can swap for a link between the open and the change; a path only devvm writes, such as a socket it just made, says why in a nolint. - pattern: ^netip\.Addr\.IsPrivate$ msg: ask proxy.Public whether an address is on the internet, the one table of the ranges that aren't. + - pattern: ^(syscall|unix)\.Flock$ + msg: take a lock with internal/platform's LockFile, LockFileShared or LockDir, which wait until the context ends and show their wait (platform.Waiting); a blocking flock waits for ever and shows nothing. - pattern: ^msg\.StatusOf$ msg: show a lock's wait through the Reporter your constructor takes (msg.Waiting with its Status); only internal/state and internal/trust, which take none, read the run's status from the context. - pattern: ^redact\.Secret\.Reveal$ @@ -245,6 +247,12 @@ linters: - path: ^internal/(state|trust|msg)/|_test\.go$ linters: [forbidigo] text: msg\.StatusOf + # platform's locks themselves; the proxy's log rotation's (the proxy + # imports the standard library alone); test stubs; and tests, which + # hold locks as another devvm would. + - path: ^internal/(platform|stubtest)/|^internal/proxy/rotate\.go$|_test\.go$ + linters: [forbidigo] + text: (syscall|unix)\.Flock # state's own writer; the proxy's (standard library only); the # message generator (a leaf); test stubs; and tests' fixtures. - path: ^internal/(state|proxy|msg/gen|stubtest)/|_test\.go$ diff --git a/CHANGELOG.md b/CHANGELOG.md index af24414e..4ccf3b0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -142,7 +142,7 @@ These changes are on `main` and go out in the next release. - **A launch warns of a project in an agent's folder:** when a VM's project folder is inside a coding agent's folder on this machine, such as `~/.claude/skills/mine`, or holds one, such as `~/.pi`, each launch of the VM warns in one line, because code in the VM can change that agent's settings on this machine ([project folders devvm refuses](https://next.devvm.dev/docs/using/settings/#project-folders-devvm-refuses)). - **Cursor's CLI in a VM can change less of your Cursor account:** its proxy refuses more of the methods that change your account, your team or your cloud agents, such as merging a cloud agent's pull request, forking or pinning a cloud agent, or writing to its machine, while every call the CLI itself makes passes. Do those from Cursor on your machine ([Cursor CLI login](https://next.devvm.dev/docs/using/coding-agents/#cursor-cli-login)). - **Pins:** Cursor's CLI is 2026.11.17-f532c45. -- **Slow steps show a status line:** in a terminal, devvm now shows what it's waiting for while it finds the folder's VM, checks it before a start, checks its network and reads its host keys, sets it up, runs a `devcontainer.json`'s commands, looks up a folder's disk, checks Lima, deletes a VM or an image, applies the retention settings and installs an upgrade, and while `devvm ls` reads the VMs, `devvm doctor` checks this machine, `devvm agent import` reads your agents' folders and copies them into the store, and `devvm agent save` reads and compares the VM's settings. `devvm clone add`, `clone fetch`, `clone on` and `clone off`, `devvm git-protect`, `devvm stop`, a `--clone` VM's check before `devvm rm`, and a history export or import show one too. While devvm waits for another devvm that's changing the same thing, such as a VM's state, its folders' layout, a group, an image's build or the shared tools, a status line says so, only while it waits, where before some of those waits showed nothing and others printed a line after a few seconds that stayed. Like every status line, it shows only in a terminal without `-v`, so a run with `-v`, or with its output piped, no longer prints that line ([a command fails](https://next.devvm.dev/docs/using/troubleshooting/#a-command-fails)). +- **Slow steps show a status line:** in a terminal, devvm now shows what it's waiting for while it finds the folder's VM, checks it before a start, checks its network and reads its host keys, sets it up, runs a `devcontainer.json`'s commands, looks up a folder's disk, checks Lima, deletes a VM or an image, applies the retention settings and installs an upgrade, and while `devvm ls` reads the VMs, `devvm doctor` checks this machine, `devvm agent import` reads your agents' folders and copies them into the store, and `devvm agent save` reads and compares the VM's settings. `devvm clone add`, `clone fetch`, `clone on` and `clone off`, `devvm git-protect`, `devvm stop`, a `--clone` VM's check before `devvm rm`, a history export or import, and `devvm ports` as it starts a running VM's port forwarder again show one too. While devvm waits for another devvm that's changing the same thing, such as a VM's state, its folders' layout, a group, an image's build or the shared tools, a status line says so, only while it waits, where before some of those waits showed nothing and others printed a line after a few seconds that stayed. Like every status line, it shows only in a terminal without `-v`, so a run with `-v`, or with its output piped, no longer prints that line ([a command fails](https://next.devvm.dev/docs/using/troubleshooting/#a-command-fails)). ### Fixed diff --git a/docs/content/docs/contributing/cli.md b/docs/content/docs/contributing/cli.md index 9a8b15df..8b74f6cb 100644 --- a/docs/content/docs/contributing/cli.md +++ b/docs/content/docs/contributing/cli.md @@ -34,7 +34,7 @@ func ListAll(ctx context.Context, e *Env) ([]Listed, []Known, error) { The status line shows only in a terminal, without `-v` and until the run is interrupted, as nothing would clear one started after that. The UI keeps status lines as a stack: a logged command or a `Status` inside another shows its own line until it ends, and then the outer one is drawn again, so a phase can show one line around steps that show their own. A message said under a status line, whether `Info`, `Warn`, `Note` or data on `Stdout()`, clears the line, prints, and draws the line again below it, so a warning never lands on the status line. A question, the picker and `ui.Terminal`, which a command in the VM that draws on the terminal gets, hold the status line until they're done, so its redraw never goes over a prompt or what the user types. -A wait for a lock that another devvm holds shows a status line only while it waits, never when the lock is free: `platform.LockFile`, `platform.LockFileShared` and `platform.LockDir` take a `platform.Waiting`, which they call once they find the lock held and whose end they call once the wait ends, and `msg.Waiting(status, label)` makes one from a Reporter's `Status` and a label, such as `vm_state_waiting`. Only `internal/state`, for a VM's lock or the layout's, and `internal/trust`, which take no Reporter, take the run's `Status` from the context (`msg.StatusOf`), which the run's root sets (`msg.WithStatus`), and forbidigo keeps it to them; the layout's migration shows `layout_migrating` while it runs. An agent's login file, whose lock is its folder's (`platform.LockDir`), which the proxy holds while it refreshes the login, takes its wait as `agentlogin.File`'s `Waiting` (`agent_login_waiting`), and its wait ends with the caller's context, as every lock's does. Only a lock that never waits, such as one on a file just made, passes `nil`, which the structure test's `status-lines` rule holds to `statusSites`; a `Waiting` that's nil at run time, or a lock taken another way than `internal/platform`'s, is review only. +A wait for a lock that another devvm holds shows a status line only while it waits, never when the lock is free: `platform.LockFile`, `platform.LockFileShared` and `platform.LockDir` take a `platform.Waiting`, which they call once they find the lock held and whose end they call once the wait ends, and `msg.Waiting(status, label)` makes one from a Reporter's `Status` and a label, such as `vm_state_waiting`. Only `internal/state`, for a VM's lock or the layout's, and `internal/trust`, which take no Reporter, take the run's `Status` from the context (`msg.StatusOf`), which the run's root sets (`msg.WithStatus`), and forbidigo keeps it to them; the layout's migration shows `layout_migrating` while it runs. An agent's login file, whose lock is its folder's (`platform.LockDir`), which the proxy holds while it refreshes the login, takes its wait as `agentlogin.File`'s `Waiting` (`agent_login_waiting`), and its wait ends with the caller's context, as every lock's does. Only a lock that never waits, such as one on a file just made, passes `platform.NoWait`, which shows nothing and which the structure test's `status-lines` rule holds to `statusSites`, as it does a `nil`. `msg.Waiting` with no status, as in a process with no UI, gives a wait that shows nothing, never `nil`, and a test build's locks panic on a `nil` one (`platform.CheckWaiting`, which the root's run calls in every test build), so the CLI tests and the end-to-end tests catch one the rule can't see, such as a zero `agentlogin.File`'s, though not a `msg.Waiting` given a nil status, which is review only. A forbidigo rule refuses `syscall.Flock` and `unix.Flock` outside `internal/platform`, the proxy's log rotation, the stubs and tests, so every lock goes through `internal/platform`'s. Work that takes the terminal never runs under a status line, as its redraw would go over what it shows: a VM's shell, `ssh-add` asking for a key's passphrase (`checkAgent`, `Agent.Ensure`) and an agent's login in the VM. A launch shows its status lines around those steps rather than across them. A background process, such as the proxy, a forwarder or a link session, has no terminal and shows none. diff --git a/docs/content/docs/contributing/structure.md b/docs/content/docs/contributing/structure.md index f68399d7..a1b6fb2d 100644 --- a/docs/content/docs/contributing/structure.md +++ b/docs/content/docs/contributing/structure.md @@ -19,7 +19,7 @@ weight: 3 | `dropped-errors` | in non-test files, no function assigns a `Wait`'s error, or a `strconv` parse's, to `_`, such as `_ = cmd.Wait()` or `n, _ := strconv.Atoi(s)`, unless `droppedErrors` lists it with why, because a failed wait would read as a clean exit and text that isn't a number as 0 | | `read-limits` | in non-test files, every `io.ReadAll` reads through an `io.LimitReader` made in its call, such as `io.ReadAll(io.LimitReader(r, limit+1))`, unless `unboundedReads` lists its function with why, so a peer or a file that never ends can't fill the memory | | `folder-ids` | in non-test files outside `internal/platform`, no function compares a folder's identity or its volume with `==` or `!=`, but with `""`, switches on one, passes one to `strings.EqualFold`, `strings.Compare`, `slices.Contains` or `slices.Index`, or keys a map by one, indexed or in a map's literal, its type written out or a named map type of the module's: a field named `Folder` or `GitID`, a call of a state's `Folder` or `FolderVolume`, of `FolderID`, `folderID` or `FolderDevice`, or a name in the same function that one of those, or such a name, was assigned to, unless `exactFolderIDs` lists it with why, because a boot can number an unchanged folder's device anew, which only `platform.SameFolder` and `platform.SameOpenFolder` allow for | -| `status-lines` | in non-test files outside the folders `statusFree` lists, a function that does slow work, which makes a host command with `exec.Command` or `exec.CommandContext`, runs host git through `internal/hostgit`, walks a folder with `fs.WalkDir`, `filepath.Walk`, `filepath.WalkDir`, `hostsafety.Walk` or `safefile.Walk`, looks up a volume with `platform.VolumeUUID`, makes a request with `internal/fetch`'s `Open`, `Resolve`, `Get` or `Download`, waits for a lock with `platform.LockFile`, `LockFileShared` or `LockDir` whose waiting is `nil`, or runs a backend's command outside a step with its `Runner`'s `Output` or `Attach`, shows a status line itself, with a Reporter's `Status`, a `LoggedCmd` step or its `Runner`'s `Run`, unless `statusSites` lists it with why, so the user sees what devvm waits for ([status lines](cli.md#status-lines)) | +| `status-lines` | in non-test files outside the folders `statusFree` lists, a function that does slow work, which makes a host command with `exec.Command` or `exec.CommandContext`, runs host git through `internal/hostgit`, walks a folder with `fs.WalkDir`, `filepath.Walk`, `filepath.WalkDir`, `hostsafety.Walk` or `safefile.Walk`, looks up a volume with `platform.VolumeUUID`, makes a request with `internal/fetch`'s `Open`, `Resolve`, `Get` or `Download`, waits for a lock with `platform.LockFile`, `LockFileShared` or `LockDir` whose waiting is `nil` or `platform.NoWait`, or runs a backend's command outside a step with its `Runner`'s `Output` or `Attach`, shows a status line itself, with a Reporter's `Status`, a `LoggedCmd` step or its `Runner`'s `Run`, unless `statusSites` lists it with why, so the user sees what devvm waits for ([status lines](cli.md#status-lines)) | The layers: diff --git a/internal/backend/lima/pin_test.go b/internal/backend/lima/pin_test.go index e5b9f98b..c67387ae 100644 --- a/internal/backend/lima/pin_test.go +++ b/internal/backend/lima/pin_test.go @@ -1,17 +1,44 @@ package lima import ( + "context" "errors" "os" "slices" "testing" + "time" "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/state" "github.com/devvmhq/devvm/internal/ubuntu" ) +// PinOrigin's wait for the Ubuntu pin's lock, held as by another devvm's +// first build, shows ubuntu_pin_waiting, and a Ctrl-C ends it with +// nothing asked or pinned. +func TestPinOriginWaits(t *testing.T) { + l, _, _ := testLima(t, "darwin") + fi := &testFinder{releases: []string{"release-20260301"}} + l.Ubuntu = fi + if err := os.MkdirAll(l.Dirs.ImageLocks(), 0o700); err != nil { + t.Fatal(err) + } + unlock, err := platform.LockFile(t.Context(), l.Dirs.UbuntuPinLock(), nil) + if err != nil { + t.Fatal(err) + } + defer unlock() + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs + defer cancel() + var said msg.Recorder + l.Reporter = &msg.Fake{OnStatus: func(m msg.M) { said.Add(m); cancel() }} + if _, err := l.PinOrigin(ctx, nil, backend.PinNewest); !errors.Is(err, context.Canceled) || !slices.Equal(said.Names(), []string{"ubuntu_pin_waiting"}) || len(fi.asked) != 0 { + t.Errorf("held: %v, showed %q, asked %q", err, said.Names(), fi.asked) + } +} + // PinOrigin pins the newest release when none is pinned, again on // PinNewest, and the newest older than the one pinned on PinOlder; a // --from base pins only when none is; e2e's release stands in for the diff --git a/internal/build/build_test.go b/internal/build/build_test.go index 84f78c5a..81adb4a1 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -518,6 +518,40 @@ func TestBuiltNeedsNoBuild(t *testing.T) { } } +// The waits for the package cache's lock and the rebuild counters', held +// as by another devvm, show their labels (packages_waiting, +// rebuilds_waiting), and a Ctrl-C ends each wait with nothing changed. +func TestImageLocksWait(t *testing.T) { + b, _ := testEnv(t) + for _, c := range []struct { + lock, want string + run func(context.Context) error + }{ + {b.Dirs.PackagesLock(), "packages_waiting", func(ctx context.Context) error { + return (Images{b}).DeletePackages(ctx, StalePackages{Sets: []string{"k"}}) + }}, + {b.Dirs.RebuildsLock(), "rebuilds_waiting", func(ctx context.Context) error { + return (Builds{b}).bumpRebuild(ctx, "foo") + }}, + } { + if err := os.MkdirAll(b.Dirs.ImageLocks(), 0o700); err != nil { + t.Fatal(err) + } + unlock, err := platform.LockFile(t.Context(), c.lock, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs + var said msg.Recorder + fake(b).OnStatus = func(m msg.M) { said.Add(m); cancel() } + if err := c.run(ctx); !errors.Is(err, context.Canceled) || !slices.Equal(said.Names(), []string{c.want}) { + t.Errorf("%s held: %v, showed %q", c.want, err, said.Names()) + } + cancel() + unlock() + } +} + // An image another devvm is building (no record, its lock held) is left // alone: a build of it waits, saying so, rebuild and Delete don't delete // it, and it's listed as building. Once its lock is free, it's a diff --git a/internal/cli/overrides.go b/internal/cli/overrides.go index 668dedb1..964e3f23 100644 --- a/internal/cli/overrides.go +++ b/internal/cli/overrides.go @@ -45,7 +45,8 @@ type Overrides struct { // lookup fail. Volume string // LockOrder, in every test build, checks the order the state's - // locks are taken in (state.CheckLockOrder). + // locks are taken in (state.CheckLockOrder), and that every lock's + // wait shows (platform.CheckWaiting). LockOrder bool } diff --git a/internal/cli/root.go b/internal/cli/root.go index cb61fb53..09f0e8af 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -10,6 +10,7 @@ import ( "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/proxy" "github.com/devvmhq/devvm/internal/state" "github.com/devvmhq/devvm/internal/ui" @@ -44,6 +45,7 @@ func NewRoot(u *ui.UI) *cobra.Command { u.SetFlags(f) if a.testOverrides().LockOrder { state.CheckLockOrder() + platform.CheckWaiting() } if wantsJSON(cmd) { u.DataOnly() // stdout is the JSON's alone diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index f7dce5a3..ee235750 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -4063,6 +4063,11 @@ func PortsRefused(count int, ports string, vm vmname.VM) M { return M{id: "ports_refused", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"ports", ports}, {"vm", string(vm)}}} } +// PortsRestarting is [ports_restarting]: "starting {{.vm}}'s port forwarder again" +func PortsRestarting(vm vmname.VM) M { + return M{id: "ports_restarting", vals: []val{{"vm", string(vm)}}} +} + // PortsRmAll is [ports_rm_all]: "Every port is forwarded, so none can be removed. Set the ones to keep instead, as in devvm ports 5173,8000-8010." func PortsRmAll() M { return M{id: "ports_rm_all"} @@ -6506,6 +6511,7 @@ var specs = map[string]spec{ "ports_list_needed": {fields: []string{"value"}}, "ports_now": {fields: []string{"ports", "vm"}}, "ports_refused": {plural: true, fields: []string{"count", "ports", "vm"}}, + "ports_restarting": {fields: []string{"vm"}}, "ports_rm_all": {}, "ports_ssh_limit": {fields: []string{"held", "limit", "others", "vms"}}, "ports_ssh_limit_all": {fields: []string{"limit", "vms"}}, diff --git a/internal/msg/waiting.go b/internal/msg/waiting.go index 17e27509..8bb521e8 100644 --- a/internal/msg/waiting.go +++ b/internal/msg/waiting.go @@ -4,11 +4,12 @@ import "context" // Waiting is the wait for a lock (platform.Waiting) that shows label on a // status line of status, a Reporter's Status, while devvm waits for -// another devvm that holds the lock, and never when it's free; nil for a -// nil status, which shows nothing. +// another devvm that holds the lock, and never when it's free. A nil +// status, as in a process with no UI, shows nothing, but the wait is +// never nil, which a test build refuses (platform.CheckWaiting). func Waiting(status func(M) func(), label M) func() func() { if status == nil { - return nil + return func() func() { return func() {} } } return func() func() { return status(label) } } diff --git a/internal/msg/waiting_test.go b/internal/msg/waiting_test.go new file mode 100644 index 00000000..ed438cc4 --- /dev/null +++ b/internal/msg/waiting_test.go @@ -0,0 +1,28 @@ +package msg + +import ( + "slices" + "testing" +) + +// A lock's wait shows its label on its status line, and ends it; with no +// status, as in a process with no UI, it shows nothing, but is never nil, +// which a test build's locks refuse. +func TestWaiting(t *testing.T) { + var shown []string + ended := 0 + status := func(m M) func() { + shown = append(shown, m.ID()) + return func() { ended++ } + } + label := M{id: "share_waiting"} + Waiting(status, label)()() + if !slices.Equal(shown, []string{"share_waiting"}) || ended != 1 { + t.Errorf("shown %q, ended %d", shown, ended) + } + w := Waiting(nil, label) + if w == nil { + t.Fatal("no status: a nil wait") + } + w()() +} diff --git a/internal/platform/folder_test.go b/internal/platform/folder_test.go index d8a4f123..0d74ce6c 100644 --- a/internal/platform/folder_test.go +++ b/internal/platform/folder_test.go @@ -3,6 +3,8 @@ package platform import ( + "errors" + "io/fs" "os" "path/filepath" "runtime" @@ -59,6 +61,20 @@ func TestStatFolderUnique(t *testing.T) { if _, err := StatFolder(filepath.Join(dir, "missing")); err == nil { t.Error("a missing folder's stat") } + // A link on the folder's path is refused, the error about the folder, as an open's is, so a + // message that names the folder takes its reason alone. + if err := os.Symlink(dir, filepath.Join(dir, "via")); err != nil { + t.Fatal(err) + } + via := filepath.Join(dir, "via", "x") + if err := os.Mkdir(filepath.Join(dir, "x"), 0o700); err != nil { + t.Fatal(err) + } + if _, err := StatFolder(via); err == nil { + t.Error("a folder through a link: stat") + } else if pe, ok := errors.AsType[*fs.PathError](err); !ok || pe.Path != via { + t.Errorf("a folder through a link: %v, not a PathError about it", err) + } switch runtime.GOOS { case "linux": // The temporary folder's file system may be any (TestUniqueFS); unique needs a birth time. diff --git a/internal/platform/folderstat_unix.go b/internal/platform/folderstat_unix.go index 3e6cdfbb..3ff54d42 100644 --- a/internal/platform/folderstat_unix.go +++ b/internal/platform/folderstat_unix.go @@ -2,7 +2,7 @@ package platform -import "fmt" +import "io/fs" // StatFolder is the folder at dir as FolderStat has it, read from the folder opened with no link // on its path (OpenNoLinks, none of the system's followed either), so nothing a VM puts at the @@ -14,7 +14,7 @@ func StatFolder(dir string) (FolderStat, error) { } defer func() { _ = f.Close() }() if hops != 0 { - return FolderStat{}, fmt.Errorf("%s: a link on its path", dir) + return FolderStat{}, &fs.PathError{Op: "open", Path: dir, Err: ErrLinkOnPath} } return openFolder(f) } diff --git a/internal/platform/lock_test.go b/internal/platform/lock_test.go index a4a404e8..211f14f7 100644 --- a/internal/platform/lock_test.go +++ b/internal/platform/lock_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "sync" "syscall" "testing" "testing/synctest" @@ -55,50 +56,63 @@ func TestLockFile(t *testing.T) { // 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) { - path := filepath.Join(t.TempDir(), "x.lock") - waits, ends := 0, 0 - waiting := func() func() { - waits++ - return func() { ends++ } - } - 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} { + 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 - ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond) - lock := LockFile - if shared { - lock = LockFileShared + 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) } - 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) + unlock() + if err := <-got; err != nil || ends != 1 { + t.Errorf("got once let go: %v, ends %d", err, ends) } - cancel() - } - // Got once let go: the wait ends then. - waits, ends = 0, 0 - got := make(chan error, 1) - started := make(chan struct{}) - go func() { - u, err := LockFile(t.Context(), path, func() func() { close(started); return func() { ends++ } }) - if err == nil { - u() + 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() } - got <- err - }() - <-started - unlock() - if err := <-got; err != nil || ends != 1 { - t.Errorf("got once let go: %v, ends %d", err, ends) - } - 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 @@ -169,6 +183,43 @@ func TestLockDir(t *testing.T) { }) } +// 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) { diff --git a/internal/platform/lock_unix.go b/internal/platform/lock_unix.go index 5e58a302..16884f0f 100644 --- a/internal/platform/lock_unix.go +++ b/internal/platform/lock_unix.go @@ -73,6 +73,7 @@ func LockHeld(path string) (bool, error) { // again lockTick apart until ctx ends; waiting, if any, is called once it // finds the lock held, and what it returned once the wait ends. func lockFile(ctx context.Context, path string, how int, waiting Waiting) (unlock func(), err error) { + checkWaiting(waiting) var end func() defer func() { if end != nil { @@ -101,6 +102,7 @@ func lockFile(ctx context.Context, path string, how int, waiting Waiting) (unloc // (Waiting) says so. It never makes the folder: one that isn't there is // os.ErrNotExist. Its descriptor isn't inherited (close on exec). func LockDir(ctx context.Context, dir string, waiting Waiting) (unlock func(), err error) { + checkWaiting(waiting) var end func() defer func() { if end != nil { diff --git a/internal/platform/lockwait.go b/internal/platform/lockwait.go index c15345b2..dbc0b4ce 100644 --- a/internal/platform/lockwait.go +++ b/internal/platform/lockwait.go @@ -1,13 +1,38 @@ package platform +import "sync/atomic" + // Waiting is what a wait for a lock shows (LockFile, LockFileShared, -// LockDir): it's -// called once, when another process holds the lock, never when it's free, -// and the func it returns once the wait ends, with the lock got or not. -// Each caller with a terminal passes a status line of its own, a label -// that says what it waits for (msg.Waiting), so a terminal never looks -// hung while devvm waits for another devvm; nil shows nothing, only for a -// lock that never waits, such as one on a file just made, which the -// structure test's status-lines rule holds to its list. A process with no -// terminal passes a Waiting all the same, whose status line draws nothing. +// LockDir): it's called once, when another process holds the lock, never +// when it's free, and the func it returns once the wait ends, with the +// lock got or not. Each caller with a terminal passes a status line of +// its own, a label that says what it waits for (msg.Waiting), so a +// terminal never looks hung while devvm waits for another devvm. A +// process with no terminal passes a Waiting all the same, whose status +// line draws nothing. NoWait shows nothing, only for a lock that never +// waits, such as one on a file just made, and the structure test's +// status-lines rule holds it, and nil, to its list; a test build panics +// on nil (CheckWaiting). type Waiting func() (end func()) + +// NoWait is the Waiting of a lock that never waits, such as one on a file +// just made, which no other process has: it shows nothing. +func NoWait() (end func()) { return func() {} } + +// waitingChecked is whether a lock taken with a nil Waiting panics +// (CheckWaiting). +var waitingChecked atomic.Bool + +// CheckWaiting makes every lock this process takes from then on panic on +// a nil Waiting, which would show nothing while another devvm holds the +// lock: test builds' runs do (internal/cli's Overrides), so the CLI tests +// and the end-to-end tests catch one that the structure test's +// status-lines rule can't see, such as a zero agentlogin.File's. +func CheckWaiting() { waitingChecked.Store(true) } + +// checkWaiting panics on a nil waiting once CheckWaiting was called. +func checkWaiting(waiting Waiting) { + if waiting == nil && waitingChecked.Load() { + panic("platform: a lock's Waiting is nil, so its wait would show nothing: pass msg.Waiting's, or NoWait for a lock that never waits") + } +} diff --git a/internal/platform/nolinks_unix.go b/internal/platform/nolinks_unix.go index 763f4e8c..bf2fe2c3 100644 --- a/internal/platform/nolinks_unix.go +++ b/internal/platform/nolinks_unix.go @@ -92,7 +92,7 @@ func openNoLinks(path string, follow func(link, dir *unix.Stat_t) bool) (*os.Fil return nil, 0, &os.PathError{Op: "open", Path: path, Err: err} case last || unix.Fstat(fd, &dir) != nil || !follow(st, &dir): _ = unix.Close(fd) - return nil, 0, fmt.Errorf("%s: %w", path, ErrLinkOnPath) + return nil, 0, &os.PathError{Op: "open", Path: path, Err: ErrLinkOnPath} } if hops++; hops > linkHops { _ = unix.Close(fd) diff --git a/internal/ports/ports.go b/internal/ports/ports.go index 2ea74690..36947eef 100644 --- a/internal/ports/ports.go +++ b/internal/ports/ports.go @@ -585,7 +585,7 @@ func (a Allocator) Build(ctx context.Context, vm vmname.VM, was int) (int, func( return err } // A new file: no other process has it, so the lock is had at once. - if unlock, err = platform.LockFile(ctx, rec, nil); err != nil { + if unlock, err = platform.LockFile(ctx, rec, platform.NoWait); err != nil { _ = os.Remove(rec) } return err diff --git a/internal/secrets/yours_test.go b/internal/secrets/yours_test.go index 50c6a9a7..ca436f31 100644 --- a/internal/secrets/yours_test.go +++ b/internal/secrets/yours_test.go @@ -1,14 +1,18 @@ package secrets import ( + "context" "errors" "os" "path/filepath" "regexp" + "slices" "strings" "testing" + "time" "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/proxy" "github.com/devvmhq/devvm/internal/redact" "github.com/devvmhq/devvm/internal/state" @@ -30,6 +34,29 @@ func stripeDef(t *testing.T, d Def) Secret { return sec } +// A save of a secret of yours waits for your secrets' lock, held as by +// another devvm, showing custom_secrets_waiting, and a Ctrl-C ends the +// wait with nothing saved. +func TestYoursLockWaits(t *testing.T) { + s, kc := testStore(t, true, nil) + if err := state.PrivateDir(s.Dirs.Data); err != nil { + t.Fatal(err) + } + unlock, err := platform.LockFile(t.Context(), s.Dirs.CustomSecretsLock(), nil) + if err != nil { + t.Fatal(err) + } + defer unlock() + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs + defer cancel() + var said msg.Recorder + s.Reporter = &msg.Fake{OnStatus: func(m msg.M) { said.Add(m); cancel() }} + err = YoursOf(s).Save(ctx, stripeDef(t, Def{}), redact.NewSecret("sk_test_x")) + if !errors.Is(err, context.Canceled) || !slices.Equal(said.Names(), []string{"custom_secrets_waiting"}) || len(kc) != 0 { + t.Errorf("held: %v, showed %q, saved %d", err, said.Names(), len(kc)) + } +} + // Your secrets in the store: the value where the known secrets' are, under // a key of its own (custom.NAME), the definition with an ID of its own in // its list, only yours to read; each variable once; saved again, the same diff --git a/internal/structure/status_test.go b/internal/structure/status_test.go index 1dd92861..4341e269 100644 --- a/internal/structure/status_test.go +++ b/internal/structure/status_test.go @@ -62,6 +62,11 @@ func slowCall(f srcFile, n ast.Node) string { if id, ok := call.Args[2].(*ast.Ident); ok && id.Name == "nil" { return "waits for a lock showing nothing" } + if sel, ok := call.Args[2].(*ast.SelectorExpr); ok && sel.Sel.Name == "NoWait" { + if x, ok := sel.X.(*ast.Ident); ok && x.Name == pkg { + return "waits for a lock showing nothing" + } + } } } if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Output" || sel.Sel.Name == "Attach") { @@ -171,6 +176,13 @@ func statusCases() []ruleCase { r: on, want: &want{ruleStatus, "list a/a.go: lock in statusSites"}, }, + { + name: "a lock's wait that says it never waits", + files: map[string]string{"a/a.go": "package a\n\nimport (\n\t\"context\"\n\n\t\"github.com/devvmhq/devvm/internal/platform\"\n)\n\n" + + "func lock(ctx context.Context) (func(), error) { return platform.LockFile(ctx, \"x\", platform.NoWait) }\n"}, + r: on, + want: &want{ruleStatus, "list a/a.go: lock in statusSites"}, + }, { name: "a lock's wait with a status line", files: map[string]string{"a/a.go": "package a\n\nimport (\n\t\"context\"\n\n\t\"github.com/devvmhq/devvm/internal/platform\"\n)\n\n" + diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index 6e342193..e9d083db 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -276,6 +276,7 @@ func devvmVars() map[string]string { "internal/structure.update": "a test flag, set on go test's command line", "internal/leaktest.allowed": table, "internal/state.held": "the state locks this process's goroutines hold, which test builds check the order of: the locks are the process's", + "internal/platform.waitingChecked": "whether this process's locks refuse a nil Waiting, which test builds turn on: the locks are the process's", } } diff --git a/internal/vm/env.go b/internal/vm/env.go index 87cc3f47..1913a64e 100644 --- a/internal/vm/env.go +++ b/internal/vm/env.go @@ -158,6 +158,20 @@ type Env struct { leftovers Leftovers } +// gitSerial is .git protection's Serial: it runs f holding devvm's git +// lock (paths.Dirs.GitLock), waiting for another devvm that holds it under +// a status line of r's (git_lock_waiting). +func gitSerial(d paths.Dirs, r msg.Reporter) func(context.Context, func() error) error { + return func(ctx context.Context, f func() error) error { + unlock, err := platform.LockFile(ctx, d.GitLock(), msg.Waiting(r.Status, msg.GitLockWaiting())) + if err != nil { + return err + } + defer unlock() + return f() + } +} + // wire makes e's parts (Env's unexported fields), each over e itself, // and returns e: NewEnv's, and every Env a test makes. func wire(e *Env) *Env { @@ -199,14 +213,7 @@ func NewEnv(d paths.Dirs, assets fs.FS, self, version string, reg *backend.Regis } return inv.GitKeeper(vm) } - p.Serial = func(ctx context.Context, f func() error) error { - unlock, err := platform.LockFile(ctx, d.GitLock(), msg.Waiting(r.Status, msg.GitLockWaiting())) - if err != nil { - return err - } - defer unlock() - return f() - } + p.Serial = gitSerial(d, r) return p } e.Links = func(st *state.VM) ([]GuestLink, error) { return guestLinks(d, st) } diff --git a/internal/vm/finder.go b/internal/vm/finder.go index 9be580a6..5f149519 100644 --- a/internal/vm/finder.go +++ b/internal/vm/finder.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io/fs" "os" "path/filepath" "strconv" @@ -161,7 +162,7 @@ func (n need) check(t *target) error { case n.has == hasMachine && !t.exists, (n.has == hasVM || n.has == hasMade) && !there: return noVM(t.f.Dir) case n.name == "" && there && t.unread != nil: - return msg.VMFolderUnreadable(t.f.Dir, t.f.Name, t.unread.Error()).Because(t.unread) + return folderUnreadable(t.f.Dir, t.f.Name, t.unread) case (n.folder || n.has == hasMade) && there && t.other: return msg.VMOtherFolder(t.f.Name, t.st.Dir) case n.has == hasMade && pending: @@ -406,7 +407,7 @@ func (e finder) parentVM(ctx context.Context) (*target, error) { return nil, err } if same, err := e.sameFolder(ctx, *found, fst); err != nil { - return nil, msg.VMFolderUnreadable(found.Dir, found.Name, err.Error()).Because(err) + return nil, folderUnreadable(found.Dir, found.Name, err) } else if !same { return nil, nil } @@ -583,6 +584,18 @@ func (e finder) inspect(ctx context.Context, f project.Folder, st *state.VM) (*t return t, nil } +// folderUnreadable is vm_folder_unreadable for the folder dir of the VM +// vm, which err says devvm can't open or read: its why is err's reason +// alone when err is about dir itself, as an open's is, since the message +// names dir already. +func folderUnreadable(dir string, vm vmname.VM, err error) error { + why := err.Error() + if pe, ok := errors.AsType[*fs.PathError](err); ok && filepath.Clean(pe.Path) == filepath.Clean(dir) { + why = pe.Err.Error() + } + return msg.VMFolderUnreadable(dir, vm, why).Because(err) +} + // sameFolder reports whether the VM was made for this folder (madeFor), // on the volume the state records (Env.keepsVolume), so a clone of the // disk mounted at the folder's own path isn't taken for it. The folder is diff --git a/internal/vm/parent_test.go b/internal/vm/parent_test.go index ab0a9ff6..c5b70cbe 100644 --- a/internal/vm/parent_test.go +++ b/internal/vm/parent_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "slices" "strings" + "syscall" "testing" "github.com/devvmhq/devvm/internal/agents" @@ -381,21 +382,22 @@ func TestUnreadableFolder(t *testing.T) { if _, err := platform.StatFolder(e.Dir); err == nil { t.Skip("an unreadable folder still opens here, as for root") } - want := "vm_folder_unreadable dir=" + e.Dir + " vm=" + vm.String() + " why=" + // The message names the folder once: why is the system's reason alone. + want := "vm_folder_unreadable dir=" + e.Dir + " vm=" + vm.String() + " why=" + syscall.EACCES.Error() for name, run := range map[string]func() error{ "launch": func() error { return (Launch{e}).Up(t.Context(), Options{}) }, "adopt": func() error { return (Lifecycle{e}).Adopt(t.Context(), "", true) }, "rm": func() error { return (Lifecycle{e}).Rm(t.Context(), RmOptions{Force: true}) }, } { - if err := run(); !strings.HasPrefix(msg.NamesOf(err), want) { - t.Errorf("%s: %v, want %s…", name, msg.NamesOf(err), want) + if err := run(); msg.NamesOf(err) != want { + t.Errorf("%s: %v, want %s", name, msg.NamesOf(err), want) } } // From a subfolder, the parent's VM is refused the same way, naming the parent. web := e.Dir sub := subfolder(t, e, web, "src/lib") - if err := (Launch{e}).Up(t.Context(), Options{}); !strings.HasPrefix(msg.NamesOf(err), want) { - t.Errorf("in %s: %v, want %s…", sub, msg.NamesOf(err), want) + if err := (Launch{e}).Up(t.Context(), Options{}); msg.NamesOf(err) != want { + t.Errorf("in %s: %v, want %s", sub, msg.NamesOf(err), want) } if err := os.Chmod(web, 0o700); err != nil { //nolint:gosec // a folder's own mode, back t.Fatal(err) diff --git a/internal/vm/ports.go b/internal/vm/ports.go index 5d844769..1e492e30 100644 --- a/internal/vm/ports.go +++ b/internal/vm/ports.go @@ -253,7 +253,9 @@ func (e Settings) SetPorts(ctx context.Context, c PortsChange) error { e.Info(msg.PortsNow(list, vm)) return nil } + end := e.Status(msg.PortsRestarting(vm)) e.forwards().Start(ctx, b, st) + end() e.Info(msg.PortsForwarding(list, vm)) return nil } diff --git a/internal/vm/status_test.go b/internal/vm/status_test.go index 8e578cb6..bc040a14 100644 --- a/internal/vm/status_test.go +++ b/internal/vm/status_test.go @@ -2,12 +2,19 @@ package vm import ( "context" + "errors" + "os" + "slices" "strings" "testing" + "time" "github.com/devvmhq/devvm/internal/backend/backendtest" + "github.com/devvmhq/devvm/internal/gitprotect" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/netpolicy" + "github.com/devvmhq/devvm/internal/paths" + "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/sshagent" ) @@ -28,6 +35,29 @@ func underStatus(f *backendtest.Fake, fake *msg.Fake) *[]string { return &off } +// .git protection's waits for devvm's git lock, held as by another devvm, +// show git_lock_waiting, and a Ctrl-C ends the wait with nothing run. +func TestGitLockWaits(t *testing.T) { + d := paths.Dirs{Data: t.TempDir()} + if err := os.MkdirAll(d.Run(), 0o700); err != nil { + t.Fatal(err) + } + unlock, err := platform.LockFile(t.Context(), d.GitLock(), nil) + if err != nil { + t.Fatal(err) + } + defer unlock() + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs + defer cancel() + var showed msg.Recorder + f := &msg.Fake{OnStatus: func(m msg.M) { showed.Add(m); cancel() }} + ran := false + err = gitSerial(d, f)(ctx, func() error { ran = true; return nil }) + if !errors.Is(err, context.Canceled) || ran || !slices.Equal(showed.Names(), []string{"git_lock_waiting"}) { + t.Errorf("held: %v, ran %v, showed %q", err, ran, showed.Names()) + } +} + // ssh-add, on the user's agent or devvm's own, never runs under a status // line, as it may ask for a key's passphrase on the terminal: in a // stopped VM's launch and a running VM's, with either agent. @@ -94,6 +124,30 @@ func TestCommandStatusLines(t *testing.T) { {"network", func(ctx context.Context) error { _, err := (Net{e}).Network(ctx); return err }}, {"tools", func(ctx context.Context) error { _, err := (Tools{e}).List(ctx); return err }}, {"git-protect", func(ctx context.Context) error { _, err := (Settings{e}).GitProtect(ctx); return err }}, + {"ports 3000", func(ctx context.Context) error { return (Settings{e}).SetPorts(ctx, PortsChange{List: "3000"}) }}, + {"ports add", func(ctx context.Context) error { + return (Settings{e}).SetPorts(ctx, PortsChange{Op: "add", List: "4000"}) + }}, + {"size --cpus 2", func(ctx context.Context) error { return (Settings{e}).SetSize(ctx, Size{CPUs: "2"}, false) }}, + {"network open", func(ctx context.Context) error { + return (Net{e}).SetTier(ctx, netpolicy.TierOpen, "devvm network open") + }}, + {"network allowlist", func(ctx context.Context) error { + return (Net{e}).SetTier(ctx, netpolicy.TierAllowlist, "devvm network allowlist") + }}, + {"network transparent off", func(ctx context.Context) error { + return (Settings{e}).SetTransparent(ctx, "off", "devvm network transparent off") + }}, + {"network transparent on", func(ctx context.Context) error { + return (Settings{e}).SetTransparent(ctx, "on", "devvm network transparent on") + }}, + {"network learn", func(ctx context.Context) error { return (Net{e}).Learn(ctx, "devvm network learn") }}, + {"network allow", func(ctx context.Context) error { + return (Net{e}).PolicyChange(ctx, []string{"example.com"}, RuleChange{}) + }}, + {"git-protect off", func(ctx context.Context) error { return (Settings{e}).SetGitProtect(ctx, gitprotect.Off) }}, + {"git-protect on", func(ctx context.Context) error { return (Settings{e}).SetGitProtect(ctx, gitprotect.On) }}, + {"ssh-agent off", func(ctx context.Context) error { return (Settings{e}).SetSSHAgent(ctx, sshagent.Off) }}, {"history export", func(ctx context.Context) error { return (Lifecycle{e}).Export(ctx, "") }}, {"stop", func(ctx context.Context) error { return (Lifecycle{e}).Stop(ctx) }}, {"rm", func(ctx context.Context) error { return (Lifecycle{e}).Rm(ctx, RmOptions{Force: true}) }}, diff --git a/internal/vmssh/forwards_test.go b/internal/vmssh/forwards_test.go index 034f5dcf..413edb25 100644 --- a/internal/vmssh/forwards_test.go +++ b/internal/vmssh/forwards_test.go @@ -67,6 +67,25 @@ func testForwards(t *testing.T) (*Forwards, *[][]string, *msg.Recorder) { return f, &starts, warned } +// A VM's forwarder's lock, held as by another devvm, is waited for under +// forwarder_waiting, naming the VM, and a Ctrl-C ends the wait. +func TestForwardsLockWaits(t *testing.T) { + vm := vmname.VM("devvm-a-0123456789abcd") + f := Forwards{Dirs: paths.Dirs{Data: t.TempDir()}} + unlock, err := f.Lock(t.Context(), vm) + if err != nil { + t.Fatal(err) + } + defer unlock() + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs + defer cancel() + var said msg.Recorder + f.Reporter = &msg.Fake{OnStatus: func(m msg.M) { said.Add(m); cancel() }} + if _, err := f.Lock(ctx, vm); !errors.Is(err, context.Canceled) || !slices.Equal(said.Names(), []string{"forwarder_waiting vm=" + vm.String()}) { + t.Errorf("held: %v, showed %q", err, said.Names()) + } +} + // A forwarder's log that an earlier one left past its cap is rotated as // the next starts. func TestForwardsRunTrimsLog(t *testing.T) { diff --git a/locales/en.toml b/locales/en.toml index 2ecda908..5904f538 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -1460,6 +1460,10 @@ other = "{{.vm}} forwards {{.ports}}" [ports_forwarding] other = "From now on, {{.vm}} forwards {{.ports}}. devvm closed the connections that were open to its ports." +[ports_restarting] +description = "a status step: devvm ports starts the running VM's port forwarder again with the VM's new ports" +other = "starting {{.vm}}'s port forwarder again" + [ports_default] other = "new VMs forward {{.ports}}" diff --git a/testdata/coverage/darwin.txt b/testdata/coverage/darwin.txt index d220cc31..86c7c6ef 100644 --- a/testdata/coverage/darwin.txt +++ b/testdata/coverage/darwin.txt @@ -7,7 +7,7 @@ internal/backend 97.1 internal/backend/backendtest 74.4 internal/backend/lima 91.5 internal/backend/registry 100.0 -internal/build 88.6 +internal/build 88.7 internal/cli 91.2 internal/cli/docgen 86.5 internal/daemon 98.3 @@ -22,7 +22,7 @@ internal/image 99.4 internal/jsonc 97.1 internal/leaktest 87.5 internal/memnet 96.8 -internal/msg 72.5 +internal/msg 72.6 internal/msg/gen 93.9 internal/netpolicy 91.9 internal/paths 98.1 @@ -33,7 +33,7 @@ internal/proxy 93.6 internal/redact 99.1 internal/safefile 97.8 internal/seatbelt 98.1 -internal/secrets 93.4 +internal/secrets 93.5 internal/settings 96.5 internal/shell 100.0 internal/sshagent 85.0 diff --git a/testdata/lint/forbidigo.go b/testdata/lint/forbidigo.go index 3ba267fa..ad6a02c8 100644 --- a/testdata/lint/forbidigo.go +++ b/testdata/lint/forbidigo.go @@ -15,6 +15,8 @@ import ( "time" "unicode" + "golang.org/x/sys/unix" + "github.com/devvmhq/devvm/internal/redact" "github.com/devvmhq/devvm/internal/testbuild" ) @@ -65,6 +67,10 @@ func reveals(s redact.Secret) string { return s.Reveal() } // want forbidigo func chmods() error { return os.Chmod("f", 0o600) } // want forbidigo +func flocks(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_EX) } // want forbidigo + +func unixFlocks(f *os.File) error { return unix.Flock(int(f.Fd()), unix.LOCK_EX) } // want forbidigo + func chtimes(t time.Time) error { return os.Chtimes("f", t, t) } // want forbidigo func chowns() error { return os.Chown("f", 0, 0) } // want forbidigo