From ba36323f942488070f3f8bcc0ac8f025a36604e4 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:59:20 +0000 Subject: [PATCH 01/22] apply: test executor rounds, stops, unfollowable tasks and error texts Pin behaviour surviving mutants showed untested: a failed listing's retry round and error keeping, stops before or during a round and RoundsSkipped, power items left untouched, a torn-down item resuming at its clone, Held refusals in a step, unfollowable tasks with no VM or a lock still held, resent snapshot requests, and half-deleted and leftover-disk error texts. --- internal/apply/executor_test.go | 187 ++++++++++++++++++++++++++++---- internal/apply/guard_test.go | 35 ++++++ internal/apply/review_test.go | 76 +++++++++++++ internal/apply/snapshot_test.go | 20 ++++ internal/apply/storage_test.go | 25 +++++ internal/apply/teardown_test.go | 4 + 6 files changed, 328 insertions(+), 19 deletions(-) diff --git a/internal/apply/executor_test.go b/internal/apply/executor_test.go index 9e5e3df..005f6e0 100644 --- a/internal/apply/executor_test.go +++ b/internal/apply/executor_test.go @@ -463,18 +463,29 @@ func TestOtherStopsDontWait(t *testing.T) { } } +// A run stopped before it starts runs nothing: every item reads not run, +// saying why the run stopped, and the rounds read as skipped. func TestCancelledRunReportsNotRun(t *testing.T) { - f := newCluster() - plan := deployTeak(t, f, "01") - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - res := testExecutor(f, &recorder{}).Run(ctx, plan) - if err := res.Interrupted["team01-teak"]; err == nil || err.Error() != "stopped before it started" || len(res.Failed) != 0 { - t.Errorf("result = %+v, want team01-teak interrupted as not run", res) - } - if len(res.Succeeded) != 0 { - t.Errorf("Succeeded = %v, want none", res.Succeeded) + for _, tc := range []struct { + cause error + want string + }{ + {nil, "stopped before it started"}, + {ErrCancelRequested, "cancelled before it started"}, + {errors.New("lost the job lock"), "stopped (lost the job lock) before it started"}, + } { + f := newCluster() + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancelCause(context.Background()) + cancel(tc.cause) + + res := testExecutor(f, &recorder{}).Run(ctx, plan) + if err := res.Interrupted["team01-teak"]; err == nil || err.Error() != tc.want || len(res.Failed) != 0 { + t.Errorf("cause %v: result = %+v, want team01-teak interrupted with %q", tc.cause, res, tc.want) + } + if len(res.Succeeded) != 0 || !res.RoundsSkipped { + t.Errorf("cause %v: Succeeded = %v, RoundsSkipped = %v; want none, true", tc.cause, res.Succeeded, res.RoundsSkipped) + } } } @@ -967,16 +978,19 @@ func TestItemWithoutStepsFails(t *testing.T) { } } +// A retry round whose VM listing fails keeps each item's earlier error; +// an item that never ran fails with the listing's. func TestFailedRefreshKeepsEarlierItemError(t *testing.T) { f := newCluster() plan := deployTeak(t, f, "01") - denied := &proxmox.APIError{Status: 403, Message: "Permission check failed (/vms/10121, VM.Config.Network)"} + // Retried next round, unlike a missing privilege. + denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} f.FailOn("setconfig:10121", denied, denied) armed := false f.OnRecord = func(key string) { if key == "setconfig:10121" && !armed { armed = true - for i := 0; i < config.Default().Retry.Attempts; i++ { + for range config.Default().Retry.Attempts { f.FailOn("cluster", &proxmox.APIError{Status: 500, Message: "pve is down"}) } } @@ -987,6 +1001,21 @@ func TestFailedRefreshKeepsEarlierItemError(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "network") { t.Errorf("error = %v, want the original network step error", err) } + if n := f.Called("setconfig:10121"); n != 1 { + t.Errorf("setconfig called %d times, want 1 (the retry round's listing failed)", n) + } + + f = newCluster() + plan = deployTeak(t, f, "01") + for range config.Default().Retry.Attempts { + f.FailOn("cluster", &proxmox.APIError{Status: 500, Message: "pve is down"}) + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + res = ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || !strings.HasPrefix(err.Error(), "listing VMs: ") || len(res.Interrupted) != 0 { + t.Errorf("never ran: result = %+v, want team01-teak failed listing VMs", res) + } } func TestShutdownTimeoutIsNotResent(t *testing.T) { @@ -1466,8 +1495,8 @@ func TestFinishedEventOmitsEmptyCleanup(t *testing.T) { testExecutor(f, rec).Run(context.Background(), deployTeak(t, f, "01")) infos := rec.find("", EventInfo) last := infos[len(infos)-1].Message - if !strings.HasPrefix(last, "finished: 1 succeeded") || strings.Contains(last, "cleanup") { - t.Errorf("last job event = %q, want no cleanup counts when there was nothing to clean up", last) + if want := "finished: 1 succeeded, 0 failed, 0 blocked"; last != want { + t.Errorf("last job event = %q, want %q: no zero interrupted or cleanup counts", last, want) } } @@ -1687,25 +1716,34 @@ func TestRoundsNotSkippedWhenRunCompletes(t *testing.T) { t.Errorf("failing run: RoundsSkipped = %v, failed = %v", res.RoundsSkipped, res.Failed) } - // A stop that arrives after the last round leaves nothing skipped. + // A stop that arrives once no item is left to retry leaves nothing + // skipped, though Run is still finishing up. f = newCluster() f.FailOn("setconfig:10121", denied, denied) ctx, cancel := context.WithCancel(context.Background()) defer cancel() ex := testExecutor(f, &recorder{}) ex.OnEvent = func(ev Event) { - if strings.HasPrefix(ev.Message, "finished:") { + if ev.Item == "team01-teak" && ev.Status == EventFailed { cancel() } } plan := deployTeak(t, f, "01") if res := ex.Run(ctx, plan); res.RoundsSkipped { - t.Errorf("stop after the run: RoundsSkipped = true") + t.Errorf("stop after the last item: RoundsSkipped = true") } + + // A run whose items all succeed at once runs no retry round. f = newCluster() - if res := testExecutor(f, &recorder{}).Run(context.Background(), deployTeak(t, f, "01")); res.RoundsSkipped || len(res.Failed) != 0 { + rec := &recorder{} + if res := testExecutor(f, rec).Run(context.Background(), deployTeak(t, f, "01")); res.RoundsSkipped || len(res.Failed) != 0 { t.Errorf("clean run: %+v", res) } + for _, ev := range rec.find("", EventInfo) { + if strings.HasPrefix(ev.Message, "retry round") { + t.Errorf("clean run: %q", ev.Message) + } + } } // A VM gone when cleanup reads it is reported gone without retries. @@ -2023,3 +2061,114 @@ func TestRebuildTearsDownExistingTeamVMsBeforeTemplateDelete(t *testing.T) { t.Errorf("failed rebuilt clone not removed by cleanup: Removed=%v AlreadyGone=%v VM=%v", res.Removed, res.AlreadyGone, f.VMs[10221]) } } + +// A round whose VM listing fails for good runs nothing; the next round +// lists again and runs the items. +func TestFailedListingIsRetriedNextRound(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + for range config.Default().Retry.Attempts { + f.FailOn("cluster", &proxmox.APIError{Status: 500, Message: "internal error"}) + } + rec := &recorder{} + + res := testExecutor(f, rec).Run(context.Background(), plan) + if len(res.Failed) != 0 || len(res.Interrupted) != 0 || !slices.Equal(res.Succeeded, []string{"team01-teak"}) { + t.Fatalf("result = %+v, want team01-teak deployed in round 1", res) + } + if ev := rec.find("", EventFailed); len(ev) != 1 || !strings.HasPrefix(ev[0].Message, "listing VMs: ") { + t.Errorf("job failure events = %+v, want the failed listing", ev) + } + if n := f.Called("clone:10121"); n != 1 { + t.Errorf("cloned %d times, want 1", n) + } +} + +// A stop while the last round lists VMs cuts that round short: its items +// read not run and the rounds read as skipped. +func TestStopDuringLastRoundListingSkipsRounds(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + f.Gate = func(_ context.Context, key string) (func(), error) { + if key == "cluster" { + cancel() + return nil, context.Canceled + } + return nil, nil + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(ctx, plan) + if !res.RoundsSkipped { + t.Errorf("RoundsSkipped = false, want true; result = %+v", res) + } + if err := res.Interrupted["team01-teak"]; err == nil || err.Error() != "stopped before it started" { + t.Errorf("Interrupted = %v, want team01-teak not run", res.Interrupted) + } +} + +// A power item a stop keeps from its retry round reads not run with its +// config untouched: power steps never change it. +func TestStopBeforeRetryRoundLeavesPowerItemsUntouched(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "stopped"}, map[string]string{"name": "team01-teak"}) + f.Add(proxmox.VM{VMID: 10221, Name: "team02-teak", Node: "birch", Status: "stopped"}, map[string]string{"name": "team02-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01", "02"}, []string{"teak"}, "start") + if err != nil { + t.Fatal(err) + } + bad := &proxmox.APIError{Status: 400, Message: "start: bad request"} + f.FailOn("power:10121:start", bad) + f.FailOn("power:10221:start", bad) + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + listings := 0 + f.OnRecord = func(key string) { + if key == "cluster" { + if listings++; listings == 2 { // round 1 lists, then the job is cancelled + cancel(ErrCancelRequested) + } + } + } + + res := testExecutor(f, &recorder{}).Run(ctx, plan) + if len(res.Failed) != 0 || len(res.Interrupted) != 2 || !res.RoundsSkipped { + t.Fatalf("result = %+v, want both interrupted, rounds skipped", res) + } + for name, err := range res.Interrupted { + if err.Error() != "cancelled before it started" || LeftBy(err) != LeftUntouched { + t.Errorf("%s: %v (left %s), want cancelled before it started, untouched", name, err, LeftBy(err)) + } + } + if n := f.Called("power:"); n != 2 { + t.Errorf("start POSTed %d times, want 2 (round 0 only)", n) + } +} + +// An item a rebuild tears down first resumes at its clone: it reports +// started once and its teardown steps once. +func TestTornDownItemResumesAtItsClone(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "spruce", Template: true}, nil) + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), pods.DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + rec := &recorder{} + res := testExecutor(f, rec).Run(context.Background(), plan) + if len(res.Failed) != 0 || !slices.Equal(res.Succeeded, []string{"team01-teak"}) { + t.Fatalf("result = %+v", res) + } + if ev := rec.find("team01-teak", EventStarted); len(ev) != 1 { + t.Errorf("started events = %+v, want one", ev) + } + for _, ev := range rec.find("team01-teak", EventSkipped) { + if ev.Step == pods.StepStop || ev.Step == pods.StepDelete { + t.Errorf("teardown step reported again: %+v", ev) + } + } +} diff --git a/internal/apply/guard_test.go b/internal/apply/guard_test.go index f143d62..ee91a20 100644 --- a/internal/apply/guard_test.go +++ b/internal/apply/guard_test.go @@ -130,6 +130,41 @@ func TestHeldBoundsEveryChange(t *testing.T) { } } +// A change Held refuses fails its item with Held's error, unless the run +// was stopped by then: then the item reads interrupted, the change not sent. +func TestHeldRefusalInAStep(t *testing.T) { + errGone := errors.New("claim uncertain") + for _, stopFirst := range []bool{false, true} { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + ex.Held = func() (time.Time, error) { + if stopFirst { + cancel() + } + return time.Time{}, errGone + } + res := ex.Run(ctx, plan) + cancel() + if stopFirst { + if err := res.Interrupted["team01-teak"]; err == nil || len(res.Failed) != 0 { + t.Errorf("stopped run: result = %+v, want team01-teak interrupted", res) + } + } else if err := res.Failed["team01-teak"]; !errors.Is(err, errGone) || len(res.Interrupted) != 0 { + t.Errorf("running run: result = %+v, want team01-teak failed with Held's error", res) + } + if n := f.Called("power:"); n != 0 { + t.Errorf("stopFirst %v: %d power calls reached Proxmox", stopFirst, n) + } + } +} + // The executor calls Proxmox through e.api, the guarded API, never e.API. func TestExecutorUsesTheGuardedAPI(t *testing.T) { files, err := filepath.Glob("*.go") diff --git a/internal/apply/review_test.go b/internal/apply/review_test.go index 56593c9..acdb20d 100644 --- a/internal/apply/review_test.go +++ b/internal/apply/review_test.go @@ -139,6 +139,77 @@ func TestUnfollowableStopsOnRefusedReads(t *testing.T) { } } +// shortUPIDs answers power calls with a UPID cut short, naming the node +// but no VM. +type shortUPIDs struct{ *podstest.Fake } + +const shortUPID = "UPID:cedar:0:0" + +func (s shortUPIDs) Power(ctx context.Context, node string, vmid int, action string) (string, error) { + if _, err := s.Fake.Power(ctx, node, vmid, action); err != nil { + return "", err + } + return shortUPID, nil +} + +// An unfollowable task whose UPID names no VM fails as outcome unknown +// without polling any VM. +func TestUnfollowableTaskNamingNoVMIsNotPolled(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") + if err != nil { + t.Fatal(err) + } + f.WaitHook = func(_ context.Context, id string) error { + if id == shortUPID { + return forbidden + } + return nil + } + ex := testExecutor(f, &recorder{}) + ex.API = shortUPIDs{f} + ex.Cfg.Retry.Rounds = 0 + res := ex.Run(context.Background(), plan) + err = res.Failed["team01-teak"] + if err == nil || !strings.Contains(err.Error(), "its VM couldn't be checked, but whether it worked is unknown") { + t.Fatalf("error = %v, want the outcome unknown, VM unchecked", err) + } + if n := f.Called("config:0"); n != 0 { + t.Errorf("read VMID 0 %d times", n) + } +} + +// A stop while waiting for an unfollowable task's VM to unlock reports the +// lock still held, not the task ended. +func TestUnfollowableTaskStillLockedAtStop(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stop := podstest.UPID("cedar", "qmstop", 10121) + f.WaitHook = func(_ context.Context, id string) error { // runs with f.Mu held + if id != stop { + return nil + } + f.WaitHook = nil + f.LockConfig, f.LockName = map[int]int{10121: 1000}, "stop" // the task runs on + cancel() + return forbidden + } + ex := testExecutor(f, &recorder{}) + ex.Sleep = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } + res := ex.Run(ctx, plan) + err = res.Failed["team01-teak"] + if err == nil || !strings.Contains(err.Error(), "VM 10121 is still locked (stop), but whether it worked is unknown") { + t.Fatalf("error = %v, want VM 10121 still locked", err) + } +} + // If authorization lapses mid-build, the stopped master is reported in the // result, doomed waits are skipped, and a never-started clone isn't called // possibly running. @@ -163,6 +234,11 @@ func TestLapseDuringBuildReportsStoppedMaster(t *testing.T) { if n := f.Called("wait:" + stop); n != 1 { t.Errorf("waited on the stop task %d times after the lapse, want 1", n) } + // The job's last line counts the stopped master, the only cleanup entry. + infos := rec.find("", EventInfo) + if last := infos[len(infos)-1].Message; !strings.HasSuffix(last, "; cleanup: 0 completed, 0 removed, 1 failed") { + t.Errorf("last job event = %q, want the cleanup failure counted", last) + } for _, ev := range rec.events { if strings.Contains(ev.Message, "clone task may still be running") { t.Errorf("event %q, but no clone started", ev.Message) diff --git a/internal/apply/snapshot_test.go b/internal/apply/snapshot_test.go index 00904dd..c48f080 100644 --- a/internal/apply/snapshot_test.go +++ b/internal/apply/snapshot_test.go @@ -141,3 +141,23 @@ func TestBaselineLostAnswerIsNotResent(t *testing.T) { t.Errorf("baseline POSTed %d times, want 1", n) } } + +// A request that failed without taking the snapshot is sent again: the +// check before the resend finds no snapshot. +func TestTakeSnapshotFailedRequestIsResent(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar"}, nil) + plan := snapshotPlan(t, f, pods.SnapshotRequest{Name: "before-scoring"}) + f.FailOn("snapshot:10121", &proxmox.APIError{Status: 500, Message: "Connection timed out"}) + + res := testExecutor(f, &recorder{}).Run(context.Background(), plan) + if len(res.Failed) != 0 || !slices.Equal(res.Succeeded, []string{"team01-teak"}) { + t.Fatalf("result = %+v", res) + } + if n := f.Called("snapshot:"); n != 2 { + t.Errorf("snapshot POSTed %d times, want 2", n) + } + if snaps := f.VMs[10121].Snapshots; !slices.Equal(snaps, []string{"before-scoring"}) { + t.Errorf("snapshots = %v", snaps) + } +} diff --git a/internal/apply/storage_test.go b/internal/apply/storage_test.go index 825b599..a5fdddc 100644 --- a/internal/apply/storage_test.go +++ b/internal/apply/storage_test.go @@ -298,6 +298,31 @@ func TestLeftoverDisksThatCannotBeFreedFailWithAdvice(t *testing.T) { } } +// Frees that report success but leave the disks fail with the advice and +// no made-up cause. +func TestLeftoverDisksFreedInVainHaveNoCause(t *testing.T) { + f := newCluster() + left := teakTeamVM(f) + plan := teardownTeam01(t, f) + f.DeleteKeepsDisks = map[int]bool{10121: true} + f.OnRecord = func(key string) { // runs with f.Mu held + if strings.HasPrefix(key, "wait:") && strings.Contains(key, ":imgdel:") { + for _, v := range left { + f.Vols[v] = 10121 // the free task ended OK, but the disk is still there + } + } + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + err := res.Failed["team01-teak"] + wantLeftoverAdvice(t, err, left...) + if err != nil && strings.Contains(err.Error(), "freeing failed") { + t.Errorf("message %q gives a cause, but every free reported success", err) + } +} + // A retry round frees what the first attempt could not. func TestLeftoverDisksAreRetriedNextRound(t *testing.T) { f := newCluster() diff --git a/internal/apply/teardown_test.go b/internal/apply/teardown_test.go index 1b2bd17..76850e7 100644 --- a/internal/apply/teardown_test.go +++ b/internal/apply/teardown_test.go @@ -62,6 +62,10 @@ func TestHalfDeletedVMFailsWithAdvice(t *testing.T) { t.Fatalf("result = %+v, want team01-teak failed", res) } wantHalfDeletedAdvice(t, proxmox.Describe(err)) + // The round that saw the delete fail says how it failed. + if ev := rec.find("team01-teak", EventFailed); len(ev) == 0 || !strings.Contains(ev[0].Message, "the delete failed with: ") || !strings.Contains(ev[0].Message, "got lock request timeout") { + t.Errorf("failure events = %+v, want the first to give the delete's error", ev) + } if ev := rec.find("team01-teak", EventDone); len(ev) != 1 || ev[0].Step != pods.StepStop { t.Errorf("done events = %+v, want only the stop", ev) } From 1a6b4f63157b2a2ea157343695c15f319060af26 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:24:44 +0000 Subject: [PATCH 02/22] apply: test behaviour surviving item, guest, cleanup and template mutants Pin behaviour that mutation testing showed unchecked: reboot of a stopped VM, clone and delete events, failures after a cancel, retire on a moved or replaced previous version, probe of a locked clone target, rebuild of a team VM gone since planning, guest agent waits and verify reports, cleanup order, budget and per-copy outcomes, unconfirmed deletes, leftover base disks under the storage-ops slot, and the copy-stop and convert waits. --- internal/apply/catalog_test.go | 43 +++- internal/apply/executor_test.go | 311 +++++++++++++++++++++++++++ internal/apply/guest_prop_test.go | 2 +- internal/apply/guest_restart_test.go | 31 +++ internal/apply/guest_test.go | 65 ++++++ internal/apply/power_test.go | 41 ++++ internal/apply/storage_test.go | 102 ++++++++- internal/apply/teardown_test.go | 77 +++++++ internal/apply/templates_test.go | 25 +++ 9 files changed, 694 insertions(+), 3 deletions(-) diff --git a/internal/apply/catalog_test.go b/internal/apply/catalog_test.go index f9d58b8..b7e9444 100644 --- a/internal/apply/catalog_test.go +++ b/internal/apply/catalog_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/netip" + "slices" "strings" "testing" "time" @@ -56,6 +57,23 @@ func TestEnvHostCloneIsRemovedWhenItFails(t *testing.T) { } } +// A clone that failed after it was started is stopped, then removed. +func TestStartedEnvHostCloneIsStoppedAndRemovedWhenItFails(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 8001, Name: "deb-v1", Node: "alder", Template: true}, map[string]string{"net0": "virtio=BC:24:11:00:80:01,bridge=vmbr0"}) + plan := &pods.Plan{Kind: pods.KindEnvCreate, Items: []pods.Item{{ + Name: "teak.kilo.alpha", Host: "teak", VMID: 2101, Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", + Source: &pods.Source{VMID: 8001, Node: "alder", Name: "deb-v1"}, NICs: map[string]string{"net0": "devint01"}, + Steps: []pods.Step{pods.StepClone, pods.StepLabel, pods.StepNetwork, pods.StepStart, pods.StepWaitAgent}}}} // no agent answers + res := catalogExec(f).Run(context.Background(), plan) + if len(res.Failed) != 1 || !slices.Equal(res.Removed, []string{"teak.kilo.alpha"}) || f.VMs[2101] != nil { + t.Errorf("result = %+v; the started clone must be removed", res) + } + if f.Called("power:2101:stop") != 1 { + t.Errorf("calls %v, want one stop before the delete", f.Calls) + } +} + func TestEnvHostIsWiredAndLabelled(t *testing.T) { f := podstest.New("alder") f.Add(proxmox.VM{VMID: 8001, Name: "deb-v1", Node: "alder", Template: true}, map[string]string{"tags": "base;linux", "net0": "virtio=BC:24:11:00:80:01,bridge=vmbr0"}) @@ -66,7 +84,7 @@ func TestEnvHostIsWiredAndLabelled(t *testing.T) { Steps: []pods.Step{pods.StepClone, pods.StepLabel, pods.StepNetwork, pods.StepStart}}}} res := catalogExec(f).Run(context.Background(), plan) v := f.VMs[2101] - if len(res.Succeeded) != 1 || v.Config["tags"] != "dev;kilo.alpha" || !strings.Contains(v.Config["net0"], "bridge=devint01") || + if len(res.Succeeded) != 1 || v.Name != "teak.kilo.alpha" || v.Config["tags"] != "dev;kilo.alpha" || !strings.Contains(v.Config["net0"], "bridge=devint01") || v.Config["description"] != "battleship: ip=192.168.100.10 os=linux base=deb-v1 dns=router" || v.Status != "running" { t.Errorf("res %+v vm %+v %v", res, v.VM, v.Config) } @@ -110,6 +128,29 @@ func TestRegisterKeepsConvertedImageWhenRetireFails(t *testing.T) { } } +// Retiring finds the previous version on the node it is listed on now, and +// never tags another VM that took its VMID. +func TestRetireFindsThePreviousVersionWhereItIs(t *testing.T) { + for _, tc := range []struct { + name string + at string // the VM at 8000, on birch since the plan + retired bool + }{ + {"moved", "deb-v1", true}, + {"replaced", "other", false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := registerFake() + f.Nodes = append(f.Nodes, "birch") + f.VMs[8000].Node, f.VMs[8000].Name = "birch", tc.at + res := catalogExec(f).Run(context.Background(), registerPlan(pods.StepClone, pods.StepRetire)) + if retired := strings.Contains(f.VMs[8000].Config["tags"], "deprecated"); retired != tc.retired || (len(res.Succeeded) == 1) != tc.retired { + t.Errorf("result %+v, tags %q; want retired %v", res, f.VMs[8000].Config["tags"], tc.retired) + } + }) + } +} + // The details step rewrites only the notes' details block, or with free // text the notes less their battleship lines. It refuses details or text // that would break them, however the plan came by them. diff --git a/internal/apply/executor_test.go b/internal/apply/executor_test.go index 005f6e0..01d7e8a 100644 --- a/internal/apply/executor_test.go +++ b/internal/apply/executor_test.go @@ -11,6 +11,7 @@ import ( "sync" "sync/atomic" "testing" + "testing/synctest" "time" "github.com/wccomps/battleship/internal/config" @@ -111,6 +112,9 @@ func TestDeployFromScratch(t *testing.T) { if n := f.Called("cloudinit:10121"); n != 1 { t.Errorf("cloud-init regenerated %d times, want 1", n) } + if ev := rec.find("team01-teak", EventDone); len(ev) == 0 || ev[0].Step != pods.StepClone { + t.Errorf("done events = %+v, want the clone first", ev) + } } func TestRerunConvergesWithoutRecloning(t *testing.T) { @@ -203,6 +207,9 @@ func TestTeardown(t *testing.T) { if _, ok := f.VMs[10121]; ok || f.Called("power:10121:stop") != 1 { t.Errorf("team01-teak not stopped and deleted: calls=%v", f.Calls) } + if ev := rec.find("team01-teak", EventDone); len(ev) != 2 || ev[0].Step != pods.StepStop || ev[1].Step != pods.StepDelete { + t.Errorf("teak done events = %+v, want the stop and the delete", ev) + } if ev := rec.find("team01-oak", EventSkipped); len(ev) != 1 || ev[0].Message != "already deleted" { t.Errorf("oak events = %+v", ev) } @@ -312,6 +319,20 @@ func TestCancelCutsAStepOffAfterTheGrace(t *testing.T) { } } +// A step under way at cancel that then fails is reported failed, not +// interrupted: the failure is its outcome. +func TestStepFailingAfterCancelIsFailed(t *testing.T) { + _, rec, res := cancelTeardownDuringStop(t, time.Hour, ErrCancelRequested, func(context.Context) error { + return &proxmox.TaskError{UPID: podstest.UPID("cedar", "qmstop", 10121), ExitStatus: "can't lock file"} + }) + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), "can't lock file") || len(res.Interrupted) != 0 { + t.Errorf("result = %+v, want team01-teak failed on the stop", res) + } + if ev := rec.find("team01-teak", EventFailed); len(ev) != 1 || ev[0].Step != pods.StepStop { + t.Errorf("failed events = %+v", ev) + } +} + // After a cancel nothing new is sent: a VM waiting for a delete slot isn't // deleted, while the delete under way finishes. func TestCancelSendsNothingNew(t *testing.T) { @@ -514,6 +535,25 @@ func TestRebuildDeletesOldTemplateOnItsNode(t *testing.T) { } } +// An old template moved since planning is deleted on the node it is on now. +func TestRebuildDeletesOldTemplateWhereItMoved(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "spruce", Template: true}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), pods.DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + f.VMs[9021].Node = "birch" // migrated + + res := testExecutor(f, &recorder{}).Run(context.Background(), plan) + if len(res.Failed) != 0 || f.Called("delete:9021") != 1 { + t.Fatalf("result = %+v, calls %v; want the old template deleted on birch", res, f.Calls) + } + if tpl := f.VMs[9021]; tpl == nil || !tpl.Template || tpl.Node != "cedar" { + t.Errorf("rebuilt template = %+v", tpl) + } +} + // A reused template stays where it is, in the images pool or not: moving // it is a rebuild's job. func TestReusedTemplateKeepsItsPool(t *testing.T) { @@ -692,6 +732,54 @@ func TestMasterRestartWaitsForCloneTask(t *testing.T) { } } +// A stopped build gives the copy it cut off up to copyStopWait to end +// before restarting the master: a copy that ends within it lets the master +// start; one still running leaves the master stopped. synctest's clock runs +// the minutes at once. +func TestStoppedBuildWaitsForItsCopyBeforeRestartingTheMaster(t *testing.T) { + for _, tc := range []struct { + copyEnds time.Duration // after the stop + master string + }{ + {time.Minute, "running"}, + {3 * time.Minute, "stopped"}, + } { + t.Run(tc.copyEnds.String(), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newCluster() + f.VMs[121].Status = "running" + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var waits atomic.Int32 + f.WaitGate = func(wctx context.Context, upid string) error { + if !strings.Contains(upid, ":qmclone:121:") { + return nil + } + if waits.Add(1) == 1 { + cancel() + return context.Canceled + } + select { + case <-time.After(tc.copyEnds): + return nil + case <-wctx.Done(): + return wctx.Err() + } + } + ex := testExecutor(f, &recorder{}) + ex.Sleep = proxmox.SleepContext + + res := ex.Run(ctx, plan) + _, reported := res.CleanupFailed["teak.tango.delta"] + if st := f.VMs[121].Status; st != tc.master || reported != (tc.master == "stopped") { + t.Errorf("master %s, CleanupFailed %v; want it %s", st, res.CleanupFailed, tc.master) + } + }) + }) + } +} + func TestMasterStaysStoppedIfCloneTaskCannotBeAwaited(t *testing.T) { f := newCluster() f.VMs[121].Status = "running" @@ -1232,6 +1320,130 @@ func TestTemplateThatCannotBeConvertedIsRemoved(t *testing.T) { } } +// Cleanup removes this run's team VMs in VMID order. +func TestCleanupRemovesTeamVMsInVMIDOrder(t *testing.T) { + f := sevenMasters() + plan := deploySeven(t, f, "h1", "h2", "h3") + denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} + for _, vmid := range []int{10103, 10101, 10102} { + f.FailOn(fmt.Sprintf("setconfig:%d", vmid), denied) + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if got := f.DeletedIDs(); !slices.Equal(got, []int{10101, 10102, 10103}) { + t.Errorf("deleted %v, want 10101, 10102, 10103 in order; result %+v", got, res) + } +} + +// Cleanup settles each template copy it can't complete one way: gone, +// failed or removed. Either way it goes on to complete the next. +func TestCleanupSettlesEachTemplateCopyOnce(t *testing.T) { + denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} + for _, tc := range []struct { + name string + // spoil makes the first copy's conversion fail and leaves it as cleanup finds it. + spoil func(f *podstest.Fake, vmid int) + gone, failed, removed bool + }{ + {"gone", func(f *podstest.Fake, vmid int) { + f.FailOn(fmt.Sprintf("template:%d", vmid), denied) + f.OnRecord = func(key string) { + if key == fmt.Sprintf("template:%d", vmid) { + delete(f.VMs, vmid) + } + } + }, true, false, false}, + {"renamed", func(f *podstest.Fake, vmid int) { + f.FailOn(fmt.Sprintf("template:%d", vmid), denied) + f.OnRecord = func(key string) { + if key == fmt.Sprintf("template:%d", vmid) { + f.VMs[vmid].Name, f.VMs[vmid].Config["name"] = "other", "other" + } + } + }, false, true, false}, + {"unconvertible", func(f *podstest.Fake, vmid int) { + f.FailOn(fmt.Sprintf("template:%d", vmid), denied, denied) + }, false, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := sevenMasters() + plan := deploySeven(t, f, "h1", "h2") + first, second := plan.Templates[0], plan.Templates[1] + tc.spoil(f, first.VMID) + f.FailOn(fmt.Sprintf("template:%d", second.VMID), denied) // fails in the run, converts in cleanup + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + _, failed := res.CleanupFailed[first.Name] + if gone := slices.Equal(res.AlreadyGone, []string{first.Name}); gone != tc.gone || len(res.AlreadyGone) > 1 || + failed != tc.failed || len(res.CleanupFailed) > 1 || slices.Equal(res.Removed, []string{first.Name}) != tc.removed { + t.Errorf("AlreadyGone = %v, CleanupFailed = %v, Removed = %v; want %s only %s", res.AlreadyGone, res.CleanupFailed, res.Removed, first.Name, tc.name) + } + if !slices.Equal(res.Completed, []string{second.Name}) { + t.Errorf("Completed = %v, want %s; result %+v", res.Completed, second.Name, res) + } + if tpl := f.VMs[second.VMID]; tpl == nil || !tpl.Template { + t.Errorf("%s = %+v, want it converted", second.Name, tpl) + } + }) + } +} + +// Once the cleanup budget runs out, every VM cleanup has not reached yet is +// reported, not just the next. The first VM's check outlasts the budget +// (synctest's clock lets 10 minutes pass at once). +func TestCleanupBudgetReportsEveryVMLeft(t *testing.T) { + denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} + for _, tc := range []struct { + name string + base int // host h's VM cleanup acts on is base+i + fail string // the call failed for each, so the run leaves it to cleanup + named string // the VM's name, by i + }{ + {"team VMs", 10100, "setconfig:%d", "team01-h%d"}, + {"template copies", 9000, "template:%d", "h%d.kilo.alpha.tpl"}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := sevenMasters() + plan := deploySeven(t, f, "h1", "h2", "h3") + for i := 1; i <= 3; i++ { + f.FailOn(fmt.Sprintf(tc.fail, tc.base+i), denied) + } + var cleaning atomic.Bool + listings := 0 + f.OnRecord = func(key string) { + if key == "cluster" { + listings++ + cleaning.Store(listings == 2) // Run's listing, then cleanup's + } + } + f.Gate = func(ctx context.Context, key string) (func(), error) { + if cleaning.Load() && key == fmt.Sprintf("config:%d", tc.base+1) { + <-ctx.Done() + return nil, ctx.Err() + } + return nil, nil + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + for i := 1; i <= 3; i++ { + name := fmt.Sprintf(tc.named, i) + err := res.CleanupFailed[name] + if err == nil || i > 1 && !strings.Contains(err.Error(), "cleanup time budget ran out") { + t.Errorf("%s: cleanup error %v, want it reported as not checked in time", name, err) + } + } + }) + }) + } +} + func TestLockedVMIsNotForceRemoved(t *testing.T) { f, plan := newlyBuiltTeamVMFails(t) denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} @@ -1333,6 +1545,21 @@ func TestPrecheckFindingSameNameVMNeverClaimsIt(t *testing.T) { } } +// A team VM already at the target under its name (an earlier POST took +// effect) is the clone: the item goes on to configure it. +func TestPrecheckFindingSameNameVMSkipsTheClone(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + appearAfterListing(f, plan.Items[0].Node, foreignConfig(), "stopped") + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 // a retry round would find it listed + + res := ex.Run(context.Background(), plan) + if !reflect.DeepEqual(res.Succeeded, []string{"team01-teak"}) || f.Called("clone:10121") != 0 { + t.Errorf("result = %+v, calls %v; want the item done without a clone", res, f.Calls) + } +} + func TestCleanupVerifiesByConfigWhenListingFails(t *testing.T) { f, plan := newlyBuiltTeamVMFails(t) // The POST fails after creating the VM, and the run's only listing predates @@ -1579,6 +1806,38 @@ func TestVMWithAnotherNameAtTheTargetIsLeftAlone(t *testing.T) { } } +// A locked VM with another name at the target is still another VM: the +// clone fails at once rather than wait for its lock. +func TestLockedVMWithAnotherNameAtTheTargetFailsTheClone(t *testing.T) { + f, plan := newlyBuiltTeamVMFails(t) + appearAfterListing(f, plan.Items[0].Node, map[string]string{"name": "someone-else"}, "running") + f.LockConfig = map[int]int{10121: 1000} + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), `used by "someone-else"`) || f.Called("clone:10121") != 0 { + t.Errorf("result = %+v, calls %v; want the clone refused", res, f.Calls) + } +} + +// A clone POST that timed out leaves its VM locked and nameless for a +// while; the resent clone waits for it rather than call it another VM. +func TestNamelessLockedCloneTargetIsWaitedOut(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + f.CloneThenFail = map[int]error{10121: &proxmox.APIError{Status: 500, Message: "Connection timed out"}} + f.LockConfig = map[int]int{10121: 2} + f.LockHidesName = true + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if len(res.Failed) != 0 || f.Called("clone:10121") != 1 { + t.Errorf("result = %+v, %d clone POSTs; want one clone and success", res, f.Called("clone:10121")) + } +} + func TestCleanupAdviceOnlyOffersRemovalOfOwnedVMs(t *testing.T) { f, plan := newlyBuiltTeamVMFails(t) denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} @@ -2172,3 +2431,55 @@ func TestTornDownItemResumesAtItsClone(t *testing.T) { } } } + +// A rebuild's team VM deleted by hand since planning needs no stop or +// delete, but the disks it left are freed before it is cloned again; if +// the storage can't be checked, it isn't. +func TestRebuildOfTeamVMGoneSincePlanning(t *testing.T) { + const vol = "competitions:10121/vm-10121-disk-0.qcow2" + for _, tc := range []struct { + name string + left bool // the VM left vol on the storage + listed error // the storage listing's error + }{ + {"no disks left", false, nil}, + {"disks left", true, nil}, + {"storage unreadable", true, &proxmox.APIError{Status: 400, Message: "storage 'competitions' is not online"}}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "spruce", Template: true}, nil) + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), pods.DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + delete(f.VMs, 10121) + if tc.left { + f.Vols[vol] = 10121 + } + if tc.listed != nil { + f.FailOn("content:competitions:10121", tc.listed) + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if f.Called("power:10121:stop") != 0 || f.Called("delete:10121") != 0 { + t.Errorf("calls %v, want no stop or delete of the gone VM", f.Calls) + } + if tc.listed != nil { + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), "not online") || f.Called("clone:10121") != 0 { + t.Errorf("result = %+v, want team01-teak failed before its clone", res) + } + return + } + if !reflect.DeepEqual(res.Succeeded, []string{"team01-teak"}) || f.VMs[10121] == nil { + t.Fatalf("result = %+v, VM = %+v", res, f.VMs[10121]) + } + if vols := f.VolumesOf(10121); slices.Contains(vols, vol) { + t.Errorf("volumes %q, want the gone VM's %s freed", vols, vol) + } + }) + } +} diff --git a/internal/apply/guest_prop_test.go b/internal/apply/guest_prop_test.go index 83221c5..d56bf45 100644 --- a/internal/apply/guest_prop_test.go +++ b/internal/apply/guest_prop_test.go @@ -65,7 +65,7 @@ func checkShown(t interface{ Fatalf(string, ...any) }, got, want string) { // one line, quoted and bounded. func TestPropGuestTail(t *testing.T) { for _, s := range []string{"", "\n", " \n \n", "a", "a\n", "\na\n\nb\n\n", "a\r\nb\r\n", " a \n b ", "a\n\n\n\nb\nc\nd\ne\nf\ng", "a\rb", "a\r\rb\r", - "\x00\x1b[2J", strings.Repeat("é", maxGuestShown), "a" + strings.Repeat("é", maxGuestShown), "a" + strings.Repeat("\x80", 2*maxGuestShown), strings.Repeat("x", 3*maxGuestShown)} { + "\x00\x1b[2J", strings.Repeat("é", maxGuestShown), strings.Repeat("x", maxGuestShown), "a" + strings.Repeat("é", maxGuestShown), "a" + strings.Repeat("\x80", 2*maxGuestShown), strings.Repeat("x", 3*maxGuestShown)} { for n := -2; n < 8; n++ { checkShown(t, guestTail(s, n), tailLines(s, n)) } diff --git a/internal/apply/guest_restart_test.go b/internal/apply/guest_restart_test.go index 7e64626..b472516 100644 --- a/internal/apply/guest_restart_test.go +++ b/internal/apply/guest_restart_test.go @@ -201,3 +201,34 @@ func TestCancelDuringRerunWaitStops(t *testing.T) { t.Errorf("execs = %+v", f.Execs) } } + +// A setup state read still running is polled until it exits; one that +// never exits fails the wait, saying how long it was given. +func TestSetupStateReadIsPolledUntilItExits(t *testing.T) { + for _, tc := range []struct { + name string + runsFor int + want string // the failure, or "" for success + }{ + {"slow", 2, ""}, + {"never exits", 1 << 20, "reading the setup state took over 30s"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := guestFake(t) + f.ExecRunsFor = func(int) int { return tc.runsFor } + it := guestItem(pods.ImageWindows) + it.Steps = []pods.Step{pods.StepGuest} + rec := &recorder{} + e := catalogExec(f) + e.OnEvent = rec.add + res := e.Run(context.Background(), &pods.Plan{Kind: pods.KindEnvCreate, Items: []pods.Item{it}}) + err := res.Failed["oak.kilo.alpha"] + switch { + case tc.want == "" && (err != nil || len(f.Execs) != 1 || len(infoMessages(rec, "oak.kilo.alpha")) != 0): + t.Errorf("failed = %v, %d execs, info %q; want the script run at once", err, len(f.Execs), infoMessages(rec, "oak.kilo.alpha")) + case tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want) || len(f.Execs) != 0): + t.Errorf("failed = %v, %d execs; want it to fail with %q", err, len(f.Execs), tc.want) + } + }) + } +} diff --git a/internal/apply/guest_test.go b/internal/apply/guest_test.go index 20ad9af..743b6de 100644 --- a/internal/apply/guest_test.go +++ b/internal/apply/guest_test.go @@ -5,6 +5,7 @@ import ( "net/netip" "strings" "testing" + "time" "github.com/wccomps/battleship/internal/pods" "github.com/wccomps/battleship/internal/pods/podstest" @@ -150,3 +151,67 @@ func TestGuestLockWaitIsUnderTheExecLimit(t *testing.T) { t.Errorf("guest lock wait %v isn't under the exec limit %v", pods.GuestLockWait, execLimit) } } + +// A guest whose agent doesn't come back after the rename's restart fails +// the step. +func TestGuestNotBackAfterRenameRestartFails(t *testing.T) { + f := guestFake(t) + f.ExecHook = applied(f, pods.RebootMarker+"\n") + f.PowerHook = func(vmid int, action string) { + if action == "start" { + f.Guests[vmid].Up = false + } + } + it := guestItem(pods.ImageWindows) + it.Steps = []pods.Step{pods.StepGuest} + res := catalogExec(f).Run(context.Background(), &pods.Plan{Kind: pods.KindEnvCreate, Items: []pods.Item{it}}) + if err := res.Failed["oak.kilo.alpha"]; err == nil || !strings.Contains(err.Error(), "guest agent didn't answer") { + t.Errorf("result = %+v, want the step failed on the agent", res) + } +} + +// The wait for the agent lasts environments.agent_timeout, no longer. +func TestWaitAgentWaitsTheAgentTimeout(t *testing.T) { + f := guestFake(t) + f.Guests[2101].Up = false + it := guestItem(pods.ImageLinux) + it.Steps = []pods.Step{pods.StepWaitAgent} + e := catalogExec(f) + var waited time.Duration + e.Sleep = func(ctx context.Context, d time.Duration) error { waited += d; return ctx.Err() } + res := e.Run(context.Background(), &pods.Plan{Kind: pods.KindEnvCreate, Items: []pods.Item{it}}) + if res.Failed["oak.kilo.alpha"] == nil { + t.Fatalf("result = %+v", res) + } + if want := e.Cfg.Environments.AgentTimeout; waited != want { + t.Errorf("waited %s for the agent, want %s", waited, want) + } +} + +// A failed verification says what the guest last reported. +func TestVerifyFailureSaysWhatTheGuestReported(t *testing.T) { + for _, tc := range []struct { + name string + setup func(f *podstest.Fake) + want string + }{ + {"no address on net0", func(f *podstest.Fake) { f.Guests[2101].NICs[0].IPs = nil }, `the guest reports host name "WIN-123" with no address;`}, + {"another address", func(*podstest.Fake) {}, `the guest reports host name "WIN-123" with "169.254.1.1/16";`}, + {"interfaces unreadable", func(f *podstest.Fake) { + for range verifyTries { + f.FailOn("agent-nics:2101", &proxmox.APIError{Method: "GET", Path: "/agent/network-get-interfaces", Status: 500, Message: "agent busy"}) + } + }, "the guest reports an error: GET /agent/network-get-interfaces: 500 agent busy;"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := guestFake(t) + tc.setup(f) + it := guestItem(pods.ImageLinux) + it.Steps = []pods.Step{pods.StepVerify} + err := catalogExec(f).Run(context.Background(), &pods.Plan{Kind: pods.KindEnvCreate, Items: []pods.Item{it}}).Failed["oak.kilo.alpha"] + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("failed = %v, want it to contain %q", err, tc.want) + } + }) + } +} diff --git a/internal/apply/power_test.go b/internal/apply/power_test.go index 4733b66..ab64ec5 100644 --- a/internal/apply/power_test.go +++ b/internal/apply/power_test.go @@ -4,6 +4,7 @@ import ( "context" "strings" "testing" + "time" "github.com/wccomps/battleship/internal/pods" "github.com/wccomps/battleship/internal/pods/podstest" @@ -37,6 +38,46 @@ func TestPowerSkipsVMsAlreadyInTheStateTheActionLeaves(t *testing.T) { } } +// A reboot reboots a running VM and starts a stopped one. +func TestRebootStartsAStoppedVM(t *testing.T) { + for status, want := range map[string]string{"running": "power:10121:reboot", "stopped": "power:10121:start"} { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: status}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "reboot") + if err != nil { + t.Fatal(err) + } + res := testExecutor(f, &recorder{}).Run(context.Background(), plan) + if len(res.Succeeded) != 1 || f.Called("power:") != 1 || f.Called(want) != 1 { + t.Errorf("reboot of a %s VM: result %+v, calls %v; want only %s", status, res, f.Calls, want) + } + } +} + +// A power job cut off mid-task has changed no config: it reports the VM's +// config converged. +func TestCancelledPowerJobLeavesTheConfigConverged(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + f.WaitGate = func(sctx context.Context, upid string) error { + cancel(ErrCancelRequested) + <-sctx.Done() // still running when the grace runs out + return sctx.Err() + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Jobs.CancelGrace = 20 * time.Millisecond + err = ex.Run(ctx, plan).Interrupted["team01-teak"] + if err == nil || LeftBy(err) != LeftConverged { + t.Errorf("interrupted = %v (left %q), want converged", err, LeftBy(err)) + } +} + // An unfollowable task (403 on its status) isn't assumed done: the step // waits for the VM to unlock, fails as outcome unknown, and the retry round // finds the VM already stopped. diff --git a/internal/apply/storage_test.go b/internal/apply/storage_test.go index a5fdddc..dd431cb 100644 --- a/internal/apply/storage_test.go +++ b/internal/apply/storage_test.go @@ -108,6 +108,69 @@ func TestConvertIsVerifiedEvenWhenTheTaskSucceeds(t *testing.T) { } } +// A copy gone once its conversion ends fails the build: with the +// conversion's own failure if it failed, else as gone. +func TestCopyGoneAfterItsConversionFailsTheBuild(t *testing.T) { + for _, tc := range []struct { + name string + convert error // the conversion's answer + goneAt string // the call after which the copy is gone + want string + }{ + {"conversion failed", &proxmox.APIError{Status: 400, Message: "convert: bad request"}, "template:9021", "convert: bad request"}, + {"conversion ran", nil, "wait:" + podstest.UPID("cedar", "qmtemplate", 9021), "converting to template: VM 9021 disappeared"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + if tc.convert != nil { + f.FailOn("template:9021", tc.convert) + } + f.OnRecord = func(key string) { + if key == tc.goneAt { + delete(f.VMs, 9021) + } + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("failed = %v, want %q", err, tc.want) + } + }) + } +} + +// A conversion whose answer was lost is given time (convertWait) to rename +// its disks before it is judged half-done. +func TestConvertWithLostAnswerWaitsForItsDisks(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + f.ConvertLeavesDisk = map[int]bool{9021: true} + f.ConvertThenFail = map[int]error{9021: &proxmox.APIError{Status: 596, Message: "Connection timed out"}} + converted, reads := false, 0 + f.OnRecord = func(key string) { + switch { + case key == "template:9021": + converted = true + case converted && key == "config:9021": + if reads++; reads == 5 { // the task renames the disk a few reads later + vm := f.VMs[9021] + vm.Config["scsi0"] = strings.Replace(vm.Config["scsi0"], "vm-9021-disk-0", "base-9021-disk-0", 1) + } + } + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + ex.Sleep = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } // polls end with their wait's deadline + + res := ex.Run(context.Background(), plan) + if len(res.Succeeded) != 1 || f.Called("template:9021") != 1 { + t.Errorf("result = %+v, %d conversions; want one, awaited", res, f.Called("template:9021")) + } +} + // A failed convert that left the VM unconverted is not restarted; its // error is reported as is. func TestFailedConvertIsNotRestarted(t *testing.T) { @@ -260,6 +323,37 @@ func TestRebuildFreesOldTemplateDisk(t *testing.T) { } } +// A template's base disk found left on the storage is freed under the +// storage-ops slot, as its destroy would have been. +func TestFoundLeftoverBaseDiskWaitsForStorageOps(t *testing.T) { + f := newCluster() + vol := "competitions:9021/base-9021-disk-0.qcow2" + f.Vols[vol] = 9021 // its template is gone + ex := testExecutor(f, &recorder{}) + ex.init() + ex.present = map[int]proxmox.VM{} + holding, release := make(chan struct{}), make(chan struct{}) + go ex.lim.storageOps.do(context.Background(), true, func() error { close(holding); <-release; return nil }) + <-holding + + done := make(chan error, 1) + go func() { done <- ex.retryLeftovers(context.Background(), 9021, "cedar", "teak.tango.delta.tpl") }() + for queued := false; !queued; time.Sleep(time.Millisecond) { + select { + case err := <-done: + t.Fatalf("freed while another storage op held the slot (err %v)", err) + default: + } + ex.lim.storageOps.mu.Lock() + queued = len(ex.lim.storageOps.lo) == 1 + ex.lim.storageOps.mu.Unlock() + } + close(release) + if err := <-done; err != nil || len(f.VolumesOf(9021)) != 0 { + t.Errorf("err = %v, volumes left %q; want %s freed", err, f.VolumesOf(9021), vol) + } +} + func wantLeftoverAdvice(t *testing.T, err error, vols ...string) { t.Helper() if err == nil { @@ -291,11 +385,17 @@ func TestLeftoverDisksThatCannotBeFreedFailWithAdvice(t *testing.T) { f.FailOn("volume:"+v, denied, denied, denied, denied) } - res := testExecutor(f, &recorder{}).Run(context.Background(), plan) + rec := &recorder{} + res := testExecutor(f, rec).Run(context.Background(), plan) wantLeftoverAdvice(t, res.Failed["team01-teak"], left...) if len(res.Succeeded) != 0 { t.Errorf("succeeded = %v, want none", res.Succeeded) } + for _, ev := range rec.find("team01-teak", EventInfo) { + if strings.HasPrefix(ev.Message, "freed disks") { + t.Errorf("info %q, but no disk was freed", ev.Message) + } + } } // Frees that report success but leave the disks fail with the advice and diff --git a/internal/apply/teardown_test.go b/internal/apply/teardown_test.go index 76850e7..2ab315e 100644 --- a/internal/apply/teardown_test.go +++ b/internal/apply/teardown_test.go @@ -6,7 +6,9 @@ import ( "slices" "strings" "testing" + "time" + "github.com/wccomps/battleship/internal/config" "github.com/wccomps/battleship/internal/pods" "github.com/wccomps/battleship/internal/pods/podstest" "github.com/wccomps/battleship/internal/proxmox" @@ -287,6 +289,7 @@ func TestResentDeleteWaitsForItsOwnDestroy(t *testing.T) { f.DestroyReads = 3 ex := testExecutor(f, &recorder{}) ex.Cfg.Retry.Rounds = 0 + ex.Sleep = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } // polls end with their wait's deadline res := ex.Run(context.Background(), plan) if len(res.Succeeded) != 1 || f.VMs[10121] != nil { @@ -373,3 +376,77 @@ func TestEnvTeardownEmptiesTheSlot(t *testing.T) { t.Errorf("dev-03 = %+v, %v; want free", envs[2], err) } } + +// A refused delete of a VM that is still there fails with Proxmox's answer. +func TestRefusedDeleteFailsWithTheRefusal(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar"}, map[string]string{"name": "team01-teak"}) + plan := teardownTeam01(t, f) + f.FailOn("delete:10121", &proxmox.APIError{Method: "DELETE", Path: "/nodes/cedar/qemu/10121", Status: 400, Message: "VM is protected"}) + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || err.Error() != "delete: DELETE /nodes/cedar/qemu/10121: 400 VM is protected" { + t.Errorf("failed = %v, want the refusal", err) + } +} + +// A delete whose task ended OK as the job was stopped is not called done +// before the VM is seen gone. +func TestDeleteEndingAsTheJobStopsIsNotDone(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar"}, map[string]string{"name": "team01-teak"}) + plan := teardownTeam01(t, f) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + f.WaitGate = func(sctx context.Context, upid string) error { + if strings.Contains(upid, ":qmdestroy:") { + cancel() + <-sctx.Done() // the stop reaches the step as its task ends OK + } + return nil + } + + res := testExecutor(f, &recorder{}).Run(ctx, plan) + if err := res.Interrupted["team01-teak"]; err == nil || len(res.Succeeded) != 0 { + t.Errorf("result = %+v, want team01-teak interrupted", res) + } +} + +// A delete whose outcome can't be read back fails: with the delete's own +// error if it failed, else saying the VM may still be there. +func TestDeleteThatCannotBeConfirmedFails(t *testing.T) { + refused := &proxmox.APIError{Method: "DELETE", Path: "/nodes/cedar/qemu/10121", Status: 400, Message: "VM is protected"} + for _, tc := range []struct { + name string + delete error + want string + }{ + {"delete refused", refused, "delete: DELETE /nodes/cedar/qemu/10121: 400 VM is protected"}, + {"delete ran", nil, "could not confirm VM 10121 is gone"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar"}, map[string]string{"name": "team01-teak"}) + plan := teardownTeam01(t, f) + if tc.delete != nil { + f.FailOn("delete:10121", tc.delete) + } + f.OnRecord = func(key string) { + if key == "delete:10121" { // every read after it fails + for range config.Default().Retry.Attempts { + f.FailOn("config:10121", &proxmox.APIError{Status: 500, Message: "pve is down"}) + } + } + } + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("failed = %v, want %q", err, tc.want) + } + }) + } +} diff --git a/internal/apply/templates_test.go b/internal/apply/templates_test.go index 4c88a48..2dc7b6b 100644 --- a/internal/apply/templates_test.go +++ b/internal/apply/templates_test.go @@ -507,3 +507,28 @@ func TestTemplateBuildSlotOnlyCoversMasterCopy(t *testing.T) { t.Fatalf("result = %+v", res) } } + +// A template built in the first round is not checked again by a retry +// round of an item that failed after cloning from it. +func TestRetryRoundDoesNotRecheckABuiltTemplate(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + f.FailOn("power:10121:start", &proxmox.APIError{Status: 400, Message: "start: bad request"}) + rec := &recorder{} + ex := testExecutor(f, rec) + ex.Cfg.Retry.Rounds = 1 + + res := ex.Run(context.Background(), plan) + if len(res.Succeeded) != 1 { + t.Fatalf("result = %+v", res) + } + var got []string + for _, e := range rec.events { + if e.Item == "teak.tango.delta.tpl" && e.Status != EventInfo { + got = append(got, string(e.Status)+" "+e.Message) + } + } + if want := []string{string(EventDone) + " template created"}; !slices.Equal(got, want) { + t.Errorf("template events = %q, want %q", got, want) + } +} From fc0b665f51120a74317ebd7aeac43c4f221858f7 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:02:50 +0000 Subject: [PATCH 03/22] apply: delete unfollowable's qmclone check Every clone passes its target VMID to taskUPID, so a zero vmid never comes with a clone's UPID; the check could not fail. --- internal/apply/calls.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/apply/calls.go b/internal/apply/calls.go index 3e7bcf3..9e7f19a 100644 --- a/internal/apply/calls.go +++ b/internal/apply/calls.go @@ -91,7 +91,7 @@ func (e *Executor) taskUPID(ctx context.Context, vmid int, start func() (string, // vmid, if given, is the locked VM (a clone locks its target). func (e *Executor) unfollowable(ctx context.Context, upid string, vmid int, err error) error { u, _ := proxmox.ParseUPID(upid) - if vmid == 0 && u.Type != "qmclone" { + if vmid == 0 { vmid, _ = strconv.Atoi(u.ID) } node := u.Node From c09edab2b5680baf6b58e3eebf10808e202e4954 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:57:34 +0000 Subject: [PATCH 04/22] pods: test the access, capacity, details, discovery and envcheck gaps mutants found --- internal/pods/access_test.go | 285 +++++++++++++++++++++++++++++++- internal/pods/capacity_test.go | 146 ++++++++++++++++ internal/pods/details_test.go | 33 ++++ internal/pods/discovery_test.go | 32 ++++ internal/pods/envcheck_test.go | 41 +++++ 5 files changed, 530 insertions(+), 7 deletions(-) diff --git a/internal/pods/access_test.go b/internal/pods/access_test.go index 0a1124f..e7136eb 100644 --- a/internal/pods/access_test.go +++ b/internal/pods/access_test.go @@ -7,6 +7,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "github.com/wccomps/battleship/internal/config" "github.com/wccomps/battleship/internal/proxmox" @@ -292,12 +293,13 @@ func TestFreeDisksNeeds(t *testing.T) { // fakePerms answers Proxmox's two reads: the listed paths, and one path's // effective privileges. type fakePerms struct { - mu sync.Mutex - err error // Permissions fails with it - listed proxmox.Permissions - at map[string]map[string]bool - tags proxmox.TagAccess - calls []string + mu sync.Mutex + err error // Permissions fails with it + listed proxmox.Permissions + at map[string]map[string]bool + tags proxmox.TagAccess + tagsErr error // TagAccess fails with it + calls []string } func (f *fakePerms) Permissions(context.Context) (proxmox.Permissions, error) { @@ -318,7 +320,7 @@ func (f *fakePerms) TagAccess(context.Context) (proxmox.TagAccess, error) { f.mu.Lock() defer f.mu.Unlock() f.calls = append(f.calls, "tags") - return f.tags, nil + return f.tags, f.tagsErr } // When datacenter user-tag-access restricts tags (or registers set-), @@ -519,3 +521,272 @@ func TestBlockUnpermittedClearsWillStopMaster(t *testing.T) { t.Fatalf("template = %+v, want Blocked set and WillStopMaster cleared", plan.Templates[0]) } } + +// Callers asking for one unlisted path at once share a read: the later one +// waits for it and gets its answer. +func TestAccessConcurrentCallersShareARead(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := &gatedPerms{fakePerms: fakePerms{listed: proxmox.Permissions{}, at: map[string]map[string]bool{"/vms/9021": {"VM.Clone": false}}}, + release: make(chan struct{})} + acc := NewAccess(f) + got := make([]map[string]bool, 2) + errs := make([]error, 2) + var wg sync.WaitGroup + for i := range 2 { + wg.Go(func() { got[i], errs[i] = acc.Privileges(context.Background(), "/vms/9021") }) + synctest.Wait() // the first is reading; the second waits for it + } + close(f.release) + wg.Wait() + for i := range 2 { + if _, ok := got[i]["VM.Clone"]; !ok || errs[i] != nil { + t.Errorf("caller %d: %v, %v", i, got[i], errs[i]) + } + } + if strings.Join(f.calls, ",") != "all,/vms/9021" { + t.Errorf("calls = %v, want one read of the path", f.calls) + } + }) +} + +// gatedPerms is fakePerms whose path reads wait for release. +type gatedPerms struct { + fakePerms + release chan struct{} +} + +func (g *gatedPerms) PermissionsAt(ctx context.Context, path string) (map[string]bool, error) { + <-g.release + return g.fakePerms.PermissionsAt(ctx, path) +} + +// Tag access is read once; a refusal is remembered, while a read the +// caller cancelled or timed out isn't. +func TestAccessTagAccessIsReadOnce(t *testing.T) { + ctx := context.Background() + f := &fakePerms{tags: proxmox.TagAccess{Mode: "list"}} + acc := NewAccess(f) + for range 2 { + if ta, err := acc.TagAccess(ctx); err != nil || ta.Mode != "list" { + t.Fatalf("tag access = %+v, %v", ta, err) + } + } + if len(f.calls) != 1 { + t.Errorf("read %d times, want once", len(f.calls)) + } + + refused := &fakePerms{tagsErr: &proxmox.APIError{Status: 403, Message: "forbidden"}} + acc = NewAccess(refused) + for range 2 { + if _, err := acc.TagAccess(ctx); err == nil { + t.Fatal("a refused read succeeded") + } + } + if len(refused.calls) != 1 { + t.Errorf("a refused read was asked %d times, want once", len(refused.calls)) + } + + for _, cause := range []error{context.Canceled, context.DeadlineExceeded} { + f := &fakePerms{tagsErr: cause} + acc := NewAccess(f) + if _, err := acc.TagAccess(ctx); !errors.Is(err, cause) { + t.Fatalf("first read: %v", err) + } + f.tagsErr, f.tags = nil, proxmox.TagAccess{Mode: "free"} + if ta, err := acc.TagAccess(ctx); err != nil || ta.Mode != "free" { + t.Errorf("after %v: %+v, %v; want it asked again", cause, ta, err) + } + } +} + +// Only a custom CPU model needs Mapping.Use on its mapping. +func TestCPUNeedsMappingOnlyForCustomModels(t *testing.T) { + for cpu, want := range map[string]string{ + "host": "", + "x86-64-v2-AES,flags=": "", + "custom-lab": "you don't have Mapping.Use on /mapping/cpu/lab", + } { + plan := &Plan{Kind: KindDeploy, Items: []Item{{Team: "01", Name: "team01-teak", VMID: 10121, CPU: cpu, Steps: []Step{StepCPU}}}} + if err := BlockUnpermitted(context.Background(), plan, grants{"/vms/10121": {"VM.Config.CPU"}}, config.Default()); err != nil { + t.Fatal(err) + } + if got := plan.Items[0].Blocked; got != want { + t.Errorf("cpu %q: blocked %q, want %q", cpu, got, want) + } + } +} + +// A clone source's team bridges need SDN.Use in the teams zone; a bridge +// that is no vnet is left to Proxmox. +func TestCloneNeedsSDNUseOnSourceTeamBridges(t *testing.T) { + cfg := config.Default() + g := grants{ + "/vms/8002": {"VM.Clone"}, + "/pool/pool-01": {"VM.Allocate"}, + "/storage/" + cfg.Deploy.Storage: {"Datastore.AllocateSpace"}, + "/sdn/zones/teams/ext01": {"SDN.Use"}, + } + plan := func() *Plan { + return &Plan{Kind: KindDeploy, Items: []Item{{Team: "01", Name: "team01-teak", VMID: 10121, + Source: &Source{VMID: 8002, Bridges: []string{"ext01", "vmbr0"}}, Steps: []Step{StepClone}}}} + } + p := plan() + if err := BlockUnpermitted(context.Background(), p, g, cfg); err != nil || p.Items[0].Blocked != "" { + t.Errorf("with SDN.Use on ext01: blocked %q, %v", p.Items[0].Blocked, err) + } + delete(g, "/sdn/zones/teams/ext01") + p = plan() + if err := BlockUnpermitted(context.Background(), p, g, cfg); err != nil || p.Items[0].Blocked != "you don't have SDN.Use on /sdn/zones/teams/ext01" { + t.Errorf("without SDN.Use on ext01: blocked %q, %v", p.Items[0].Blocked, err) + } +} + +// An environment host's NICs need SDN.Use only on catalog vnets. +func TestNICsNeedSDNUseOnlyOnCatalogVnets(t *testing.T) { + cfg := envConfig() + vnet := "/sdn/zones/" + cfg.Environments.SDNZone + "/devint01" + g := grants{"/vms/2101": {"VM.Config.Network"}, vnet: {"SDN.Use"}} + plan := func() *Plan { + return &Plan{Kind: KindEnvAdd, Items: []Item{{Name: "oak.kilo.alpha", VMID: 2101, + NICs: map[string]string{"net0": "devint01", "net1": "vmbr0"}, Steps: []Step{StepNetwork}}}} + } + p := plan() + if err := BlockUnpermitted(context.Background(), p, g, cfg); err != nil || p.Items[0].Blocked != "" { + t.Errorf("with SDN.Use on devint01: blocked %q, %v", p.Items[0].Blocked, err) + } + delete(g, vnet) + p = plan() + if err := BlockUnpermitted(context.Background(), p, g, cfg); err != nil || p.Items[0].Blocked != "you don't have SDN.Use on "+vnet { + t.Errorf("without SDN.Use on devint01: blocked %q, %v", p.Items[0].Blocked, err) + } +} + +// Reconfiguring an existing VM's network doesn't touch its template's +// bridges, so it needs no SDN.Use there. +func TestExistingVMNeedsNoSDNUseOnTemplateBridges(t *testing.T) { + tpl := TemplateSpec{Name: "teak.x.tpl", VMID: 9021, MasterVMID: 121, Exists: true, Interfaces: 1, Bridges: []string{"ext01"}} + plan := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{tpl}, + Items: []Item{{Team: "01", Name: "team01-teak", VMID: 10121, Template: tpl.Name, Steps: []Step{StepNetwork}}}} + acc := grants{"/vms/10121": {"VM.Config.Network"}, "/sdn/zones/teams/int01": {"SDN.Use"}} + if err := BlockUnpermitted(context.Background(), plan, acc, config.Default()); err != nil || plan.Items[0].Blocked != "" { + t.Errorf("blocked %q, %v", plan.Items[0].Blocked, err) + } +} + +// The guest step's reboot of a Windows host needs VM.PowerMgmt; a Linux +// host's doesn't reboot. +func TestGuestStepPowerNeedsWindows(t *testing.T) { + for os, want := range map[string]string{ImageWindows: "you don't have VM.PowerMgmt on /vms/2101", ImageLinux: ""} { + plan := &Plan{Kind: KindEnvAdd, Items: []Item{{Name: "oak.kilo.alpha", VMID: 2101, Guest: &Guest{OS: os}, Steps: []Step{StepGuest}}}} + if err := BlockUnpermitted(context.Background(), plan, grants{"/vms/2101": {"VM.GuestAgent.Unrestricted"}}, envConfig()); err != nil { + t.Fatal(err) + } + if got := plan.Items[0].Blocked; got != want { + t.Errorf("%s: blocked %q, want %q", os, got, want) + } + } +} + +// Every template and item is checked, whatever is before it: an item +// blocked already, one blocked with its template, or a clone without one. +// Unpermitted marks just the items blocked for privileges here. +func TestBlockUnpermittedChecksEveryTemplateAndItem(t *testing.T) { + plan := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{ + {Name: "elm.x.tpl", VMID: 9023, MasterVMID: 123, Blocked: "no master"}, + {Name: "teak.x.tpl", VMID: 9021, MasterVMID: 121, Interfaces: 1}, + }, Items: []Item{ + {Team: "01", Name: "team01-dc", VMID: 10101, Steps: []Step{StepPower}, Blocked: "no snapshot"}, + {Team: "01", Name: "team01-elm", VMID: 10123, Template: "elm.x.tpl", Steps: []Step{StepClone}}, + {Team: "01", Name: "team01-ash", VMID: 10124, Template: "ash.x.tpl", Steps: []Step{StepClone}}, + {Team: "01", Name: "team01-web", VMID: 10102, Steps: []Step{StepPower}}, + {Team: "01", Name: "team01-db", VMID: 10103, Steps: []Step{StepPower}}, + }} + if err := BlockUnpermitted(context.Background(), plan, grants{"/vms/10103": {"VM.PowerMgmt"}}, config.Default()); err != nil { + t.Fatal(err) + } + if got := plan.Templates[1].Blocked; !strings.HasPrefix(got, "you don't have VM.Clone on /vms/121") { + t.Errorf("teak.x.tpl blocked %q", got) + } + want := []struct { + blocked string + unpermitted bool + }{ + {"no snapshot", false}, + {"template elm.x.tpl: no master", false}, + {"", false}, + {"you don't have VM.PowerMgmt on /vms/10102", true}, + {"", false}, + } + for i, it := range plan.Items { + if it.Blocked != want[i].blocked || it.Unpermitted != want[i].unpermitted { + t.Errorf("%s: blocked %q, unpermitted %v; want %q, %v", it.Name, it.Blocked, it.Unpermitted, want[i].blocked, want[i].unpermitted) + } + } +} + +// failingAt is grants whose reads of path fail. +type failingAt struct { + grants + path string +} + +func (f failingAt) Privileges(ctx context.Context, path string) (map[string]bool, error) { + if path == f.path { + return nil, errors.New("proxmox: 500") + } + return f.grants.Privileges(ctx, path) +} + +// A privilege read that fails fails the check, but a need held on its pool +// isn't then read on the VM's path. +func TestBlockUnpermittedReadFailures(t *testing.T) { + cfg := config.Default() + if err := BlockUnpermitted(context.Background(), powerPlan(), failingAt{grants{}, "/vms/10102"}, cfg); err == nil { + t.Error("a failed read was ignored") + } + acc := failingAt{grants{ + "/vms/8002": {"VM.Clone"}, + "/pool/pool-01": {"VM.Allocate"}, + "/storage/" + cfg.Deploy.Storage: {"Datastore.AllocateSpace"}, + }, "/vms/10121"} + plan := &Plan{Kind: KindDeploy, Items: []Item{{Team: "01", Name: "team01-teak", VMID: 10121, Source: &Source{VMID: 8002}, Steps: []Step{StepClone}}}} + if err := BlockUnpermitted(context.Background(), plan, acc, cfg); err != nil || plan.Items[0].Blocked != "" { + t.Errorf("held on the pool: blocked %q, %v", plan.Items[0].Blocked, err) + } +} + +// noTagAccess is grants that can't read tag access. +type noTagAccess struct{ grants } + +func (noTagAccess) TagAccess(context.Context) (proxmox.TagAccess, error) { + return proxmox.TagAccess{}, errors.New("proxmox: 500") +} + +// Tag access is read only for a set tag an unblocked item writes. +func TestBlockUnpermittedReadsTagAccessOnlyForSetTags(t *testing.T) { + plan := &Plan{Kind: KindDeploy, Items: []Item{ + {Team: "01", Name: "team01-teak", VMID: 10121, Set: "kilo.alpha", Steps: []Step{StepSetTag}, Blocked: "no template"}, + {Team: "01", Name: "team01-dc", VMID: 10101, Steps: []Step{StepSetTag}}, + }} + if err := BlockUnpermitted(context.Background(), plan, noTagAccess{grants{"/vms/10101": {"VM.Config.Options"}}}, config.Default()); err != nil { + t.Fatalf("tag access read: %v", err) + } + if b := plan.Items[1].Blocked; b != "" { + t.Errorf("blocked %q", b) + } +} + +// Retiring the version a register supersedes edits that version's tags; +// a first version retires nothing. +func TestRetireNeedsOptionsOnTheSupersededVersion(t *testing.T) { + plan := &Plan{Kind: KindImageRegister, Items: []Item{ + {Name: "debian-12-v2", VMID: 8002, Supersedes: &Source{VMID: 8001}, Steps: []Step{StepRetire}}, + {Name: "debian-13-v1", VMID: 8003, Steps: []Step{StepRetire}}, + }} + if err := BlockUnpermitted(context.Background(), plan, grants{}, envConfig()); err != nil { + t.Fatal(err) + } + if got := blocked(plan); len(got) != 1 || got["debian-12-v2"] != "you don't have VM.Config.Options on /vms/8001" { + t.Errorf("blocked = %v", got) + } +} diff --git a/internal/pods/capacity_test.go b/internal/pods/capacity_test.go index a2f97ba..f02c9c9 100644 --- a/internal/pods/capacity_test.go +++ b/internal/pods/capacity_test.go @@ -313,3 +313,149 @@ func TestCapacityRebuildCrossNodeLocalStorage(t *testing.T) { t.Errorf("usage = %+v, want %+v", c.Usage, want) } } + +// Needing exactly what is free isn't over, and leaving exactly 10% isn't +// near full; a usage without a total is never near full. +func TestCapacityUsageBoundaries(t *testing.T) { + for _, c := range []struct { + u Usage + over, near bool + }{ + {Usage{Used: 50, Total: 100, Needed: 50}, false, true}, + {Usage{Used: 50, Total: 100, Needed: 51}, true, true}, + {Usage{Used: 80, Total: 100, Needed: 10}, false, false}, + {Usage{Used: 80, Total: 100, Needed: 11}, false, true}, + {Usage{Total: 0, Needed: 5}, true, false}, + } { + if got := c.u.Over(); got != c.over { + t.Errorf("%+v: over = %v, want %v", c.u, got, c.over) + } + if got := c.u.Near(); got != c.near { + t.Errorf("%+v: near = %v, want %v", c.u, got, c.near) + } + } +} + +// A blocked or reused template before a built one doesn't hide the build's +// copy of its master, nor what its clones need. +func TestCapacityCountsEveryTemplate(t *testing.T) { + res := capCluster() + res.VMs = append(res.VMs, proxmox.VM{VMID: 122, Name: "oak.x", Node: "birch", Status: "stopped", MaxMem: 2 * gib, MaxDisk: 16 * gib}) + p := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{ + {Name: "elm.x.tpl", VMID: 9023, MasterVMID: 123, MasterNode: "cedar", Blocked: "no master"}, + {Name: "teak.x.tpl", VMID: 9021, Exists: true, MasterVMID: 121, MasterNode: "cedar"}, + {Name: "oak.x.tpl", VMID: 9022, MasterVMID: 122, MasterNode: "birch"}, + }} + oak := deployItemOn("01", "birch", 10122, true) + oak.Host, oak.Name, oak.Template = "oak", "team01-oak", "oak.x.tpl" + p.Items = []Item{oak} + c := EstimateCapacity(p, res, deployCfg(false)) + want := []Usage{ + {Kind: UsageMemory, Node: "birch", Used: 32 * gib, Total: 256 * gib, Needed: 2 * gib}, + {Kind: UsageStorage, Node: "birch", Storage: "competitions", Used: 100 * gib, Total: 1000 * gib, Needed: 32 * gib}, + } + if !reflect.DeepEqual(c.Usage, want) { + t.Errorf("usage =\n %+v\nwant\n %+v", c.Usage, want) + } +} + +// A deploy that only starts an existing VM needs its memory if it is +// stopped, and nothing if it already runs. +func TestCapacityDeployStartCountsStoppedVMsOnly(t *testing.T) { + start := func(team string, vmid int) Item { + return Item{Team: team, Host: "teak", Name: "team" + team + "-teak", VMID: vmid, Node: "birch", Steps: []Step{StepStart}} + } + stopped := EstimateCapacity(&Plan{Kind: KindDeploy, Items: []Item{start("03", 10321)}}, capCluster(), deployCfg(true)) + if want := []Usage{{Kind: UsageMemory, Node: "birch", Used: 32 * gib, Total: 256 * gib, Needed: 4 * gib}}; !reflect.DeepEqual(stopped.Usage, want) { + t.Errorf("starting a stopped VM: usage = %+v, want %+v", stopped.Usage, want) + } + running := EstimateCapacity(&Plan{Kind: KindDeploy, Items: []Item{start("04", 10421)}}, capCluster(), deployCfg(true)) + if len(running.Usage) != 0 { + t.Errorf("starting a running VM: usage = %+v, want none", running.Usage) + } +} + +// Replacing a VM with a clone of the same size needs nothing more on its +// node, which gets no row; other nodes are still checked. +func TestCapacityReplacementNetsOut(t *testing.T) { + res := capCluster() + res.VMs[1].MaxMem, res.VMs[1].MaxDisk = 4*gib, 32*gib // the template is team04-teak's size + p := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{{Name: "teak.x.tpl", VMID: 9021, Exists: true, MasterVMID: 121, MasterNode: "cedar"}}} + replace := deployItemOn("04", "birch", 10421, true) + replace.Steps = append([]Step{StepStop, StepDelete}, replace.Steps...) + p.Items = []Item{replace, deployItemOn("05", "cedar", 10521, true)} + c := EstimateCapacity(p, res, deployCfg(false)) + want := []Usage{ + {Kind: UsageMemory, Node: "cedar", Used: 216 * gib, Total: 256 * gib, Needed: 4 * gib}, + {Kind: UsageStorage, Node: "cedar", Storage: "competitions", Used: 900 * gib, Total: 1000 * gib, Needed: 32 * gib}, + } + if !reflect.DeepEqual(c.Usage, want) || len(c.Notes) != 0 { + t.Errorf("usage =\n %+v\nwant\n %+v\nnotes %q", c.Usage, want, c.Notes) + } +} + +// Nodes that can't be checked, sorting before one that can, don't stop it +// being checked. +func TestCapacityChecksNodesAfterUncheckedOnes(t *testing.T) { + res := capCluster() + res.Nodes = []proxmox.NodeResource{ + {Node: "alder", Status: "offline"}, + {Node: "birch", Status: "online"}, + {Node: "cedar", Status: "online", Mem: 216 * gib, MaxMem: 256 * gib}, + } + p := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{{Name: "teak.x.tpl", VMID: 9021, Exists: true, MasterVMID: 121, MasterNode: "cedar"}}, + Items: []Item{deployItemOn("01", "alder", 10121, true), deployItemOn("02", "birch", 10221, true), deployItemOn("03", "cedar", 10321, true)}} + c := EstimateCapacity(p, res, deployCfg(true)) + if want := []Usage{{Kind: UsageMemory, Node: "cedar", Used: 216 * gib, Total: 256 * gib, Needed: 6 * gib}}; !reflect.DeepEqual(c.Usage, want) { + t.Errorf("usage = %+v, want %+v", c.Usage, want) + } + want := []string{ + "Memory on birch is unknown: you don't have Sys.Audit on /nodes there, so Proxmox shows no memory figures. Nothing is blocked for it.", + "alder reports no memory (it may be offline), so its 6 GiB can't be checked.", + } + if !reflect.DeepEqual(c.Notes, want) { + t.Errorf("notes =\n %q\nwant\n %q", c.Notes, want) + } +} + +// Linked clones copy nothing, so shared storage gets no row. +func TestCapacityLinkedClonesNeedNoSharedStorage(t *testing.T) { + res := capCluster() + res.Storage = []proxmox.StorageResource{{Storage: "competitions", Node: "cedar", Shared: true, Disk: 100 * gib, MaxDisk: 1000 * gib}} + p := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{{Name: "teak.x.tpl", VMID: 9021, Exists: true, MasterVMID: 121, MasterNode: "cedar"}}, + Items: []Item{deployItemOn("01", "birch", 10121, true)}} + for _, u := range EstimateCapacity(p, res, deployCfg(true)).Usage { + if u.Kind == UsageStorage { + t.Errorf("storage row %+v for linked clones", u) + } + } +} + +// Node-local storage is the configured storage on that node: not another +// storage there, nor the storage elsewhere, nor one without figures. +func TestCapacityLocalStorageIsTheNodesOwn(t *testing.T) { + p := &Plan{Kind: KindDeploy, Templates: []TemplateSpec{{Name: "teak.x.tpl", VMID: 9021, Exists: true, MasterVMID: 121, MasterNode: "cedar"}}, + Items: []Item{deployItemOn("01", "cedar", 10121, true)}} + res := capCluster() + res.Storage = []proxmox.StorageResource{ + {Storage: "local", Node: "cedar", Disk: 0, MaxDisk: 100 * gib}, + {Storage: "competitions", Node: "birch", Disk: 100 * gib, MaxDisk: 1000 * gib}, + {Storage: "competitions", Node: "cedar", Disk: 900 * gib, MaxDisk: 1000 * gib}, + } + c := EstimateCapacity(p, res, deployCfg(false)) + want := Usage{Kind: UsageStorage, Node: "cedar", Storage: "competitions", Used: 900 * gib, Total: 1000 * gib, Needed: 20 * gib} + if n := len(c.Usage); n == 0 || c.Usage[n-1] != want { + t.Errorf("usage = %+v, want it to end with %+v", c.Usage, want) + } + + res.Storage = []proxmox.StorageResource{{Storage: "competitions", Node: "cedar"}} // no Datastore.Audit + c = EstimateCapacity(p, res, deployCfg(false)) + for _, u := range c.Usage { + if u.Kind == UsageStorage { + t.Errorf("storage row %+v without figures", u) + } + } + if want := []string{"cedar reports no storage competitions, so the 20 GiB copied there can't be checked."}; !reflect.DeepEqual(c.Notes, want) { + t.Errorf("notes = %q, want %q", c.Notes, want) + } +} diff --git a/internal/pods/details_test.go b/internal/pods/details_test.go index 261de01..ea69ca9 100644 --- a/internal/pods/details_test.go +++ b/internal/pods/details_test.go @@ -149,6 +149,39 @@ func TestCheckDetails(t *testing.T) { } } +// A value of exactly MaxDetail characters is allowed. +func TestCheckDetailsAtMaxLength(t *testing.T) { + if err := CheckDetails(ImageDetails{OS: strings.Repeat("é", MaxDetail)}); err != nil { + t.Error(err) + } +} + +// The login is checked as the line it is written as: a user and password +// each short enough can still make it too long. A login already refused +// for its user isn't refused again. +func TestCheckDetailsLogin(t *testing.T) { + long := ImageDetails{User: strings.Repeat("u", 150), Password: strings.Repeat("p", 100)} + if err := CheckDetails(long); err == nil || err.Error() != "the login is too long: at most 200 characters" { + t.Errorf("a 253-character login: %v", err) + } + tab := ImageDetails{User: "a\tb", Password: "c"} + if err := CheckDetails(tab); err == nil || err.Error() != "the login's user must be printable text on one line" { + t.Errorf("a user with a tab: %v", err) + } +} + +// Notes that already say what they would be written as are no change. +func TestDetailsChangesNothingWhenWritten(t *testing.T) { + n := ImageNotes{ImageDetails: winDetails} + desc, err := n.apply("Patched monthly.\nbattleship: source=150") + if err != nil { + t.Fatal(err) + } + if ch, err := n.Changes(map[string]string{"description": desc}); ch != nil || err != nil { + t.Errorf("changes = %q, %v; want none", ch, err) + } +} + // Register keeps a source's block, and from notes written as prose takes // the login, build and OS, which are plainly said; an unreadable block // gives none. diff --git a/internal/pods/discovery_test.go b/internal/pods/discovery_test.go index 606a2c6..df9165f 100644 --- a/internal/pods/discovery_test.go +++ b/internal/pods/discovery_test.go @@ -212,6 +212,38 @@ func TestAssignNodes(t *testing.T) { }, wantAssign: map[string]string{"01": "a"}, }, + { + name: "a team without VMs doesn't stop later teams staying on their node", + teams: []string{"01", "02"}, + nodes: []string{"a", "b"}, + vms: []proxmox.VM{ + {Node: "a", VMID: 10201, Name: "team02-elmer", Status: "stopped", MaxMem: 8 << 30, MaxCPU: 2}, + {Node: "a", VMID: 1, Status: "running", MaxMem: 64 << 30, MaxCPU: 16}, + }, + podVMs: []proxmox.VM{{Name: "elmer.kilo.alpha", MaxMem: 8 << 30, MaxCPU: 2}}, + wantAssign: map[string]string{"01": "b", "02": "a"}, + }, + { + name: "a pod split evenly stays on the first node alphabetically", + teams: []string{"01"}, + nodes: []string{"b", "a"}, + vms: []proxmox.VM{ + {Node: "b", VMID: 10101, Name: "team01-elmer", Status: "stopped"}, + {Node: "a", VMID: 10102, Name: "team01-bugs", Status: "stopped"}, + }, + wantAssign: map[string]string{"01": "a"}, + }, + { + name: "a pod host already running on its node adds no load there", + teams: []string{"01", "02"}, + nodes: []string{"a", "b"}, + vms: []proxmox.VM{ + {Node: "a", VMID: 10101, Name: "team01-elmer", Status: "running", MaxMem: 8 << 30, MaxCPU: 2}, + {Node: "b", VMID: 1, Status: "running", MaxMem: 12 << 30, MaxCPU: 3}, + }, + podVMs: []proxmox.VM{{Name: "elmer.kilo.alpha", MaxMem: 8 << 30, MaxCPU: 2}}, + wantAssign: map[string]string{"01": "a", "02": "a"}, + }, { name: "empty nodes returns empty map", teams: []string{"01"}, diff --git a/internal/pods/envcheck_test.go b/internal/pods/envcheck_test.go index d831334..c7ee84d 100644 --- a/internal/pods/envcheck_test.go +++ b/internal/pods/envcheck_test.go @@ -9,6 +9,7 @@ import ( "pgregory.net/rapid" + "github.com/wccomps/battleship/internal/pods/podstest" "github.com/wccomps/battleship/internal/proxmox" ) @@ -178,6 +179,46 @@ func TestRouterRowNeedsARouterImage(t *testing.T) { } } +// Only a router before it makes a router host a second one; another host +// doesn't. +func TestCheckEnvRouterAfterOtherHosts(t *testing.T) { + p := checkFake() + envs, vms, err := p.Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + req := EnvRequest{Domain: "kilo.bravo", Slot: 2, Hosts: []HostSpec{{Host: "web", Family: "debian-12"}, {Host: "fw", Family: "gw"}}} + if got := CheckEnv(KindEnvCreate, envs, nil, BaseImages(vms), req); !slices.Equal(got, []EnvProblem{errNoRouter}) { + t.Errorf("CheckEnv = %+v, want only the missing router row", got) + } +} + +// A resumed host keeps the address it has; one without an address yet +// claims the one it names, before any new host can, and a resumed host +// doesn't stop later hosts claiming theirs. +func TestCheckEnvResumedHostsAndAddressClaims(t *testing.T) { + f := checkFake().API.(*podstest.Fake) + f.Add(proxmox.VM{VMID: 2103, Name: "elm.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "stopped"}, + map[string]string{"description": "battleship: os=linux base=debian-12-v1 dns=router"}) + p := NewPlanner(f, envConfig()) + envs, vms, err := p.Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + for _, c := range []struct { + hosts []HostSpec + want []EnvProblem + }{ + {[]HostSpec{{Host: "teak", Family: "debian-12"}, {Host: "web", Family: "debian-12", Octet: 30}}, nil}, + {[]HostSpec{{Host: "elm", Family: "debian-12", Octet: 30}, {Host: "web", Family: "debian-12", Octet: 30}}, + []EnvProblem{{Row: 2, Field: FieldAddress, Why: "address .30 is already taken in kilo.alpha"}}}, + } { + if got := CheckEnv(KindEnvAdd, envs, nil, BaseImages(vms), EnvRequest{Domain: "kilo.alpha", Hosts: c.hosts}); !slices.Equal(got, c.want) { + t.Errorf("%+v:\n got %+v\nwant %+v", c.hosts, got, c.want) + } + } +} + func mustVMs(t *testing.T, p Planner) []proxmox.VM { t.Helper() vms, err := p.API.ClusterVMs(context.Background()) From 117e15386ca27eb743a767881027e1fa9a31ef74 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:19:56 +0000 Subject: [PATCH 05/22] pods: test a Windows host name at the length limit --- internal/pods/envcheck_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/pods/envcheck_test.go b/internal/pods/envcheck_test.go index c7ee84d..9234cc8 100644 --- a/internal/pods/envcheck_test.go +++ b/internal/pods/envcheck_test.go @@ -193,6 +193,19 @@ func TestCheckEnvRouterAfterOtherHosts(t *testing.T) { } } +// A Windows host name of exactly MaxWindowsHostname characters is allowed. +func TestCheckEnvWindowsNameAtMaxLength(t *testing.T) { + p := checkFake() + envs, vms, err := p.Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + name := strings.Repeat("w", MaxWindowsHostname) + if got := CheckEnv(KindEnvAdd, envs, nil, BaseImages(vms), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{{Host: name, Family: "win2022"}}}); len(got) != 0 { + t.Errorf("%q: %+v", name, got) + } +} + // A resumed host keeps the address it has; one without an address yet // claims the one it names, before any new host can, and a resumed host // doesn't stop later hosts claiming theirs. From 083ab3742f2ac33be4f8a9473aba8b0b5c26f316 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:29:59 +0000 Subject: [PATCH 06/22] pods: test that a resumed host without an address is checked, and a router's octet isn't --- internal/pods/envcheck_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/pods/envcheck_test.go b/internal/pods/envcheck_test.go index 9234cc8..86f7ff1 100644 --- a/internal/pods/envcheck_test.go +++ b/internal/pods/envcheck_test.go @@ -207,8 +207,9 @@ func TestCheckEnvWindowsNameAtMaxLength(t *testing.T) { } // A resumed host keeps the address it has; one without an address yet -// claims the one it names, before any new host can, and a resumed host -// doesn't stop later hosts claiming theirs. +// claims the one it names, before any new host can, unless it is taken, +// and a resumed host doesn't stop later hosts claiming theirs. A router's +// octet isn't checked as an address. func TestCheckEnvResumedHostsAndAddressClaims(t *testing.T) { f := checkFake().API.(*podstest.Fake) f.Add(proxmox.VM{VMID: 2103, Name: "elm.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "stopped"}, @@ -225,6 +226,9 @@ func TestCheckEnvResumedHostsAndAddressClaims(t *testing.T) { {[]HostSpec{{Host: "teak", Family: "debian-12"}, {Host: "web", Family: "debian-12", Octet: 30}}, nil}, {[]HostSpec{{Host: "elm", Family: "debian-12", Octet: 30}, {Host: "web", Family: "debian-12", Octet: 30}}, []EnvProblem{{Row: 2, Field: FieldAddress, Why: "address .30 is already taken in kilo.alpha"}}}, + {[]HostSpec{{Host: "elm", Family: "debian-12", Octet: 10}}, + []EnvProblem{{Row: 1, Field: FieldAddress, Why: "address .10 is already taken in kilo.alpha"}}}, + {[]HostSpec{{Host: "gw", Family: "gw", Octet: 10}}, nil}, } { if got := CheckEnv(KindEnvAdd, envs, nil, BaseImages(vms), EnvRequest{Domain: "kilo.alpha", Hosts: c.hosts}); !slices.Equal(got, c.want) { t.Errorf("%+v:\n got %+v\nwant %+v", c.hosts, got, c.want) From 24ceb4c5af15a6abbc0818ff9f50d7578889e438 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:33:53 +0000 Subject: [PATCH 07/22] pods: test EnvEdit's checks, blocks, addresses, DNS, tags and locks --- internal/pods/envedit_test.go | 269 ++++++++++++++++++++++++++++++++++ 1 file changed, 269 insertions(+) diff --git a/internal/pods/envedit_test.go b/internal/pods/envedit_test.go index 9e71437..2a6ec14 100644 --- a/internal/pods/envedit_test.go +++ b/internal/pods/envedit_test.go @@ -140,3 +140,272 @@ func TestEnvPowerAndDeleteHost(t *testing.T) { t.Fatalf("HostToEdit on concurrently deleted VM = %v, want ErrNoEnvHost not-found error", err) } } + +// editFixture is dev slot 01 holding kilo.alpha: router gw, Windows dc +// (.20, its own DNS server), Linux teak (.10, DNS dc, CPU lab-baseline) and +// other host box (.30, no guest agent). +func editFixture() (*podstest.Fake, Planner) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router;keep", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devext01", "net1": "virtio=BC:24:11:00:00:02,bridge=devint01", + "description": "battleship: base=gw-v1 dns=router"}) + f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;keep", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", "cpu": "custom-lab-baseline", + "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1 dns=dc"}) + f.Add(proxmox.VM{VMID: 2102, Name: "dc.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:04,bridge=devint01", "agent": "1", + "description": "battleship: ip=192.168.100.20 os=windows base=debian-12-v1 dns=dc"}) + f.Add(proxmox.VM{VMID: 2103, Name: "box.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:05,bridge=devint01", + "description": "battleship: ip=192.168.100.30 base=debian-12-v1"}) + return f, NewPlanner(f, envConfig()) +} + +func TestHostEditInputCheck(t *testing.T) { + for _, tc := range []struct { + in HostEditInput + ok bool + }{ + {HostEditInput{Host: "oak"}, true}, + {HostEditInput{Host: "Oak"}, false}, + {HostEditInput{Host: "oak.kilo.alpha"}, true}, + {HostEditInput{Host: "Oak.kilo.alpha"}, false}, + {HostEditInput{Host: "oak.alpha"}, false}, + {HostEditInput{Octet: ClearOctet}, true}, + {HostEditInput{Octet: 1}, false}, + {HostEditInput{Octet: 3}, false}, + {HostEditInput{Octet: FirstHostOctet}, true}, + {HostEditInput{Octet: LastHostOctet}, true}, + {HostEditInput{Octet: 255}, false}, + {HostEditInput{Image: NoBaseImage}, true}, + {HostEditInput{Image: "debian-12-v2"}, true}, + {HostEditInput{Image: "debian-12"}, false}, + {HostEditInput{CPU: "lab-baseline"}, true}, + {HostEditInput{CPU: "lab baseline"}, false}, + } { + if err := tc.in.Check(); (err == nil) != tc.ok { + t.Errorf("Check(%+v) = %v, want ok %v", tc.in, err, tc.ok) + } + } +} + +func TestEnvEditItem(t *testing.T) { + name16 := "abcdefghijklmnop" + for _, tc := range []struct { + name string + prep func(f *podstest.Fake, p *Planner) + req HostEditInput + blocked string // substring of Blocked; "" wants it unblocked + check func(t *testing.T, plan *Plan, it Item) + }{ + {name: "rename keeps DNS on another host", req: HostEditInput{VMID: 2101, Host: "oak"}, + check: func(t *testing.T, _ *Plan, it Item) { + want := []Step{StepLabel, StepWaitAgent, StepGuest, StepVerify} + if it.Rename != "oak.kilo.alpha" || !slices.Equal(it.Steps, want) || it.Notes.DNS != "dc" || + it.Guest == nil || it.Guest.DNS.String() != "192.168.100.20" { + t.Errorf("item = %+v, guest %+v", it, it.Guest) + } + }}, + {name: "renamed DNS server keeps serving itself", req: HostEditInput{VMID: 2102, Host: "ad"}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.DNS != "ad" || it.Guest == nil || it.Guest.DNS.String() != "192.168.100.20" { + t.Errorf("notes = %+v, guest %+v", it.Notes, it.Guest) + } + }}, + {name: "other host made Linux takes the environment's DNS", req: HostEditInput{VMID: 2103, Kind: ImageLinux}, + blocked: "box.kilo.alpha has no QEMU guest agent enabled", + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.OS != ImageLinux || it.Notes.DNS != "dc" { + t.Errorf("notes = %+v", it.Notes) + } + }}, + {name: "Windows name at the limit", req: HostEditInput{VMID: 2102, Host: name16[:MaxWindowsHostname]}}, + {name: "Windows name over the limit", req: HostEditInput{VMID: 2102, Host: name16}, + blocked: "Windows host names are at most 15 characters"}, + {name: "Linux name over the Windows limit", req: HostEditInput{VMID: 2101, Host: name16}}, + {name: "first host octet", req: HostEditInput{VMID: 2101, Octet: FirstHostOctet}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.IP.String() != "192.168.100.4" { + t.Errorf("notes = %+v", it.Notes) + } + }}, + {name: "octet of a host listed after it", req: HostEditInput{VMID: 2102, Octet: 10}, + blocked: "address .10 is already taken by teak.kilo.alpha"}, + {name: "kept address another host claims", + prep: func(f *podstest.Fake, _ *Planner) { + f.Add(proxmox.VM{VMID: 2104, Name: "twin.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:06,bridge=devint01", "agent": "1", + "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1 dns=dc"}) + }, + req: HostEditInput{VMID: 2104, Image: "debian-12-v2"}, blocked: "address .10 is already taken by teak.kilo.alpha"}, + {name: "other host clears its address", req: HostEditInput{VMID: 2103, Octet: ClearOctet}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.IP.IsValid() { + t.Errorf("notes = %+v", it.Notes) + } + }}, + {name: "other host keeps its address", req: HostEditInput{VMID: 2103, Image: "debian-12-v2"}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.IP.String() != "192.168.100.30" { + t.Errorf("notes = %+v", it.Notes) + } + }}, + {name: "other host takes the first host octet", req: HostEditInput{VMID: 2103, Octet: FirstHostOctet}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Notes.IP.String() != "192.168.100.4" { + t.Errorf("notes = %+v", it.Notes) + } + }}, + {name: "other host takes a used octet", req: HostEditInput{VMID: 2103, Octet: 10}, + blocked: "address .10 is already taken by teak.kilo.alpha"}, + {name: "second router", req: HostEditInput{VMID: 2101, Kind: ImageRouter}, + blocked: "an environment has one router (gw.kilo.alpha)"}, + {name: "router edit keeps router and other tags", req: HostEditInput{VMID: 2100, Image: "gw-v2"}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Tags != "dev;kilo.alpha;router;keep" || it.Notes.Base != "gw-v2" { + t.Errorf("item = %+v", it) + } + }}, + {name: "router with one NIC", + prep: func(f *podstest.Fake, _ *Planner) { delete(f.VMs, 2100) }, + req: HostEditInput{VMID: 2101, Kind: ImageRouter}, blocked: "teak.kilo.alpha has one NIC"}, + {name: "name in use", req: HostEditInput{VMID: 2101, Host: "dc"}, + blocked: "a VM named dc.kilo.alpha already exists"}, + {name: "eject without a CD-ROM", req: HostEditInput{VMID: 2101, EjectCDROM: true}, + blocked: "teak.kilo.alpha has no CD-ROM attached"}, + {name: "eject without a CD-ROM beside another change", req: HostEditInput{VMID: 2101, EjectCDROM: true, Image: "debian-12-v2"}, + check: func(t *testing.T, _ *Plan, it Item) { + if !slices.Equal(it.Steps, []Step{StepLabel}) { + t.Errorf("steps = %v", it.Steps) + } + }}, + {name: "CPU on a node listing no custom models", req: HostEditInput{VMID: 2101, CPU: "lab-baseline-nested"}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.CPU != "custom-lab-baseline-nested" || !slices.Equal(it.Steps, []Step{StepCPU}) { + t.Errorf("item = %+v", it) + } + }}, + {name: "CPU already set", req: HostEditInput{VMID: 2101, CPU: "lab-baseline"}, + blocked: "teak.kilo.alpha already has these settings", + check: func(t *testing.T, _ *Plan, it Item) { + if it.CPU != "" { + t.Errorf("CPU = %q", it.CPU) + } + }}, + {name: "full name in the slot's domain", req: HostEditInput{VMID: 2101, Host: "oak.kilo.alpha"}, + check: func(t *testing.T, _ *Plan, it Item) { + if it.Rename != "oak.kilo.alpha" { + t.Errorf("rename = %q", it.Rename) + } + }}, + {name: "sole host moves to another domain", + prep: func(f *podstest.Fake, _ *Planner) { + f.Add(proxmox.VM{VMID: 2201, Name: "solo.kilo.beta", Node: "alder", Pool: "dev-02", Tags: "dev;kilo.beta;keep", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:07,bridge=devint02", "agent": "1", + "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1 dns=router"}) + }, + req: HostEditInput{VMID: 2201, Host: "solo.new.domain"}, + check: func(t *testing.T, plan *Plan, it Item) { + if it.Rename != "solo.new.domain" || it.Tags != "dev;new.domain;keep" { + t.Errorf("item = %+v", it) + } + if want := []string{"slot:02", "domain:kilo.beta", "domain:new.domain"}; !slices.Equal(plan.Locks, want) { + t.Errorf("locks = %v, want %v", plan.Locks, want) + } + }}, + {name: "bad ops CA key", + prep: func(_ *podstest.Fake, p *Planner) { p.Cfg.Environments.OpsCAKey = "not-a-key" }, + req: HostEditInput{VMID: 2101, Host: "oak"}, blocked: "ops CA key: "}, + {name: "bad ops CA key after a missing agent", + prep: func(_ *podstest.Fake, p *Planner) { p.Cfg.Environments.OpsCAKey = "not-a-key" }, + req: HostEditInput{VMID: 2103, Kind: ImageLinux}, blocked: "box.kilo.alpha has no QEMU guest agent enabled"}, + {name: "guest host without a domain", + prep: func(f *podstest.Fake, _ *Planner) { + f.Add(proxmox.VM{VMID: 2301, Name: "lonely", Node: "alder", Pool: "dev-03", Tags: "dev", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:08,bridge=devint03", "agent": "1", + "description": "battleship: ip=192.168.100.40 base=debian-12-v1"}) + }, + req: HostEditInput{VMID: 2301, Kind: ImageLinux}, blocked: "lonely has no valid domain", + check: func(t *testing.T, _ *Plan, it Item) { + if it.Guest != nil || !slices.Equal(it.Steps, []Step{StepLabel}) { + t.Errorf("item = %+v, guest %+v", it, it.Guest) + } + }}, + {name: "no free address", + prep: func(f *podstest.Fake, _ *Planner) { + for o := FirstHostOctet; o <= LastHostOctet; o++ { + if o == 10 || o == 20 || o == 30 { + continue + } + f.Add(proxmox.VM{VMID: 3000 + o, Name: fmt.Sprintf("h%d.kilo.alpha", o), Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"description": fmt.Sprintf("battleship: ip=192.168.100.%d", o)}) + } + f.Add(proxmox.VM{VMID: 2104, Name: "spare.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", Status: "running"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:06,bridge=devint01", "agent": "1"}) + }, + req: HostEditInput{VMID: 2104, Kind: ImageLinux}, blocked: "no free address left in kilo.alpha", + check: func(t *testing.T, _ *Plan, it Item) { + if it.Guest != nil { + t.Errorf("guest = %+v", it.Guest) + } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, p := editFixture() + if tc.prep != nil { + tc.prep(f, &p) + } + plan, err := p.EnvEdit(context.Background(), tc.req) + if err != nil { + t.Fatal(err) + } + it := plan.Items[0] + if tc.blocked == "" && it.Blocked != "" || !strings.Contains(it.Blocked, tc.blocked) { + t.Errorf("blocked = %q, want %q", it.Blocked, tc.blocked) + } + if tc.check != nil { + tc.check(t, plan, it) + } + }) + } +} + +func TestEnvEditNameInOtherDomain(t *testing.T) { + _, p := editFixture() + _, err := p.EnvEdit(context.Background(), HostEditInput{VMID: 2101, Host: "oak.other.env"}) + if err == nil || !strings.Contains(err.Error(), "dev slot 01 holds kilo.alpha") { + t.Fatalf("EnvEdit(oak.other.env in kilo.alpha's slot) = %v, want error", err) + } +} + +func TestEnvEditStaleDetails(t *testing.T) { + f, p := editFixture() + ctx := context.Background() + vms, err := p.API.ClusterVMs(ctx) + if err != nil { + t.Fatal(err) + } + at, err := p.HostToEdit(ctx, vms, 2101) + if err != nil { + t.Fatal(err) + } + det := at.Edit() + det.OS = "Debian 13" + f.VMs[2101].Config["description"] = "Changed elsewhere.\n\n" + f.VMs[2101].Config["description"] + + plan, err := p.EnvEdit(ctx, HostEditInput{VMID: 2101, Details: &det}) + if err != nil { + t.Fatal(err) + } + if b := plan.Items[0].Blocked; !strings.Contains(b, "the notes of teak.kilo.alpha changed since you opened this form") { + t.Errorf("stale details blocked = %q", b) + } + // An earlier block reason stands. + plan, err = p.EnvEdit(ctx, HostEditInput{VMID: 2101, Host: "dc", Details: &det}) + if err != nil { + t.Fatal(err) + } + if b := plan.Items[0].Blocked; b != "a VM named dc.kilo.alpha already exists" { + t.Errorf("stale details after a name clash blocked = %q", b) + } +} From c1a8a27b31053ea2e29261293dd11610e495e8ad Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:05:32 +0000 Subject: [PATCH 08/22] pods: test environment reading, host warnings and env planning edges --- internal/pods/environments_test.go | 262 +++++++++++++++++++++++++++++ internal/pods/envplan_test.go | 177 ++++++++++++++++++- internal/pods/envspec_test.go | 16 +- internal/pods/envteardown_test.go | 9 +- 4 files changed, 457 insertions(+), 7 deletions(-) diff --git a/internal/pods/environments_test.go b/internal/pods/environments_test.go index 66a37a3..1c93b6e 100644 --- a/internal/pods/environments_test.go +++ b/internal/pods/environments_test.go @@ -2,6 +2,7 @@ package pods import ( "context" + "fmt" "slices" "testing" @@ -161,3 +162,264 @@ func TestEnvironmentHostWarnings(t *testing.T) { t.Errorf("rgw.Warnings = %v, want %v", rgw.Warnings, wantRouter) } } + +// reversedListing lists the cluster's VMs highest VMID first: Proxmox lists +// them in no promised order. +type reversedListing struct{ *podstest.Fake } + +func (r reversedListing) ClusterVMs(ctx context.Context) ([]proxmox.VM, error) { + vms, err := r.Fake.ClusterVMs(ctx) + slices.Reverse(vms) + return vms, err +} + +func hostNames(hs []EnvHost) []string { + var out []string + for _, h := range hs { + out = append(out, h.Name) + } + return out +} + +func hostVMIDs(hs []EnvHost) []int { + var out []int + for _, h := range hs { + out = append(out, h.VMID) + } + return out +} + +// A slot's hosts are in name order and its half-deleted VMs in VMID order, +// however Proxmox lists them. A half-deleted VM outside every pool is the +// slot's whose VMID block holds it, its first and last VMIDs included. +func TestEnvironmentsOrderHostsAndHalfDeleted(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2110, Name: "oak.kilo.alpha", Node: "alder", Pool: "dev-01"}, nil) + f.Add(proxmox.VM{VMID: 2111, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01"}, nil) + f.Add(proxmox.VM{VMID: 2112, Name: "elm.kilo.alpha", Node: "alder", Pool: "dev-01"}, nil) + for _, id := range []int{2100, 2150, 2199, 2200} { + f.Add(proxmox.VM{VMID: id, Name: fmt.Sprintf("VM %d", id), Node: "alder"}, map[string]string{"lock": "destroyed"}) + } + envs, _, err := NewPlanner(reversedListing{f}, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + if got := hostNames(envs[0].Hosts); !slices.Equal(got, []string{"elm.kilo.alpha", "oak.kilo.alpha", "teak.kilo.alpha"}) { + t.Errorf("slot 1 hosts = %q", got) + } + if got := hostVMIDs(envs[0].HalfDeleted); !slices.Equal(got, []int{2100, 2150, 2199}) { + t.Errorf("slot 1 half-deleted = %v", got) + } + if got := hostVMIDs(envs[1].HalfDeleted); !slices.Equal(got, []int{2200}) { + t.Errorf("slot 2 half-deleted = %v", got) + } +} + +// A VM gone between the listing and reading its config is left out; the +// VMs listed after it are still read. +func TestEnvironmentsSkipAVMGoneSinceTheListing(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 200, Name: "gone", Node: "alder"}, map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devint01"}) + f.FailOn("config:200", podstest.NotExist("alder", 200)) + f.Add(proxmox.VM{VMID: 300, Name: "stray", Node: "alder"}, map[string]string{"net0": "virtio=BC:24:11:00:00:02,bridge=devint02"}) + f.Add(proxmox.VM{VMID: 2100, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01"}, nil) + envs, _, err := NewPlanner(f, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(envs[0].Users) != 0 || !slices.Equal(hostNames(envs[0].Hosts), []string{"teak.kilo.alpha"}) { + t.Errorf("slot 1 = %+v", envs[0]) + } + if !slices.Equal(envs[1].Users, []string{"stray"}) { + t.Errorf("slot 2 users = %q", envs[1].Users) + } +} + +// A VM outside the pools holds a slot only through a NIC on that slot's +// bridges, and is named once however many it has there. +func TestEnvironmentsUsersAreOnTheSlotBridges(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 300, Name: "lab", Node: "alder"}, map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=vmbr0"}) + f.Add(proxmox.VM{VMID: 301, Name: "bridged", Node: "alder"}, map[string]string{ + "net0": "virtio=BC:24:11:00:00:02,bridge=devext02", "net1": "virtio=BC:24:11:00:00:03,bridge=devint02"}) + envs, _, err := NewPlanner(f, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + if !envs[0].Free() || !envs[2].Free() { + t.Errorf("slots 1 and 3 = %+v, %+v; a VM on vmbr0 holds neither", envs[0], envs[2]) + } + if !slices.Equal(envs[1].Users, []string{"bridged"}) { + t.Errorf("slot 2 users = %q", envs[1].Users) + } +} + +// A host's details block is read as unreadable only when it is, and a +// CD-ROM only when an image is in a drive (a cloud-init drive isn't one). +func TestEnvironmentsReadHostNotesAndCDROM(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2100, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01"}, map[string]string{ + "ide2": "competitions:vm-2100-cloudinit,media=cdrom", "description": "**Details**\n- Colour: blue\nbattleship: base=debian-12-v1"}) + f.Add(proxmox.VM{VMID: 2101, Name: "oak.kilo.alpha", Node: "alder", Pool: "dev-01"}, map[string]string{ + "ide2": "local:iso/debian.iso,media=cdrom", "description": "Login: root / pw\nbattleship: base=debian-12-v1"}) + envs, _, err := NewPlanner(f, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + teak, _ := envs[0].Host("teak.kilo.alpha") + oak, _ := envs[0].Host("oak.kilo.alpha") + if !teak.Unreadable || teak.CDROM { + t.Errorf("teak: Unreadable %v, CDROM %v", teak.Unreadable, teak.CDROM) + } + if oak.Unreadable || !oak.CDROM || oak.UserNotes != "Login: root / pw" { + t.Errorf("oak: Unreadable %v, CDROM %v, notes %q", oak.Unreadable, oak.CDROM, oak.UserNotes) + } +} + +// DNS can point at a Windows or Linux host with an address, named by its +// host name as CheckHostname takes it; at no other host. +func TestEnvironmentDNSAddress(t *testing.T) { + lan := envConfig().Environments.Subnet + host := func(name, os string, octet int) EnvHost { + n := Notes{IP: lan.Host(octet), OS: os} + return EnvHost{Name: name, Notes: n, Addr: n.IP} + } + e := Environment{Domain: "kilo.alpha", LAN: lan, Hosts: []EnvHost{ + host("teak.kilo.alpha", ImageLinux, 10), host("oak.kilo.alpha", ImageWindows, 11), + host("box.kilo.alpha", "", 12), host("Elm.kilo.alpha", ImageLinux, 13)}} + for choice, want := range map[string]string{"": "192.168.100.2", DNSRouter: "192.168.100.2", "teak": "192.168.100.10", "oak": "192.168.100.11"} { + if got, err := e.DNSAddress(choice); err != nil || AddrText(got) != want { + t.Errorf("DNSAddress(%q) = %v, %v; want %s", choice, got, err, want) + } + } + for _, choice := range []string{"box", "Elm", "nope"} { + if got, err := e.DNSAddress(choice); err == nil { + t.Errorf("DNSAddress(%q) = %v", choice, got) + } + } +} + +// A router's WAN and LAN MACs are those of its first NICs on the slot's +// external and internal bridges, else net0's and net1's unless that NIC is +// the other one's. +func TestRouterMACs(t *testing.T) { + s := Slots(envConfig().Environments)[0] + nic := func(n int, bridge string) string { + return fmt.Sprintf("virtio=BC:24:11:00:00:0%d,bridge=%s", n, bridge) + } + mac := func(n int) string { return fmt.Sprintf("bc:24:11:00:00:0%d", n) } + for _, tc := range []struct { + name string + bridges []string // by NIC: net0, net1, ... + wan, lan string + }{ + {"in order", []string{"devext01", "devint01"}, mac(0), mac(1)}, + {"swapped", []string{"devint01", "devext01"}, mac(1), mac(0)}, + {"more NICs on the slot's bridges", []string{"devext01", "devint01", "devext01", "devint01"}, mac(0), mac(1)}, + {"on no slot bridge", []string{"vmbr0", "vmbr1"}, mac(0), mac(1)}, + {"LAN on net0, net1 elsewhere", []string{"devint01", "vmbr1"}, "", mac(0)}, + {"WAN on net1, net0 elsewhere", []string{"vmbr0", "devext01"}, mac(1), ""}, + {"WAN past net1", []string{"vmbr0", "devint01", "devext01"}, mac(2), mac(1)}, + {"LAN past net1", []string{"devext01", "vmbr1", "devint01"}, mac(0), mac(2)}, + } { + cfg := map[string]string{} + for i, b := range tc.bridges { + cfg[fmt.Sprintf("net%d", i)] = nic(i, b) + } + if wan, lan := routerMACs(cfg, s); wan != tc.wan || lan != tc.lan { + t.Errorf("%s: WAN %q, LAN %q; want %q, %q", tc.name, wan, lan, tc.wan, tc.lan) + } + } +} + +// A slot VM without NICs or disks (a config being built) isn't missing a +// NIC, and wants a guest agent only once it has a disk or an agent option. +// Memory over the usual is given in GiB when whole. +func TestEnvironmentHostWarningsByHardware(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, nil) + f.Add(proxmox.VM{VMID: 2101, Name: "bare.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, nil) + f.Add(proxmox.VM{VMID: 2102, Name: "disk.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"scsi0": "competitions:2102/vm-2102-disk-0.qcow2"}) + f.Add(proxmox.VM{VMID: 2103, Name: "win.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha", MaxMem: 13 << 30}, + map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", "description": "battleship: os=windows"}) + envs, _, err := NewPlanner(f, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + for name, want := range map[string][]string{ + "gw.kilo.alpha": nil, + "bare.kilo.alpha": nil, + "disk.kilo.alpha": {"no net0 NIC", "guest agent off"}, + "win.kilo.alpha": {"13 GiB of memory (Windows VMs are usually at most 12 GiB)"}, + } { + if h, _ := envs[0].Host(name); !slices.Equal(h.Warnings, want) { + t.Errorf("%s warnings = %q, want %q", name, h.Warnings, want) + } + } +} + +// cpuBlind is an API that can't list a node's custom CPU models. +type cpuBlind struct{ Reads } + +// Without a way to list custom CPU models, no CPU model is wanted. +func TestEnvironmentsWithoutCPUModels(t *testing.T) { + f := podstest.New("alder") + f.CPUModels = []string{"baseline"} + f.Add(proxmox.VM{VMID: 2100, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devint01", "cpu": "x86-64-v2-AES"}) + envs, _, err := NewPlanner(cpuBlind{f}, envConfig()).Environments(context.Background()) + if err != nil { + t.Fatal(err) + } + if h, _ := envs[0].Host("teak.kilo.alpha"); len(h.Warnings) != 0 || len(h.CPUModels) != 0 { + t.Errorf("teak warnings %q, CPU models %q", h.Warnings, h.CPUModels) + } +} + +// Registering an image without a guest agent is noted for a router or an +// "other" image once its VM has a disk or an agent option; a router's NICs +// may be on any bridge. +func TestImageRegisterAgentAndBridgeWarnings(t *testing.T) { + for _, tc := range []struct { + kind string + cfg map[string]string + want []string + }{ + {ImageOther, map[string]string{"agent": "0"}, []string{"box: guest agent off."}}, + {ImageOther, map[string]string{}, nil}, + {ImageOther, map[string]string{"scsi0": "competitions:160/vm-160-disk-0.qcow2"}, []string{"box: guest agent off."}}, + {ImageRouter, map[string]string{"net1": "virtio=BC:24:11:00:01:61,bridge=vmbr1", "agent": "1"}, nil}, + } { + f := imageFake() + tc.cfg["net0"] = "virtio=BC:24:11:00:01:60,bridge=vmbr0" + f.Add(proxmox.VM{VMID: 160, Name: "box", Node: "birch"}, tc.cfg) + plan, err := NewPlanner(f, envConfig()).ImageRegister(context.Background(), ImageRequest{VMID: 160, Family: "box", ImageKind: tc.kind}) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(plan.Notices, tc.want) { + t.Errorf("%s %v: notices %q, want %q", tc.kind, tc.cfg, plan.Notices, tc.want) + } + } +} + +// A deploy master in a slot wants a guest agent once it has a disk or an +// agent option; one outside the slots only with an agent option. +func TestDeployMasterAgentWarnings(t *testing.T) { + f := podstest.New("cedar") + disk := func(id int) string { return fmt.Sprintf("competitions:%d/vm-%d-disk-0.qcow2", id, id) } + f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "cedar", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devint01"}) + f.Add(proxmox.VM{VMID: 2102, Name: "oak.kilo.alpha", Node: "cedar", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:02,bridge=devint01", "scsi0": disk(2102)}) + f.Add(proxmox.VM{VMID: 500, Name: "elm.kilo.alpha", Node: "cedar", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=vmbr0", "scsi0": disk(500)}) + plan, err := NewPlanner(f, config.Default()).Deploy(context.Background(), DeployRequest{Pattern: "*.kilo.alpha", Teams: []string{"01"}}) + if err != nil { + t.Fatal(err) + } + if want := []string{"oak.kilo.alpha: guest agent off."}; !slices.Equal(plan.Notices, want) { + t.Errorf("Notices = %q, want %q", plan.Notices, want) + } +} diff --git a/internal/pods/envplan_test.go b/internal/pods/envplan_test.go index cbb5ad7..9a00147 100644 --- a/internal/pods/envplan_test.go +++ b/internal/pods/envplan_test.go @@ -2,6 +2,7 @@ package pods import ( "context" + "fmt" "reflect" "slices" "strings" @@ -53,7 +54,7 @@ func TestEnvCreatePlansSlotOne(t *testing.T) { } if teak.Guest == nil || AddrText(teak.Guest.IP) != "192.168.100.10" || AddrText(teak.Guest.Gateway) != "192.168.100.2" || AddrText(teak.Guest.DNS) != "192.168.100.2" || AddrText(teak.Notes.IP) != "192.168.100.10" || teak.Notes.OS != "linux" || teak.Notes.Base != "debian-12-v1" || teak.Notes.DNS != "router" || - teak.NICs["net0"] != "devint01" || !slices.Equal(teak.Steps, []Step{StepClone, StepLabel, StepNetwork, StepStart, StepWaitAgent, StepGuest, StepVerify}) { + teak.NICs["net0"] != "devint01" || teak.Tags != "dev;kilo.alpha" || !slices.Equal(teak.Steps, []Step{StepClone, StepLabel, StepNetwork, StepStart, StepWaitAgent, StepGuest, StepVerify}) { t.Errorf("teak = %+v guest %+v notes %+v", teak, teak.Guest, teak.Notes) } if oak.VMID%100 == teak.VMID%100 || oak.Node != "birch" || oak.Guest.OS != ImageWindows || oak.Guest.IP.As4()[3] == 10 { @@ -185,3 +186,177 @@ func TestEnvCreateWithoutALANBlocksGuests(t *testing.T) { } } } + +// With every slot held and none hidden or queued, a create is refused with +// just that. +func TestEnvCreateWhenEverySlotIsInUse(t *testing.T) { + f := envFake() + for n := 1; n <= 3; n++ { + f.Add(proxmox.VM{VMID: 2000 + n*100, Name: fmt.Sprintf("x.other%d.env", n), Node: "alder", Pool: fmt.Sprintf("dev-0%d", n)}, nil) + } + _, err := NewPlanner(f, envConfig()).EnvCreate(context.Background(), EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}}) + if err == nil || err.Error() != allSlotsInUse { + t.Errorf("err = %v, want %q", err, allSlotsInUse) + } +} + +// A host added to an environment whose DNS is one of its hosts points at +// that host. +func TestEnvAddUsesTheEnvironmentsDNSHost(t *testing.T) { + f := envFake() + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"description": "battleship: base=gw-v1 dns=teak"}) + f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=devint01", "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1 dns=teak"}) + hs, _ := ParseHostSpec("oak=debian-12") + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + if err != nil { + t.Fatal(err) + } + if oak := plan.Items[0]; oak.Blocked != "" || oak.Guest == nil || AddrText(oak.Guest.DNS) != "192.168.100.10" || oak.Notes.DNS != "teak" { + t.Errorf("oak = %+v guest %+v notes %+v", oak, oak.Guest, oak.Notes) + } +} + +// A host whose name a VM outside the pool already has is blocked; the +// hosts after it are still planned. +func TestEnvAddBlocksANameTakenOutsideThePool(t *testing.T) { + f := envFake() + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"description": "battleship: base=gw-v1 dns=router"}) + f.Add(proxmox.VM{VMID: 300, Name: "teak.kilo.alpha", Node: "alder"}, nil) + var hosts []HostSpec + for _, s := range []string{"teak=debian-12", "oak=debian-12"} { + hs, _ := ParseHostSpec(s) + hosts = append(hosts, hs) + } + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hosts}) + if err != nil { + t.Fatal(err) + } + teak, oak := plan.Items[0], plan.Items[1] + if teak.Blocked != "a VM named teak.kilo.alpha already exists outside dev-01" || len(teak.Steps) != 0 { + t.Errorf("teak = %+v", teak) + } + if oak.Blocked != "" || !slices.Contains(oak.Steps, StepClone) { + t.Errorf("oak = %+v", oak) + } +} + +// An ops CA key that doesn't parse blocks every guest-configured host, each +// of them; the router is still planned. +func TestEnvCreateWithABadOpsCAKey(t *testing.T) { + cfg := envConfig() + cfg.Environments.OpsCAKey = "not a key" + plan := create(t, NewPlanner(envFake(), cfg), "teak=debian-12", "oak=win2022") + if gw := plan.Items[0]; gw.Blocked != "" || len(gw.Steps) == 0 { + t.Errorf("router = %+v", gw) + } + for _, it := range plan.Items[1:] { + if !strings.HasPrefix(it.Blocked, "ops CA key: ") { + t.Errorf("%s = %+v", it.Name, it) + } + } +} + +// A base image without the NICs its kind needs blocks the host cloned from +// it, which then plans no steps; the hosts after it are still planned. +func TestEnvCreateBlocksAnImageShortOfNICs(t *testing.T) { + f := envFake() + f.VMs[8000].Config = map[string]string{"net0": "virtio=BC:24:11:00:80:00,bridge=vmbr0"} + f.VMs[8001].Config = map[string]string{"agent": "1"} + plan := create(t, NewPlanner(f, envConfig()), "teak=debian-12", "oak=win2022") + gw, teak, oak := plan.Items[0], plan.Items[1], plan.Items[2] + if gw.Blocked != "base image gw-v1 has one NIC; a router needs two (WAN on net0, LAN on net1)" || len(gw.Steps) != 0 { + t.Errorf("router = %+v", gw) + } + if teak.Blocked != "base image debian-12-v1 has no net0" || len(teak.Steps) != 0 || teak.Guest != nil { + t.Errorf("teak = %+v", teak) + } + if oak.Blocked != "" || !slices.Contains(oak.Steps, StepGuest) { + t.Errorf("oak = %+v", oak) + } +} + +// A slot whose VMIDs are all taken blocks each new host, which then plans +// no steps; a host already there is still resumed. +func TestEnvAddInAFullSlot(t *testing.T) { + f := envFake() + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"description": "battleship: base=gw-v1 dns=router"}) + for id := 2101; id <= 2199; id++ { + f.Add(proxmox.VM{VMID: id, Name: fmt.Sprintf("other%d", id), Node: "alder"}, nil) + } + var hosts []HostSpec + for _, s := range []string{"teak=debian-12", "oak=win2022"} { + hs, _ := ParseHostSpec(s) + hosts = append(hosts, hs) + } + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}, Hosts: hosts}) + if err != nil { + t.Fatal(err) + } + if gw := plan.Items[0]; gw.Blocked != "" || gw.VMID != 2100 { + t.Errorf("router = %+v", gw) + } + for _, it := range plan.Items[1:] { + if it.Blocked != "dev slot 01 has no free VMID in 2100-2199" || len(it.Steps) != 0 || it.Guest != nil { + t.Errorf("%s = %+v", it.Name, it) + } + } +} + +// With every host address taken, each new guest-configured host is +// blocked, every one of them. +func TestEnvAddWithNoAddressLeft(t *testing.T) { + f := envFake() + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"description": "battleship: base=gw-v1 dns=router"}) + for o := FirstHostOctet; o <= LastHostOctet; o++ { + f.Add(proxmox.VM{VMID: 30000 + o, Name: fmt.Sprintf("h%d.kilo.alpha", o), Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"description": fmt.Sprintf("battleship: ip=192.168.100.%d os=linux base=debian-12-v1 dns=router", o)}) + } + var hosts []HostSpec + for _, s := range []string{"teak=debian-12", "oak=win2022"} { + hs, _ := ParseHostSpec(s) + hosts = append(hosts, hs) + } + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hosts}) + if err != nil { + t.Fatal(err) + } + for _, it := range plan.Items { + if it.Blocked != "no free address left in kilo.alpha" { + t.Errorf("%s = %+v", it.Name, it) + } + } +} + +// A valid ops CA key reaches each guest as its type and key. +func TestEnvCreateWithAnOpsCAKey(t *testing.T) { + cfg := envConfig() + cfg.Environments.OpsCAKey = podstest.DefaultSSHCAKey + " ops@vault" + plan := create(t, NewPlanner(envFake(), cfg), "teak=debian-12", "oak=win2022") + for _, it := range plan.Items[1:] { + if it.Blocked != "" || it.Guest == nil || it.Guest.OpsCAKey != podstest.DefaultSSHCAKey { + t.Errorf("%s = %+v guest %+v", it.Name, it, it.Guest) + } + } +} + +// A resumed host whose notes record no address is given one. +func TestEnvAddResumesAHostWithoutAnAddress(t *testing.T) { + f := envFake() + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"description": "battleship: base=gw-v1 dns=router"}) + f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=devint01", "description": "battleship: os=linux base=debian-12-v1 dns=router"}) + hs, _ := ParseHostSpec("teak=debian-12") + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + if err != nil { + t.Fatal(err) + } + if it := plan.Items[0]; it.Blocked != "" || it.VMID != 2101 || it.Guest == nil || !it.Guest.IP.IsValid() || it.Notes.IP != it.Guest.IP { + t.Errorf("teak = %+v guest %+v", it, it.Guest) + } +} diff --git a/internal/pods/envspec_test.go b/internal/pods/envspec_test.go index 974847f..9e39d8b 100644 --- a/internal/pods/envspec_test.go +++ b/internal/pods/envspec_test.go @@ -31,12 +31,14 @@ func TestParseHostSpec(t *testing.T) { } func TestCheckDomain(t *testing.T) { - for _, ok := range []string{"kilo.alpha", "a.b.c", "x-1.y2"} { + // The longest domain allowed is 200 characters. + long := strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + "." + strings.Repeat("c", 63) + "." + strings.Repeat("d", 8) + for _, ok := range []string{"kilo.alpha", "a.b.c", "x-1.y2", long} { if err := CheckDomain(ok); err != nil { t.Errorf("CheckDomain(%q) = %v", ok, err) } } - for _, bad := range []string{"", "kilo", "Kilo.alpha", "kilo..alpha", ".kilo.alpha", "kilo.alpha.", "ki_lo.alpha"} { + for _, bad := range []string{"", "kilo", "Kilo.alpha", "kilo..alpha", ".kilo.alpha", "kilo.alpha.", "ki_lo.alpha", long + "d"} { if CheckDomain(bad) == nil { t.Errorf("CheckDomain(%q) accepted", bad) } @@ -89,6 +91,12 @@ func TestPickOctetIsStableAndAvoidsUsed(t *testing.T) { for o := FirstHostOctet; o <= LastHostOctet; o++ { used[o] = true } + // The last free octet is found, the subnet's last host included. + used[LastHostOctet] = false + if d, ok := PickOctet("kilo.alpha", "teak", used); !ok || d != LastHostOctet { + t.Errorf("PickOctet with only .%d free = %d, %v", LastHostOctet, d, ok) + } + used[LastHostOctet] = true if _, ok := PickOctet("kilo.alpha", "teak", used); ok { t.Error("PickOctet found an octet in a full subnet") } @@ -111,6 +119,10 @@ func TestUserNotes(t *testing.T) { if got := []rune(UserNotes(long)); len(got) != maxUserNotes+1 || got[maxUserNotes] != '…' { t.Errorf("long notes keep %d runes, want %d and an ellipsis", len(got), maxUserNotes+1) } + exact := strings.Repeat("é", maxUserNotes) + if got := UserNotes(exact); got != exact { + t.Errorf("notes of exactly %d runes keep %d runes", maxUserNotes, len([]rune(got))) + } } // UserNotes never keeps battleship's lines or format characters, stays within diff --git a/internal/pods/envteardown_test.go b/internal/pods/envteardown_test.go index ac888f7..74b7fbd 100644 --- a/internal/pods/envteardown_test.go +++ b/internal/pods/envteardown_test.go @@ -117,8 +117,8 @@ func TestEnvTeardownRefuses(t *testing.T) { // What a failed teardown leaves is planned again in its slot: a VM left // half-deleted (in its pool, or out of it) is listed blocked with how to -// finish it, and disks a gone VM left in the slot's VMIDs are freed. Disks -// at a VMID outside the slot are not its. +// finish it, and disks a gone VM left in the slot's VMIDs, its last one +// included, are freed. Disks at a VMID outside the slot are not its. func TestEnvTeardownPlansWhatAFailedOneLeft(t *testing.T) { f := teardownFake() for _, id := range []int{2100, 2101, 2102} { @@ -128,15 +128,16 @@ func TestEnvTeardownPlansWhatAFailedOneLeft(t *testing.T) { f.Add(proxmox.VM{VMID: 2103, Name: "VM 2103", Node: "birch", Pool: "dev-01"}, map[string]string{"lock": "destroyed"}) f.Add(proxmox.VM{VMID: 2104, Name: "VM 2104", Node: "alder"}, map[string]string{"lock": "destroyed"}) f.Vols["competitions:vm-2105-disk-0"] = 2105 + f.Vols["competitions:vm-2199-disk-0"] = 2199 f.Vols["competitions:vm-2405-disk-0"] = 2405 plan := envTeardown(t, f, EnvRequest{Domain: "kilo.alpha", Slot: 1}) - if got := itemNames(plan); !slices.Equal(got, []string{"disks-2105", "half-deleted-2103", "half-deleted-2104"}) { + if got := itemNames(plan); !slices.Equal(got, []string{"disks-2105", "disks-2199", "half-deleted-2103", "half-deleted-2104"}) { t.Fatalf("items = %q", got) } if it := plan.Items[0]; it.Blocked != "" || !slices.Equal(it.Steps, []Step{StepFreeDisks}) || it.VMID != 2105 { t.Errorf("disks = %+v", it) } - for _, it := range plan.Items[1:] { + for _, it := range plan.Items[2:] { if !strings.Contains(it.Blocked, "half-deleted") || !strings.Contains(it.Blocked, "qm destroy") { t.Errorf("%s = %+v", it.Name, it) } From 329f2bef6f101bb5f667eb5a2e10de6740e3830e Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:30:08 +0000 Subject: [PATCH 09/22] pods: test that a bad ops CA key still plans every host --- internal/pods/envplan_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/pods/envplan_test.go b/internal/pods/envplan_test.go index 9a00147..5456e03 100644 --- a/internal/pods/envplan_test.go +++ b/internal/pods/envplan_test.go @@ -249,6 +249,9 @@ func TestEnvCreateWithABadOpsCAKey(t *testing.T) { cfg := envConfig() cfg.Environments.OpsCAKey = "not a key" plan := create(t, NewPlanner(envFake(), cfg), "teak=debian-12", "oak=win2022") + if len(plan.Items) != 3 { + t.Fatalf("items = %+v", plan.Items) + } if gw := plan.Items[0]; gw.Blocked != "" || len(gw.Steps) == 0 { t.Errorf("router = %+v", gw) } From acb1cf723c208491de421efbbb60ac6ed3da6925 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:58:19 +0000 Subject: [PATCH 10/22] pods: delete Environments' unreachable template skip A template is read only when it is in a slot's pool, and the pool branch handles it first, so the skip could never run. --- internal/pods/environments.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/pods/environments.go b/internal/pods/environments.go index 272535d..ec7b189 100644 --- a/internal/pods/environments.go +++ b/internal/pods/environments.go @@ -303,9 +303,6 @@ func (p Planner) Environments(ctx context.Context) ([]Environment, []proxmox.VM, envs[si].Hosts = append(envs[si].Hosts, p.buildEnvHost(vm, cfg, envs[si].Slot, p.nodeCPUModels(ctx, cpuByNode, vm.Node))) continue } - if vm.Template { - continue - } for _, b := range nicBridgesAll(cfg) { if si, ok := bridgeSlot[b]; ok && !slices.Contains(envs[si].Users, vm.Name) { envs[si].Users = append(envs[si].Users, vm.Name) From 18943ae1dba69eb623424434a8072d4cf58378ab Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:19:08 +0000 Subject: [PATCH 11/22] pods: test guest prefix bounds, image listing, register and host-edit gaps --- internal/pods/candidates_test.go | 14 ++++++++++ internal/pods/envedit_test.go | 42 ++++++++++++++++++++++++++++ internal/pods/guest_test.go | 12 ++++++++ internal/pods/imageplan_test.go | 48 ++++++++++++++++++++++++++++++++ internal/pods/images_test.go | 45 ++++++++++++++++++++++++++++++ 5 files changed, 161 insertions(+) diff --git a/internal/pods/candidates_test.go b/internal/pods/candidates_test.go index 25d8269..83335bc 100644 --- a/internal/pods/candidates_test.go +++ b/internal/pods/candidates_test.go @@ -117,3 +117,17 @@ func TestPropBuiltTemplatesAreNotImages(t *testing.T) { } }) } + +// VMs that aren't candidates don't hide the ones listed after them. +func TestRegisterCandidatesPastSkippedVMs(t *testing.T) { + cfg := envConfig() + pool := cfg.Images.Pool + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 300, Name: "old-v1", Node: "alder", Pool: pool, Template: true}, nil) + f.Add(proxmox.VM{VMID: 301, Name: "teak-build", Node: "alder", Pool: pool, Status: "stopped"}, map[string]string{"agent": "1", "ostype": "l26"}) + vms, _ := f.ClusterVMs(context.Background()) + got := NewPlanner(f, cfg).RegisterCandidates(context.Background(), vms, nil) + if len(got) != 1 || got[0].VMID != 301 || got[0].Family != "teak" || got[0].Blocked != "" { + t.Errorf("RegisterCandidates = %+v, want 301", got) + } +} diff --git a/internal/pods/envedit_test.go b/internal/pods/envedit_test.go index 2a6ec14..4575b01 100644 --- a/internal/pods/envedit_test.go +++ b/internal/pods/envedit_test.go @@ -189,6 +189,33 @@ func TestHostEditInputCheck(t *testing.T) { } } +// A host's DNS note follows a rename only when it names the host itself. +func TestEnvEditRenameKeepsOtherDNS(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devext01", "net1": "virtio=BC:24:11:00:00:02,bridge=devint01", + "description": "battleship: base=gw-v1 dns=router"}) + f.Add(proxmox.VM{VMID: 2101, Name: "dc.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", + "description": "battleship: ip=192.168.100.10 os=windows base=win-v1 dns=dc"}) + f.Add(proxmox.VM{VMID: 2102, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:04,bridge=devint01", "agent": "1", + "description": "battleship: ip=192.168.100.11 os=linux base=debian-12-v1 dns=dc"}) + p := NewPlanner(f, envConfig()) + for _, c := range []struct { + vmid int + host, dns string + }{{2102, "oak", "dc"}, {2101, "ad", "ad"}} { + plan, err := p.EnvEdit(context.Background(), HostEditInput{VMID: c.vmid, Host: c.host}) + if err != nil { + t.Fatal(err) + } + if it := plan.Items[0]; it.Notes == nil || it.Notes.DNS != c.dns { + t.Errorf("rename %d to %s: notes = %+v, want dns=%s", c.vmid, c.host, it.Notes, c.dns) + } + } +} + func TestEnvEditItem(t *testing.T) { name16 := "abcdefghijklmnop" for _, tc := range []struct { @@ -409,3 +436,18 @@ func TestEnvEditStaleDetails(t *testing.T) { t.Errorf("stale details after a name clash blocked = %q", b) } } + +// Moving a lone host to another domain swaps its domain tag. +func TestEnvEditNewDomainDropsOldDomainTag(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;keep"}, + map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", + "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1"}) + plan, err := NewPlanner(f, envConfig()).EnvEdit(context.Background(), HostEditInput{VMID: 2101, Host: "teak.lima.bravo"}) + if err != nil { + t.Fatal(err) + } + if it := plan.Items[0]; it.Rename != "teak.lima.bravo" || it.Tags != "dev;lima.bravo;keep" { + t.Errorf("item = %+v, want tags dev;lima.bravo;keep", it) + } +} diff --git a/internal/pods/guest_test.go b/internal/pods/guest_test.go index d84776f..17cb528 100644 --- a/internal/pods/guest_test.go +++ b/internal/pods/guest_test.go @@ -308,3 +308,15 @@ func TestLinuxGuestScriptConfiguresSSHCA(t *testing.T) { } } } + +// Any prefix length from /1 to /32 is taken; 0 and 33 aren't. +func TestGuestPrefixBounds(t *testing.T) { + for prefix, ok := range map[int]bool{0: false, 1: true, 32: true, 33: false} { + g := testGuest + g.OS = ImageLinux + g.Prefix = prefix + if err := g.Check(); (err == nil) != ok { + t.Errorf("prefix %d: Check = %v", prefix, err) + } + } +} diff --git a/internal/pods/imageplan_test.go b/internal/pods/imageplan_test.go index 6025d52..c071adf 100644 --- a/internal/pods/imageplan_test.go +++ b/internal/pods/imageplan_test.go @@ -2,6 +2,7 @@ package pods import ( "context" + "errors" "maps" "slices" "strings" @@ -112,6 +113,7 @@ func TestSourceVMID(t *testing.T) { "battleship: source=0150": 0, "battleship: source=+150": 0, "battleship: source=99": 0, + "battleship: source=100": 100, "battleship: source=x": 0, "source=8920": 0, "": 0, @@ -156,3 +158,49 @@ func TestImageRegisterWarnings(t *testing.T) { t.Errorf("Notices = %v, want %v", plan.Notices, want) } } + +// The last VMID of the images range is handed out when it's the only free one. +func TestImageRegisterTakesTheRangesLastVMID(t *testing.T) { + cfg := envConfig() + cfg.Images.VMIDRange = "8000-8001" + plan, err := NewPlanner(imageFake(), cfg).ImageRegister(context.Background(), ImageRequest{VMID: 150, Family: "debian-12"}) + if err != nil || plan.Items[0].VMID != 8001 { + t.Fatalf("ImageRegister = %+v, %v; want VMID 8001", plan, err) + } +} + +// A source with nothing to warn about gives no notice. +func TestImageRegisterCleanSourceHasNoNotices(t *testing.T) { + f := imageFake() + f.Add(proxmox.VM{VMID: 152, Name: "clean-debian", Node: "birch", Status: "stopped"}, + map[string]string{"agent": "1", "net0": "virtio=BC:24:11:00:01:52,bridge=vmbr0"}) + plan, err := NewPlanner(f, envConfig()).ImageRegister(context.Background(), ImageRequest{VMID: 152, Family: "debian-12"}) + if err != nil || plan.Items[0].Blocked != "" { + t.Fatalf("ImageRegister = %+v, %v", plan, err) + } + if len(plan.Notices) != 0 { + t.Errorf("Notices = %q, want none", plan.Notices) + } +} + +// SourceDetails reads the VM's notes, and gives none when it can't. +func TestSourceDetails(t *testing.T) { + ctx := context.Background() + f := imageFake() + f.VMs[150].Config["description"] = "**Details**\n- OS: Debian 12" + p := NewPlanner(f, envConfig()) + if d := p.SourceDetails(ctx, 150); d != (ImageDetails{OS: "Debian 12"}) { + t.Errorf("SourceDetails = %+v, want OS Debian 12", d) + } + if d := p.SourceDetails(ctx, 999); !d.Empty() { + t.Errorf("missing VM: %+v", d) + } + f.FailOn("config:150", errors.New("no access")) + if d := p.SourceDetails(ctx, 150); !d.Empty() { + t.Errorf("unreadable config: %+v", d) + } + f.FailOn("cluster", errors.New("down")) + if d := p.SourceDetails(ctx, 150); !d.Empty() { + t.Errorf("no cluster list: %+v", d) + } +} diff --git a/internal/pods/images_test.go b/internal/pods/images_test.go index 2fb2ac1..c3b9320 100644 --- a/internal/pods/images_test.go +++ b/internal/pods/images_test.go @@ -2,6 +2,7 @@ package pods import ( "context" + "errors" "strconv" "strings" "testing" @@ -189,3 +190,47 @@ func TestPropImageRegisterPlansAParsableName(t *testing.T) { checkRegister(t, fam, versions, deprecated) }) } + +// Families lists each family once, at its newest usable version. +func TestFamiliesListsEachNewestVersion(t *testing.T) { + images := BaseImages([]proxmox.VM{ + {VMID: 8001, Name: "debian-12-v1", Node: "alder", Template: true, Tags: "base;linux"}, + {VMID: 8002, Name: "debian-12-v2", Node: "alder", Template: true, Tags: "base;linux"}, + {VMID: 8003, Name: "gw-v1", Node: "alder", Template: true, Tags: "base;router"}, + }) + fs := Families(images, "") + if len(fs) != 2 || fs[0].Name != "debian-12-v2" || fs[1].Name != "gw-v1" { + t.Errorf("Families = %+v, want debian-12-v2 and gw-v1", fs) + } +} + +// ReadNotes fills in each image's details, notes and source; an unreadable +// details block is flagged, and an image whose config can't be read keeps none. +func TestReadNotes(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 8001, Name: "debian-12-v1", Node: "alder", Template: true, Tags: "base;linux"}, + map[string]string{"description": "**Details**\n- OS: Debian 12\n\nHello.\n\nbattleship: source=150"}) + f.Add(proxmox.VM{VMID: 8002, Name: "win-v1", Node: "alder", Template: true, Tags: "base;windows"}, + map[string]string{"description": "**Details**\n- Colour: blue"}) + f.Add(proxmox.VM{VMID: 8003, Name: "gw-v1", Node: "alder", Template: true, Tags: "base;router"}, + map[string]string{"description": "**Details**\n- OS: pfSense\n\nbattleship: source=160"}) + f.FailOn("config:8003", errors.New("no access")) + vms, _ := f.ClusterVMs(context.Background()) + got := NewPlanner(f, envConfig()).ReadNotes(context.Background(), BaseImages(vms)) + if len(got) != 3 { + t.Fatalf("ReadNotes = %+v", got) + } + byName := map[string]BaseImage{} + for _, im := range got { + byName[im.Name] = im + } + if im := byName["debian-12-v1"]; im.Details.OS != "Debian 12" || im.Notes != "Hello." || im.Source != 150 || im.Unreadable { + t.Errorf("debian-12-v1 = %+v", im) + } + if im := byName["win-v1"]; !im.Unreadable || !im.Details.Empty() { + t.Errorf("win-v1 = %+v, want unreadable", im) + } + if im := byName["gw-v1"]; !im.Details.Empty() || im.Notes != "" || im.Source != 0 || im.Unreadable { + t.Errorf("gw-v1 = %+v, want nothing read", im) + } +} From 660c73036385e87a9d69355616484061761fe402 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:02:29 +0000 Subject: [PATCH 12/22] web: test confirm refusals, submit summaries and cancels of jobs with no VMs Kills surviving mutants in confirm.go and jobpages.go: a confirm at another environment's Add hosts path is refused, a wrong typed confirm says what was typed, the submit flash names one pod or several, and a job with no VMs is cancelled only by whoever started it. --- internal/web/environments_test.go | 20 ++++++++++++++++++++ internal/web/jobpages_test.go | 29 +++++++++++++++++++++++++++++ internal/web/ops_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) diff --git a/internal/web/environments_test.go b/internal/web/environments_test.go index 3232688..ee50d06 100644 --- a/internal/web/environments_test.go +++ b/internal/web/environments_test.go @@ -199,6 +199,26 @@ func TestEnvironmentRoutes(t *testing.T) { } } +// A confirm at another environment's Add hosts path is refused: the preview +// was of adding hosts to kilo.alpha, not oscar.lima. +func TestEnvAddConfirmAtAnotherEnvironment(t *testing.T) { + h := newHarness(t) + h.poll() + addImages(h) + addEnvs(h) + sess := h.login(asLead) + action, form, _ := h.preview(&sess, "/environments/kilo.alpha/add", url.Values{"env_hosts": {"oak=debian-12"}}) + rec := h.post(&sess, "/environments/oscar.lima/add/confirm", form) + if rec.Code != http.StatusBadRequest { + t.Fatalf("kilo.alpha's preview confirmed at oscar.lima = %d, want 400", rec.Code) + } + contains(t, "confirm at another environment", rec.Body.String(), "Confirm refused") + h.noJobs("after a confirm at another environment") + if rec := h.post(&sess, action, form); rec.Code != http.StatusSeeOther { + t.Errorf("confirm at its own environment = %d, want 303", rec.Code) + } +} + // The old addresses, with the environment in a domain field, lead to its // path, keeping the rest of the query, or of a posted body; without a // domain, back to Environments. diff --git a/internal/web/jobpages_test.go b/internal/web/jobpages_test.go index 6b79572..bede271 100644 --- a/internal/web/jobpages_test.go +++ b/internal/web/jobpages_test.go @@ -1128,3 +1128,32 @@ func TestCancelRefusedWhenPrivilegesCantBeRead(t *testing.T) { t.Errorf("after lead's cancel: %+v", j) } } + +// A job with no VMs leaves no privilege to hold on them: only whoever +// started it may cancel it, not a lead who holds every privilege. +func TestCancelOfAJobWithNoVMs(t *testing.T) { + h := newHarness(t) + h.poll() + id, err := h.st.CreateJob(context.Background(), store.NewJob{ + Kind: string(pods.KindPower), Inputs: json.RawMessage(`{"kind":"power","teams":"1","action":"start"}`), + Plan: json.RawMessage(`{"kind":"power"}`), Fingerprint: "fp", LockKeys: []string{"team:01"}, + CreatedBy: "test-operator@example.org", + }) + if err != nil { + t.Fatal(err) + } + lead := h.login(asLead) + if rec := h.post(&lead, "/logs/"+itoa(id)+"/cancel", url.Values{}); rec.Code != http.StatusForbidden { + t.Errorf("lead's cancel of another's job with no VMs = %d, want 403", rec.Code) + } + if j, _ := h.st.Job(context.Background(), id); j.CancelRequested { + t.Fatalf("cancelled by someone who didn't start it: %+v", j) + } + op := h.login(asOperator) + if rec := h.post(&op, "/logs/"+itoa(id)+"/cancel", url.Values{}); rec.Code != http.StatusSeeOther { + t.Errorf("starter's cancel = %d, want 303", rec.Code) + } + if j, _ := h.st.Job(context.Background(), id); j.Status != store.StatusCancelled { + t.Errorf("job after its starter's cancel = %s, want cancelled", j.Status) + } +} diff --git a/internal/web/ops_test.go b/internal/web/ops_test.go index a90777b..c23a973 100644 --- a/internal/web/ops_test.go +++ b/internal/web/ops_test.go @@ -727,6 +727,12 @@ func TestTypedConfirmation(t *testing.T) { t.Errorf("typed %q: confirm = %d, want 422", wrong, rec.Code) } contains(t, "wrongly typed", rec.Body.String(), "Type the pod range to confirm", "exactly as shown: "+tc.typed) + // Nothing typed asks for it; something wrong says what was typed. + said := "To confirm, type the pod range exactly as shown: " + tc.typed + "." + if wrong != "" { + said = "You typed "" + wrong + "", which isn't the pod range." + } + contains(t, "wrongly typed", rec.Body.String(), said) // The page can be confirmed again: same preview. if _, again := confirmOf(t, rec.Body.String()); again.Get("nonce") != form.Get("nonce") { t.Errorf("typed %q: the page has another preview", wrong) @@ -746,6 +752,27 @@ func TestTypedConfirmation(t *testing.T) { } } +// The flash after a confirm says what was submitted, naming one pod or +// several. +func TestSubmitFlashNamesThePods(t *testing.T) { + h := newHarness(t) + h.poll() + op := h.login(asOperator) + for _, tc := range []struct{ teams, want string }{ + {"1", "force stop on pod 01 (2 VMs)."}, + {"1-2", "force stop on pods 01, 02 (4 VMs)."}, + } { + action, form, _ := h.preview(&op, "/power", url.Values{"teams": {tc.teams}, "action": {"stop"}}) + rec := h.post(&op, action, form) + if rec.Code != http.StatusSeeOther { + t.Fatalf("teams %s: confirm = %d\n%s", tc.teams, rec.Code, rec.Body) + } + if f := flashOf(rec); !strings.Contains(f, " submitted: "+tc.want) { + t.Errorf("teams %s: flash = %q, want it to say %q", tc.teams, f, tc.want) + } + } +} + func TestOperationPostsNeedCSRF(t *testing.T) { h := newHarness(t) h.poll() From 4ab7edbcf1744e344f8bf0128ac639bc451cb06c Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:49:40 +0000 Subject: [PATCH 13/22] pods: test live address reads and SSH check parsing --- internal/pods/liveaddr_test.go | 192 +++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) diff --git a/internal/pods/liveaddr_test.go b/internal/pods/liveaddr_test.go index 90704c5..cb2155d 100644 --- a/internal/pods/liveaddr_test.go +++ b/internal/pods/liveaddr_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/netip" + "slices" "strconv" "strings" "sync" @@ -542,6 +543,66 @@ func TestCheckSSHOutput(t *testing.T) { "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ncert-authority,principals=\"other-team\" " + ca + "\n", ca, "missing ops CA principal", }, + { + "comment before root login disabled", + "sshd=running\n===SSHD===\n# sshd_config\npermitrootlogin no\n", + ca, "SSH root login off", + }, + { + "TrustedUserCAKeys none", + "sshd=running\n===SSHD===\ntrustedusercakeys none\nauthorizedprincipalsfile none\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\n", + ca, "missing ops CA key", + }, + { + "CA key in TrustedUserCAKeys with AuthorizedPrincipalsFile none", + "sshd=running\n===SSHD===\ntrustedusercakeys /etc/ssh/vault-ca.pub\nauthorizedprincipalsfile none\n===CA===\n" + ca + "\n===PRINCIPALS===\ncore-infrastructure\n===AUTHKEYS===\n", + ca, "missing ops CA principal", + }, + { + "comment before the CA key", + "sshd=running\n===SSHD===\ntrustedusercakeys /etc/ssh/vault-ca.pub\nauthorizedprincipalsfile /etc/ssh/auth_principals/%u\n===CA===\n# vault\n" + ca + "\n===PRINCIPALS===\ncore-infrastructure\n===AUTHKEYS===\n", + ca, "", + }, + { + "authorized_keys line of one word", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ngarbage\n", + ca, "missing ops CA key", + }, + { + "commented-out cert-authority", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\n#cert-authority " + ca + "\n", + ca, "missing ops CA key", + }, + { + "comment before cert-authority", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\n# ops CA\ncert-authority " + ca + "\n", + ca, "", + }, + { + "user key before cert-authority", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\n" + otherKey + " admin\ncert-authority " + ca + "\n", + ca, "", + }, + { + "cert-authority with another key when ops_ca_key is configured", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ncert-authority " + otherKey + "\n", + ca, "missing ops CA key", + }, + { + "cert-authority with any key when ops_ca_key is empty", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ncert-authority " + otherKey + "\n", + "", "", + }, + { + "another cert-authority before the ops one", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ncert-authority " + otherKey + "\ncert-authority " + ca + "\n", + ca, "", + }, + { + "cert-authority with unreadable principals before one with ops principal", + "sshd=running\n===SSHD===\n===CA===\n===PRINCIPALS===\n===AUTHKEYS===\ncert-authority,command=\"principals=\" " + ca + "\ncert-authority,principals=\"core-infrastructure\" " + ca + "\n", + ca, "", + }, } { if got := CheckSSHOutput(c.out, c.key); got != c.want { t.Errorf("%s: CheckSSHOutput = %q, want %q", c.name, got, c.want) @@ -582,3 +643,134 @@ func TestLiveAddrsSSHWarnings(t *testing.T) { } } } + +// sshAgent is a fake whose SSH checks exit with exitCode; it keeps the +// command each VM's check ran. +type sshAgent struct { + *podstest.Fake + exitCode int + mu sync.Mutex + cmds map[int][]string +} + +func (a *sshAgent) AgentRead(ctx context.Context, node string, vmid int, command []string) (int, error) { + a.mu.Lock() + if a.cmds == nil { + a.cmds = map[int][]string{} + } + a.cmds[vmid] = command + a.mu.Unlock() + return a.Fake.AgentRead(ctx, node, vmid, command) +} + +func (a *sshAgent) AgentExecStatus(ctx context.Context, node string, vmid, pid int, limit int64) (proxmox.ExecStatus, error) { + st, err := a.Fake.AgentExecStatus(ctx, node, vmid, pid, limit) + if st.Exited { + st.ExitCode = a.exitCode + } + return st, err +} + +// The SSH check runs the Windows command on a host whose notes say Windows +// or whose agent reports Windows' loopback interface, and the POSIX one on +// the rest. +func TestLiveAddrsSSHCheckCommand(t *testing.T) { + f := podstest.New("alder") + for vmid, nic := range map[int]string{2110: "eth0", 2111: "Ethernet", 2112: "Loopback Pseudo-Interface 1"} { + f.Add(proxmox.VM{VMID: vmid, Name: fmt.Sprint(vmid), Node: "alder", Status: "running"}, nil) + f.SetGuest(vmid, podstest.Guest{Up: true, NICs: []proxmox.GuestNIC{{Name: nic, MAC: lanMAC, IPs: podstest.IPs("192.168.100.10/24")}}}) + } + host := func(vmid int, os string) EnvHost { + return EnvHost{VMID: vmid, Node: "alder", Status: "running", Agent: true, LANMAC: lanMAC, Notes: Notes{OS: os}} + } + a := &sshAgent{Fake: f} + NewPlanner(a, envConfig()).LiveAddrs(context.Background(), + []Environment{{Hosts: []EnvHost{host(2110, ImageLinux), host(2111, ImageWindows), host(2112, "")}}}, 3, time.Second) + for vmid, windows := range map[int]bool{2110: false, 2111: true, 2112: true} { + if !slices.Equal(a.cmds[vmid], SSHCheckCommand(windows)) { + t.Errorf("%d: SSH check %q, want the windows=%v one", vmid, a.cmds[vmid], windows) + } + } +} + +// A check that exits non-zero with output, as the Windows one does when an +// authorized_keys file is missing, is still read; and one still running at +// the first poll is read once it exits. +func TestLiveAddrsSSHCheckExit(t *testing.T) { + f := podstest.New("alder") + f.Add(proxmox.VM{VMID: 2110, Name: "2110", Node: "alder", Status: "running"}, nil) + f.SetGuest(2110, podstest.Guest{Up: true, NICs: []proxmox.GuestNIC{{MAC: lanMAC, IPs: podstest.IPs("192.168.100.10/24")}}, + SSHOut: "sshd=stopped\n===SSHD===\n"}) + envs := []Environment{{Hosts: []EnvHost{{VMID: 2110, Node: "alder", Status: "running", Agent: true, LANMAC: lanMAC}}}} + got := NewPlanner(&sshAgent{Fake: f, exitCode: 1}, envConfig()).LiveAddrs(context.Background(), envs, 1, time.Second) + if got[2110].SSHWarning != "SSH not running" { + t.Errorf("exit 1: SSHWarning = %q, want %q", got[2110].SSHWarning, "SSH not running") + } + f.ExecRunsFor = func(int) int { return 1 } + got = NewPlanner(f, envConfig()).LiveAddrs(context.Background(), envs, 1, time.Second) + if got[2110].SSHWarning != "SSH not running" { + t.Errorf("polled twice: SSHWarning = %q, want %q", got[2110].SSHWarning, "SSH not running") + } +} + +// HostLiveAddrs reads h's agent and, for a host on the router's LAN, the +// router's, for its external address; it asks an agent exactly when +// HostAsksAgent says it will, and reads each agent once. +func TestHostLiveAddrs(t *testing.T) { + f := podstest.New("alder") + addVM := func(vmid int, nics ...proxmox.GuestNIC) { + f.Add(proxmox.VM{VMID: vmid, Name: fmt.Sprint(vmid), Node: "alder", Status: "running"}, nil) + f.SetGuest(vmid, podstest.Guest{Up: true, NICs: nics, SSHOut: "sshd=stopped\n===SSHD===\n"}) + } + routerNICs := []proxmox.GuestNIC{{MAC: lanMAC, IPs: podstest.IPs("192.168.100.2/24")}, {MAC: wanMAC, IPs: podstest.IPs("10.50.12.133/24")}} + addVM(2100, routerNICs...) + addVM(2190, routerNICs...) + addVM(2110, proxmox.GuestNIC{MAC: "bc:24:11:00:00:10", IPs: podstest.IPs("192.168.100.30/24")}) + running := func(h EnvHost) EnvHost { h.Node, h.Status, h.Agent = "alder", "running", true; return h } + stopped := func(h EnvHost) EnvHost { h.Node, h.Status, h.Agent = "alder", "stopped", true; return h } + gw := running(EnvHost{VMID: 2100, Router: true, WANMAC: wanMAC, LANMAC: lanMAC}) + gw2 := running(EnvHost{VMID: 2190, Router: true, WANMAC: wanMAC, LANMAC: lanMAC}) + live := running(EnvHost{VMID: 2110, LANMAC: "bc:24:11:00:00:10"}) // no assigned address + assigned := stopped(EnvHost{VMID: 2111, LANMAC: "bc:24:11:00:00:11", Addr: parsedIP("192.168.100.11")}) + unassigned := stopped(EnvHost{VMID: 2112, LANMAC: "bc:24:11:00:00:12"}) + env := func(hosts ...EnvHost) Environment { + return Environment{Slot: Slots(envConfig().Environments)[0], LAN: kiloLAN, Hosts: hosts} + } + for _, c := range []struct { + name string + env Environment + h EnvHost + want LiveAddrs + reads []string + }{ + {"live host without an address", env(gw, live), live, + LiveAddrs{Live: true, LAN: "192.168.100.30", External: "10.50.12.30", SSHWarning: "SSH not running"}, []string{"agent-nics:2100", "agent-nics:2110"}}, + {"stopped host with an address", env(gw, assigned), assigned, + LiveAddrs{External: "10.50.12.11"}, []string{"agent-nics:2100"}}, + {"stopped host without an address", env(gw, unassigned), unassigned, LiveAddrs{}, nil}, + {"router", env(gw, live), gw, + LiveAddrs{Live: true, LAN: "192.168.100.2", WAN: "10.50.12.133", SSHWarning: "SSH not running"}, []string{"agent-nics:2100"}}, + {"first router stopped", env(stopped(gw), gw2, assigned), assigned, LiveAddrs{}, nil}, + } { + f.Mu.Lock() + f.Calls = nil + f.Mu.Unlock() + got := NewPlanner(f, envConfig()).HostLiveAddrs(context.Background(), c.env, c.h, time.Second) + if got != c.want { + t.Errorf("%s: %+v, want %+v", c.name, got, c.want) + } + var reads []string + for _, k := range f.Calls { + if strings.HasPrefix(k, "agent-nics:") { + reads = append(reads, k) + } + } + slices.Sort(reads) + if !slices.Equal(reads, c.reads) { + t.Errorf("%s: read %q, want %q", c.name, reads, c.reads) + } + if asks := HostAsksAgent(c.env, c.h); asks != (len(reads) > 0) { + t.Errorf("%s: HostAsksAgent = %v, but read %q", c.name, asks, reads) + } + } +} From 4974d10e77942f74f99247537cd40589f77bf8bc Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:55:04 +0000 Subject: [PATCH 14/22] web: test review folding, env edit/power/delete reviews, router rows and disk-only teardowns --- internal/web/envhost_test.go | 100 ++++++++++++++++++++++++++++++ internal/web/envteardown_test.go | 25 ++++++++ internal/web/opreview_test.go | 84 +++++++++++++++++++++++-- internal/web/teardownform_test.go | 24 +++++++ 4 files changed, 228 insertions(+), 5 deletions(-) diff --git a/internal/web/envhost_test.go b/internal/web/envhost_test.go index 56c0828..a1de9e7 100644 --- a/internal/web/envhost_test.go +++ b/internal/web/envhost_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/wccomps/battleship/internal/pods" + "github.com/wccomps/battleship/internal/proxmox" "github.com/wccomps/battleship/internal/status" ) @@ -179,6 +180,105 @@ func TestEnvHostPowerAndDelete(t *testing.T) { } } +// The Edit host review lists what changes, and its sentence says what +// confirming does: configure the guest, only eject the CD-ROM, only set the +// CPU, or update the host; a blocked edit says why. +func TestEnvEditReview(t *testing.T) { + h := newHarness(t) + addCatalog(h) + addEnvs(h) + h.api.CPUModels = []string{"lab-baseline", "lab-baseline-nested"} + h.api.VMs[2101].Config["agent"] = "1" + h.api.VMs[2101].Config["ide0"] = "local:iso/debian.iso,media=cdrom" + h.api.VMs[2102].Config["ide0"] = "local:iso/debian.iso,media=cdrom" + h.api.VMs[2103].Config["net0"] = "virtio=BC:24:11:00:21:00,bridge=vmbr0" // off dev-01's bridges + sess := h.login(asLead) + review := func(form url.Values) string { + _, _, body := h.preview(&sess, "/environments/edit", form) + return body + } + elm := func(kv ...string) url.Values { + f := url.Values{"vmid": {"2102"}, "env_host": {"elm"}, "image_kind": {"other"}, "image": {"win10-v1"}} + for i := 0; i+1 < len(kv); i += 2 { + f.Set(kv[i], kv[i+1]) + } + return f + } + + body := review(url.Values{"vmid": {"2101"}, "env_host": {"oak"}, "image_kind": {"linux"}, "octet": {"25"}, "image": {"debian-12-v1"}, + "cpu": {"lab-baseline"}, "eject_cdrom": {"yes"}, "details": {"with-notes"}, "detail_os": {"Debian 12"}, "notes": {"updated notes"}}) + contains(t, "teak renamed and readdressed", body, + `Updates teak.kilo.alpha in dev-01 and configures its hostname and address through the guest agent.`, + `
Rename
teak.kilo.alpha -> oak.kilo.alpha · VMID 2101 · n1
`, + `
Kind
linux
`, `
Address
.25
`, `
Base image
debian-12-v1
`, + `
CD-ROM
ejects attached install media
`, `
CPU
lab-baseline
`, + `
Guest agent
sets hostname oak and address 192.168.100.25 inside the guest
`, + `OS changed—Debian 12`, + `
Before
debian / Changeme1!
`, + `
After
updated notes
`) + lacks(t, "teak renamed and readdressed", body, "
Host
", "
Network
") + + body = review(elm("eject_cdrom", "yes")) + contains(t, "elm's CD-ROM ejected", body, + `Ejects the attached CD-ROM from elm.kilo.alpha.`, + `
Host
elm.kilo.alpha · VMID 2102 · n1
`, `
CD-ROM
ejects attached install media
`) + lacks(t, "elm's CD-ROM ejected", body, "
Kind
", "
Address
", "
Guest agent
") + + body = review(elm("cpu", "lab-baseline")) + contains(t, "elm's CPU set", body, + `Sets the CPU of elm.kilo.alpha to lab-baseline.`, + `
CPU
lab-baseline
`) + + body = review(elm("octet", "30")) + contains(t, "elm given an address", body, + `Updates elm.kilo.alpha in dev-01.`, + `
Kind
other
`, `
Address
.30
`, `
Base image
win10-v1
`) + + body = review(elm("env_host", "ash")) + contains(t, "elm renamed", body, `
Rename
elm.kilo.alpha -> ash.kilo.alpha · VMID 2102 · n1
`, + `
Address
none
`) + + body = review(url.Values{"vmid": {"2100"}, "env_host": {"gw2"}, "image_kind": {"router"}, "image": {"gw-v1"}}) + contains(t, "the router renamed", body, `
Kind
router
`, `
Address
.2
`) + + body = review(url.Values{"vmid": {"2103"}, "env_host": {"yew"}, "image_kind": {"linux"}, "octet": {"5"}, "image": {"debian-12-v1"}}) + contains(t, "yew off its bridges", body, `
Network
moves NICs onto dev-01's bridges
`, + `Updates yew.kilo.alpha in dev-01.`) + + // Renamed onto a name in use: why, and nothing to confirm. + body = h.post(&sess, "/environments/edit/preview", url.Values{"vmid": {"2101"}, "env_host": {"elm"}, "image_kind": {"linux"}, "octet": {"10"}, "image": {"debian-12-v2"}}).Body.String() + contains(t, "teak renamed onto elm", body, `

`, `A VM named elm.kilo.alpha already exists.`) + lacks(t, "teak renamed onto elm", body, "/confirm", "Updates") +} + +// A host's power and delete reviews say what happens, red when it cuts the +// power or deletes; a template in the slot can't be either, and says so. +func TestEnvHostPowerAndDeleteReviews(t *testing.T) { + h := newHarness(t) + addEnvs(h) + h.api.add(proxmox.VM{VMID: 2150, Name: "base.kilo.alpha", Node: "n1", Pool: "dev-01", Template: true}, nil) + sess := h.login(asLead) + + _, _, body := h.preview(&sess, "/environments/power", url.Values{"vmid": {"2101"}, "action": {"reboot"}}) + contains(t, "reboot", body, `

Review · Reboot teak.kilo.alpha

`, + `

1 VM will be asked to restart by its operating system.") + lacks(t, "reboot", body, `

`) + _, _, body = h.preview(&sess, "/environments/power", url.Values{"vmid": {"2101"}, "action": {"stop"}}) + contains(t, "force stop", body, `

`, "1 VM loses power at once. Unsaved work is lost.") + + _, _, body = h.preview(&sess, "/environments/delete", url.Values{"vmid": {"2101"}, "env_host": {"teak.kilo.alpha"}}) + contains(t, "delete", body, `

`, + `Stops and deletes teak.kilo.alpha in dev-01 with its disks. The other VMs in dev-01 stay as they are. This can't be undone.`) + + body = h.post(&sess, "/environments/power/preview", url.Values{"vmid": {"2150"}, "action": {"start"}}).Body.String() + contains(t, "a template started", body, `

`, "Is a template.") + lacks(t, "a template started", body, "/confirm") + body = h.post(&sess, "/environments/delete/preview", url.Values{"vmid": {"2150"}, "env_host": {"base.kilo.alpha"}}).Body.String() + contains(t, "a template deleted", body, `

`, + `Is a template, not an environment host; move it out of dev-01 first.`) + lacks(t, "a template deleted", body, "/confirm", "Stops and deletes") +} + func TestBrowserEnvHostPanel(t *testing.T) { h := browserHarness(t) addCatalog(h) diff --git a/internal/web/envteardown_test.go b/internal/web/envteardown_test.go index 4df8eb0..5a986a7 100644 --- a/internal/web/envteardown_test.go +++ b/internal/web/envteardown_test.go @@ -243,6 +243,31 @@ func TestEnvTeardownRetry(t *testing.T) { } } +// A retry that finds only the disks a delete left frees them, and says +// nothing of deleting VMs. +func TestEnvTeardownRetryReviewOfOnlyDisks(t *testing.T) { + h := newHarness(t) + addEnvs(h) + sess := h.login(asLead) + id := h.submitJob(jobs.Inputs{Kind: pods.KindEnvTeardown, Domain: "kilo.alpha"}, byLead) + h.start(id) + h.api.remove("gw.kilo.alpha", "teak.kilo.alpha", "elm.kilo.alpha", "yew.kilo.alpha") + h.api.Mu.Lock() + h.api.Vols["competitions:vm-2100-disk-0"] = 2100 // gw's delete left a disk + h.api.Mu.Unlock() + h.finish(id, store.Outcome{Status: store.StatusCompletedWithFailures, Items: map[string]store.ItemOutcome{ + "gw.kilo.alpha": {Status: store.ItemFailed, Error: "delete: refused"}, + }}) + rec := h.post(&sess, "/logs/"+itoa(id)+"/retry", url.Values{}) + if rec.Code != http.StatusOK { + t.Fatalf("retry = %d\n%s", rec.Code, rec.Body) + } + body := rec.Body.String() + contains(t, "the retry", body, `Frees the disks deleted VMs left at VMID 2100. The slot is free again afterwards.`, + `disks-2100`, "Tear down kilo.alpha") + lacks(t, "the retry", body, "Deletes 0 VMs") +} + // Tear down environment is in the header, red; each environment block // collapses and expands as an accordion; the teardown form and review fit // a phone and a laptop, light and dark, with its blocked row striped and diff --git a/internal/web/opreview_test.go b/internal/web/opreview_test.go index e67783f..30e14a3 100644 --- a/internal/web/opreview_test.go +++ b/internal/web/opreview_test.go @@ -108,16 +108,19 @@ func TestImageReviews(t *testing.T) { }{ {"/images/deprecate", url.Values{"image": {"debian-12-v2"}}, []string{ `Review · Deprecate debian-12-v2`, + `

debian-12-v2 will no longer be offered for new hosts. Hosts made from it keep working.`, `Back`, `"}}, {"/images/delete", url.Values{"image": {"debian-12-v1"}}, []string{ `Review · Delete debian-12-v1`, + `

Back`, `"}}, {"/images/edit", url.Values{"family": {"gw"}}, []string{ `Review · Edit gw`, + `

Copies gw-v1 as gw-edit on the edit network, for you to patch and register as the next version.`, `Back`, "Copy as gw-edit"}}, @@ -128,17 +131,88 @@ func TestImageReviews(t *testing.T) { } // Blocked: the reason in the summary, and nothing to confirm. - for path, form := range map[string]url.Values{ - "/images/deprecate": {"image": {"debian-12-v1"}}, - "/images/edit": {"family": {"debian-12"}}, + for path, c := range map[string]struct { + form url.Values + why string + }{ + "/images/deprecate": {url.Values{"image": {"debian-12-v1"}}, "Is already deprecated."}, + "/images/edit": {url.Values{"family": {"debian-12"}}, "already exists: register it as the next version, or delete it in Proxmox, first."}, } { - rec := h.post(&sess, path+"/preview", form) + rec := h.post(&sess, path+"/preview", c.form) body := rec.Body.String() - contains(t, path+" blocked", body, `

`) + contains(t, path+" blocked", body, `

`, c.why) lacks(t, path+" blocked", body, "/confirm", `class="btn pri`, "

VMs

` + body := add(oaks(9)) + contains(t, "nine VMs", body, fold+`· 9 VMs`, `oak9.kilo.alpha`, "Add 9 hosts") + body = add(oaks(8)) + contains(t, "eight VMs", body, `oak8.kilo.alpha`, "Add 8 hosts") + lacks(t, "eight VMs", body, fold) + body = add(append(oaks(8), "elm=debian-12:10")) + contains(t, "nine VMs, one blocked", body, `elm.kilo.alpha`, "Add 8 hosts") + lacks(t, "nine VMs, one blocked", body, fold) +} + +// An Add or Create review marks the router, whether its image or the +// request's router line makes it one, and gives it .2; a blocked host +// leaves the rows and sentence of the hosts after it; without a Windows +// or Linux host, nothing is said of the guest agent. +func TestEnvReviewRoutersBlockedHostsAndGuests(t *testing.T) { + h := newHarness(t) + addImages(h) + addEnv(h, true) // teak at .10 + sess := h.login(asLead) + _, _, body := h.preview(&sess, "/environments/kilo.alpha/add", url.Values{"env_hosts": {"elm=debian-12:10\noak=debian-12:11"}}) + contains(t, "a blocked host first", body, + `Clones oak into dev-01 and starts it. Then oak gets its name, address, gateway .2 and DNS (.10) through the guest agent.`, + `elm.kilo.alpha`, + `oak.kilo.alphadebian-12-v1.112102 · n1`, + "Add 1 host") + + // A second router, by its image: blocked, and still the router at .2. + body = h.post(&sess, "/environments/kilo.alpha/add/preview", url.Values{"env_hosts": {"gw2=gw"}}).Body.String() + contains(t, "a second router", body, + `gw2.kilo.alpha routergw-v1.2`, + "an environment has one router") + + h = newHarness(t) + addFormImages(h) + addDNSEnv(h, "router") + sess = h.login(asLead) + _, _, body = h.preview(&sess, "/environments/kilo.alpha/add", url.Values{"env_hosts": {"app=appliance"}}) + contains(t, "an other-kind host", body, `Clones app into dev-01 and starts it.`, + `app.kilo.alphaappliance-v2—`) + lacks(t, "an other-kind host", body, "guest agent") + + // The router line names a host whose image isn't a router: blocked, + // and still the router at .2. + _, _, body = h.preview(&sess, "/environments/new", url.Values{"domain": {"kilo.bravo"}, "router": {"gw=debian-12"}, "env_hosts": {"web=debian-12"}}) + contains(t, "a router line on a Linux image", body, + `gw.kilo.bravo routerdebian-12-v1.2`, + "the router needs a router image", "Create 1 VM") +} + // The image and environment reviews fit a phone and a laptop, light and // dark. A blocked row is striped. func TestBrowserReviews(t *testing.T) { diff --git a/internal/web/teardownform_test.go b/internal/web/teardownform_test.go index 455e302..757ec15 100644 --- a/internal/web/teardownform_test.go +++ b/internal/web/teardownform_test.go @@ -167,6 +167,30 @@ func TestTeardownReviewOfASet(t *testing.T) { } } +// A pod teardown that finds only the disks gone VMs left frees them and +// deletes nothing; one narrowed to named VMs lists them, and one that +// isn't lists none. +func TestPodTeardownReviewOfDisksAndNamedVMs(t *testing.T) { + h := newHarness(t) + h.api.remove("team01-dc", "team01-web") + h.api.add(proxmox.VM{VMID: 9001, Name: "dc.kilo.alpha.tpl", Node: "n1", Template: true}, nil) + h.api.Mu.Lock() + h.api.Vols["competitions:vm-10101-disk-0"] = 10101 // team01-dc's delete left a disk + h.api.Mu.Unlock() + h.poll() + lead := h.login(asLead) + + _, _, body := h.preview(&lead, "/teardown", url.Values{"teams": {"1"}, "set": {""}}) + contains(t, "only disks", body, `Frees the disks deleted VMs left at VMID 10101.`, `team01-disks-10101`) + lacks(t, "only disks", body, "0 VMs", "stopped and deleted") + + _, _, body = h.preview(&lead, "/teardown", url.Values{"teams": {"2"}, "set": {""}, "vms": {"team02-dc"}}) + contains(t, "named VMs", body, "
Only these VMs
team02-dc
", "Tears down every matching VM in pod 02: 1 VM.") + _, _, body = h.preview(&lead, "/teardown", url.Values{"teams": {"2"}, "set": {""}}) + contains(t, "the whole pod", body, "Tears down everything in pod 02: 2 VMs.") + lacks(t, "the whole pod", body, "Only these VMs") +} + // A VM's page names its set, or says it has none recorded; several set // tags or a bare "set-" tag are drift and show "unknown set". func TestVMPageShowsItsSet(t *testing.T) { From b856ce5a6300606fcf85b073627fe09d0deef553 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:41:12 +0000 Subject: [PATCH 15/22] pods: test planner paths surviving mutation --- internal/pods/naming_test.go | 11 ++ internal/pods/plan_test.go | 287 ++++++++++++++++++++++++++++++++- internal/pods/snapshot_test.go | 14 ++ internal/pods/vmconfig_test.go | 30 ++++ 4 files changed, 334 insertions(+), 8 deletions(-) diff --git a/internal/pods/naming_test.go b/internal/pods/naming_test.go index 991b81c..9170844 100644 --- a/internal/pods/naming_test.go +++ b/internal/pods/naming_test.go @@ -129,6 +129,7 @@ func TestCloneVMIDPanicsOnBadTeam(t *testing.T) { {"negative", "-1", true}, {"out of range", "100", true}, {"valid", "05", false}, + {"top of range", "99", false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -290,3 +291,13 @@ func blockVMIDs(cfg config.Naming, team string) []int { return []int{start, start + 1, start + 50, start + 99, start + 100, start - 1, start + cfg.CloneVMIDTeamStride, start - cfg.CloneVMIDTeamStride, 100, 8000, cfg.CloneVMIDBase - 1} } + +func TestTeamOfCloneVMID(t *testing.T) { + n := NewNaming(config.Default().Naming) + for vmid, want := range map[int]string{10000: "00", 10105: "01", 19999: "99", 9999: "", 9901: "", 10150: "01", 10199: "01", 20000: ""} { + team, ok := n.TeamOfCloneVMID(vmid) + if team != want || ok != (want != "") { + t.Errorf("TeamOfCloneVMID(%d) = %q, %v, want %q", vmid, team, ok, want) + } + } +} diff --git a/internal/pods/plan_test.go b/internal/pods/plan_test.go index fc4214b..cf694ee 100644 --- a/internal/pods/plan_test.go +++ b/internal/pods/plan_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "reflect" + "strconv" "strings" "testing" @@ -96,7 +97,8 @@ func TestDeployPlanReusesTemplateAndConvergesExistingVM(t *testing.T) { t.Errorf("template not reused: %+v", plan.Templates[0]) } it := plan.Items[0] - if it.Node != "spruce" || it.Steps[0] == StepClone { + // Converging keeps the VM: no stop, delete or clone. + if want := []Step{StepNetwork, StepDiskLimits, StepCDROM, StepNotes, StepSetTag, StepStart}; it.Node != "spruce" || !reflect.DeepEqual(it.Steps, want) { t.Errorf("existing VM should converge without cloning: %+v", it) } @@ -132,23 +134,125 @@ func TestDeployPlanRebuildBlockedByClones(t *testing.T) { f := newCluster() f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) f.Add(proxmox.VM{VMID: 10521, Name: "team05-teak", Node: "cedar"}, nil) + f.Add(proxmox.VM{VMID: 10621, Name: "team06-teak", Node: "cedar"}, nil) + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "spruce"}, nil) plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) if err != nil { t.Fatal(err) } - if !strings.Contains(plan.Templates[0].Blocked, "team05-teak") { - t.Errorf("template Blocked = %q", plan.Templates[0].Blocked) + // The first clone found (by VMID) is named. + if got, want := plan.Templates[0].Blocked, "pod VMs such as team05-teak still use this template; tear them down first"; got != want { + t.Errorf("template Blocked = %q, want %q", got, want) } - if !strings.HasPrefix(plan.Items[0].Blocked, "template teak.tango.delta.tpl:") { - t.Errorf("item Blocked = %q", plan.Items[0].Blocked) + // The pod's own VM is blocked where it is. + if it := plan.Items[0]; !strings.HasPrefix(it.Blocked, "template teak.tango.delta.tpl:") || it.Node != "spruce" { + t.Errorf("item = %+v", it) + } +} + +// A rebuild is held up only by other pods' VMs of the template's host. +func TestDeployPlanRebuildIgnoresOtherHostsClones(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + f.Add(proxmox.VM{VMID: 10225, Name: "team02-oak", Node: "birch"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + if tpl := plan.Templates[0]; tpl.Blocked != "" || !tpl.Rebuild { + t.Errorf("template = %+v", tpl) + } +} + +// A rebuild whose pod VMs can't be deleted blocks the template, naming the +// first such VM, past a template that isn't rebuilt. +func TestDeployPlanRebuildBlockedByUndeletableVMs(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + f.Add(proxmox.VM{VMID: 10150, Name: "team01-teak", Node: "cedar"}, nil) + f.Add(proxmox.VM{VMID: 10250, Name: "team02-teak", Node: "cedar"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "*.tango.delta", Teams: []string{"01", "02"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + if oak := plan.Templates[0]; oak.Name != "oak.tango.delta.tpl" || oak.Rebuild || oak.Blocked != "" { + t.Fatalf("oak = %+v", oak) + } + if got, want := plan.Templates[1].Blocked, "pod VMs such as team01-teak still use this template; tear them down first"; got != want { + t.Errorf("teak Blocked = %q, want %q", got, want) + } +} + +// A pod VM that is converged, not rebuilt, stays on its node even when the +// pod's other VMs are mostly elsewhere. +func TestDeployPlanConvergedVMStaysOnItsNode(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "spruce"}, nil) + f.Add(proxmox.VM{VMID: 10110, Name: "team01-elm", Node: "birch"}, nil) + f.Add(proxmox.VM{VMID: 10111, Name: "team01-ash", Node: "birch"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "teak.*", Teams: []string{"01"}}) + if err != nil { + t.Fatal(err) + } + if it := plan.Items[0]; it.Node != "spruce" || it.Blocked != "" { + t.Errorf("item = %+v", it) + } +} + +// A template may sit at template_vmid_base itself; a clean master gives no +// notices. +func TestDeployPlanTemplateAtVMIDBase(t *testing.T) { + f := podstest.New("cedar") + f.Add(proxmox.VM{VMID: 100, Name: "edge.x", Node: "cedar", Tags: "dev"}, map[string]string{"net0": "virtio=BC:24:11:00:01:00,bridge=vmbr0", "agent": "1"}) + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "edge.*", Teams: []string{"01"}}) + if err != nil { + t.Fatal(err) + } + if tpl := plan.Templates[0]; tpl.VMID != 9000 || tpl.Blocked != "" { + t.Errorf("template = %+v", tpl) + } + if it := plan.Items[0]; it.VMID != 10100 || it.Blocked != "" { + t.Errorf("item = %+v", it) + } + if plan.Notices != nil { + t.Errorf("Notices = %q", plan.Notices) + } +} + +// New pods are spread by the size of the pod being deployed, which a +// blocked template's master doesn't add to. +func TestDeployPlanSpreadsPodsBySizeOfUnblockedTemplates(t *testing.T) { + f := podstest.New("cedar", "birch") + f.Add(proxmox.VM{VMID: 50, Name: "load", Node: "cedar", Status: "running", MaxMem: 4 << 30}, nil) + f.Add(proxmox.VM{VMID: 101, Name: "a.x", Node: "cedar", Tags: "dev", MaxMem: 8 << 30}, nil) + f.Add(proxmox.VM{VMID: 102, Name: "b.x", Node: "cedar", Tags: "dev"}, nil) + f.Add(proxmox.VM{VMID: 9002, Name: "b.x.tpl", Node: "cedar"}, nil) // not a template: b is blocked + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "*.x", Teams: []string{"01", "02", "03"}}) + if err != nil { + t.Fatal(err) + } + // Pods of 8 GiB: birch (0), then cedar (4 GiB), then birch (8 GiB). + nodes := map[string]string{} + for _, it := range plan.Items { + if it.Host == "a" { + nodes[it.Team] = it.Node + } + } + if want := map[string]string{"01": "birch", "02": "cedar", "03": "birch"}; !reflect.DeepEqual(nodes, want) { + t.Errorf("nodes = %v, want %v", nodes, want) } } func TestDeployPlanExplainsUntaggedMasters(t *testing.T) { _, err := testPlanner(newCluster()).Deploy(context.Background(), DeployRequest{Pattern: "notes.*", Teams: []string{"01"}}) - if err == nil || !strings.Contains(err.Error(), "lack the tag") { - t.Errorf("err = %v", err) + if want := `no master VMs match "notes.*" with tag "dev" (1 match but lack the tag, e.g. notes.tango.delta)`; err == nil || err.Error() != want { + t.Errorf("err = %v, want %s", err, want) + } + _, err = testPlanner(newCluster()).Deploy(context.Background(), DeployRequest{Pattern: "pine.*", Teams: []string{"01"}}) + if want := `no master VMs match "pine.*" with tag "dev"`; err == nil || err.Error() != want { + t.Errorf("err = %v, want %s", err, want) } } @@ -433,7 +537,7 @@ func TestDuplicateHostAcrossMastersBlocksBothTemplates(t *testing.T) { t.Fatalf("templates = %+v", plan.Templates) } for _, tpl := range plan.Templates { - if !strings.Contains(tpl.Blocked, "both map to pod VM names like team01-teak") || + if !strings.HasPrefix(tpl.Blocked, "hosts of ") || !strings.Contains(tpl.Blocked, "both map to pod VM names like team01-teak") || !strings.Contains(tpl.Blocked, "teak.tango.delta") || !strings.Contains(tpl.Blocked, "teak.kilo.delta") { t.Errorf("%s Blocked = %q", tpl.Name, tpl.Blocked) } @@ -551,3 +655,170 @@ func TestDeployPlanRebuildReplacesInTeamVMsAndBlocksOnBlockedVM(t *testing.T) { t.Errorf("team01-teak = %+v", plan.Items[0]) } } + +func TestKindFacts(t *testing.T) { + for _, k := range Kinds { + onEnv := k == KindEnvAdd || k == KindEnvTeardown + retryable := !k.Teamless() || k == KindEnvCreate || k == KindEnvAdd || k == KindEnvTeardown + if k.OnEnvironment() != onEnv || k.Retryable() != retryable || k.RetriedWhole() != (k == KindEnvTeardown) { + t.Errorf("%s: OnEnvironment %v, Retryable %v, RetriedWhole %v", k, k.OnEnvironment(), k.Retryable(), k.RetriedWhole()) + } + } +} + +func TestItemPool(t *testing.T) { + n := NewNaming(config.Default().Naming) + plan := &Plan{Items: []Item{{Name: "gw", Pool: "dev-02"}, {Name: "dc"}, {Name: "dc", Pool: "dev-01"}}} + for _, c := range []struct{ name, team, want string }{ + {"dc", "", "dev-01"}, // the first item of the name with a pool + {"gw", "07", "pool-07"}, + {"web", "", ""}, + } { + if got := plan.ItemPool(n, c.name, c.team); got != c.want { + t.Errorf("ItemPool(%q, %q) = %q, want %q", c.name, c.team, got, c.want) + } + } +} + +// orphanFake is a one-node cluster with template 9001, whose pod 01 and 02 +// clones (10101, 10201) are gone; vols puts volumes on deploy.storage, each +// "/". +func orphanFake(vols ...string) *podstest.Fake { + f := podstest.New("cedar") + f.Add(proxmox.VM{VMID: 9001, Name: "dc.kilo.alpha.tpl", Node: "cedar", Template: true}, nil) + for _, v := range vols { + owner, _, _ := strings.Cut(v, "/") + id, err := strconv.Atoi(owner) + if err != nil { + panic(err) + } + f.Vols[config.Default().Deploy.Storage+":"+v] = id + } + return f +} + +func teardownItems(t *testing.T, api Reads) []string { + t.Helper() + plan, err := NewPlanner(api, config.Default()).Teardown(context.Background(), []string{"01", "02"}, nil, "") + if err != nil { + t.Fatal(err) + } + var out []string + for _, it := range plan.Items { + out = append(out, it.Name+"@"+it.Node) + } + return out +} + +// Every gone VM's disks are freed, however many disks each left. +func TestTeardownFreesEveryGoneVMsDisks(t *testing.T) { + f := orphanFake("10101/vm-10101-disk-0.qcow2", "10101/vm-10101-disk-1.qcow2", "10201/vm-10201-disk-0.qcow2", "10201/vm-10201-disk-1.qcow2") + if got, want := teardownItems(t, f), []string{"team01-disks-10101@cedar", "team02-disks-10201@cedar"}; !reflect.DeepEqual(got, want) { + t.Errorf("items = %v, want %v", got, want) + } +} + +// Disks at a VMID a VM the user can't see holds are that VM's: not freed. +func TestTeardownKeepsDisksOfUnseenVM(t *testing.T) { + f := orphanFake("10101/vm-10101-disk-0.qcow2", "10201/vm-10201-disk-0.qcow2") + f.Unseen = map[int]bool{10101: true} + if got, want := teardownItems(t, f), []string{"team02-disks-10201@cedar"}; !reflect.DeepEqual(got, want) { + t.Errorf("items = %v, want %v", got, want) + } + // A disk of 10201's filed under 10101 is still 10201's to free. + f = orphanFake("10101/vm-10101-disk-0.qcow2", "10101/vm-10201-disk-0.qcow2") + f.Unseen = map[int]bool{10101: true} + if got, want := teardownItems(t, f), []string{"team02-disks-10201@cedar"}; !reflect.DeepEqual(got, want) { + t.Errorf("filed under 10101: items = %v, want %v", got, want) + } +} + +// A teardown that can't tell whether a VMID is free fails rather than +// freeing its disks. +func TestTeardownFailsWhenVMIDUseUnknown(t *testing.T) { + f := orphanFake("10101/vm-10101-disk-0.qcow2") + f.FailOn("vmid-held:10101", errors.New("boom")) + _, err := NewPlanner(f, config.Default()).Teardown(context.Background(), []string{"01"}, nil, "") + if err == nil || !strings.Contains(err.Error(), "checking whether VMID 10101 is free: boom") { + t.Errorf("err = %v", err) + } +} + +// Disks are looked for where deploy.storage is: on one node if it is shared, +// else on each node that has it; with no node reporting it, on every node. +func TestTeardownListsDisksWhereTheStorageIs(t *testing.T) { + storage := config.Default().Deploy.Storage + for _, c := range []struct { + name string + res []proxmox.StorageResource + want string + }{ + {"shared", []proxmox.StorageResource{{Storage: "local", Node: "cedar"}, {Storage: storage, Node: "birch", Shared: true}}, "birch"}, + {"node-local", []proxmox.StorageResource{{Storage: storage, Node: "spruce"}, {Storage: storage, Node: "birch"}}, "birch"}, + {"unreported", []proxmox.StorageResource{{Storage: "local", Node: "spruce"}}, "cedar"}, + } { + f := orphanFake("10101/vm-10101-disk-0.qcow2") + f.Nodes = []string{"cedar", "birch", "spruce"} + api := &resourceAPI{Fake: f, res: proxmox.Resources{Storage: c.res}} + if got, want := teardownItems(t, api), []string{"team01-disks-10101@" + c.want}; !reflect.DeepEqual(got, want) { + t.Errorf("%s: items = %v, want %v", c.name, got, want) + } + } +} + +// VMs sharing a name stay in VMID order. +func TestTeardownKeepsSameNamedVMsInVMIDOrder(t *testing.T) { + f := orphanFake() + f.Add(proxmox.VM{VMID: 10102, Name: "team01-dc", Node: "cedar", Pool: "pool-01"}, nil) + f.Add(proxmox.VM{VMID: 10101, Name: "team01-dc", Node: "cedar", Pool: "pool-01"}, nil) + plan, err := NewPlanner(f, config.Default()).Teardown(context.Background(), []string{"01"}, nil, "") + if err != nil { + t.Fatal(err) + } + var ids []int + for _, it := range plan.Items { + ids = append(ids, it.VMID) + } + if want := []int{10101, 10102}; !reflect.DeepEqual(ids, want) { + t.Errorf("VMIDs = %v, want %v", ids, want) + } +} + +// Disks are looked for only at the clone VMIDs of templates: .tpl-named +// templates in template_vmid_base..+99. +func TestTeardownLooksForDisksOfTemplatesInRange(t *testing.T) { + for _, c := range []struct { + name string + tpl proxmox.VM + want bool + }{ + {"at the base", proxmox.VM{VMID: 9000, Name: "dc.x.tpl", Template: true}, true}, + {"past the range", proxmox.VM{VMID: 9100, Name: "dc.x.tpl", Template: true}, false}, + {"not a template", proxmox.VM{VMID: 9000, Name: "dc.x.tpl"}, false}, + {"not .tpl", proxmox.VM{VMID: 9000, Name: "dc.x", Template: true}, false}, + } { + f := podstest.New("cedar") + f.Add(proxmox.VM{VMID: 50, Name: "other", Node: "cedar"}, nil) // listed before the template + c.tpl.Node = "cedar" + f.Add(c.tpl, nil) + f.Vols[config.Default().Deploy.Storage+":10100/vm-10100-disk-0.qcow2"] = 10100 + got := teardownItems(t, f) + if want := []string{"team01-disks-10100@cedar"}; c.want != reflect.DeepEqual(got, want) { + t.Errorf("%s: items = %v", c.name, got) + } + } +} + +// A VM blocked for its pool doesn't stop the VMs after it being checked. +func TestResetChecksVMsPastABlockedOne(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-ash", Node: "cedar", Pool: "pool-02"}, nil, "initial") + f.Add(proxmox.VM{VMID: 10125, Name: "team01-oak", Node: "birch"}, nil) + rs, err := testPlanner(f).Reset(context.Background(), []string{"01"}, nil, "initial") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(rs.Items[0].Blocked, "is in pool pool-02") || rs.Items[1].Blocked != `no snapshot "initial" (has none)` { + t.Errorf("items = %+v", rs.Items) + } +} diff --git a/internal/pods/snapshot_test.go b/internal/pods/snapshot_test.go index 7220eb6..e78cdd9 100644 --- a/internal/pods/snapshot_test.go +++ b/internal/pods/snapshot_test.go @@ -171,3 +171,17 @@ func TestPropSnapshotPlanNeverOverwrites(t *testing.T) { } }) } + +// A VM blocked for its pool doesn't stop the VMs after it being checked. +func TestSnapshotPlanChecksVMsPastABlockedOne(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-ash", Node: "cedar", Pool: "pool-02"}, nil) + f.Add(proxmox.VM{VMID: 10125, Name: "team01-oak", Node: "birch"}, nil, "before-scoring") + plan, err := testPlanner(f).Snapshot(context.Background(), SnapshotRequest{Teams: []string{"01"}, Name: "before-scoring"}) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(plan.Items[0].Blocked, "is in pool pool-02") || plan.Items[1].Blocked != alreadyHas("before-scoring") { + t.Errorf("items = %+v", plan.Items) + } +} diff --git a/internal/pods/vmconfig_test.go b/internal/pods/vmconfig_test.go index 9fb098f..c351681 100644 --- a/internal/pods/vmconfig_test.go +++ b/internal/pods/vmconfig_test.go @@ -416,3 +416,33 @@ func TestPropVolumeOwner(t *testing.T) { checkVolumeOwner(t, vol) }) } + +// A drive with only one of its limits off gets both set. +func TestDiskLimitChangesOneLimitOff(t *testing.T) { + cur := map[string]string{ + "scsi0": "competitions:vm-1-disk-0.qcow2,mbps_rd=100,mbps_wr=300", + "scsi1": "competitions:vm-1-disk-1.qcow2,mbps_rd=300,mbps_wr=100", + } + want := map[string]string{ + "scsi0": "competitions:vm-1-disk-0.qcow2,mbps_rd=300,mbps_wr=300", + "scsi1": "competitions:vm-1-disk-1.qcow2,mbps_rd=300,mbps_wr=300", + } + if got := DiskLimitChanges(cur, 300, 300); !reflect.DeepEqual(got, want) { + t.Errorf("DiskLimitChanges = %v, want %v", got, want) + } +} + +func TestCPUChanges(t *testing.T) { + for _, c := range []struct { + cur, cpu string + want map[string]string + }{ + {"host", "", map[string]string{}}, // no model configured + {"custom-lab", "custom-lab", map[string]string{}}, + {"host", "custom-lab", map[string]string{"cpu": "custom-lab"}}, + } { + if got := CPUChanges(map[string]string{"cpu": c.cur}, c.cpu); !reflect.DeepEqual(got, c.want) { + t.Errorf("CPUChanges(%q, %q) = %v, want %v", c.cur, c.cpu, got, c.want) + } + } +} From f626554e05a1cd91fb8288acb58863102f31f8d4 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:34:28 +0000 Subject: [PATCH 16/22] pods: delete SetOfPattern's redundant empty-set check ParseSet already refuses an empty set, so the check could not fail. --- internal/pods/sets.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/pods/sets.go b/internal/pods/sets.go index 14912d1..38fb28a 100644 --- a/internal/pods/sets.go +++ b/internal/pods/sets.go @@ -34,7 +34,7 @@ func SetOfPattern(pattern string) (Set, bool) { return "", false } set, err := ParseSet(rest) - return set, err == nil && set != "" + return set, err == nil } // SplitMaster splits a master or template name into its host and set: From 452a7f310cfe4482f08864e95aedb2539702f4d4 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:35:49 +0000 Subject: [PATCH 17/22] apply: test behaviour surviving template copy, restart, rebuild and conversion mutants --- internal/apply/templates_test.go | 201 +++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) diff --git a/internal/apply/templates_test.go b/internal/apply/templates_test.go index 2dc7b6b..95895c2 100644 --- a/internal/apply/templates_test.go +++ b/internal/apply/templates_test.go @@ -2,11 +2,13 @@ package apply import ( "context" + "errors" "fmt" "slices" "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -532,3 +534,202 @@ func TestRetryRoundDoesNotRecheckABuiltTemplate(t *testing.T) { t.Errorf("template events = %q, want %q", got, want) } } + +// A stop that cuts off the copy's POST before it answered leaves no task to +// stop: none is, and cleanup completes the copy it finds intact rather than +// removing it as failed. +func TestStopDuringCopyPostDoesNotStopATaskThatNeverStarted(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + f.CloneThenFail = map[int]error{9021: context.Canceled} + f.OnRecord = func(key string) { + if key == "clone:9021" { + cancel() + } + } + + res := testExecutor(f, &recorder{}).Run(ctx, plan) + if n := f.Called("stoptask:"); n != 0 { + t.Errorf("%d StopTask calls, want none: no copy task was started", n) + } + if !slices.Contains(res.Completed, "teak.tango.delta.tpl") || slices.Contains(res.Removed, "teak.tango.delta.tpl") { + t.Errorf("Completed %v, Removed %v; want the copy completed", res.Completed, res.Removed) + } +} + +// A copy whose task failed, then was re-copied OK in a later round, is no +// longer the leftover of a failed copy: a round after that finishes it. +func TestCopyRedoneAfterAFailedCopyIsFinished(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + copyTask := podstest.UPID("cedar", "qmclone", 121) + failed := false + f.WaitHook = func(_ context.Context, upid string) error { // runs with f.Mu held + if upid != copyTask || failed { + return nil + } + failed = true + delete(f.VMs, 9021) // Proxmox removes a failed copy's target + return &proxmox.TaskError{UPID: upid, ExitStatus: "clone failed: storage error"} + } + f.FailOn("template:9021", &proxmox.APIError{Status: 400, Message: "Parameter verification failed."}) + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 2 + + res := ex.Run(context.Background(), plan) + if len(res.Failed) != 0 || !slices.Equal(res.Succeeded, []string{"team01-teak"}) { + t.Fatalf("result = %+v", res) + } + if n := f.Called("clone:9021"); n != 2 { + t.Errorf("copied %d times, want 2", n) + } + if tpl := f.VMs[9021]; tpl == nil || !tpl.Template { + t.Errorf("template = %+v", tpl) + } +} + +// A master whose stop failed is still running: it is not started again. +func TestMasterStillRunningAfterAFailedStopIsNotStarted(t *testing.T) { + f := newRunningMaster() + plan := deployTeak(t, f, "01") + f.FailOn("power:121:stop", &proxmox.APIError{Status: 400, Message: "Parameter verification failed."}) + ex := testExecutor(f, &recorder{}) + ex.Cfg.Retry.Rounds = 0 + + res := ex.Run(context.Background(), plan) + if err := res.Failed["team01-teak"]; err == nil || !strings.Contains(err.Error(), "stopping master") { + t.Fatalf("result = %+v, want the stop's failure", res) + } + if n := f.Called("power:121:start"); n != 0 || f.VMs[121].Status != "running" { + t.Errorf("master %s, started %d times; want it left running, never started", f.VMs[121].Status, n) + } +} + +// A copy a later wait saw finish OK stays OK when the job is then stopped: +// stopping it says how the stop went, and cleanup completes the copy rather +// than removing it as cut off. +func TestCopySeenOKBeforeTheStopIsCompleted(t *testing.T) { + for _, tc := range []struct { + name string + stopErr error + event string + }{ + {"stopped", nil, "stopped the copy of teak.tango.delta (the job was stopped)"}, + {"stop failed", &proxmox.APIError{Status: 500, Message: "no such task"}, + "stopping the copy of teak.tango.delta: "}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newRunningMaster() + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rec := &recorder{} + copyTask := podstest.UPID("cedar", "qmclone", 121) + var waits int + var seenOK atomic.Bool + f.WaitHook = func(_ context.Context, upid string) error { // runs with f.Mu held + if upid != copyTask { + return nil + } + if waits++; waits == 1 { + return errors.New("no answer") // the copy's end is not seen + } + seenOK.Store(true) // restartMaster's wait sees it end OK + return nil + } + f.StopHook = func(string) error { return tc.stopErr } + // Once restartMaster has recorded the copy OK, the job is stopped; + // the restart goes on once the stop has stopped the copy. + f.Gate = func(_ context.Context, key string) (func(), error) { + if key != "config:9021" || !seenOK.CompareAndSwap(true, false) { + return nil, nil + } + cancel() + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + for _, e := range rec.find("teak.tango.delta.tpl", EventInfo) { + if strings.Contains(e.Message, "the copy of teak.tango.delta") { + return nil, nil + } + } + } + return nil, nil + } + + res := testExecutor(f, rec).Run(ctx, plan) + if n := f.Called("stoptask:" + copyTask); n != 1 { + t.Errorf("copy stopped %d times, want 1", n) + } + found := false + for _, e := range rec.find("teak.tango.delta.tpl", EventInfo) { + found = found || strings.HasPrefix(e.Message, tc.event) + } + if !found { + t.Errorf("events = %+v, want %q", rec.find("teak.tango.delta.tpl", EventInfo), tc.event) + } + if !slices.Contains(res.Completed, "teak.tango.delta.tpl") || slices.Contains(res.Removed, "teak.tango.delta.tpl") { + t.Errorf("Completed %v, Removed %v; want the copy completed", res.Completed, res.Removed) + } + if st := f.VMs[121].Status; st != "running" { + t.Errorf("master status = %s, want running", st) + } + }) + } +} + +// A rebuild is held back only by team VMs of its own host, and names the +// lowest-numbered one. +func TestRebuildHeldBackOnlyByItsHostsTeamVMs(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), pods.DeployRequest{Pattern: "teak.*", Teams: []string{"02"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + f.Add(proxmox.VM{VMID: 10125, Name: "team01-oak", Node: "birch"}, nil) + + res := testExecutor(f, &recorder{}).Run(context.Background(), plan) + if len(res.Failed) != 0 || !slices.Equal(res.Succeeded, []string{"team02-teak"}) { + t.Fatalf("another host's team VM: result = %+v", res) + } + + f = newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + plan, err = testPlanner(f).Deploy(context.Background(), pods.DeployRequest{Pattern: "teak.*", Teams: []string{"02"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar"}, nil) + f.Add(proxmox.VM{VMID: 10321, Name: "team03-teak", Node: "cedar"}, nil) + res = testExecutor(f, &recorder{}).Run(context.Background(), plan) + if err := res.Failed["team02-teak"]; err == nil || !strings.Contains(err.Error(), "pod VMs such as team01-teak still use") { + t.Errorf("error = %v, want it to name team01-teak, the lowest VMID", err) + } +} + +// A conversion that ends OK just as the job stops is still checked: a +// conversion that left a disk unrenamed is not taken for a template. +func TestConversionEndingAsTheJobStopsIsStillChecked(t *testing.T) { + f := newCluster() + plan := deployTeak(t, f, "01") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + f.ConvertLeavesDisk = map[int]bool{9021: true} + convTask := podstest.UPID("cedar", "qmtemplate", 9021) + f.WaitHook = func(_ context.Context, upid string) error { + if upid == convTask { + cancel() + } + return nil + } + rec := &recorder{} + + res := testExecutor(f, rec).Run(ctx, plan) + if got := rec.find("teak.tango.delta.tpl", EventDone); len(got) != 0 { + t.Errorf("done events = %+v, want none: the conversion left a disk", got) + } + if !slices.Contains(res.Removed, "teak.tango.delta.tpl") || f.VMs[9021] != nil { + t.Errorf("Removed %v, template %+v; want the half-converted template removed", res.Removed, f.VMs[9021]) + } +} From 32ce3130b8f6d196a902529ce9502ce764bdc9a5 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:35:50 +0000 Subject: [PATCH 18/22] apply: stop TestUnfollowableTaskStillLockedAtStop racing the stop's arrival --- internal/apply/review_test.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/internal/apply/review_test.go b/internal/apply/review_test.go index acdb20d..afc0de0 100644 --- a/internal/apply/review_test.go +++ b/internal/apply/review_test.go @@ -202,7 +202,20 @@ func TestUnfollowableTaskStillLockedAtStop(t *testing.T) { return forbidden } ex := testExecutor(f, &recorder{}) - ex.Sleep = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } + // The stop reaches the step's context asynchronously (stepContext). A + // sleep that returned at once until then would let the poll spin through + // every locked read first; a real one lasts until the step sees the stop. + ex.Sleep = func(sctx context.Context, _ time.Duration) error { + if ctx.Err() == nil { + return nil + } + select { + case <-sctx.Done(): + return sctx.Err() + case <-time.After(10 * time.Second): + return nil + } + } res := ex.Run(ctx, plan) err = res.Failed["team01-teak"] if err == nil || !strings.Contains(err.Error(), "VM 10121 is still locked (stop), but whether it worked is unknown") { From 3fa439ef817b3d40fa5c04123526a2a6ca4d7d2e Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:47:42 +0000 Subject: [PATCH 19/22] pods: pin where a rebuilt pod VM goes, and where a blocked one is reported --- internal/pods/plan_test.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/internal/pods/plan_test.go b/internal/pods/plan_test.go index cf694ee..2895960 100644 --- a/internal/pods/plan_test.go +++ b/internal/pods/plan_test.go @@ -822,3 +822,30 @@ func TestResetChecksVMsPastABlockedOne(t *testing.T) { t.Errorf("items = %+v", rs.Items) } } + +// A rebuilt pod VM is recloned on its pod's node, not where the old one +// was; one the rebuild can't delete is reported where it is. +func TestDeployPlanRebuildPlacesVMOnPodNode(t *testing.T) { + for _, tc := range []struct { + vmid int + node string + wantBlocked bool + }{ + {10121, "birch", false}, + {10150, "spruce", true}, // wrong VMID: blocked + } { + f := newCluster() + f.Add(proxmox.VM{VMID: 9021, Name: "teak.tango.delta.tpl", Node: "cedar", Template: true}, nil) + f.Add(proxmox.VM{VMID: tc.vmid, Name: "team01-teak", Node: "spruce"}, nil) + f.Add(proxmox.VM{VMID: 10110, Name: "team01-elm", Node: "birch"}, nil) + f.Add(proxmox.VM{VMID: 10111, Name: "team01-ash", Node: "birch"}, nil) + plan, err := testPlanner(f).Deploy(context.Background(), DeployRequest{Pattern: "teak.*", Teams: []string{"01"}, Rebuild: true}) + if err != nil { + t.Fatal(err) + } + it := plan.Items[0] + if it.Node != tc.node || it.OldNode != "spruce" || (it.Blocked != "") != tc.wantBlocked { + t.Errorf("VMID %d: item = %+v, want Node %s", tc.vmid, it, tc.node) + } + } +} From 93f42bddd40795eaa8ee0d91968b18184ffd8b43 Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:25:45 +0000 Subject: [PATCH 20/22] apply: make timing tests deterministic and drop the delete-order test Run the stop-while-locked and leftover-disk tests under synctest, gate the copy-stop test on its event, and stop pinning cleanup's incidental delete order. --- internal/apply/executor_test.go | 31 +++++----------- internal/apply/review_test.go | 63 ++++++++++++++------------------ internal/apply/storage_test.go | 41 ++++++++++----------- internal/apply/templates_test.go | 19 ++++++---- 4 files changed, 68 insertions(+), 86 deletions(-) diff --git a/internal/apply/executor_test.go b/internal/apply/executor_test.go index 01d7e8a..ddf43df 100644 --- a/internal/apply/executor_test.go +++ b/internal/apply/executor_test.go @@ -1320,23 +1320,6 @@ func TestTemplateThatCannotBeConvertedIsRemoved(t *testing.T) { } } -// Cleanup removes this run's team VMs in VMID order. -func TestCleanupRemovesTeamVMsInVMIDOrder(t *testing.T) { - f := sevenMasters() - plan := deploySeven(t, f, "h1", "h2", "h3") - denied := &proxmox.APIError{Status: 400, Message: "Parameter verification failed."} - for _, vmid := range []int{10103, 10101, 10102} { - f.FailOn(fmt.Sprintf("setconfig:%d", vmid), denied) - } - ex := testExecutor(f, &recorder{}) - ex.Cfg.Retry.Rounds = 0 - - res := ex.Run(context.Background(), plan) - if got := f.DeletedIDs(); !slices.Equal(got, []int{10101, 10102, 10103}) { - t.Errorf("deleted %v, want 10101, 10102, 10103 in order; result %+v", got, res) - } -} - // Cleanup settles each template copy it can't complete one way: gone, // failed or removed. Either way it goes on to complete the next. func TestCleanupSettlesEachTemplateCopyOnce(t *testing.T) { @@ -1421,10 +1404,16 @@ func TestCleanupBudgetReportsEveryVMLeft(t *testing.T) { cleaning.Store(listings == 2) // Run's listing, then cleanup's } } + var first atomic.Int64 // the VM cleanup checks first, whatever its order f.Gate = func(ctx context.Context, key string) (func(), error) { - if cleaning.Load() && key == fmt.Sprintf("config:%d", tc.base+1) { - <-ctx.Done() - return nil, ctx.Err() + if !cleaning.Load() { + return nil, nil + } + for i := int64(1); i <= 3; i++ { + if key == fmt.Sprintf("config:%d", int64(tc.base)+i) && (first.CompareAndSwap(0, i) || first.Load() == i) { + <-ctx.Done() + return nil, ctx.Err() + } } return nil, nil } @@ -1435,7 +1424,7 @@ func TestCleanupBudgetReportsEveryVMLeft(t *testing.T) { for i := 1; i <= 3; i++ { name := fmt.Sprintf(tc.named, i) err := res.CleanupFailed[name] - if err == nil || i > 1 && !strings.Contains(err.Error(), "cleanup time budget ran out") { + if err == nil || int64(i) != first.Load() && !strings.Contains(err.Error(), "cleanup time budget ran out") { t.Errorf("%s: cleanup error %v, want it reported as not checked in time", name, err) } } diff --git a/internal/apply/review_test.go b/internal/apply/review_test.go index afc0de0..6d2d210 100644 --- a/internal/apply/review_test.go +++ b/internal/apply/review_test.go @@ -4,6 +4,7 @@ import ( "context" "strings" "testing" + "testing/synctest" "time" "github.com/wccomps/battleship/internal/pods/podstest" @@ -181,46 +182,36 @@ func TestUnfollowableTaskNamingNoVMIsNotPolled(t *testing.T) { } // A stop while waiting for an unfollowable task's VM to unlock reports the -// lock still held, not the task ended. +// lock still held, not the task ended. synctest's clock lets the lock poll's +// real sleeps run until the step sees the stop. func TestUnfollowableTaskStillLockedAtStop(t *testing.T) { - f := newCluster() - f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) - plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stop := podstest.UPID("cedar", "qmstop", 10121) - f.WaitHook = func(_ context.Context, id string) error { // runs with f.Mu held - if id != stop { - return nil + synctest.Test(t, func(t *testing.T) { + f := newCluster() + f.Add(proxmox.VM{VMID: 10121, Name: "team01-teak", Node: "cedar", Status: "running"}, map[string]string{"name": "team01-teak"}) + plan, err := testPlanner(f).Power(context.Background(), []string{"01"}, []string{"teak"}, "stop") + if err != nil { + t.Fatal(err) } - f.WaitHook = nil - f.LockConfig, f.LockName = map[int]int{10121: 1000}, "stop" // the task runs on - cancel() - return forbidden - } - ex := testExecutor(f, &recorder{}) - // The stop reaches the step's context asynchronously (stepContext). A - // sleep that returned at once until then would let the poll spin through - // every locked read first; a real one lasts until the step sees the stop. - ex.Sleep = func(sctx context.Context, _ time.Duration) error { - if ctx.Err() == nil { - return nil + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stop := podstest.UPID("cedar", "qmstop", 10121) + f.WaitHook = func(_ context.Context, id string) error { // runs with f.Mu held + if id != stop { + return nil + } + f.WaitHook = nil + f.LockConfig, f.LockName = map[int]int{10121: 1000}, "stop" // the task runs on + cancel() + return forbidden } - select { - case <-sctx.Done(): - return sctx.Err() - case <-time.After(10 * time.Second): - return nil + ex := testExecutor(f, &recorder{}) + ex.Sleep = proxmox.SleepContext + res := ex.Run(ctx, plan) + err = res.Failed["team01-teak"] + if err == nil || !strings.Contains(err.Error(), "VM 10121 is still locked (stop), but whether it worked is unknown") { + t.Fatalf("error = %v, want VM 10121 still locked", err) } - } - res := ex.Run(ctx, plan) - err = res.Failed["team01-teak"] - if err == nil || !strings.Contains(err.Error(), "VM 10121 is still locked (stop), but whether it worked is unknown") { - t.Fatalf("error = %v, want VM 10121 still locked", err) - } + }) } // If authorization lapses mid-build, the stopped master is reported in the diff --git a/internal/apply/storage_test.go b/internal/apply/storage_test.go index dd431cb..4bad468 100644 --- a/internal/apply/storage_test.go +++ b/internal/apply/storage_test.go @@ -10,6 +10,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" "github.com/wccomps/battleship/internal/config" @@ -326,32 +327,30 @@ func TestRebuildFreesOldTemplateDisk(t *testing.T) { // A template's base disk found left on the storage is freed under the // storage-ops slot, as its destroy would have been. func TestFoundLeftoverBaseDiskWaitsForStorageOps(t *testing.T) { - f := newCluster() - vol := "competitions:9021/base-9021-disk-0.qcow2" - f.Vols[vol] = 9021 // its template is gone - ex := testExecutor(f, &recorder{}) - ex.init() - ex.present = map[int]proxmox.VM{} - holding, release := make(chan struct{}), make(chan struct{}) - go ex.lim.storageOps.do(context.Background(), true, func() error { close(holding); <-release; return nil }) - <-holding - - done := make(chan error, 1) - go func() { done <- ex.retryLeftovers(context.Background(), 9021, "cedar", "teak.tango.delta.tpl") }() - for queued := false; !queued; time.Sleep(time.Millisecond) { + synctest.Test(t, func(t *testing.T) { + f := newCluster() + vol := "competitions:9021/base-9021-disk-0.qcow2" + f.Vols[vol] = 9021 // its template is gone + ex := testExecutor(f, &recorder{}) + ex.init() + ex.present = map[int]proxmox.VM{} + holding, release := make(chan struct{}), make(chan struct{}) + go ex.lim.storageOps.do(context.Background(), true, func() error { close(holding); <-release; return nil }) + <-holding + + done := make(chan error, 1) + go func() { done <- ex.retryLeftovers(context.Background(), 9021, "cedar", "teak.tango.delta.tpl") }() + synctest.Wait() select { case err := <-done: t.Fatalf("freed while another storage op held the slot (err %v)", err) default: } - ex.lim.storageOps.mu.Lock() - queued = len(ex.lim.storageOps.lo) == 1 - ex.lim.storageOps.mu.Unlock() - } - close(release) - if err := <-done; err != nil || len(f.VolumesOf(9021)) != 0 { - t.Errorf("err = %v, volumes left %q; want %s freed", err, f.VolumesOf(9021), vol) - } + close(release) + if err := <-done; err != nil || len(f.VolumesOf(9021)) != 0 { + t.Errorf("err = %v, volumes left %q; want %s freed", err, f.VolumesOf(9021), vol) + } + }) } func wantLeftoverAdvice(t *testing.T, err error, vols ...string) { diff --git a/internal/apply/templates_test.go b/internal/apply/templates_test.go index 95895c2..43b5e44 100644 --- a/internal/apply/templates_test.go +++ b/internal/apply/templates_test.go @@ -642,22 +642,25 @@ func TestCopySeenOKBeforeTheStopIsCompleted(t *testing.T) { f.StopHook = func(string) error { return tc.stopErr } // Once restartMaster has recorded the copy OK, the job is stopped; // the restart goes on once the stop has stopped the copy. + copyStopped := make(chan struct{}) f.Gate = func(_ context.Context, key string) (func(), error) { if key != "config:9021" || !seenOK.CompareAndSwap(true, false) { return nil, nil } cancel() - for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) { - for _, e := range rec.find("teak.tango.delta.tpl", EventInfo) { - if strings.Contains(e.Message, "the copy of teak.tango.delta") { - return nil, nil - } - } - } + <-copyStopped return nil, nil } - res := testExecutor(f, rec).Run(ctx, plan) + ex := testExecutor(f, rec) + var once sync.Once + ex.OnEvent = func(e Event) { + rec.add(e) + if e.Item == "teak.tango.delta.tpl" && e.Status == EventInfo && strings.Contains(e.Message, "the copy of teak.tango.delta") { + once.Do(func() { close(copyStopped) }) + } + } + res := ex.Run(ctx, plan) if n := f.Called("stoptask:" + copyTask); n != 1 { t.Errorf("copy stopped %d times, want 1", n) } From 39cfed3b93ef296bf5559bf5f787578bec984bff Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:28:31 +0000 Subject: [PATCH 21/22] pods: record SSH checks in the fake and trim duplicate tests podstest.Guest gains SSHExit and the Fake records SSH checks, replacing liveaddr_test's sshAgent wrapper. Drop two EnvEdit tests TestEnvEditItem already covers, share a hostSpecs helper in envplan tests, and correct Environments' docstring on templates. --- internal/pods/envedit_test.go | 42 ------------------------- internal/pods/environments.go | 8 ++--- internal/pods/envplan_test.go | 50 ++++++++++++------------------ internal/pods/liveaddr_test.go | 42 ++++++------------------- internal/pods/podstest/agent.go | 5 ++- internal/pods/podstest/podstest.go | 10 +++--- 6 files changed, 43 insertions(+), 114 deletions(-) diff --git a/internal/pods/envedit_test.go b/internal/pods/envedit_test.go index 4575b01..2a6ec14 100644 --- a/internal/pods/envedit_test.go +++ b/internal/pods/envedit_test.go @@ -189,33 +189,6 @@ func TestHostEditInputCheck(t *testing.T) { } } -// A host's DNS note follows a rename only when it names the host itself. -func TestEnvEditRenameKeepsOtherDNS(t *testing.T) { - f := podstest.New("alder") - f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, - map[string]string{"net0": "virtio=BC:24:11:00:00:01,bridge=devext01", "net1": "virtio=BC:24:11:00:00:02,bridge=devint01", - "description": "battleship: base=gw-v1 dns=router"}) - f.Add(proxmox.VM{VMID: 2101, Name: "dc.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, - map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", - "description": "battleship: ip=192.168.100.10 os=windows base=win-v1 dns=dc"}) - f.Add(proxmox.VM{VMID: 2102, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, - map[string]string{"net0": "virtio=BC:24:11:00:00:04,bridge=devint01", "agent": "1", - "description": "battleship: ip=192.168.100.11 os=linux base=debian-12-v1 dns=dc"}) - p := NewPlanner(f, envConfig()) - for _, c := range []struct { - vmid int - host, dns string - }{{2102, "oak", "dc"}, {2101, "ad", "ad"}} { - plan, err := p.EnvEdit(context.Background(), HostEditInput{VMID: c.vmid, Host: c.host}) - if err != nil { - t.Fatal(err) - } - if it := plan.Items[0]; it.Notes == nil || it.Notes.DNS != c.dns { - t.Errorf("rename %d to %s: notes = %+v, want dns=%s", c.vmid, c.host, it.Notes, c.dns) - } - } -} - func TestEnvEditItem(t *testing.T) { name16 := "abcdefghijklmnop" for _, tc := range []struct { @@ -436,18 +409,3 @@ func TestEnvEditStaleDetails(t *testing.T) { t.Errorf("stale details after a name clash blocked = %q", b) } } - -// Moving a lone host to another domain swaps its domain tag. -func TestEnvEditNewDomainDropsOldDomainTag(t *testing.T) { - f := podstest.New("alder") - f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;keep"}, - map[string]string{"net0": "virtio=BC:24:11:00:00:03,bridge=devint01", "agent": "1", - "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1"}) - plan, err := NewPlanner(f, envConfig()).EnvEdit(context.Background(), HostEditInput{VMID: 2101, Host: "teak.lima.bravo"}) - if err != nil { - t.Fatal(err) - } - if it := plan.Items[0]; it.Rename != "teak.lima.bravo" || it.Tags != "dev;lima.bravo;keep" { - t.Errorf("item = %+v, want tags dev;lima.bravo;keep", it) - } -} diff --git a/internal/pods/environments.go b/internal/pods/environments.go index ec7b189..4b57fc0 100644 --- a/internal/pods/environments.go +++ b/internal/pods/environments.go @@ -255,10 +255,10 @@ func (e Environment) DNS() string { } // Environments reads every slot: the VMs in its pool with their notes, the -// other VMs on its bridges, and its half-deleted VMs. Templates never run, -// so they hold no slot; team VMs (see Classify) are on team bridges, so -// they aren't read, but a VM only named like one may be anywhere. It also -// returns the VM listing it read. +// other VMs on its bridges, and its half-deleted VMs. Templates outside a +// slot's pool never run, so their NICs hold no slot; team VMs (see +// Classify) are on team bridges, so they aren't read, but a VM only named +// like one may be anywhere. It also returns the VM listing it read. func (p Planner) Environments(ctx context.Context) ([]Environment, []proxmox.VM, error) { vms, err := p.API.ClusterVMs(ctx) if err != nil { diff --git a/internal/pods/envplan_test.go b/internal/pods/envplan_test.go index 5456e03..217e027 100644 --- a/internal/pods/envplan_test.go +++ b/internal/pods/envplan_test.go @@ -24,16 +24,23 @@ func envFake() *podstest.Fake { return f } -func create(t *testing.T, p Planner, hosts ...string) *Plan { +// hostSpecs parses each spec as ParseHostSpec does. +func hostSpecs(t *testing.T, specs ...string) []HostSpec { t.Helper() - req := EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}} - for _, h := range hosts { - hs, err := ParseHostSpec(h) + var hosts []HostSpec + for _, s := range specs { + hs, err := ParseHostSpec(s) if err != nil { t.Fatal(err) } - req.Hosts = append(req.Hosts, hs) + hosts = append(hosts, hs) } + return hosts +} + +func create(t *testing.T, p Planner, hosts ...string) *Plan { + t.Helper() + req := EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}, Hosts: hostSpecs(t, hosts...)} plan, err := p.EnvCreate(context.Background(), req) if err != nil { t.Fatal(err) @@ -109,8 +116,7 @@ func TestEnvAddResumesExistingHost(t *testing.T) { map[string]string{"description": "battleship: base=gw-v1 dns=router"}) f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=vmbr0", "description": "battleship: ip=192.168.100.77 os=linux base=debian-12-v1 dns=router"}) - hs, _ := ParseHostSpec("teak=debian-12") - plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hostSpecs(t, "teak=debian-12")}) if err != nil { t.Fatal(err) } @@ -130,8 +136,7 @@ func TestEnvAddBlocksResumeOfAnotherKind(t *testing.T) { f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=vmbr0", "description": "battleship: ip=192.168.100.77 os=linux base=debian-12-v1 dns=router"}) for _, spec := range []string{"teak=win2022", "teak=gw"} { - hs, _ := ParseHostSpec(spec) - plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hostSpecs(t, spec)}) if err != nil { t.Fatal(err) } @@ -156,9 +161,8 @@ func TestEnvAddResumesTheExistingRouter(t *testing.T) { f := envFake() f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, map[string]string{"description": "battleship: base=gw-v1 dns=router"}) - hs, _ := ParseHostSpec("oak=win2022") plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), - EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}, Hosts: []HostSpec{hs}}) + EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}, Hosts: hostSpecs(t, "oak=win2022")}) if err != nil { t.Fatal(err) } @@ -208,8 +212,7 @@ func TestEnvAddUsesTheEnvironmentsDNSHost(t *testing.T) { map[string]string{"description": "battleship: base=gw-v1 dns=teak"}) f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=devint01", "description": "battleship: ip=192.168.100.10 os=linux base=debian-12-v1 dns=teak"}) - hs, _ := ParseHostSpec("oak=debian-12") - plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hostSpecs(t, "oak=debian-12")}) if err != nil { t.Fatal(err) } @@ -225,11 +228,7 @@ func TestEnvAddBlocksANameTakenOutsideThePool(t *testing.T) { f.Add(proxmox.VM{VMID: 2100, Name: "gw.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha;router"}, map[string]string{"description": "battleship: base=gw-v1 dns=router"}) f.Add(proxmox.VM{VMID: 300, Name: "teak.kilo.alpha", Node: "alder"}, nil) - var hosts []HostSpec - for _, s := range []string{"teak=debian-12", "oak=debian-12"} { - hs, _ := ParseHostSpec(s) - hosts = append(hosts, hs) - } + hosts := hostSpecs(t, "teak=debian-12", "oak=debian-12") plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hosts}) if err != nil { t.Fatal(err) @@ -290,11 +289,7 @@ func TestEnvAddInAFullSlot(t *testing.T) { for id := 2101; id <= 2199; id++ { f.Add(proxmox.VM{VMID: id, Name: fmt.Sprintf("other%d", id), Node: "alder"}, nil) } - var hosts []HostSpec - for _, s := range []string{"teak=debian-12", "oak=win2022"} { - hs, _ := ParseHostSpec(s) - hosts = append(hosts, hs) - } + hosts := hostSpecs(t, "teak=debian-12", "oak=win2022") plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Router: HostSpec{Host: "gw", Family: "gw"}, Hosts: hosts}) if err != nil { t.Fatal(err) @@ -319,11 +314,7 @@ func TestEnvAddWithNoAddressLeft(t *testing.T) { f.Add(proxmox.VM{VMID: 30000 + o, Name: fmt.Sprintf("h%d.kilo.alpha", o), Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, map[string]string{"description": fmt.Sprintf("battleship: ip=192.168.100.%d os=linux base=debian-12-v1 dns=router", o)}) } - var hosts []HostSpec - for _, s := range []string{"teak=debian-12", "oak=win2022"} { - hs, _ := ParseHostSpec(s) - hosts = append(hosts, hs) - } + hosts := hostSpecs(t, "teak=debian-12", "oak=win2022") plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hosts}) if err != nil { t.Fatal(err) @@ -354,8 +345,7 @@ func TestEnvAddResumesAHostWithoutAnAddress(t *testing.T) { map[string]string{"description": "battleship: base=gw-v1 dns=router"}) f.Add(proxmox.VM{VMID: 2101, Name: "teak.kilo.alpha", Node: "alder", Pool: "dev-01", Tags: "dev;kilo.alpha"}, map[string]string{"net0": "virtio=BC:24:11:00:21:01,bridge=devint01", "description": "battleship: os=linux base=debian-12-v1 dns=router"}) - hs, _ := ParseHostSpec("teak=debian-12") - plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: []HostSpec{hs}}) + plan, err := NewPlanner(f, envConfig()).EnvAdd(context.Background(), EnvRequest{Domain: "kilo.alpha", Hosts: hostSpecs(t, "teak=debian-12")}) if err != nil { t.Fatal(err) } diff --git a/internal/pods/liveaddr_test.go b/internal/pods/liveaddr_test.go index cb2155d..6dd35a3 100644 --- a/internal/pods/liveaddr_test.go +++ b/internal/pods/liveaddr_test.go @@ -644,33 +644,6 @@ func TestLiveAddrsSSHWarnings(t *testing.T) { } } -// sshAgent is a fake whose SSH checks exit with exitCode; it keeps the -// command each VM's check ran. -type sshAgent struct { - *podstest.Fake - exitCode int - mu sync.Mutex - cmds map[int][]string -} - -func (a *sshAgent) AgentRead(ctx context.Context, node string, vmid int, command []string) (int, error) { - a.mu.Lock() - if a.cmds == nil { - a.cmds = map[int][]string{} - } - a.cmds[vmid] = command - a.mu.Unlock() - return a.Fake.AgentRead(ctx, node, vmid, command) -} - -func (a *sshAgent) AgentExecStatus(ctx context.Context, node string, vmid, pid int, limit int64) (proxmox.ExecStatus, error) { - st, err := a.Fake.AgentExecStatus(ctx, node, vmid, pid, limit) - if st.Exited { - st.ExitCode = a.exitCode - } - return st, err -} - // The SSH check runs the Windows command on a host whose notes say Windows // or whose agent reports Windows' loopback interface, and the POSIX one on // the rest. @@ -683,12 +656,15 @@ func TestLiveAddrsSSHCheckCommand(t *testing.T) { host := func(vmid int, os string) EnvHost { return EnvHost{VMID: vmid, Node: "alder", Status: "running", Agent: true, LANMAC: lanMAC, Notes: Notes{OS: os}} } - a := &sshAgent{Fake: f} - NewPlanner(a, envConfig()).LiveAddrs(context.Background(), + NewPlanner(f, envConfig()).LiveAddrs(context.Background(), []Environment{{Hosts: []EnvHost{host(2110, ImageLinux), host(2111, ImageWindows), host(2112, "")}}}, 3, time.Second) + cmds := map[int][]string{} + for _, c := range f.SSHChecks { + cmds[c.VMID] = c.Command + } for vmid, windows := range map[int]bool{2110: false, 2111: true, 2112: true} { - if !slices.Equal(a.cmds[vmid], SSHCheckCommand(windows)) { - t.Errorf("%d: SSH check %q, want the windows=%v one", vmid, a.cmds[vmid], windows) + if !slices.Equal(cmds[vmid], SSHCheckCommand(windows)) { + t.Errorf("%d: SSH check %q, want the windows=%v one", vmid, cmds[vmid], windows) } } } @@ -700,9 +676,9 @@ func TestLiveAddrsSSHCheckExit(t *testing.T) { f := podstest.New("alder") f.Add(proxmox.VM{VMID: 2110, Name: "2110", Node: "alder", Status: "running"}, nil) f.SetGuest(2110, podstest.Guest{Up: true, NICs: []proxmox.GuestNIC{{MAC: lanMAC, IPs: podstest.IPs("192.168.100.10/24")}}, - SSHOut: "sshd=stopped\n===SSHD===\n"}) + SSHOut: "sshd=stopped\n===SSHD===\n", SSHExit: 1}) envs := []Environment{{Hosts: []EnvHost{{VMID: 2110, Node: "alder", Status: "running", Agent: true, LANMAC: lanMAC}}}} - got := NewPlanner(&sshAgent{Fake: f, exitCode: 1}, envConfig()).LiveAddrs(context.Background(), envs, 1, time.Second) + got := NewPlanner(f, envConfig()).LiveAddrs(context.Background(), envs, 1, time.Second) if got[2110].SSHWarning != "SSH not running" { t.Errorf("exit 1: SSHWarning = %q, want %q", got[2110].SSHWarning, "SSH not running") } diff --git a/internal/pods/podstest/agent.go b/internal/pods/podstest/agent.go index d7574c3..189c14a 100644 --- a/internal/pods/podstest/agent.go +++ b/internal/pods/podstest/agent.go @@ -29,6 +29,8 @@ type Guest struct { // SSHOut is what the live SSH check command prints; "" prints a running // sshd that trusts DefaultSSHCAKey. SSHOut string + // SSHExit is the live SSH check's exit code. + SSHExit int } // DefaultSSHCAKey is the synthetic OpenSSH CA public key a fake guest @@ -154,7 +156,8 @@ func (f *Fake) AgentExec(ctx context.Context, node string, vmid int, command []s st := proxmox.ExecStatus{Exited: true} switch { case isSSHCheck(command): - st.Out = g.SSHOut + f.SSHChecks = append(f.SSHChecks, ExecCall{VMID: vmid, Command: slices.Clone(command), Input: input}) + st.ExitCode, st.Out = g.SSHExit, g.SSHOut if st.Out == "" { st.Out = defaultSSHOut } diff --git a/internal/pods/podstest/podstest.go b/internal/pods/podstest/podstest.go index 9cc68b3..fc7d8d0 100644 --- a/internal/pods/podstest/podstest.go +++ b/internal/pods/podstest/podstest.go @@ -142,10 +142,12 @@ type Fake struct { Restarts map[int]Restart // Execs are the guest commands run, in order, except setup state reads // and SSH checks. - Execs []ExecCall - execs map[int]proxmox.ExecStatus // by PID - polls map[int]int // status reads, by PID - nextPID int + Execs []ExecCall + // SSHChecks are the live SSH check commands run, in order. + SSHChecks []ExecCall + execs map[int]proxmox.ExecStatus // by PID + polls map[int]int // status reads, by PID + nextPID int } // New returns an empty cluster whose online nodes are nodes. From 981a76258dbc70caa3cd35c90938453a9ca2c54f Mon Sep 17 00:00:00 2001 From: tire-fire <84106878+tire-fire@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:42:19 +0000 Subject: [PATCH 22/22] test: name the stop-report gate for what it waits on; drop a redundant helper comment --- internal/apply/templates_test.go | 8 ++++---- internal/pods/envplan_test.go | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/internal/apply/templates_test.go b/internal/apply/templates_test.go index 43b5e44..c66c7a5 100644 --- a/internal/apply/templates_test.go +++ b/internal/apply/templates_test.go @@ -641,14 +641,14 @@ func TestCopySeenOKBeforeTheStopIsCompleted(t *testing.T) { } f.StopHook = func(string) error { return tc.stopErr } // Once restartMaster has recorded the copy OK, the job is stopped; - // the restart goes on once the stop has stopped the copy. - copyStopped := make(chan struct{}) + // the restart goes on once stopCopy has reported how its stop went. + stopReported := make(chan struct{}) f.Gate = func(_ context.Context, key string) (func(), error) { if key != "config:9021" || !seenOK.CompareAndSwap(true, false) { return nil, nil } cancel() - <-copyStopped + <-stopReported return nil, nil } @@ -657,7 +657,7 @@ func TestCopySeenOKBeforeTheStopIsCompleted(t *testing.T) { ex.OnEvent = func(e Event) { rec.add(e) if e.Item == "teak.tango.delta.tpl" && e.Status == EventInfo && strings.Contains(e.Message, "the copy of teak.tango.delta") { - once.Do(func() { close(copyStopped) }) + once.Do(func() { close(stopReported) }) } } res := ex.Run(ctx, plan) diff --git a/internal/pods/envplan_test.go b/internal/pods/envplan_test.go index 217e027..6903c63 100644 --- a/internal/pods/envplan_test.go +++ b/internal/pods/envplan_test.go @@ -24,7 +24,6 @@ func envFake() *podstest.Fake { return f } -// hostSpecs parses each spec as ParseHostSpec does. func hostSpecs(t *testing.T, specs ...string) []HostSpec { t.Helper() var hosts []HostSpec