mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
build(lint): enforce contexts, nolint reasons, reassign and function size
.golangci.yml: - forbidigo bans context.Background and context.TODO outside internal/ui and cmd/devvm. - nolintlint requires each //nolint to name its linters and say why, and reports unused ones. - reassign (patterns .*) forbids setting another package's variables, tests included. - revive keeps its default rules and adds function-length (100 statements, 160 lines) and cognitive-complexity (75). Fixes: - Backend.Lifeline takes a ctx: smolvm's machine data-dir lookup runs with the caller's. - The proxy's TLS handshake with a VM uses the request's context, limited to 30 seconds. - OAuth token refreshes run within refreshTimeout (30 seconds). - Tests use t.Context(). - Launch.create is split into plan, newVM.record and undoCreate. - lima's TestStartConfined is split into helpers. - smolvm's Terminal comes from its UI's StdinIsTerminal. - Unused //nolint directives are removed. - Fresh contexts that remain (an in-memory TLS parse, lookups shared by every request, a test cleanup) each carry a nolint saying why. Docs: contributing.md lists which lint rule enforces which convention; AGENTS.md names the linters behind its Go conventions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
35 files changed
+341
-232
No files matched your search
+20
-2
@@ -13,6 +13,8 @@ linters:
|
||||
- misspell
|
||||
- nilerr
|
||||
- noctx
|
||||
- nolintlint
|
||||
- reassign
|
||||
- revive
|
||||
- unconvert
|
||||
- usestdlibvars
|
||||
@@ -80,16 +82,32 @@ linters:
|
||||
msg: print through internal/ui.
|
||||
- pattern: ^os\.(Stdout|Stderr)$
|
||||
msg: print through internal/ui.
|
||||
- pattern: ^context\.(Background|TODO)$
|
||||
msg: take the caller's ctx; a fresh one only where it must outlive it, with a nolint saying why.
|
||||
nolintlint:
|
||||
require-explanation: true
|
||||
require-specific: true
|
||||
reassign:
|
||||
patterns:
|
||||
- ".*"
|
||||
revive:
|
||||
enable-default-rules: true
|
||||
rules:
|
||||
# Just above the largest today: statements, then lines.
|
||||
- name: function-length
|
||||
arguments: [100, 160]
|
||||
- name: cognitive-complexity
|
||||
arguments: [75]
|
||||
exclusions:
|
||||
presets:
|
||||
- std-error-handling
|
||||
rules:
|
||||
- path: ^cmd/devvm/
|
||||
linters: [forbidigo]
|
||||
text: os\.Exit
|
||||
text: os\.Exit|context\.(Background|TODO)
|
||||
- path: ^internal/ui/
|
||||
linters: [forbidigo]
|
||||
text: fmt\.Print|os\.(Stdout|Stderr)
|
||||
text: fmt\.Print|os\.(Stdout|Stderr)|context\.(Background|TODO)
|
||||
paths:
|
||||
- ^\.agents/
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ Still to come: smolvm's emulations, the docker backend; the release keys (`packa
|
||||
## Go conventions
|
||||
|
||||
- **Only `internal/ui` prints.** forbidigo bans `fmt.Print*`, `os.Stdout`/`os.Stderr` elsewhere and `os.Exit` outside `cmd/devvm`. Data goes to the UI's `Stdout()`, non-message log lines to its `Stderr()`.
|
||||
- **Functions take their caller's `ctx`:** forbidigo bans `context.Background`/`TODO` outside `internal/ui` and `cmd/devvm`; one that must outlive its caller's gets `//nolint:forbidigo // why`.
|
||||
- **Every `//nolint` names its linters and says why** (nolintlint). Functions stay within revive's `function-length` and `cognitive-complexity` limits: split one that grows past them.
|
||||
- **Only `cmd/devvm` and `internal/cli` import `internal/ui`** (depguard): cli passes the run's `*ui.UI` to each command; other packages take what they need as fields (`Info`/`Warn func(msg.M)`, `LoggedCmd`, `AddCleanup`, `Interrupted`…), set from a small `UI` interface of their own that their constructors take, or cli asks first and passes the answer in.
|
||||
- **Fail with `u.Die(msg.X(...))`:** it prints and panics; `ui.Main` recovers, runs the cleanups, returns 1. Commands end with `fail` (`DieLogged` for a `LoggedError`). INT/TERM/HUP cancel the root context, wait for the logged command, run the cleanups and return 130; a second signal is ignored; after one, `Die` prints nothing. A logged command a signal ended (or 128+) waits up to 1 s for devvm's own interrupt, as Ctrl+C can end it first.
|
||||
- **Cleanups:** whatever a failure would leave (a build VM, a temp file) registers with the UI's `AddCleanup` and is removed once done; one only for interrupts checks `Interrupted()`. Cleanups get a fresh context.
|
||||
@@ -62,7 +64,7 @@ Still to come: smolvm's emulations, the docker backend; the release keys (`packa
|
||||
- **OS-specific code goes behind build tags** in `internal/platform` (`*_darwin.go`, `*_linux.go`, `*_other.go`).
|
||||
- **Dependencies:** the depguard allowlist (cobra, pflag, cobra/doc, go-i18n, BurntSushi/toml, x/text, x/term, x/sys; go-internal in tests; cobra/doc's own deps never imported directly). `internal/proxy` is stdlib only. Adding one: ask.
|
||||
- **External tools are commands, never linked** (`limactl`, `docker`, `security`, `git`, `chflags`…); prefer the standard library to shelling out. Strings into a backend's shell are quoted with `shq()`.
|
||||
- **Test seams are fields** tests set (`Host`, `Exec`, `Runner`, `OS`, `Warn`…), never package vars; the one exception is `internal/proxy`'s globals (set by `Main`).
|
||||
- **Test seams are fields** tests set (`Host`, `Exec`, `Runner`, `OS`, `Warn`…), never package vars (reassign: no package sets another's); the one exception is `internal/proxy`'s globals (set by `Main`).
|
||||
- **A command exists only once it's ported;** `TestReferenceIsCurrent` fails on a stale CLI reference.
|
||||
- `CGO_ENABLED=0`. `internal/proxy` is unix-only for now (`syscall.Kill`, `Flock`).
|
||||
|
||||
|
||||
@@ -59,6 +59,20 @@ Before and after every change, `mise run fmt && mise run lint && mise run test`
|
||||
|
||||
CI runs `lint` and `test` on macOS and Linux.
|
||||
|
||||
## Go lint rules
|
||||
|
||||
golangci-lint enforces the [Go conventions](https://github.com/w3cj/devvm/blob/main/AGENTS.md#go-conventions) in `.golangci.yml`:
|
||||
|
||||
| Rule | Enforces |
|
||||
| --- | --- |
|
||||
| forbidigo | only `internal/ui` prints (`fmt.Print*`, `os.Stdout`, `os.Stderr`); only `cmd/devvm` calls `os.Exit`; only `internal/ui` and `cmd/devvm` make a context (`context.Background`, `context.TODO`), every other function takes its caller's |
|
||||
| depguard | the allowed modules; `internal/proxy` uses only the standard library; only `cmd/devvm` and `internal/cli` import `internal/ui` |
|
||||
| nolintlint | every `//nolint` names its linters and says why, and is still needed |
|
||||
| reassign | no package reassigns another package's variables, tests included |
|
||||
| revive | at most 100 statements or 160 lines a function (`function-length`), and a cognitive complexity of 75 (`cognitive-complexity`) |
|
||||
|
||||
A fresh context elsewhere, such as for a cleanup that outlives a canceled run, or a lookup that many requests share, takes `//nolint:forbidigo // <why>`.
|
||||
|
||||
## CLI tests
|
||||
|
||||
CLI tests are [testscript](https://pkg.go.dev/github.com/rogpeppe/go-internal/testscript) scripts in `testdata/script/*.txtar`, run by `internal/cli/script_test.go` against a freshly built `devvm`. Call it with `exec devvm …`:
|
||||
|
||||
@@ -73,7 +73,7 @@ type Backend interface {
|
||||
// Lifeline is the pid file of the host process that runs the VM once
|
||||
// it starts, which the VM's proxy follows: it exits when that process
|
||||
// does. Not a VM's own file: the VM can't write it.
|
||||
Lifeline(vm string) string
|
||||
Lifeline(ctx context.Context, vm string) string
|
||||
// ProxyURL is devvm's proxy as a VM started with c reaches it, its
|
||||
// user and password included; "" unless c.Net is NetProxy.
|
||||
ProxyURL(c Confinement) string
|
||||
|
||||
@@ -303,7 +303,7 @@ func (f *Fake) Exec(_ context.Context, vm string, argv []string, o backend.ExecO
|
||||
}
|
||||
|
||||
// Lifeline returns LifelineFile.
|
||||
func (f *Fake) Lifeline(string) string { return f.LifelineFile }
|
||||
func (f *Fake) Lifeline(context.Context, string) string { return f.LifelineFile }
|
||||
|
||||
// UsesDecider returns Decides.
|
||||
func (f *Fake) UsesDecider() bool { return f.Decides }
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package backendtest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
@@ -10,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func TestFakeRecordsAndAnswers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
f := New("fake", backend.Caps{backend.FeatureClone: backend.Native})
|
||||
f.ShellCmd = backend.Command{Path: "/bin/true", Args: []string{"true"}}
|
||||
|
||||
@@ -58,7 +57,7 @@ func TestFakeRecordsAndAnswers(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFakePresetErrors(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
boom := errors.New("boom")
|
||||
f := New("fake", nil)
|
||||
f.Errs = map[string]error{"CreateVM": boom}
|
||||
|
||||
@@ -347,7 +347,7 @@ func (l *Lima) Confined(_ context.Context, vm string) (bool, error) {
|
||||
|
||||
// Lifeline is the VM's hostagent's pid file: the process that runs the VM
|
||||
// and its network.
|
||||
func (l *Lima) Lifeline(vm string) string { return l.haPIDFile(vm) }
|
||||
func (l *Lima) Lifeline(_ context.Context, vm string) string { return l.haPIDFile(vm) }
|
||||
|
||||
// ProxyURL is devvm's proxy as a VM started with c reaches it.
|
||||
func (l *Lima) ProxyURL(c backend.Confinement) string {
|
||||
|
||||
@@ -86,39 +86,11 @@ func TestStartConfined(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
l, f, _ := testLima(t, tc.os)
|
||||
t.Setenv(GuestFwdEnv, "left over")
|
||||
f.out["limactl list --json"] = stoppedVM
|
||||
if err := os.MkdirAll(l.Dirs.LimaVM("v"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(l.haPIDFile("v"), []byte("12345\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// limactl edit writes the environment it's given into lima.yaml.
|
||||
yaml := filepath.Join(l.Dirs.LimaVM("v"), "lima.yaml")
|
||||
if err := os.WriteFile(yaml, []byte("cpus: 4\n"), 0o644); err != nil { //nolint:gosec // as Lima writes it
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.do = func(c call) {
|
||||
if i := slices.IndexFunc(c.argv, func(a string) bool { return strings.HasPrefix(a, ".env = ") }); i >= 0 && c.argv[1] == "edit" {
|
||||
if err := os.WriteFile(yaml, []byte("cpus: 4\nenv: "+strings.TrimPrefix(c.argv[i], ".env = ")+"\n"), 0o644); err != nil { //nolint:gosec // as Lima writes it
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
yaml := stoppedWithYAML(t, l, f)
|
||||
if err := l.Start(t.Context(), "v", tc.c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var edits []string
|
||||
for _, c := range f.calls {
|
||||
if c.argv[1] == "edit" {
|
||||
for i, a := range c.argv {
|
||||
if a == "--set" {
|
||||
edits = append(edits, c.argv[i+1])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !slices.Equal(edits, tc.edits) {
|
||||
if edits := editSets(f); !slices.Equal(edits, tc.edits) {
|
||||
t.Errorf("edits\n%s\nwant\n%s", strings.Join(edits, "\n"), strings.Join(tc.edits, "\n"))
|
||||
}
|
||||
// The password is in no command's arguments: devvm writes it into
|
||||
@@ -128,35 +100,9 @@ func TestStartConfined(t *testing.T) {
|
||||
t.Errorf("the password is in %q", c.line())
|
||||
}
|
||||
}
|
||||
data, err := os.ReadFile(yaml) //nolint:gosec // the test's own file
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := l.ProxyURL(tc.c)
|
||||
if tc.c.Net == backend.NetProxy {
|
||||
fi, err := os.Stat(yaml)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(data), `"HTTP_PROXY":"`+u+`"`) || strings.Contains(string(data), passwordStandIn) || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("lima.yaml (%v):\n%s", fi.Mode(), data)
|
||||
}
|
||||
} else if u != "" || string(data) != "cpus: 4\n" {
|
||||
t.Errorf("ProxyURL = %q, lima.yaml:\n%s", u, data)
|
||||
}
|
||||
checkLimaYAML(t, l, yaml, tc.c)
|
||||
s := startCall(t, f)
|
||||
args := s.argv[slices.Index(s.argv, "start"):]
|
||||
if !slices.Equal(args, []string{"start", "--tty=false", "v"}) {
|
||||
t.Errorf("start's arguments: %q", args)
|
||||
}
|
||||
if wrapped := s.argv[0] == "sandbox-exec"; wrapped != tc.wrapped {
|
||||
t.Errorf("under sandbox-exec: %q", s.argv)
|
||||
} else if wrapped {
|
||||
lc := s.argv[3]
|
||||
if !slices.Equal(s.argv[1:3], []string{"-f", l.profileFile("v")}) || !filepath.IsAbs(lc) || filepath.Base(lc) != "limactl" {
|
||||
t.Errorf("sandbox-exec's arguments: %q", s.argv)
|
||||
}
|
||||
}
|
||||
checkStartCall(t, l, s, tc.wrapped)
|
||||
w, ok := envOf(s, "QEMU_SYSTEM_AARCH64")
|
||||
if ok != tc.qemu || ok && w != filepath.Join(l.Dirs.Run(), "qemu", "qemu-system-aarch64") {
|
||||
t.Errorf("QEMU_SYSTEM_AARCH64=%q (%v)", w, ok)
|
||||
@@ -164,9 +110,6 @@ func TestStartConfined(t *testing.T) {
|
||||
if fwd, _ := envOf(s, GuestFwdEnv); tc.qemu && fwd != tc.guestfwd {
|
||||
t.Errorf("%s=%q, want %q", GuestFwdEnv, fwd, tc.guestfwd)
|
||||
}
|
||||
if s.dir != l.Dirs.Data {
|
||||
t.Errorf("ran in %s", s.dir)
|
||||
}
|
||||
if ok, err := l.Confined(t.Context(), "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if ok {
|
||||
@@ -176,6 +119,95 @@ func TestStartConfined(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// stoppedWithYAML makes v a stopped VM with a stale hostagent pid and a
|
||||
// lima.yaml that limactl edit writes the environment it's given into,
|
||||
// and returns lima.yaml's path.
|
||||
func stoppedWithYAML(t *testing.T, l *Lima, f *fakeRunner) string {
|
||||
t.Helper()
|
||||
f.out["limactl list --json"] = stoppedVM
|
||||
if err := os.MkdirAll(l.Dirs.LimaVM("v"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(l.haPIDFile("v"), []byte("12345\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
yaml := filepath.Join(l.Dirs.LimaVM("v"), "lima.yaml")
|
||||
if err := os.WriteFile(yaml, []byte("cpus: 4\n"), 0o644); err != nil { //nolint:gosec // as Lima writes it
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.do = func(c call) {
|
||||
if i := slices.IndexFunc(c.argv, func(a string) bool { return strings.HasPrefix(a, ".env = ") }); i >= 0 && c.argv[1] == "edit" {
|
||||
if err := os.WriteFile(yaml, []byte("cpus: 4\nenv: "+strings.TrimPrefix(c.argv[i], ".env = ")+"\n"), 0o644); err != nil { //nolint:gosec // as Lima writes it
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return yaml
|
||||
}
|
||||
|
||||
// editSets returns the --set values of every limactl edit, in order.
|
||||
func editSets(f *fakeRunner) []string {
|
||||
var edits []string
|
||||
for _, c := range f.calls {
|
||||
if c.argv[1] != "edit" {
|
||||
continue
|
||||
}
|
||||
for i, a := range c.argv {
|
||||
if a == "--set" {
|
||||
edits = append(edits, c.argv[i+1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return edits
|
||||
}
|
||||
|
||||
// checkLimaYAML checks that a start with c left lima.yaml with the proxy's
|
||||
// address and password (owner-only), or untouched without the proxy.
|
||||
func checkLimaYAML(t *testing.T, l *Lima, yaml string, c backend.Confinement) {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(yaml) //nolint:gosec // the test's own file
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := l.ProxyURL(c)
|
||||
if c.Net != backend.NetProxy {
|
||||
if u != "" || string(data) != "cpus: 4\n" {
|
||||
t.Errorf("ProxyURL = %q, lima.yaml:\n%s", u, data)
|
||||
}
|
||||
return
|
||||
}
|
||||
fi, err := os.Stat(yaml)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(data), `"HTTP_PROXY":"`+u+`"`) || strings.Contains(string(data), passwordStandIn) || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("lima.yaml (%v):\n%s", fi.Mode(), data)
|
||||
}
|
||||
}
|
||||
|
||||
// checkStartCall checks limactl start's arguments, folder and, when
|
||||
// wrapped, its sandbox-exec profile.
|
||||
func checkStartCall(t *testing.T, l *Lima, s call, wrapped bool) {
|
||||
t.Helper()
|
||||
args := s.argv[slices.Index(s.argv, "start"):]
|
||||
if !slices.Equal(args, []string{"start", "--tty=false", "v"}) {
|
||||
t.Errorf("start's arguments: %q", args)
|
||||
}
|
||||
if s.dir != l.Dirs.Data {
|
||||
t.Errorf("ran in %s", s.dir)
|
||||
}
|
||||
if (s.argv[0] == "sandbox-exec") != wrapped {
|
||||
t.Errorf("under sandbox-exec: %q", s.argv)
|
||||
return
|
||||
}
|
||||
if wrapped {
|
||||
lc := s.argv[3]
|
||||
if !slices.Equal(s.argv[1:3], []string{"-f", l.profileFile("v")}) || !filepath.IsAbs(lc) || filepath.Base(lc) != "limactl" {
|
||||
t.Errorf("sandbox-exec's arguments: %q", s.argv)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fillPassword fails, changing nothing, when lima.yaml lacks the stand-in or
|
||||
// the URL isn't plain YAML.
|
||||
func TestFillPassword(t *testing.T) {
|
||||
|
||||
@@ -24,6 +24,7 @@ func (quietUI) LogNote() {}
|
||||
func (quietUI) WithSteps(ctx context.Context, _ int) context.Context { return ctx }
|
||||
func (quietUI) AddCleanup(func(context.Context)) func() { return func() {} }
|
||||
func (quietUI) Interrupted() bool { return false }
|
||||
func (quietUI) StdinIsTerminal() bool { return false }
|
||||
|
||||
// DEVVM_UNREVIEWED counts only in a test build: a release ignores it.
|
||||
func TestUnreviewedOnlyInTestBuilds(t *testing.T) {
|
||||
|
||||
@@ -34,8 +34,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/from"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
@@ -101,11 +99,12 @@ type Smolvm struct {
|
||||
Interrupted func() bool
|
||||
}
|
||||
|
||||
// UI is where the backend prints, the run log its commands run into, and
|
||||
// the run's cleanup stack.
|
||||
// UI is where the backend prints, the run log its commands run into, the
|
||||
// run's cleanup stack, and whether devvm's input is a terminal.
|
||||
type UI interface {
|
||||
Info(msg.M)
|
||||
Warn(msg.M)
|
||||
StdinIsTerminal() bool
|
||||
LoggedCmd(ctx context.Context, step msg.M, cmd *exec.Cmd) error
|
||||
WithSteps(ctx context.Context, total int) context.Context
|
||||
AddCleanup(f func(context.Context)) (remove func())
|
||||
@@ -125,7 +124,7 @@ func New(d paths.Dirs, assets fs.FS, u UI) *Smolvm {
|
||||
Dirs: d, Runner: logRunner{u.LoggedCmd}, OS: runtime.GOOS, Arch: runtime.GOARCH, Assets: assets,
|
||||
Getenv: os.Getenv, User: user.Current, Memory: platform.Memory,
|
||||
Digest: from.NewRegistry().Digest, KVM: kvm,
|
||||
Terminal: func() bool { return term.IsTerminal(int(os.Stdin.Fd())) },
|
||||
Terminal: u.StdinIsTerminal,
|
||||
FreePort: freePort, PortFree: portFree,
|
||||
Info: u.Info, Warn: u.Warn,
|
||||
WithSteps: u.WithSteps, AddCleanup: u.AddCleanup, Interrupted: u.Interrupted,
|
||||
|
||||
@@ -37,6 +37,7 @@ func (testUI) LoggedCmd(_ context.Context, _ msg.M, cmd *exec.Cmd) error { retur
|
||||
func (testUI) WithSteps(ctx context.Context, _ int) context.Context { return ctx }
|
||||
func (testUI) AddCleanup(func(context.Context)) func() { return func() {} }
|
||||
func (testUI) Interrupted() bool { return false }
|
||||
func (testUI) StdinIsTerminal() bool { return false }
|
||||
|
||||
// sandbox is a smolvm backend on the stub (testdata/stubs/smolvm), first
|
||||
// on PATH, with devvm's folders in a new temporary folder; its user is u,
|
||||
@@ -352,7 +353,7 @@ func TestStart(t *testing.T) {
|
||||
if b, _ := os.ReadFile(filepath.Join(s.stub, "smolvm-agent-"+fw)); strings.TrimSpace(string(b)) != "/a.sock" {
|
||||
t.Errorf("agent: %q", b)
|
||||
}
|
||||
if got := s.Lifeline(fw); got != filepath.Join(s.stub, "smolvm-data", fw, "agent.pid") {
|
||||
if got := s.Lifeline(t.Context(), fw); got != filepath.Join(s.stub, "smolvm-data", fw, "agent.pid") {
|
||||
t.Errorf("Lifeline = %q", got)
|
||||
}
|
||||
if err := s.Stop(t.Context(), fw); err != nil {
|
||||
|
||||
@@ -178,7 +178,7 @@ func (s *Smolvm) Start(ctx context.Context, vm string, c backend.Confinement) er
|
||||
return backend.Logged(msg.StartFailed(vm))
|
||||
}
|
||||
if proxy {
|
||||
if r.Confined, err = s.lifeline(vm); err != nil {
|
||||
if r.Confined, err = s.lifeline(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
@@ -281,7 +281,7 @@ func (s *Smolvm) Confined(ctx context.Context, vm string) (bool, error) {
|
||||
if m.status() != backend.StatusRunning || !m.closed() {
|
||||
return false, nil
|
||||
}
|
||||
cur, err := s.lifeline(vm)
|
||||
cur, err := s.lifeline(ctx, vm)
|
||||
if err != nil || cur != r.Confined {
|
||||
return false, err
|
||||
}
|
||||
@@ -295,8 +295,8 @@ func (s *Smolvm) Confined(ctx context.Context, vm string) (bool, error) {
|
||||
|
||||
// lifeline returns what the machine's lifeline holds (its pid and start
|
||||
// time), "" when there's none.
|
||||
func (s *Smolvm) lifeline(vm string) (string, error) {
|
||||
path := s.Lifeline(vm)
|
||||
func (s *Smolvm) lifeline(ctx context.Context, vm string) (string, error) {
|
||||
path := s.Lifeline(ctx, vm)
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
@@ -319,10 +319,9 @@ func alive(pid int) bool {
|
||||
// Lifeline is the pid file of the process that runs the machine, in
|
||||
// smolvm's folder for it: its first line is the pid, its second the start
|
||||
// time. "" when smolvm can't say where that is.
|
||||
func (s *Smolvm) Lifeline(vm string) string {
|
||||
out, err := s.Runner.Output(s.smolvm(context.Background(), "machine", "data-dir", "--name", vm))
|
||||
dir := strings.TrimSpace(string(out))
|
||||
if err != nil || !filepath.IsAbs(dir) {
|
||||
func (s *Smolvm) Lifeline(ctx context.Context, vm string) string {
|
||||
dir := s.dataDir(ctx, vm)
|
||||
if dir == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(dir, "agent.pid")
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ func newLogCmd(u *ui.UI) *cobra.Command {
|
||||
"command that allows each.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
o.Lines = int(min(lines, 1<<31-1)) //nolint:gosec // bounded
|
||||
o.Lines = int(min(lines, 1<<31-1))
|
||||
withEnv(u, func(env *vm.Env) error { return vm.Net{Env: env}.Log(cmd.Context(), u.Stdout(), o) }, msg.LogFailed)
|
||||
return nil
|
||||
},
|
||||
|
||||
@@ -58,7 +58,7 @@ func sandbox(env *testscript.Env, bin, stubs string) error {
|
||||
env.Defer(func() {
|
||||
// VMs' proxies follow a stub hostagent that's gone before they
|
||||
// look: stop them with the sandbox.
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_proxy -listen .* -lifeline "+root+"/").Run() //nolint:gosec // the test's own folder
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_proxy -listen .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end
|
||||
_ = os.RemoveAll(root)
|
||||
})
|
||||
|
||||
|
||||
@@ -325,7 +325,7 @@ func hasHooks(dir string) bool {
|
||||
found = true
|
||||
return fs.SkipAll
|
||||
}
|
||||
return nil //nolint:nilerr // unreadable: skipped, like find
|
||||
return nil // unreadable: skipped, like find
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ func NewLog(d paths.Dirs, vm string) *Log {
|
||||
// With follow it then writes each new one, until ctx ends. Lines that
|
||||
// aren't events are skipped.
|
||||
func (l *Log) Write(ctx context.Context, w io.Writer, n int, follow bool) error {
|
||||
f, err := os.Open(l.Path) //nolint:gosec // the VM's event log, in devvm's folder
|
||||
f, err := os.Open(l.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func oneLine(s string) string {
|
||||
// whatever the allowlist says, or a host the policy doesn't take, gets -
|
||||
// instead: the command is meant to be pasted into a shell.
|
||||
func (l *Log) WriteBlocked(w io.Writer) error {
|
||||
f, err := os.Open(l.Path) //nolint:gosec // the VM's event log, in devvm's folder
|
||||
f, err := os.Open(l.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestWriteLog(t *testing.T) {
|
||||
{0, ""},
|
||||
} {
|
||||
var b bytes.Buffer
|
||||
if err := (&Log{Path: path}).Write(context.Background(), &b, c.n, false); err != nil || b.String() != c.want {
|
||||
if err := (&Log{Path: path}).Write(t.Context(), &b, c.n, false); err != nil || b.String() != c.want {
|
||||
t.Errorf("n=%d: %q, %v; want %q", c.n, b.String(), err, c.want)
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func TestWriteLogFollow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
var out syncBuffer
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
l := &Log{Path: path, Tick: 5 * time.Millisecond}
|
||||
go func() { done <- l.Write(ctx, &out, 1, true) }()
|
||||
|
||||
@@ -217,9 +217,9 @@ func (f *proxies) start(t *testing.T) func(string, []string, *os.File) (int, err
|
||||
return func(path string, args []string, out *os.File) (int, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
cmd := exec.CommandContext(context.Background(), "sleep", "30")
|
||||
cmd := exec.CommandContext(t.Context(), "sleep", "30")
|
||||
if f.quiet {
|
||||
cmd = exec.CommandContext(context.Background(), "true")
|
||||
cmd = exec.CommandContext(t.Context(), "true")
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -195,7 +195,7 @@ func (p *Proxy) Forget(vm string) error {
|
||||
// decider too, with a token new at each start.
|
||||
func (p *Proxy) Prepare(ctx context.Context, b backend.Backend, st *state.VM, running bool) (backend.Confinement, error) {
|
||||
vm := st.Name()
|
||||
lifeline := b.Lifeline(vm)
|
||||
lifeline := b.Lifeline(ctx, vm)
|
||||
none := backend.Confinement{}
|
||||
// The CA lasts 30 days: a new one is made when it has under a week left
|
||||
// (VMs trust it from their next start). Kept out of backups: a copy of
|
||||
|
||||
@@ -31,5 +31,5 @@ func DevIno(fi fs.FileInfo) string {
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatUint(uint64(st.Dev), 10) + ":" + strconv.FormatUint(st.Ino, 10) //nolint:gosec,unconvert // Dev's type differs between systems
|
||||
return strconv.FormatUint(uint64(st.Dev), 10) + ":" + strconv.FormatUint(st.Ino, 10) //nolint:gosec,unconvert,nolintlint // Dev's type differs between systems: each needs one of the two
|
||||
}
|
||||
@@ -186,13 +186,13 @@ func TestSetIDFiles(t *testing.T) {
|
||||
mkdirs(t, filepath.Join(d, "sub"))
|
||||
tool := filepath.Join(d, "sub", "tool")
|
||||
touch(t, filepath.Join(d, "plain"), tool)
|
||||
if err := os.Chmod(tool, fs.ModeSetuid|0o755); err != nil { //nolint:gosec // the test's own file
|
||||
if err := os.Chmod(tool, fs.ModeSetuid|0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := SetIDFiles(d); !slices.Equal(got, []string{tool}) {
|
||||
t.Errorf("SetIDFiles = %v, want %s", got, tool)
|
||||
}
|
||||
if err := os.Chmod(tool, fs.ModeSetgid|0o755); err != nil { //nolint:gosec // the test's own file
|
||||
if err := os.Chmod(tool, fs.ModeSetgid|0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := SetIDFiles(d); len(got) != 1 {
|
||||
|
||||
@@ -35,7 +35,7 @@ func preludeFor(token []byte, dest netip.AddrPort, first []byte) []byte {
|
||||
}
|
||||
_ = binary.Write(&b, binary.BigEndian, dest.Port())
|
||||
b.Write(a.AsSlice())
|
||||
_ = binary.Write(&b, binary.BigEndian, uint16(min(len(first), 0xffff))) //nolint:gosec // capped
|
||||
_ = binary.Write(&b, binary.BigEndian, uint16(min(len(first), 0xffff)))
|
||||
b.Write(first)
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ var (
|
||||
// Refresh this long before an access token expires: the proxy caches values for valueTTL.
|
||||
refreshMargin = 10 * time.Minute
|
||||
farFuture = time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
httpClient = &http.Client{Timeout: 30 * time.Second}
|
||||
// How long a token refresh may take.
|
||||
refreshTimeout = 30 * time.Second
|
||||
// -login-salt: the VM's key, which ends every placeholder, so each VM's are its own (a proxy
|
||||
// only puts a value in for the placeholders bound for its VM).
|
||||
loginSalt = ""
|
||||
@@ -105,11 +106,11 @@ func lockLogin(path string) (func(), error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := syscall.Flock(int(d.Fd()), syscall.LOCK_EX); err != nil { //nolint:gosec // file descriptors fit in an int
|
||||
if err := syscall.Flock(int(d.Fd()), syscall.LOCK_EX); err != nil {
|
||||
_ = d.Close()
|
||||
return nil, err
|
||||
}
|
||||
return func() { _ = syscall.Flock(int(d.Fd()), syscall.LOCK_UN); _ = d.Close() }, nil //nolint:gosec // as above
|
||||
return func() { _ = syscall.Flock(int(d.Fd()), syscall.LOCK_UN); _ = d.Close() }, nil
|
||||
}
|
||||
|
||||
// writeJSON replaces path atomically, keeping it mode 600.
|
||||
@@ -398,7 +399,9 @@ func opencodeGet(path, name string) (string, error) {
|
||||
return "", fmt.Errorf("no opencode login %q", id)
|
||||
}
|
||||
|
||||
// refresh posts an OAuth refresh request, as JSON (Codex) or a form (opencode).
|
||||
// refresh posts an OAuth refresh request, as JSON (Codex) or a form (opencode), within
|
||||
// refreshTimeout. It runs under the login file's lock and rewrites it, for every request that
|
||||
// needs the token: no one request's end cancels it.
|
||||
func refresh(u string, form bool, fields map[string]string) (map[string]any, error) {
|
||||
var body []byte
|
||||
ctype := "application/json"
|
||||
@@ -411,12 +414,14 @@ func refresh(u string, form bool, fields map[string]string) (map[string]any, err
|
||||
} else {
|
||||
body, _ = json.Marshal(fields)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, u, bytes.NewReader(body))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), refreshTimeout) //nolint:forbidigo // shared by every request
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
resp, err := httpClient.Do(req)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -422,7 +422,7 @@ func handleConnect(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
_, _ = client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
intercept(bufConn{client, buf.Reader}, host, port, e)
|
||||
intercept(r.Context(), bufConn{client, buf.Reader}, host, port, e)
|
||||
return
|
||||
}
|
||||
up, err := dial(r.Context(), host, port)
|
||||
|
||||
@@ -132,7 +132,9 @@ var secretValue = func(name string) (string, error) {
|
||||
if secretCmd == "" {
|
||||
return "", errors.New("no -secret-cmd")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
// The value is cached for every request: no one request's end cancels it.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) //nolint:forbidigo // shared by every request
|
||||
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, secretCmd, "secret", "get", name).Output() //nolint:gosec // devvm names itself
|
||||
if err != nil {
|
||||
@@ -339,15 +341,19 @@ func leafFor(host string) (*tls.Certificate, error) {
|
||||
// intercept serves one CONNECT tunnel to host:443 whose host has bindings: TLS with a minted
|
||||
// certificate on the client side, HTTP/1.1 or HTTP/2 inside, and each request forwarded upstream
|
||||
// over a new TLS connection with the secrets put in. Each request must be for host itself: the
|
||||
// secrets are bound to it, so another Host (a site on the same CDN, say) gets 421.
|
||||
func intercept(client net.Conn, host string, port int, e Event) {
|
||||
// secrets are bound to it, so another Host (a site on the same CDN, say) gets 421. The handshake
|
||||
// with the VM gets 30 seconds.
|
||||
func intercept(ctx context.Context, client net.Conn, host string, port int, e Event) {
|
||||
tconn := tls.Server(client, &tls.Config{
|
||||
NextProtos: []string{"h2", "http/1.1"},
|
||||
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
return leafFor(host)
|
||||
},
|
||||
})
|
||||
if err := tconn.HandshakeContext(context.Background()); err != nil {
|
||||
hctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
err := tconn.HandshakeContext(hctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
e.Event, e.Reason = "blocked", "TLS with the VM failed (is the devvm CA installed?): "+err.Error()
|
||||
record(e)
|
||||
_ = client.Close()
|
||||
|
||||
@@ -22,7 +22,7 @@ func sniOf(rec []byte) string {
|
||||
return nil, errStop
|
||||
},
|
||||
})
|
||||
_ = c.HandshakeContext(context.Background())
|
||||
_ = c.HandshakeContext(context.Background()) //nolint:forbidigo // reads a record in memory: nothing to wait for or cancel
|
||||
return name
|
||||
}
|
||||
|
||||
|
||||
@@ -363,7 +363,7 @@ func TestRealAgent(t *testing.T) {
|
||||
if err := os.MkdirAll(d.Data, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent := exec.CommandContext(context.Background(), "ssh-agent", "-D", "-a", d.AgentSock()) //nolint:gosec // the test's own socket
|
||||
agent := exec.CommandContext(t.Context(), "ssh-agent", "-D", "-a", d.AgentSock()) //nolint:gosec // the test's own socket
|
||||
if err := agent.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ func (t *Tools) Resolve(ctx context.Context, out string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(tmp, "mise.toml"), config, 0o600); err != nil { //nolint:gosec // devvm's own temporary folder
|
||||
if err := os.WriteFile(filepath.Join(tmp, "mise.toml"), config, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd, err := miseCmd(ctx, mise, tmp, "lock", "--platform", strings.Join(t.platforms(), ","))
|
||||
|
||||
@@ -20,7 +20,7 @@ func (u *UI) logged(ctx context.Context, step msg.M, argv ...string) error {
|
||||
|
||||
func writeFile(t *testing.T, path, s string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(s), 0o600); err != nil { //nolint:gosec // the test's own files
|
||||
if err := os.WriteFile(path, []byte(s), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ func TestKeepsTheLast20Logs(t *testing.T) {
|
||||
u, _, _ := testUI(t, "")
|
||||
runs, _ := u.runLogs()
|
||||
logs := filepath.Dir(runs)
|
||||
if err := os.MkdirAll(runs, 0o700); err != nil { //nolint:gosec // the test's own folder
|
||||
if err := os.MkdirAll(runs, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := time.Now().Add(-time.Hour)
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ func runLogs() (string, error) {
|
||||
return d.RunLogs(), nil
|
||||
}
|
||||
|
||||
func fd(f *os.File) int { return int(f.Fd()) } //nolint:gosec // file descriptors fit in an int
|
||||
func fd(f *os.File) int { return int(f.Fd()) }
|
||||
|
||||
func isTerminal(f *os.File) bool { return term.IsTerminal(fd(f)) }
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package vm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -63,9 +62,9 @@ func cloneEnv(t *testing.T) (e *Env, f *backendtest.Fake, vmfs string) {
|
||||
var cmd *exec.Cmd
|
||||
switch {
|
||||
case len(argv) > 3 && argv[0] == "git" && argv[1] == "-C":
|
||||
cmd = exec.CommandContext(context.Background(), "git", append([]string{"-C", vmfs + argv[2]}, argv[3:]...)...) //nolint:gosec // the test's own
|
||||
cmd = exec.CommandContext(t.Context(), "git", append([]string{"-C", vmfs + argv[2]}, argv[3:]...)...) //nolint:gosec // the test's own
|
||||
case len(argv) == 6 && argv[0] == "sh" && strings.Contains(argv[2], "receive.denyCurrentBranch"):
|
||||
cmd = exec.CommandContext(context.Background(), "bash", "-c", `sudo() { "$@"; }; `+argv[2], argv[3], vmfs+argv[4], argv[5]) //nolint:gosec // the test's own
|
||||
cmd = exec.CommandContext(t.Context(), "bash", "-c", `sudo() { "$@"; }; `+argv[2], argv[3], vmfs+argv[4], argv[5]) //nolint:gosec // the test's own
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ func testProxy(t *testing.T, d paths.Dirs, home string) *netpolicy.Proxy {
|
||||
var mu sync.Mutex
|
||||
args := map[int][]string{}
|
||||
p.Start = func(path string, a []string, out *os.File) (int, error) {
|
||||
cmd := exec.CommandContext(context.Background(), "sleep", "30")
|
||||
cmd := exec.CommandContext(t.Context(), "sleep", "30")
|
||||
if err := cmd.Start(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ func ThisHost() (Host, error) {
|
||||
if err != nil {
|
||||
return Host{}, err
|
||||
}
|
||||
return Host{CPUs: runtime.NumCPU(), MemoryGiB: int(mem >> 30)}, nil //nolint:gosec // GiB fit in an int
|
||||
return Host{CPUs: runtime.NumCPU(), MemoryGiB: int(mem >> 30)}, nil
|
||||
}
|
||||
|
||||
// Check refuses a parsed size the host can't give, or a disk smaller than
|
||||
|
||||
+1
-1
@@ -180,7 +180,7 @@ func (e syncer) stage(ctx context.Context, st *state.VM, slug string, files []st
|
||||
// settings files with the values under secret-looking keys taken out (one
|
||||
// that can't be read that way isn't sent).
|
||||
func (e syncer) stageNet(s *stage, store *secrets.Store, vm, img, salt string) error {
|
||||
ca, err := os.ReadFile(filepath.Join(e.Dirs.CA(), "ca.pem")) //nolint:gosec // devvm's own CA
|
||||
ca, err := os.ReadFile(filepath.Join(e.Dirs.CA(), "ca.pem"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+145
-111
@@ -72,87 +72,44 @@ func (e Launch) Up(ctx context.Context, o Options) error {
|
||||
return e.open(ctx, o, t)
|
||||
}
|
||||
|
||||
// newVM is what create checked and chose for a new VM before building
|
||||
// anything.
|
||||
type newVM struct {
|
||||
img string
|
||||
size Size
|
||||
ports string
|
||||
net bool
|
||||
agent string // sshagent.On or Off
|
||||
mode string // ModeClone, or ""
|
||||
spec backend.VMSpec
|
||||
conf backend.Confinement
|
||||
builder *build.Builder
|
||||
}
|
||||
|
||||
// create makes the folder's VM and opens a shell in it.
|
||||
func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backend.Backend, size Size, ports string) error {
|
||||
vm := f.Name
|
||||
if o.Clone {
|
||||
if err := checkCloneRepo(ctx, f.Dir); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := e.checkUnsafe(f.Dir, o.UnsafeFolder); err != nil {
|
||||
return err
|
||||
}
|
||||
// Defaults are checked again: the files may be edited by hand. All
|
||||
// before the build, which can take minutes.
|
||||
def, err := e.defaultSize()
|
||||
n, err := e.plan(ctx, o, f, b, size, ports)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
size = size.Or(def)
|
||||
host, err := e.Host()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := size.Check(host, BaseDisk(e.Assets), vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if ports == "" {
|
||||
if ports, err = e.defaultPorts(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
builder := e.builder(b, o.From)
|
||||
img, err := e.resolveImage(o.Image, f.Dir, builder)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Asked before the build, which can take minutes.
|
||||
net := e.Proxy.Choose(o.NetworkPolicy, o.NoNetworkPolicy, vm)
|
||||
// Every VM has the share, read-only: a tool added later is mounted
|
||||
// from it. Its agents' folders on the host are mounted read-only.
|
||||
spec := backend.VMSpec{
|
||||
Name: vm, Project: f.Dir, AgentDirs: e.AgentMounts(img), Tools: e.Dirs.Tools(), ToolsAt: tools.ShareAt,
|
||||
AgentForwarding: o.SSHAgent, Size: size.Backend(), Ports: PortsBackend(ports),
|
||||
}
|
||||
agent := sshagent.Off
|
||||
if o.SSHAgent {
|
||||
agent = sshagent.On
|
||||
}
|
||||
e.useAgent(agent)
|
||||
mode := ""
|
||||
if o.Clone {
|
||||
spec.Project, mode = "", ModeClone
|
||||
}
|
||||
conf := backend.Confinement{Net: backend.NetDirect}
|
||||
if net {
|
||||
conf.Net = backend.NetProxy
|
||||
}
|
||||
need := append(spec.Features(), conf.Features()...)
|
||||
if o.Clone {
|
||||
// Its clone is copied in and fetched over ssh.
|
||||
need = append(need, backend.FeatureSSH)
|
||||
}
|
||||
if err := e.Registry.Require(b, vm, need...); err != nil {
|
||||
return err
|
||||
}
|
||||
// A new VM gets the newest tools: check now when the daily check is
|
||||
// due.
|
||||
groups := image.ToolsOf(img)
|
||||
groups := image.ToolsOf(n.img)
|
||||
if len(groups) > 0 && e.Tools.CheckDue() {
|
||||
e.Tools.Check(ctx)
|
||||
}
|
||||
if err := builder.Build(ctx, img); err != nil {
|
||||
if err := n.builder.Build(ctx, n.img); err != nil {
|
||||
return err
|
||||
}
|
||||
chain, err := builder.Chain(image.WithoutTools(img))
|
||||
chain, err := n.builder.Chain(image.WithoutTools(n.img))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tg, err := builder.ToolTarget()
|
||||
tg, err := n.builder.ToolTarget()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
libc := tg.Libc
|
||||
files, err := e.Tools.Files(ctx, groups, tg)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -165,34 +122,14 @@ func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backe
|
||||
return err
|
||||
}
|
||||
|
||||
e.Info(msg.CreatingFrom(img, vm))
|
||||
e.Info(msg.CreatingFrom(n.img, vm))
|
||||
e.LogNote()
|
||||
// Until its first shell nothing of anyone's is in it: an interrupt
|
||||
// deletes it and its state, and takes off .git's locks, or removes
|
||||
// the repo's remote for its clone.
|
||||
var locking atomic.Bool
|
||||
done := e.AddCleanup(func(ctx context.Context) {
|
||||
if !e.Interrupted() {
|
||||
return
|
||||
}
|
||||
e.Info(msg.InterruptedVM(vm))
|
||||
if err := b.Delete(ctx, vm); err != nil && !errors.Is(err, backend.ErrNotFound) {
|
||||
e.Warn(msg.DeleteFailed(vm))
|
||||
}
|
||||
if locking.Load() {
|
||||
e.Protector(f.Dir).Unlock(ctx)
|
||||
}
|
||||
if st, err := state.ReadVM(e.Dirs, vm); err == nil && isClone(st) {
|
||||
clones(e).removeRemote(ctx, f.Dir, vm, st.Get(KeyCloneRemote))
|
||||
}
|
||||
_ = e.sshConfig().ForgetHostKeys(vm)
|
||||
_ = e.Proxy.Forget(vm)
|
||||
_ = os.Remove(e.Dirs.VMState(vm))
|
||||
})
|
||||
done := e.AddCleanup(e.undoCreate(b, f, &locking))
|
||||
// The state first, with the network choice: if a later step fails,
|
||||
// the VM never starts without it.
|
||||
st, err := state.CreateVM(e.Dirs, vm, state.NewVM{
|
||||
Image: img, Dir: f.Dir, Folder: id, Chain: chain.String(), From: o.From, Backend: b.Name(),
|
||||
Image: n.img, Dir: f.Dir, Folder: id, Chain: chain.String(), From: o.From, Backend: b.Name(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -202,33 +139,15 @@ func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backe
|
||||
if err := e.Proxy.Forget(vm); err != nil {
|
||||
return err
|
||||
}
|
||||
netState := "off"
|
||||
if net {
|
||||
netState = "on"
|
||||
}
|
||||
for _, kv := range [][2]string{
|
||||
{KeyNet, netState},
|
||||
{KeyMode, mode},
|
||||
{sshagent.Key, agent},
|
||||
{KeyLibc, libc},
|
||||
{KeyTools, strings.Join(files, " ")},
|
||||
{KeyCPUs, size.CPUs},
|
||||
{KeyMemory, size.Memory},
|
||||
{KeyDisk, size.Disk},
|
||||
} {
|
||||
if kv[1] == "" {
|
||||
continue
|
||||
}
|
||||
if err := st.Set(kv[0], kv[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := b.CreateVM(ctx, chain.Key(), spec); err != nil {
|
||||
if err := n.record(st, tg.Libc, files); err != nil {
|
||||
return err
|
||||
}
|
||||
if ports != "" && ports != PortsAll {
|
||||
if err := b.CreateVM(ctx, chain.Key(), n.spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if n.ports != "" && n.ports != PortsAll {
|
||||
for _, k := range []string{KeyPorts, KeyPortsSet} {
|
||||
if err := st.Set(k, ports); err != nil {
|
||||
if err := st.Set(k, n.ports); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -245,7 +164,7 @@ func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backe
|
||||
// Files an earlier VM of this folder made are named too.
|
||||
e.checkSetID(f.Dir)
|
||||
}
|
||||
if spec.AgentForwarding {
|
||||
if n.spec.AgentForwarding {
|
||||
e.checkAgent(ctx)
|
||||
}
|
||||
e.Info(msg.Starting(vm))
|
||||
@@ -253,7 +172,7 @@ func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backe
|
||||
var started backend.Confinement
|
||||
start := func(ctx context.Context) error {
|
||||
var err error
|
||||
started, err = e.start(ctx, b, st, conf)
|
||||
started, err = e.start(ctx, b, st, n.conf)
|
||||
return err
|
||||
}
|
||||
if err := start(ctx); err != nil {
|
||||
@@ -271,6 +190,121 @@ func (e Launch) create(ctx context.Context, o Options, f project.Folder, b backe
|
||||
return e.Exec(cmd)
|
||||
}
|
||||
|
||||
// plan checks and chooses what a new VM gets, all before the build,
|
||||
// which can take minutes: its image, size, ports, network policy (asked
|
||||
// for), SSH agent and the backend features it needs.
|
||||
func (e Launch) plan(ctx context.Context, o Options, f project.Folder, b backend.Backend, size Size, ports string) (newVM, error) {
|
||||
vm := f.Name
|
||||
if o.Clone {
|
||||
if err := checkCloneRepo(ctx, f.Dir); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
} else if err := e.checkUnsafe(f.Dir, o.UnsafeFolder); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
// Defaults are checked again: the files may be edited by hand.
|
||||
def, err := e.defaultSize()
|
||||
if err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
n := newVM{size: size.Or(def), ports: ports, agent: sshagent.Off, conf: backend.Confinement{Net: backend.NetDirect}}
|
||||
host, err := e.Host()
|
||||
if err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
if err := n.size.Check(host, BaseDisk(e.Assets), vm); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
if n.ports == "" {
|
||||
if n.ports, err = e.defaultPorts(); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
}
|
||||
n.builder = e.builder(b, o.From)
|
||||
if n.img, err = e.resolveImage(o.Image, f.Dir, n.builder); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
n.net = e.Proxy.Choose(o.NetworkPolicy, o.NoNetworkPolicy, vm)
|
||||
// Every VM has the share, read-only: a tool added later is mounted
|
||||
// from it. Its agents' folders on the host are mounted read-only.
|
||||
n.spec = backend.VMSpec{
|
||||
Name: vm, Project: f.Dir, AgentDirs: e.AgentMounts(n.img), Tools: e.Dirs.Tools(), ToolsAt: tools.ShareAt,
|
||||
AgentForwarding: o.SSHAgent, Size: n.size.Backend(), Ports: PortsBackend(n.ports),
|
||||
}
|
||||
if o.SSHAgent {
|
||||
n.agent = sshagent.On
|
||||
}
|
||||
e.useAgent(n.agent)
|
||||
if o.Clone {
|
||||
n.spec.Project, n.mode = "", ModeClone
|
||||
}
|
||||
if n.net {
|
||||
n.conf.Net = backend.NetProxy
|
||||
}
|
||||
need := append(n.spec.Features(), n.conf.Features()...)
|
||||
if o.Clone {
|
||||
// Its clone is copied in and fetched over ssh.
|
||||
need = append(need, backend.FeatureSSH)
|
||||
}
|
||||
if err := e.Registry.Require(b, vm, need...); err != nil {
|
||||
return newVM{}, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// record writes a new VM's choices into its state, with the libc and
|
||||
// tool files it was given.
|
||||
func (n newVM) record(st *state.VM, libc string, files []string) error {
|
||||
netState := "off"
|
||||
if n.net {
|
||||
netState = "on"
|
||||
}
|
||||
for _, kv := range [][2]string{
|
||||
{KeyNet, netState},
|
||||
{KeyMode, n.mode},
|
||||
{sshagent.Key, n.agent},
|
||||
{KeyLibc, libc},
|
||||
{KeyTools, strings.Join(files, " ")},
|
||||
{KeyCPUs, n.size.CPUs},
|
||||
{KeyMemory, n.size.Memory},
|
||||
{KeyDisk, n.size.Disk},
|
||||
} {
|
||||
if kv[1] == "" {
|
||||
continue
|
||||
}
|
||||
if err := st.Set(kv[0], kv[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// undoCreate is create's cleanup. Until its first shell nothing of
|
||||
// anyone's is in the VM: an interrupt deletes it and its state, and
|
||||
// takes off .git's locks (once locking is set), or removes the repo's
|
||||
// remote for its clone.
|
||||
func (e Launch) undoCreate(b backend.Backend, f project.Folder, locking *atomic.Bool) func(context.Context) {
|
||||
vm := f.Name
|
||||
return func(ctx context.Context) {
|
||||
if !e.Interrupted() {
|
||||
return
|
||||
}
|
||||
e.Info(msg.InterruptedVM(vm))
|
||||
if err := b.Delete(ctx, vm); err != nil && !errors.Is(err, backend.ErrNotFound) {
|
||||
e.Warn(msg.DeleteFailed(vm))
|
||||
}
|
||||
if locking.Load() {
|
||||
e.Protector(f.Dir).Unlock(ctx)
|
||||
}
|
||||
if st, err := state.ReadVM(e.Dirs, vm); err == nil && isClone(st) {
|
||||
clones(e).removeRemote(ctx, f.Dir, vm, st.Get(KeyCloneRemote))
|
||||
}
|
||||
_ = e.sshConfig().ForgetHostKeys(vm)
|
||||
_ = e.Proxy.Forget(vm)
|
||||
_ = os.Remove(e.Dirs.VMState(vm))
|
||||
}
|
||||
}
|
||||
|
||||
// setUp sets up a running VM, started with conf, for a shell in the
|
||||
// folder (setUpVM), and returns the shell's command.
|
||||
func (e Launch) setUp(ctx context.Context, b backend.Backend, st *state.VM, f project.Folder, conf backend.Confinement) (backend.Command, error) {
|
||||
|
||||
Reference in new issue
Block a user