diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml new file mode 100644 index 00000000..41b987f4 --- /dev/null +++ b/.github/workflows/multiplane-acceptance.yml @@ -0,0 +1,221 @@ +name: multiplane-acceptance +# The multi-plane acceptance in CI mode (docs/operations/multiplane.md#ci-mode) +# on a disposable GitHub-hosted runner: three kind clusters, Milo, Karmada, kro, +# Flux and a privileged libvirt/QEMU site Pod. Both modes run their guests +# under KVM. It runs on demand, +# nightly, and on a pull request only when the multiplane-acceptance label is +# applied, never on every push. +on: + workflow_dispatch: + inputs: + mode: + description: Site provider + type: choice + options: [both, localvm, redfish] + default: both + schedule: + - cron: '23 5 * * *' + pull_request: + types: [labeled] +permissions: + contents: read +jobs: + acceptance: + if: github.event_name != 'pull_request' || github.event.label.name == 'multiplane-acceptance' + name: acceptance (${{ matrix.mode }}, ${{ matrix.group }}) + # Each suite runs as two shards on separate runners, after the same setup + # and core install scenarios: flux runs the Flux scenarios, release the + # reflection, release, reuse, deadline and rebuild scenarios. The + # acceptance job below passes only if every shard passed. A new suite is + # one more mode here and in the task selection below. + strategy: + fail-fast: false + matrix: + mode: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode != 'both' && format('["{0}"]', inputs.mode) || '["localvm","redfish"]') }} + group: [flux, release] + # A newer labeled run for the same pull request replaces an older one; + # nightly and manual runs never cancel each other. A cancelled run never + # counts as passed. + concurrency: + group: multiplane-acceptance-${{ github.event.pull_request.number || github.run_id }}-${{ matrix.mode }}-${{ matrix.group }} + cancel-in-progress: true + runs-on: ubuntu-24.04 + timeout-minutes: 120 + env: + FLEET_MULTIPLANE_RUNTIME: ci + FLEET_MULTIPLANE_DOCKER_CONTEXT: default + FLEET_MULTIPLANE_ARCH: amd64 + FLEET_MULTIPLANE_ACCEL: kvm + FLEET_MULTIPLANE_GROUP: ${{ matrix.group }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: {persist-credentials: false} + # A pull request run tests GitHub's merge of the head into the base. + - name: Record the tested commits + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: printf 'Tested commit %s for head %s\n' "$(git rev-parse HEAD)" "$HEAD_SHA" | tee -a "$GITHUB_STEP_SUMMARY" + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: {go-version-file: go.mod, cache: false} + # This job's own Go build cache: the readiness tests build with the race + # detector and the site binary without cgo, so a cache saved by another + # workflow holds neither. Keyed by commit, restoring the newest for the + # same go.sum. + # Saved after the build phase even when the run later fails, so a failing + # run still warms the next one. + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}-${{ github.sha }} + restore-keys: | + multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}- + multiplane-go-${{ matrix.mode }}- + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: {python-version: '3.12.12'} + - uses: imranismail/setup-kustomize@2ba527d4d055ab63514ba50a99456fc35684947f # v2 + with: {kustomize-version: 5.8.1} + - name: Install pinned kind, kubectl and task + run: | + set -euo pipefail + go install sigs.k8s.io/kind@v0.31.0 + go install github.com/go-task/task/v3/cmd/task@v3.53.1 + directory=$(mktemp -d) + trap 'rm -rf "$directory"' EXIT + cd "$directory" + curl --fail --location --retry 3 --max-time 60 -o kubectl https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl + curl --fail --location --retry 3 --max-time 60 -o kubectl.sha256 https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl.sha256 + echo "$(cat kubectl.sha256) kubectl" | sha256sum --check + chmod +x kubectl + mkdir -p "$HOME/.local/bin" + mv kubectl "$HOME/.local/bin/kubectl" + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + # The runner's disk has far more free space than the 12 GiB the harness + # requires in the Docker data root, and preflight checks it. + - name: Record runner capacity + run: | + { + echo "FLEET_MULTIPLANE_STATE_ROOT=$RUNNER_TEMP/fleet-multiplane" + echo "METRICS=$RUNNER_TEMP/runner-metrics" + } >> "$GITHUB_ENV" + nproc + free -m + df -h / /var/lib/docker + docker version --format 'docker {{.Server.Version}}' + # Hosted runners restrict /dev/kvm to the kvm group; grant the runner + # access, as GitHub documents for hardware acceleration. + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + ls -l /dev/kvm || true + - name: Sample runner memory + run: | + mkdir -m 0700 "$METRICS" + # Every 10 s: memory, swap, the run's container memory and free disk. Container + # names and byte counts only. The script expands in its own shell. + # shellcheck disable=SC2016 + nohup sh -c 'while :; do + printf "%s %s\n" "$(date -u +%FT%TZ)" "$(awk "/^(MemTotal|MemAvailable|SwapTotal|SwapFree):/ {printf \"%s=%s \", \$1, \$2}" /proc/meminfo)" >> "$1/meminfo.log" + docker stats --no-stream --format "{{.Name}} {{.MemUsage}}" 2>/dev/null | sed "s/^/$(date -u +%FT%TZ) /" >> "$1/containers.log" + printf "%s %s\n" "$(date -u +%FT%TZ)" "$(df -k --output=avail /var/lib/docker | tail -1)" >> "$1/disk.log" + sleep 10 + done' sh "$METRICS" >/dev/null 2>&1 & + echo $! > "$METRICS/sampler.pid" + - name: Run multi-plane acceptance (${{ matrix.mode }}) + timeout-minutes: 100 + env: + TASK: ${{ matrix.mode == 'localvm' && 'multiplane:acceptance' || 'multiplane:redfish-acceptance' }} + run: | + mkdir -m 0700 "$FLEET_MULTIPLANE_STATE_ROOT" + task "$TASK" + # A timeout or cancellation can stop run.sh before its own scan, so the + # evidence is scanned again here. A match is redacted in place, and the + # second scan must be clean before anything is uploaded. + - name: Record memory and secret-scan evidence + id: scan + if: always() + run: | + kill "$(cat "$METRICS/sampler.pid")" 2>/dev/null || true + sudo dmesg | grep -iE 'out of memory|oom-kill' > "$METRICS/oom.log" || true + python3 - "$METRICS" <<'PY' | tee "$METRICS/summary.txt" >> "$GITHUB_STEP_SUMMARY" + import pathlib, sys + m = pathlib.Path(sys.argv[1]) + rows = [dict(f.split('=') for f in l.split()[1:]) for l in (m / 'meminfo.log').read_text().splitlines()] if (m / 'meminfo.log').exists() else [] + if rows: + total = int(rows[0]['MemTotal:']) / 2**20 + low = min(int(r['MemAvailable:']) for r in rows) / 2**20 + swap = max(int(r['SwapTotal:']) - int(r['SwapFree:']) for r in rows) / 2**20 + print('Runner memory: %.1f GiB total, %.1f GiB peak used, %.1f GiB minimum available, %.2f GiB peak swap, %d samples' % (total, total - low, low, swap, len(rows))) + disk = [int(l.split()[1]) for l in (m / 'disk.log').read_text().splitlines()] if (m / 'disk.log').exists() else [] + if disk: + print('Runner disk: %.1f GiB minimum available in the Docker data root' % (min(disk) / 2**20)) + oom = (m / 'oom.log').read_text().strip().splitlines() if (m / 'oom.log').exists() else [] + print('Kernel OOM events: %d' % len(oom)) + PY + found=false + for state in "$FLEET_MULTIPLANE_STATE_ROOT"/fleet-multiplane.*; do + [ -d "$state/evidence" ] || continue + mkdir -p "$state/evidence/runner" + cp "$METRICS"/meminfo.log "$METRICS"/containers.log "$METRICS"/summary.txt "$METRICS"/oom.log "$METRICS"/disk.log "$state/evidence/runner/" 2>/dev/null || true + if ! python3 hack/multiplane/harness.py scan --state "$state"; then + redacted=true + python3 hack/multiplane/harness.py scan --state "$state" + fi + found=true + done + echo "found=$found" >> "$GITHUB_OUTPUT" + echo "redacted=${redacted:-false}" >> "$GITHUB_OUTPUT" + # Both shards of a mode build the same binaries; one save per commit is + # enough, and a second save of the same key is skipped. + - name: Save the Go build cache + if: always() && matrix.group == 'release' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}-${{ github.sha }} + # Only evidence/ is uploaded, never the private state directory. + - name: Upload sanitized evidence + if: always() && steps.scan.outcome == 'success' && steps.scan.outputs.found == 'true' + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: multiplane-evidence-${{ matrix.mode }}-${{ matrix.group }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/fleet-multiplane/fleet-multiplane.*/evidence/ + if-no-files-found: error + retention-days: 14 + # The job passes only if exactly one run recorded passed with every phase + # passed and teardown passed. A killed, timed-out or cancelled run fails. + - name: Verify the recorded result + if: always() + run: | + states=("$FLEET_MULTIPLANE_STATE_ROOT"/fleet-multiplane.*) + [ "${#states[@]}" -eq 1 ] && [ -d "${states[0]}" ] || { echo "expected exactly one run, found ${#states[@]}"; exit 1; } + python3 hack/multiplane/harness.py verify --state "${states[0]}" --group "$FLEET_MULTIPLANE_GROUP" + # A secret that reached evidence fails the job, even after its redaction. + - name: Fail on redacted evidence + if: always() && steps.scan.outputs.redacted == 'true' + run: | + echo 'evidence matched a retained secret and was redacted; see the scan step' + exit 1 + # The one result for a run: it fails unless every shard of every suite + # passed, including when a shard was skipped or cancelled. + acceptance-result: + name: acceptance + if: always() && (github.event_name != 'pull_request' || github.event.label.name == 'multiplane-acceptance') + needs: acceptance + # A newer labeled run replaces this one too, so a replaced run leaves no + # stale result beside the new one. + concurrency: + group: multiplane-acceptance-${{ github.event.pull_request.number || github.run_id }}-result + cancel-in-progress: true + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require every shard to pass + env: + RESULT: ${{ needs.acceptance.result }} + run: | + [ "$RESULT" = success ] || { echo "a multi-plane acceptance shard did not pass: $RESULT"; exit 1; } + echo 'every multi-plane acceptance shard passed' diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index ad806389..72264be3 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -32,7 +32,7 @@ func main() { func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-denials|dhcp-feed|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one attempt, for fault injection") @@ -49,6 +49,8 @@ func run() error { uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") pin := fs.String("pin", "", "the BMC's approved key digest; the probe connects only to that key (redfish-probe)") syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") + installationDeadline := fs.Duration("installation-deadline", 0, "replace the installation deadline for operations this coordinator admits (coordinator)") + skewMargin := fs.Duration("skew-margin", 0, "replace the margin after a deadline before the coordinator declares it exceeded (coordinator)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -61,10 +63,10 @@ func run() error { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() fmt.Println("coordinator: custody coordinator running") - return multiplane.Coordinate(ctx, config, func(err error) { + return multiplane.Coordinate(ctx, config, multiplane.CoordinatorOptions{InstallationDeadline: *installationDeadline, SkewMargin: *skewMargin}, func(err error) { fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) }) - case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse": + case "seed", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin) @@ -77,6 +79,8 @@ func run() error { return nil case "boot-service", "boot-denials", "dhcp-feed": return boot(os.Args[1], *origin, *extraMAC, *syncToken) + case "boot-withhold": + return armWithhold(fs.Arg(0)) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") @@ -142,8 +146,9 @@ func phase(name, configPath string, once bool) error { return err } action := map[string]func(context.Context) error{ - "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "install-b": r.InstallSecond, + "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "release": r.Release, "release-b": r.ReleaseSecond, "reuse": r.Reuse, + "admit-install-b": r.AdmitInstallSecond, "recovery-mismatch": r.RecoveryMismatch, "probe-unallocatable": r.ProbeUnallocatable, "tenant-isolation": r.TenantIsolation, }[name] last := "" for { @@ -154,10 +159,13 @@ func phase(name, configPath string, once bool) error { last = err.Error() fmt.Printf("%s: waiting: %v\n", name, err) } - if name == "admit-install" && errors.Is(err, multiplane.ErrAdmittedUnknown) { + if strings.HasPrefix(name, "admit-install") && errors.Is(err, multiplane.ErrAdmittedUnknown) { fmt.Println("Installation admitted and delivered; its result remains Unknown") return nil } + if err == nil && (name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation") { + return nil + } if err == nil { fmt.Println(name + ": verified local acceptance phase (synthetic authority)") return nil @@ -180,7 +188,8 @@ func redfishMode() bool { return os.Getenv("FLEET_SITE_PROVIDER") == "redfish" } // probe performs read-only Redfish discovery of one enrolled System and // prints only an outcome class. Exit codes: 0 discovered, 10 credential -// rejected, 11 capability unsupported, 12 identity mismatch. +// rejected, 11 capability unsupported, 12 identity mismatch, 13 TLS key +// other than the pin. func probe(endpoint, credentials, system, uuid, pin string) error { user, err1 := os.ReadFile(credentials + "/username") password, err2 := os.ReadFile(credentials + "/password") @@ -204,6 +213,9 @@ func probe(endpoint, credentials, system, uuid, pin string) error { case errors.Is(err, redfish.ErrUnsupported): fmt.Println("redfish-probe: required capability not advertised; no effect issued") os.Exit(11) + case errors.Is(err, redfish.ErrPinMismatch): + fmt.Println("redfish-probe: the BMC's TLS key does not match the pin; no request sent") + os.Exit(13) case errors.Is(err, redfish.ErrIdentity): fmt.Println("redfish-probe: enrolled identity not matched exactly; no effect issued") os.Exit(12) diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 459f59c8..9fce8af2 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -96,15 +96,16 @@ func vmConfig() (vmwork.Config, fixture.Enrollment, error) { default: return vmwork.Config{}, nil, errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") } - if accelerator == "kvm" { - if _, err := os.Stat("/dev/kvm"); err != nil { - return vmwork.Config{}, nil, err - } - } uri := os.Getenv("FLEET_LIBVIRT_URI") if !strings.HasPrefix(uri, "qemu:///system?socket="+libvirtSocketDir+"/") { return vmwork.Config{}, nil, errors.New("FLEET_LIBVIRT_URI must name the site's libvirt socket") } + // The worker starts no hypervisor itself: the runtime behind the socket + // does, and it checks its own device. A worker runs only against a + // runtime that published the same accelerator. + if err := runtimeAccelerator(libvirtSocketDir, accelerator); err != nil { + return vmwork.Config{}, nil, err + } var enrollment fixture.Enrollment decoder := json.NewDecoder(strings.NewReader(os.Getenv("FLEET_SITE_ENROLLMENT"))) decoder.DisallowUnknownFields() @@ -115,6 +116,19 @@ func vmConfig() (vmwork.Config, fixture.Enrollment, error) { return config, enrollment, nil } +// runtimeAccelerator checks that the VM runtime sharing dir published +// accelerator. +func runtimeAccelerator(dir, accelerator string) error { + data, err := os.ReadFile(filepath.Join(dir, "accelerator")) + if err != nil { + return errors.New("the site's VM runtime has not published its accelerator") + } + if published := strings.TrimSpace(string(data)); published != accelerator { + return fmt.Errorf("the site's VM runtime runs %s guests, not %s", published, accelerator) + } + return nil +} + // redfishBootServer is what the Redfish boot server needs: the artifacts it // serves, the image they are, the listener firmware reaches, and where it // records deliveries. It reads no enrollment or credential. @@ -245,7 +259,7 @@ func boot(command, origin, extraMAC, syncToken string) error { } return server.ServeDHCP(strings.TrimSpace(string(token))) } - return server.Serve(vmwork.DefaultBootWindow * 2) + return serveBoot(server.Handler(), vmwork.DefaultBootWindow*2) } if command == "dhcp-feed" { return errors.New("the DHCP reservation feed serves only a Redfish site") @@ -254,5 +268,6 @@ func boot(command, origin, extraMAC, syncToken string) error { if err != nil { return err } - return vm.ServeBoot(store) + // Emulated firmware takes minutes to fetch the installer. + return serveBoot(vm.BootHandler(store), vmwork.DefaultBootWindow) } diff --git a/cmd/fleet-multiplane/site_test.go b/cmd/fleet-multiplane/site_test.go new file mode 100644 index 00000000..59daaf6a --- /dev/null +++ b/cmd/fleet-multiplane/site_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +// TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator refuses a runtime +// that published nothing or another accelerator. +func TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator(t *testing.T) { + dir := t.TempDir() + if err := runtimeAccelerator(dir, "kvm"); err == nil { + t.Fatal("a runtime that published no accelerator was accepted") + } + if err := os.WriteFile(filepath.Join(dir, "accelerator"), []byte("tcg\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := runtimeAccelerator(dir, "kvm"); err == nil { + t.Fatal("a KVM worker accepted a TCG runtime") + } + if err := runtimeAccelerator(dir, "tcg"); err != nil { + t.Fatalf("a TCG worker refused a TCG runtime: %v", err) + } +} diff --git a/cmd/fleet-multiplane/withhold.go b/cmd/fleet-multiplane/withhold.go new file mode 100644 index 00000000..0d4a7428 --- /dev/null +++ b/cmd/fleet-multiplane/withhold.go @@ -0,0 +1,83 @@ +package main + +import ( + "errors" + "fmt" + "net/http" + "os" + "strings" + "time" +) + +// labWithholdEnv names the lab-only fault hook's arm file. Only the local +// multi-plane site's Flux source (config/site) sets it, on the boot service; +// no production root may reference that source. The hook lives in this +// acceptance binary, so no production binary contains it. +const labWithholdEnv = "FLEET_LAB_BOOT_WITHHOLD" + +// withhold denies every boot request while the arm file exists, so an +// admitted installation's firmware never receives its installer and the +// worker waits for a receipt until its deadline. The listener stays up, so +// the boot service stays Ready and kro still creates workers. It records no +// delivery evidence for a withheld request, but counts each denial in a file +// beside the arm file, so the lab can prove the hook withheld a boot. +// Without the variable it returns the handler unchanged. +func withhold(next http.Handler) http.Handler { + path := os.Getenv(labWithholdEnv) + if path == "" { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + if _, err := os.Stat(path); err == nil { + // The count is evidence only; a failed write still denies. + if f, err := os.OpenFile(path+deniedSuffix, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600); err == nil { + _, _ = f.WriteString("denied\n") + _ = f.Close() + } + w.Header().Set("Cache-Control", "no-store") + http.Error(w, "boot denied", http.StatusForbidden) + return + } + next.ServeHTTP(w, request) + }) +} + +// deniedSuffix names the file beside the arm file that counts denials. +const deniedSuffix = ".denied" + +// armWithhold creates or removes the arm file, and reports how many boots +// the hook denied since it was last armed. It runs in the boot service's +// container, through the cell API. +func armWithhold(action string) error { + path := os.Getenv(labWithholdEnv) + if path == "" { + return errors.New("the lab boot withhold hook is not configured") + } + switch action { + case "arm": + if err := os.Remove(path + deniedSuffix); err != nil && !os.IsNotExist(err) { + return err + } + return os.WriteFile(path, nil, 0o600) + case "denied": + data, err := os.ReadFile(path + deniedSuffix) + if err != nil && !os.IsNotExist(err) { + return err + } + fmt.Println(strings.Count(string(data), "\n")) + return nil + case "clear": + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + return errors.New("boot-withhold takes arm, clear or denied") +} + +// serveBoot listens on :8080 with the same bounds as the site's boot +// servers. The write bound covers emulated firmware fetching the initrd. +func serveBoot(handler http.Handler, window time.Duration) error { + server := &http.Server{Addr: ":8080", Handler: withhold(handler), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} + return server.ListenAndServe() +} diff --git a/cmd/fleet-multiplane/withhold_test.go b/cmd/fleet-multiplane/withhold_test.go new file mode 100644 index 00000000..cf6e9c83 --- /dev/null +++ b/cmd/fleet-multiplane/withhold_test.go @@ -0,0 +1,196 @@ +package main + +import ( + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func served(t *testing.T, handler http.Handler, path string) int { + t.Helper() + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + return recorder.Code +} + +var ok = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + +func TestWithholdIsOffWithoutTheLabVariable(t *testing.T) { + t.Setenv(labWithholdEnv, "") + if err := armWithhold("arm"); err == nil { + t.Fatal("the hook armed without its lab variable") + } + if code := served(t, withhold(ok), "/pxe/52-54-00-77-01-0a/boot.ipxe"); code != http.StatusOK { + t.Fatalf("an unconfigured hook changed the response: %d", code) + } +} + +func TestAnArmedWithholdDeniesEveryBootRequest(t *testing.T) { + path := filepath.Join(t.TempDir(), "withhold") + t.Setenv(labWithholdEnv, path) + handler := withhold(ok) + paths := []string{"/pxe/boot.ipxe", "/pxe/52-54-00-77-01-0a/boot.ipxe", "/0123456789abcdef/token/kernel", "/0123456789abcdef/token/installer.gz"} + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusOK { + t.Fatalf("an unarmed hook denied %s: %d", p, code) + } + } + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusForbidden { + t.Fatalf("an armed hook served %s: %d", p, code) + } + } + if data, err := os.ReadFile(path + deniedSuffix); err != nil || strings.Count(string(data), "\n") != len(paths) { + t.Fatalf("denials counted = %q, %v, want %d", data, err, len(paths)) + } + // Arming again starts a new count. + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path + deniedSuffix); !os.IsNotExist(err) { + t.Fatalf("arming kept the earlier count: %v", err) + } + if err := armWithhold("clear"); err != nil { + t.Fatal(err) + } + if err := armWithhold("clear"); err != nil { + t.Fatalf("clearing a cleared hook: %v", err) + } + if code := served(t, handler, paths[1]); code != http.StatusOK { + t.Fatalf("a cleared hook still denies: %d", code) + } +} + +// TestOnlyTheLabSiteSourceSetsTheWithholdHook keeps the hook out of +// production. The primary control is the binary: only this acceptance +// binary reads the variable, and no production image runs it. The test adds +// that only the boot service of the local multi-plane site's Flux source +// sets the variable, that no other configuration includes or points a Flux +// path at that source, and that no other package names the variable. +func TestOnlyTheLabSiteSourceSetsTheWithholdHook(t *testing.T) { + root := filepath.Join("..", "..") + var setters []string + err := filepath.WalkDir(filepath.Join(root, "config"), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + text := string(data) + if strings.Contains(text, labWithholdEnv) { + setters = append(setters, rel) + } + lab := strings.HasPrefix(rel, filepath.Join("config", "site")+string(filepath.Separator)) || strings.HasPrefix(rel, filepath.Join("config", "multiplane")+string(filepath.Separator)) + if !lab && filepath.Ext(path) != ".md" && strings.Contains(text, "config/site") { + t.Errorf("%s points at the lab site source", rel) + } + if !lab && filepath.Base(path) == "kustomization.yaml" { + for _, line := range strings.Split(text, "\n") { + entry := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "- ")) + if strings.HasPrefix(entry, "#") { + continue + } + if strings.Contains(entry, "/site") && !strings.Contains(entry, "/site-") || strings.Contains(entry, "multiplane") { + t.Errorf("%s references the lab site source: %s", rel, entry) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + want := filepath.Join("config", "site", "services", "services.yaml") + if len(setters) != 1 || setters[0] != want { + t.Fatalf("the hook is set in %v, want only %s", setters, want) + } + services, err := os.ReadFile(filepath.Join(root, want)) + if err != nil { + t.Fatal(err) + } + boot := strings.Index(string(services), "kind: Deployment\nmetadata:\n name: fleet-site-boot\n") + next := strings.Index(string(services)[boot+1:], "\n---") + if boot < 0 || next < 0 || !strings.Contains(string(services)[boot:boot+1+next], labWithholdEnv) { + t.Fatal("the hook is set outside the boot service's Deployment") + } + for _, dir := range []string{"internal", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, dir), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || filepath.Dir(path) == "." { + return err + } + if abs, _ := filepath.Abs(filepath.Dir(path)); abs == mustAbs(t, ".") { + return nil + } + data, err := os.ReadFile(path) + if err == nil && strings.Contains(string(data), labWithholdEnv) { + t.Errorf("%s names the lab hook", path) + } + return err + }) + if err != nil { + t.Fatal(err) + } + } +} + +func mustAbs(t *testing.T, path string) string { + t.Helper() + abs, err := filepath.Abs(path) + if err != nil { + t.Fatal(err) + } + return abs +} + +// TestNothingElseInTheRepositorySetsTheWithholdHook scans every tracked +// kind of file outside the docs: only this package, the lab boot service's +// one env entry, and the lab steps that arm and clear it may name the hook. +func TestNothingElseInTheRepositorySetsTheWithholdHook(t *testing.T) { + root := mustAbs(t, filepath.Join("..", "..")) + allowed := map[string]int{ + filepath.Join("config", "site", "services", "services.yaml"): 1, + filepath.Join("hack", "multiplane", "steps.sh"): -1, + } + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + if entry.IsDir() { + switch rel { + case ".git", "docs", filepath.Join("cmd", "fleet-multiplane"): + return filepath.SkipDir + } + return nil + } + if strings.HasSuffix(rel, ".md") { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + count := strings.Count(string(data), labWithholdEnv) + want, ok := allowed[rel] + switch { + case !ok && (count > 0 || strings.Contains(string(data), "boot-withhold")): + t.Errorf("%s names the lab boot hook", rel) + case ok && want >= 0 && count != want: + t.Errorf("%s sets the lab boot hook %d times, want %d", rel, count, want) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/config/multiplane/milo/base/milo.yaml b/config/multiplane/milo/base/milo.yaml index 0610c3e5..c38c3ee9 100644 --- a/config/multiplane/milo/base/milo.yaml +++ b/config/multiplane/milo/base/milo.yaml @@ -75,8 +75,10 @@ spec: enableServiceLinks: false containers: - name: apiserver - # Milo v0.32.5 (go.mod pin), native arm64 image. - image: ghcr.io/milo-os/milo@sha256:ec90618ecc723d6e175fbf49bc14292fd930be3e0251acb161c1166e6224279f + # Milo v0.32.5 (go.mod pin): the multi-arch index. It resolves to the arm64 + # manifest sha256:ec90618e… on Colima and the amd64 manifest + # sha256:5db875d3… in CI mode. + image: ghcr.io/milo-os/milo@sha256:3b4f2890491220c4c79731d9e9b350881ce15dcca9de15b9f511cd7e5323f609 args: - apiserver - --etcd-servers=http://milo-etcd-0.milo-etcd:2379 diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml index fd996eab..b06e319d 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -25,6 +25,9 @@ spec: # Workers are created only after dispatch is enabled. The acceptance uses # this to prove delivery and retention before any effect can start. dispatch: boolean | default=false + # The shared runtime's accelerator. Workers refuse a runtime that + # published another, and each installation's journal binds it. + accelerator: string | required=true status: bootOrigin: ${"http://" + bootService.spec.clusterIP + ":8080"} workerImage: ${hypervisor.spec.template.spec.containers[0].image} @@ -201,7 +204,7 @@ spec: imagePullPolicy: IfNotPresent command: [fleet-multiplane, site-worker, --handoff, "${handoff.metadata.name}", --cell, "${schema.spec.cell}"] env: - - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_LOCAL_VM_ACCEL, value: "${schema.spec.accelerator}"} # The site's enrollment of the Devices it serves. - name: FLEET_SITE_ENROLLMENT valueFrom: diff --git a/config/site/instance/dispatcher.yaml b/config/site/instance/dispatcher.yaml index 5bb6bdf5..77740c10 100644 --- a/config/site/instance/dispatcher.yaml +++ b/config/site/instance/dispatcher.yaml @@ -16,3 +16,4 @@ metadata: spec: cell: "${FLEET_CELL}" dispatch: ${FLEET_SITE_DISPATCH} + accelerator: "${FLEET_LOCAL_VM_ACCEL}" diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml index 258caa56..2abd7558 100644 --- a/config/site/redfish/services/bmc.yaml +++ b/config/site/redfish/services/bmc.yaml @@ -41,6 +41,8 @@ spec: env: - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + # Lab targets run only while the site runtime publishes this accelerator. + - {name: FLEET_LAB_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} - {name: HOME, value: /tmp} ports: - {name: redfish, containerPort: 8443} diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml index d1290c1a..49f24515 100644 --- a/config/site/services/services.yaml +++ b/config/site/services/services.yaml @@ -56,7 +56,7 @@ spec: imagePullPolicy: IfNotPresent command: [/usr/local/bin/fleet-site-runtime] env: - - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} securityContext: privileged: true @@ -100,9 +100,13 @@ spec: imagePullPolicy: IfNotPresent command: [fleet-multiplane, boot-service] env: - - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + # Lab-only fault hook: while this file exists the boot service + # withholds every boot, and stays Ready. The deadline scenario + # arms it with `fleet-multiplane boot-withhold`. + - {name: FLEET_LAB_BOOT_WITHHOLD, value: /var/lib/fleet-boot/lab-withhold} ports: - {name: http, containerPort: 8080} readinessProbe: @@ -146,7 +150,7 @@ spec: imagePullPolicy: IfNotPresent command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --interval, 10s] env: - - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} securityContext: runAsUser: 0 allowPrivilegeEscalation: false diff --git a/docs/development/README.md b/docs/development/README.md index faf64def..d59b3565 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -36,7 +36,8 @@ Increment C, the cutover. Every mode allocates, installs and releases on `DeviceCustody`, with the custody coordinator as its only writer. The Secret-backed coordinator, its private records and the old executors are deleted, and an allocation's private facts live on its MachineAllocation. The standalone -smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. +smoke and both multi-plane runs verify it. The end-to-end failure scenarios +(Increment D) are implemented, and both multi-plane runs verify them. The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes the [local VM site](../operations/local-vm.md) with native Milo project APIs, the @@ -46,13 +47,13 @@ Each local cluster's [Flux](../operations/gitops.md) installs Milo, Karmada, kro an OCI artifact staged from the checkout. Run it with `task multiplane:acceptance`. Its exit codes, bounded phases and sanitized `evidence/` directory are documented there; `task multiplane:test-harness` runs its -offline tests, which CI also runs. Verification of that run on custody is -pending. The Redfish site workers (`internal/site/redfishwork`) read each +offline tests, which CI also runs. The run passes every phase on custody. The +Redfish site workers (`internal/site/redfishwork`) read each Device's own credential and connect only to its approved TLS key. [Redfish-mode acceptance](../operations/redfish-lab.md) (`task multiplane:redfish-acceptance`) exercises them against the unmodified DMTF -Redfish Interface Emulator and a lab-only libvirt adapter, and its verification is -pending too. They are not qualified against a physical BMC or server, and the +Redfish Interface Emulator and a lab-only libvirt adapter, and that run passes +every phase on custody too. They are not qualified against a physical BMC or server, and the production manager does not use them. Production Kustomize roots now package the implemented manager, admission, API, diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9a8f0d78..71e36863 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -15,7 +15,7 @@ marked **implemented and verified**, **implemented and inert**, or | A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and verified**, except the capacity projector, which is **implemented and inert**. Verified with unit tests and with tests against a real API server. Increment C wires the rest into every mode. | | B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | | C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | -| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | +| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | ## What Increment A adds @@ -381,6 +381,52 @@ event. - Bootstrap stays refused (O10). - `DeviceRecovery` needs no second person. +## Failure scenarios (Increment D) + +Both multi-plane runs, local VM and Redfish, run the #174 acceptance tests +end to end. The [coverage +inventory](../../test/acceptance/coverage.md#device-custody-and-operations) maps +each test to its phase, and the [multi-plane +phases](../operations/multiplane.md#acceptance-phases) describe each one. + +| Scenario | How the run produces it | +| --- | --- | +| Importing sends nothing | Checked before any allocation: no operation, assignment, worker Job, journal entry or BMC effect | +| Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | +| Contention | Custody names the one MachineAllocation, the winner's | +| Tenant isolation | The losing consumer's project has no Device API, and an installation for its unheld allocation is refused before delivery | +| Deadline | The coordinator restarts with a short installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | +| Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | +| Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | +| A wipe settles the hold | The release wipe is admitted above the held fence after the worker stopped | +| Rebuild | Custody is deleted while the site observer is stopped, so no fence report arrives | +| Pin mismatch | The Redfish probe connects with another key's digest and reaches no request | + +The scenarios found two site gaps, both fixed: + +- **A worker stopped at its deadline left its boot admission open** until the + boot window expired, so the server could still fetch the installer when + nothing could resume or observe the operation. Both workers now close it at + the deadline. A worker stopped from outside still leaves it open for its + replacement. +- **The local VM wipe refused to run while a guest was up**, so it could never + settle an installation stopped at its deadline, which leaves its guest + running. The wipe now powers the guest off first, as a Redfish wipe does, + and still refuses if the guest keeps running. + +The shorter installation deadline is a flag of the acceptance binary's +coordinator, and only the deadline scenario sets it. The boot hook lives in +the acceptance binary's boot service, and only the local multi-plane site's +Flux source configures it, which no production root may reference. +`TestOnlyTheLabSiteSourceSetsTheWithholdHook` fails if any production root +references that source or any other package names it, and +`TestNothingElseInTheRepositorySetsTheWithholdHook` fails if any file outside +the docs, the acceptance binary and the lab steps names it, or the boot +service sets it more than once. The hook counts each boot it denies, and the +`deadline-hold` phase requires at least one denial, so a boot that never +arrived for another reason does not pass as withheld. The emulator lab's limits +are listed in the coverage inventory. + ## Implementation decisions Each decision lists the open point from the implementation brief it settles. @@ -938,7 +984,8 @@ a real API server: | CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | Increment A has no site, so "nothing was sent" means custody admitted nothing -and the fence did not rise. Increment D proves it with the lab BMC audit. +and the fence did not rise. Increment D's phases prove it end to end, with the +site journal and, in the Redfish run, the lab BMC audit. Both local end-to-end runs include the `custody-crd-rules` phase. It proves that a Milo project API refuses every write the CRD rules forbid, which @@ -968,14 +1015,35 @@ Increment C's tests run with `task test:envtest`, and the smoke runs with | An allocation that never held its Device is deleted and the allocator selects again | `TestAnAllocationThatLostItsDeviceIsReplaced` | | The quota claim is named from the Machine and granted once; release is observed, not assumed | `TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce`, `TestReleaseIsObservedNotAssumed` | | Federation: an assignment's round trip, only this cell's observation accepted, a stale fence report ignored, a cell runs only its own assignments | `TestAssignmentRoundTrip`, `TestReflectionIsRejectedUnlessItIsThisCellsObservation`, `TestAStaleFenceReportIsNoReport`, `TestTheCellRunsOnlyItsOwnAssignments` | -| The local VM site: install then wipe, a wipe with a running domain not proven, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipeWithARunningDomainIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | +| The local VM site: install then wipe, a wipe that powers off a running guest first and is not proven while the guest keeps running, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | | Synchronized DHCP follows the open admission; a worker waits for the reservation and for its withdrawal | `TestSyncedDHCPFollowsTheOpenAdmission` | | The simulator site's token, enrollment and server bounds | `TestReadToken`, `TestReadEnrollmentRequiresCompleteTargets`, `TestNewServerHasFiniteResourceBounds` | | The manager's synthetic flags, and the creator webhook's trusted caller | `TestSyntheticFlagsRequireAndScopeStaging`, `TestRemovedSingleProjectFlagsAreRejected`, `TestWebhookRequiresTrustedAPIServerClient` | | Where the component ships | `TestComponentRoots` | | The standalone smoke: contention, install, a simulator restart and recovery, reinstall, release with a wipe, reuse, and the role checks that keep one writer per kind | `task standalone:test` | +Increment D's site tests run with `go test -race ./internal/site/...`: + +| Area | Tests | +| --- | --- | +| A worker stopped at its deadline closes its boot admission, in both workers | `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission` | +| A local VM wipe powers off a running guest, and is not proven while it keeps running | `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven` | + +Increment D also adds coordinator tests, run with `task test:envtest`, that +fail if the use of site fence reports is weakened. Each was checked against +the change it guards: + +| Guard | Test | +| --- | --- | +| A recovery on a Device that no site serves is never confirmed | `TestARecoveryOnADeviceNoSiteServesIsNeverConfirmed` | +| A recovery records the lowest fence its sites confirmed, and waits for every site | `TestARecoveryConfirmsTheLowestFenceOfItsSites` | +| A Resolve raises custody's fence above every fence a site has seen | `TestAResolveRaisesTheFenceAboveEverySeenFence` | + +`TestFencesFollowTheSiteReport` already fails if admission ignores the seen +fence, if a recovery is confirmed by the seen fence alone, or if an +unreported site counts as confirmed. + The multi-plane local VM and Redfish runs (`task multiplane:acceptance` and -`task multiplane:redfish-acceptance`) run the same workers. Their verification -is pending. The acceptance state of each #174 test is in the [coverage +`task multiplane:redfish-acceptance`) run the same workers and the failure +scenarios. The acceptance state of each #174 test is in the [coverage inventory](../../test/acceptance/coverage.md#device-custody-and-operations). diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index c4bfd7b6..9f842409 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -50,9 +50,9 @@ per-allocation fencing with one custody record per Device, ahead of real hardware qualification. Increment A (the control-plane foundation), Increment B (site execution) and Increment C (the cutover) are implemented. C moves every mode onto custody and deletes the Secret-backed path. An allocation's private -facts live on its MachineAllocation. The standalone smoke verifies C. Verification -of the two multi-plane runs, local VM and Redfish, is pending. Increment D -(end-to-end failure scenarios) is proposed. +facts live on its MachineAllocation. The standalone smoke and both multi-plane +runs, local VM and Redfish, verify C. Increment D (end-to-end failure +scenarios) is implemented, and both multi-plane runs verify it. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local end-to-end runs, with "nothing sent" proven by the lab BMC audit. diff --git a/docs/operations/README.md b/docs/operations/README.md index 915aab13..faa1907b 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -14,8 +14,8 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Build and test locally or run the simulator | [Implementation commands](../development/README.md#build-test-and-run) | Behavior of the implemented code and synthetic provider | | Exercise allocation, install recovery, release with a wipe, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle on Device custody, with a simulator site and namespaces as project stand-ins | | Understand the local VM site that the multi-plane run drives | [Local VM site](local-vm.md) | The workers that install a real OS over firmware PXE into a disposable libvirt domain, boot it from disk, and wipe it; the single-plane harness is retired; not KVM or hardware qualification | -| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; verification of the run on the custody path is pending; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | -| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; verification of the run is pending; not physical BMC or hardware qualification | +| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; the run on the custody path passes every phase; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | +| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; the run on custody passes every phase; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-Device BMC endpoints and provisioning attachments, a reservation feed read from the site store that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md index 7d32b86b..91c1c14a 100644 --- a/docs/operations/gitops.md +++ b/docs/operations/gitops.md @@ -122,7 +122,7 @@ hash. | Source | OCI artifact `fleet-gitops:local` in the run registry, `registry:3.0.0@sha256:6c5666b8…457e` | The Flux OCI pattern Datum uses for `*-kustomize` bundles, with no external publication of uncommitted changes | | Karmada | chart v1.16.0 from `HelmRepository` `raw.githubusercontent.com/karmada-io/karmada/master/charts`; chart archive SHA-256 `773ab194…34fe` verified in Flux's HelmChart artifact | Same chart as the connected test-infra federation. The repository and release shape follow datum-cloud/infra `infrastructure/karmada`. The chart's floating `cfssl` and `kubectl` hook images are now pinned by index digest. | | kro | `OCIRepository` `oci://registry.k8s.io/kro/charts/kro` at manifest digest `sha256:4e8de4d3…a67c` (chart layer `ceeb6307…`), image `v0.9.4@sha256:eaf9fbad…` | Unchanged from [site execution](site-execution.md#versions); `OCIRepository` as a chart source is the Flux-native way to pin an OCI chart by digest | -| Milo | `ghcr.io/milo-os/milo@sha256:ec90618e…` (v0.32.5, arm64); etcd `registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11c…` | Same Milo build as before, now as Flux-managed workloads | +| Milo | `ghcr.io/milo-os/milo@sha256:3b4f2890…` (v0.32.5 multi-arch index: arm64 on Colima, amd64 in CI mode); etcd `registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11c…` | Same Milo build as before, now as Flux-managed workloads | ## Dependency, health and upgrade policy diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 64929739..ff1dc7b0 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -10,7 +10,7 @@ not KVM or hardware qualification. Status: **implemented**. The standalone smoke does not use it. The [multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) runs it, -and verification of that run after the cutover is pending. +and that run passes every phase after the cutover. ## The single-plane harness is retired diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 7bcdfe81..8b29262d 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -10,8 +10,8 @@ artifact built from the checkout; see [Flux-reconciled local environment](gitops production overlay. Production authority and deployment equivalence remain **unqualified**. -Status: the run on Device custody is **implemented**. Verification of the local VM -run and of the [Redfish run](redfish-lab.md) on custody is pending. The run +Status: the run on Device custody is **implemented and verified**: the local VM +run and the [Redfish run](redfish-lab.md) both pass every phase on custody. The run records under [Verification and remaining gaps](#verification-and-remaining-gaps) were observed on the path before the cutover, with the Secret-backed coordinator, and are not evidence for the custody path. @@ -34,7 +34,7 @@ and reach two persistent lab VMs only through the DMTF Redfish Interface Emulato | Coordination intent | Karmada v1.16.0 API (hub Flux `HelmRelease`), separate from the host Kubernetes API | The coordinator's credential creates immutable handoffs and labels them answered; it cannot write status | | Selected cell | Separate kind Kubernetes API running its own Flux, the Flux-owned shared site services, kro v0.9.4 and the `HandoffDispatcher` graph | Karmada delivers intent; the site observer ServiceAccount is the only local status writer | | Reflected results | Karmada interpreter aggregates each member's identity and observation | Karmada; management validates before projection | -| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG | One bounded kro-created worker Job per assignment runs the site worker; the site store holds each Device's fence, journal and results, and the boot evidence, on a retained, Flux-owned PVC | +| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG on Colima, or under KVM on an amd64 runner in [CI mode](#ci-mode) | One bounded kro-created worker Job per assignment runs the site worker; the site store holds each Device's fence, journal and results, and the boot evidence, on a retained, Flux-owned PVC | The platform integration choices were discovered in these connected sources: @@ -121,12 +121,19 @@ Exit codes and `evidence/result.json` status: | Exit | Status | Meaning | Resources | | --- | --- | --- | --- | -| 0 | `passed` | Every phase and evidence assertion passed | Owned containers, clusters and image tag deleted; private credentials removed | +| 0 | `passed` | Every phase and evidence assertion passed, and the run reached its last line | Owned containers, clusters and image tag deleted; private credentials removed | +| 0 | `preflight-passed` | `--preflight-only`: every prerequisite is present; no acceptance ran | None created | | 1 | `failed` | A phase or assertion failed | Owned containers stopped, state retained, custody Unknown | | 2 | `preflight-failed` | A local prerequisite is missing | None created | | 3 | `blocked` | Implementation readiness gate failed | None created | | 4 | `timeout` | A bounded phase expired; its process group was terminated | Stopped and retained as for 1 | | 64 | `usage` | Invalid option | None created | +| 129, 130, 143 | `interrupted` | The run received HUP, INT or TERM. It stops every phase it started, records the phase it was in as `interrupted`, and names it as the failed phase | Stopped and retained as for 1 | +| 1 | `interrupted` | The run exited 0 before its last line, so nothing proves it finished | Stopped and retained as for 1 | + +Only a run that reaches its last line writes the completion marker the result +requires for `passed`. A result recorded as `passed` before this rule, by a run +that was interrupted, proves nothing. The full run uses three kind nodes (platform, hub, cell), a registry, Flux on each node, three small Milo/etcd pairs, Karmada and kro. Node caps are @@ -144,6 +151,92 @@ in the runtime Pod, any kind node, or the site, kro, Flux, Karmada or Milo conta mostly bootstrap, image pulls and builds. Every phase has an explicit bound. Do not run another full acceptance topology concurrently on an 8 GiB VM. +### CI mode + +The `multiplane-acceptance` workflow runs the same acceptance on a disposable +GitHub-hosted `ubuntu-24.04` runner, two shards per mode. Status: +**verified** for local VM mode under KVM; **implemented, not yet verified** +for Redfish mode under KVM and for the shards. Both modes passed unsharded on +a hosted runner, with Redfish mode under TCG. + +To run it, apply the `multiplane-acceptance` label to a pull request whose +branch contains the workflow. Each application starts one run of both modes, +and a newer run for the same pull request cancels the older one. Pushing to a +labeled pull request does not start a run, so its result goes stale: remove and +reapply the label to test the new head. The workflow +also runs nightly on `main`, and on demand from `main` with a `mode` input +(`both`, `localvm` or `redfish`). It never runs on every push. + +Explicit run parameters select the runtime. Their defaults are the Colima run +above, unchanged: + +| Variable | Default | CI value | +| --- | --- | --- | +| `FLEET_MULTIPLANE_RUNTIME` | `colima` | `ci` | +| `FLEET_MULTIPLANE_DOCKER_CONTEXT` | `colima-fleet-acceptance-tcg` | `default` | +| `FLEET_MULTIPLANE_ARCH` (site binary and runtime architecture) | `arm64` | `amd64` | +| `FLEET_MULTIPLANE_ACCEL` | `tcg` | `kvm` | +| `FLEET_MULTIPLANE_GROUP` (scenario group) | `all` | `flux` or `release`, one per shard | + +Lab timers shorten the waits the scenarios provoke, in every runtime. Each +scenario still proves the same outcome, and production defaults are unchanged: + +| Variable | Default | Production | Scenario | +| --- | --- | --- | --- | +| `FLEET_MULTIPLANE_INSTALLATION_DEADLINE` | `2m` | 40 minutes | The short-deadline installation ends `OutcomeUnknown` | +| `FLEET_MULTIPLANE_SKEW_MARGIN` | `30s` in CI mode, `2m` otherwise | 2 minutes | The coordinator waits this long past a deadline before declaring it exceeded | +| `FLEET_MULTIPLANE_FAIL_CLOSED_TIMEOUT` | `45s` | 3 minutes in the lab topology | The bad kro revision reports not Ready; the recovery revision restores the usual timeout | + +The skew margin covers clock skew between the coordinator and a site. In CI +mode every process reads one Linux kernel clock. A Colima VM's clock can drift +from the workstation's, so that run keeps the production margin. The deadline +scenario still requires the wipe to be admitted after the worker stopped. On a +host too slow to journal the installer boot and delete the Machine within the +deadline, the scenario fails saying so; raise +`FLEET_MULTIPLANE_INSTALLATION_DEADLINE` there. + +In CI mode, preflight requires a GitHub-hosted runner (`GITHUB_ACTIONS=true` and +`RUNNER_ENVIRONMENT=github-hosted`) and a context that points at +exactly `unix:///var/run/docker.sock`. It reads free disk, inotify and a readable, writable `/dev/kvm` +on the runner itself, and memory and CPUs from the runner's daemon. It never +calls Colima. Every other check still applies. Preflight fails closed on an +accelerator it cannot honor: KVM without an amd64 runtime or without +`/dev/kvm`, and any unknown value. `preflight.json` records the +parameters. + +Every component must agree on the accelerator. The site runtime refuses KVM +without `/dev/kvm`, with no software fallback, and publishes the accelerator it +runs. A worker runs only against a runtime that published its own accelerator, +and each installation's journaled boot admission binds it, so a replacement +worker never resumes an installation under another. Evidence then requires both +domain definitions and every QEMU command line to show the selected accelerator, +and `summary.json` records it. + +The workflow runs each suite as two shards on separate runners. Both shards +build the same topology and run the same scenarios up to the Pod and Job +lifecycle checks. The `flux` shard then runs the Flux scenarios: graph +lifecycle, drift, restart, fail-closed and retention. The `release` shard runs +the reflection faults, release, reuse, deadline, rebuild, wrong-location and +closed-boot scenarios. Each shard checks the evidence its scenarios produce: +the `flux` shard leaves the Device allocated, so the release, wipe and final +custody checks run in the `release` shard. A local run defaults to `all` and +runs every scenario in one topology. + +A shard passes only if exactly one run recorded `passed` with every phase +passed, teardown passed, the expected scenario group and no retained +container. The workflow's `acceptance` result passes only if every shard of +every suite passed. After the run, including +after a timeout or cancellation, the job scans the evidence for secrets again +and redacts any match. It uploads only `evidence/`, and only after a clean scan. +A match fails the job even after its redaction. +The evidence includes `runner/`, the runner's memory, swap and free disk in +the Docker data root sampled every 10 seconds, per-container memory, and any +kernel OOM events. Every tool and action is pinned. + +KVM on a GitHub-hosted runner is nested virtualization in a cloud VM. It is a +qualification target of its own, separate from the Colima TCG runs and from +physical hardware, and a pass in one qualifies neither of the others. + ### State and evidence layout All containers have one fresh `fleet-mp-` prefix. The command prints a @@ -155,12 +248,13 @@ mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with | `result.json` | Final status, exit code, failed phase, every phase record, retained containers, custody statement | | `phases.jsonl` | One record per bounded phase: name, status, exit code, bound, duration | | `preflight.json` | Each prerequisite and readiness check | -| `summary.json` | Pass only: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags | +| `summary.json` | Written when the evidence checks pass, with `acceptance: evidence-verified`: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags. It does not say the run passed; `result.json` does | | `flux-verify.json`, `flux-initial.json`, `flux-rbac-restore.json`, `flux-drift.json`, `flux-graph-lifecycle.json`, `flux-restart.json`, `flux-fail-closed.json`, `flux-retention.json`, `flux-final.json`, `flux-ownership-final.json`, `flux-reconciles.json`, `flux-partition.json`, `flux-reflection-suspension.json`, `gitops-r.SHA256SUMS` | Flux source revisions and digests, Ready/generation/revision of every Kustomization and HelmRelease, inventories and single-writer ownership, and each GitOps scenario ([details](gitops.md#acceptance-coverage)) | | `kro-rbac.json` | kro's allowed and denied verbs and each admission probe's outcome | | `custody-crd-rules.json` | Each forbidden custody or operation write and whether the provider project API refused it, and that the CRDs were removed | | `kubernetes-execution.json` | kro version, image and RGD/instance state; Flux-owned site Deployments; retained volume identity; every worker Job's UID, conditions, Pods, exit codes and policies; per-operation RBAC | | `interrupt.json`, `lifecycle.json`, `delivery-faults.json`, `wrong-location.json` | Scenario-specific observations, no secrets | +| `import-inert.json`, `staff-access.json`, `contention.json`, `release-waits.json`, `deadline-hold.json`, `deadline-settled.json`, `rebuild.json` | The #174 failure scenarios ([coverage](../../test/acceptance/coverage.md#device-custody-and-operations)) | | `source-SHA256SUMS`, `binary-SHA256SUMS`, `image-id`, `sysctl.json`, `teardown.json` | Tested inputs and teardown record | Before reporting, the harness scans `evidence/` for every retained static token, @@ -219,9 +313,22 @@ The phases are then: another Device. It then removes the objects and the CRDs. Milo ignores admission policies stored in a project, so this proves the rules hold there. It sends nothing to any server. + `import-inert` then requires that importing the Devices admitted, + delivered and sent nothing: no operation, allocation, assignment, worker + Job or journal entry, and custody with no operation, result or hold. In + Redfish mode the BMC audit must hold no effect. `staff-access` requires + the staff identity to read custody and list recoveries, and to be + forbidden Secrets, every other operation, allocations and custody writes. + Staff hold no consumer-project or hub credential. 2. **Contention.** Two consumers request one provider capacity. Custody grants one allocation; `verify-contention` independently reads Bound for A and - Pending/InsufficientCapacity for B. + Pending/InsufficientCapacity for B, and requires custody to name the one + MachineAllocation, A's. `tenant-isolation` then requires that B, which + holds nothing, cannot reach the server: its project serves no Device API, + and an installation the Metal provider names for its unheld allocation is + refused by custody admission for `HolderMismatch`. The fence, the site + store and, in Redfish mode, the BMC audit stay unchanged, and nothing is + delivered. 3. **Admission before effects.** The coordinator admits the `DeviceInstallation` and raises the Device's fence, then writes one immutable hub handoff carrying that exact assignment, before any effect. `await-delivery` requires the @@ -234,7 +341,14 @@ The phases are then: The cell's own Flux reconciles it from the registry with no hub access. kro creates the per-operation ServiceAccount, Role, RoleBinding and Job from its local replica. -5. **Pod interruption.** `interrupt-pod` waits until the Device's journal shows +5. **Pod interruption.** Before dispatch, `hold-installer` arms a watcher in the + runtime Pod. It suspends the installer guest as soon as its kernel prints, + and reports it missed if the guest printed its receipt first, so the + interruptions land mid-install at any accelerator speed. The guest is + therefore paused, not running, while its worker is lost. A guest that + finishes while no worker runs is covered by the site worker's unit tests and + by Redfish mode, not by this phase. `interrupt-pod` + requires that hold, then waits until the Device's journal shows the install's installer boot requested *and* its libvirt domain running. It then force-deletes the worker Pod with no grace period. It requires: - no local result; @@ -243,12 +357,16 @@ The phases are then: - the same unfinished operation. 6. **Job interruption.** `interrupt-job` deletes the whole worker Job as soon as the replacement exists, still mid-install. kro must recreate the Job under - a new UID for the same operation. + a new UID for the same operation. `release-installer` then resumes the + guest, which still has printed no receipt, and records the hold in + `interrupt.json`. Evidence fails without it. Redfish mode holds lab target A + the same way, from its append-only console, through the BMC interruption + as well. 7. **Exact resume.** `resume` requires the recreated Job to be `Complete` with one succeeded Pod, and the observer to publish the stored `Succeeded` result. The Device's journal must show the installer boot requested exactly once. Evidence later proves exactly one firmware-network installer start followed by exactly one disk-only start. - It uses libvirt's append-only QEMU log, plus one `sfdisk`, one installer + It uses libvirt's append-only QEMU log, plus one partition marker, one installer receipt and one disk-boot receipt in the guest serial logs. `worker-rbac` then proves the worker token can read only its own handoff: no list, no other names, no status or spec writes, no Secrets, no site writes. @@ -316,24 +434,48 @@ The phases are then: Each of the last two creates a kro Job that must fail once with exit 65 by `podFailurePolicy`. The site store must be unchanged, no status may appear, - consumer B must stay Bound, and kro must prune them once deleted. After B - installs and is released, `release-status-b` repeats the released checks for - B. -14. **Wrong location.** With capacity free, the consumer A customer recreates its + consumer B must stay Bound, and kro must prune them once deleted. In + Redfish mode the BMC audit must gain no effect. +14. **Deadline and Machine deletion.** `deadline-admit` arms a lab-only hook + in the boot service, which then withholds every boot while staying Ready, + and restarts the coordinator with the lab installation deadline for + consumer B's installation only. kro still creates the worker, and the + installer boot is requested but never served. `machine-delete` has the + customer delete B's Machine mid-install. One release pass must leave + custody holding the Device for release with the installation still active + and no wipe. `deadline-hold` requires the hook to have denied at least + one boot request, and the installation to end + `OutcomeUnknown` with `DeadlineExceeded`, custody to hold it at its fence, + and its worker to have stopped. A staff `DeviceRecovery` naming the + held operation at the wrong fence must be refused for `HoldMismatch`, with custody, the site + store and, in Redfish mode, the BMC audit unchanged. The hook is then + cleared. The release's wipe must be admitted above the held fence + after the worker stopped, succeed, and clear the hold. `release-status-b` + requires the deleted Machine to be gone. +15. **Custody rebuild.** `rebuild` stops the site observer, so the cell cannot + report its fence, and deletes the free Device's custody as the provider + bootstrap admin. The coordinator must rebuild it `Unverified`, and a new + consumer A Machine must find no eligible capacity and record no + allocation. Once Flux restores the observer, custody must become + `Verified` with a fence above every fence the site stored. +16. **Wrong location.** With capacity free, the consumer A customer recreates its request with `locationRef: remote-elsewhere`. Allocation must fail with the location-not-served error. The custody records, the site store's state, and the Machine's finalizers and status must be unchanged. Free capacity rules out contention as the reason for denial. -15. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the +17. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the boot Service are denied after closure. Evidence requires all of: - - PXE mode, one install and two wipes, each `Succeeded` at its own fence, with - the fences strictly increasing; + - PXE mode, one install and two wipes, each `Succeeded` at its own fence, + and B's installation `OutcomeUnknown` at its deadline, with the fences + strictly increasing; - completed broker writes and a DHCP lease for the installer NIC; - network-only installer XML, and disk XML with no NIC or direct kernel; - closed boot admission, no remaining domain or disk; - - kro-created, `Complete` worker Jobs for exactly the one install and two - wipes, each with one successful Pod; + - kro-created, `Complete` worker Jobs for exactly these four operations, + each with one successful Pod; + - custody `Verified` with no holder at the rebuilt fence, and only the + refused recovery; - zero OOM kills. -16. **Final convergence and teardown.** `flux-final` requires all three +18. **Final convergence and teardown.** `flux-final` requires all three clusters at the last revision with nothing suspended, and repeats the single-writer ownership audit. After a pass, only exact-prefix resources are deleted, the inotify value is restored, and private credentials are removed. @@ -350,7 +492,7 @@ hack/multiplane/teardown.sh /tmp/fleet-multiplane.REPLACE --discard-unknown ``` `teardown.sh` without `--discard-unknown` refuses unless `summary.json` records -a pass. `--discard-unknown` is an explicit human decision after inspection: it +verified acceptance evidence. `--discard-unknown` is an explicit human decision after inspection: it deletes the same exact-prefix resources, keeps every private file, and records in `teardown.json` that it is not release evidence. Neither script touches other prefixes. The original limit of 128 inotify instances was insufficient for this @@ -478,7 +620,7 @@ path before the cutover to Device custody. They used the Secret-backed coordinator, a site-wide provider journal and a single-writer `executor.Client`. They show what the earlier composition proved, and the Flux, kro and Karmada findings there still describe the same infrastructure. They are not evidence for -the custody path. Verification of the local VM run on custody is pending. +the custody path. The local VM and Redfish runs on custody pass every phase. ### Flux-owned shared site acceptance (2026-11-16) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 029fadc1..7e7cc631 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -15,7 +15,7 @@ is the same pipeline: Status: the Redfish workers are **implemented and verified** by unit tests, including against TLS BMC stubs. The multi-plane Redfish run on custody is -**implemented**, and its verification is pending. The execution records at the +**implemented and verified**: it passes every phase. The execution records at the end of this page describe runs on the path before the cutover. It is a **local MVP proof**, not hardware qualification. No physical server, BMC, @@ -35,6 +35,15 @@ Prerequisites, exit codes, the state and evidence layout, `--keep`, [multi-plane harness](multiplane.md#run). Redfish mode also needs network access to GitHub release archives, Docker Hub and PyPI to build the lab BMC image. +Redfish mode also runs in [CI mode](multiplane.md#ci-mode), as the `redfish` +job of the `multiplane-acceptance` workflow, with the lab targets under KVM. +Status: implemented, not yet verified under KVM. +The lab adapter defines and starts a target only while the site runtime +publishes the accelerator the adapter was given, and evidence requires every +QEMU command line of target A to show it. KVM on a cloud runner is its own +qualification target, separate from the Colima runs below and from physical +hardware. + ## Upstream emulator and provenance | Item | Pin | @@ -96,7 +105,7 @@ upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. ```text cell Flux layers (Redfish overlays of config/site) fleet-site-runtime (privileged) fleet-site-bmc (unprivileged, all caps dropped) - libvirtd + QEMU TCG ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter + libvirtd + QEMU ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter lab-target-a lab-target-b ▲ Redfish over TLS (pinned key), Basic auth (persistent disks, serial capture) │ Service 10.96.0.81:8443 │ firmware DHCP/iPXE (static) │ @@ -332,7 +341,7 @@ These are documented lab seams, not production designs: `hack/multiplane/acceptance-redfish.sh` runs every scenario of the [libvirt-mode sequence](multiplane.md#acceptance-phases) through the same federation and kro path, with these differences. The phase descriptions follow the -harness at this change; verification of the run on custody is pending. +harness at this change, and the run on custody passes every phase. **Before topology:** @@ -351,23 +360,24 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | Phase | What it proves | | --- | --- | | `redfish-baseline` | Both target disks exist and neither target was ever started; records target B's disk digest | -| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. The BMC audit shows only GETs in the window. | +| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. A TLS key other than the pin exits 13 and reaches no request. The BMC audit shows only GETs in the window. | | `redfish-bmc-interrupt` | As soon as the installer is running, the BMC Pod is force-deleted and replaced. The guest keeps running; the worker tolerates a bounded BMC outage. | | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | | `resume` | The recreated Job completes the exact operation with one succeeded Pod | -| `install-b` | After the wipe and reuse, consumer B installs on the same physical target under a higher fence with a new receipt | +| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under the lab installation deadline with the lab boot hook armed. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | | `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | -| `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | +| `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes, and no domain is running, except in the `flux` scenario group, which runs no release; there target B must not be running. Exports the BMC audit. | The final `evidence` phase adds these independent checks in Redfish mode: - **Console.** Target A's console holds exactly one receipt line per boot, in - operation order: install, disk boot, wipe, install, disk boot, wipe. -- **QEMU.** libvirt's append-only log shows exactly six starts of target A, in - the boot order network, disk, network, network, disk, network (read from + operation order: install, disk boot, wipe, wipe. B's held installation + prints none. +- **QEMU.** libvirt's append-only log shows exactly five starts of target A, in + the boot order network, disk, network, network, network (read from `bootindex`), and none of target B. -- **BMC audit.** Exactly six effective `On` requests, all to System-1, of which +- **BMC audit.** Exactly five effective `On` requests, all to System-1, of which exactly one carried the lost-response fault. - **Kubernetes and admission.** Every worker Job selects the Redfish provider with no hypervisor mount or URI, and the admission probes denied each @@ -444,8 +454,8 @@ kustomize and checks the following: The records below describe runs on the path before the cutover to Device custody, with the old executor, a site-wide journal and a shared credential over plain HTTP. They show what the lab and the harness proved then. They are not evidence -for the Redfish workers. The multi-plane Redfish run on custody is implemented, -and its verification is pending. +for the Redfish workers. The multi-plane Redfish run on custody is implemented +and passes every phase. ### Attempts before the first pass (2026-11-16) diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 134e3035..439868af 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -357,8 +357,8 @@ journal in the site store. ## Implemented versus proposed Rows marked "exercised" were observed in runs on the path before the cutover to -Device custody. The same phases now run on custody. Verification of that run is -pending. +Device custody. The same phases now run on custody, and that run passes every +phase. | Behavior | Status | | --- | --- | @@ -371,7 +371,7 @@ pending. | Pod/Job lifecycle not changing the site store, guest or allocation | Implemented and exercised | | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | A credential broker so no worker holds a long-lived BMC credential | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | -| Redfish workers with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md). Verification of the run on custody is pending. | +| Redfish workers with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode and verified by the Redfish run on custody; see [Redfish-mode acceptance](redfish-lab.md). | | Synchronized DHCP boot reservations with served and withdrawn evidence, read from the site store | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | | Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | | Per-Device fence store and journal, older-worker stop with a confirmation, worker deadlines, fenced typed results, per-Device credentials with the approved TLS pin, and the operation handoff payload ([device custody](../development/device-custody.md#site-execution-increment-b)) | Implemented: unit tested, and every site runs it since the cutover. The multi-plane run on it awaits verification. | diff --git a/hack/local-vm/init b/hack/local-vm/init index a4303d6b..56c2d598 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -35,6 +35,9 @@ if [ "$mode" = wipe ]; then fi [ "$mode" = install ] || /bin/busybox poweroff -f printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda +# One line, in one write, once the disk is partitioned: the shell trace above +# reaches the console in pieces the kernel's own messages can split. +printf 'FLEET-PARTITIONED:%s\n' "$receipt" mkfs.ext4 -F /dev/vda1 mkdir -p /target mount /dev/vda1 /target diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index 3f85135c..bf4899ad 100755 --- a/hack/local-vm/site-runtime +++ b/hack/local-vm/site-runtime @@ -2,13 +2,20 @@ # VM runtime for the Kubernetes site: libvirtd only. Workers reach it through # the socket directory shared on the site volume; nothing listens on TCP. set -eu -[ "${FLEET_LOCAL_VM_ACCEL:-}" = tcg ] || { echo 'site runtime requires FLEET_LOCAL_VM_ACCEL=tcg' >&2; exit 1; } +accel=${FLEET_LOCAL_VM_ACCEL:-} +case "$accel" in + tcg) ;; + kvm) [ -c /dev/kvm ] && [ -r /dev/kvm ] && [ -w /dev/kvm ] || { echo 'KVM device unavailable; no automatic software fallback' >&2; exit 1; } ;; + *) echo 'site runtime requires FLEET_LOCAL_VM_ACCEL=tcg or kvm' >&2; exit 1 ;; +esac boot_ip=${FLEET_BOOT_IP:?boot Service ClusterIP required} case "$boot_ip" in *[!0-9.]*|'') echo 'invalid boot Service IP' >&2; exit 1 ;; esac sock=/run/fleet-libvirt mkdir -p "$sock" /run/libvirt /var/lib/libvirt/images /var/log/libvirt/qemu # A previous runtime Pod's socket is stale; libvirtd recreates it. rm -f "$sock"/libvirt-sock "$sock"/libvirt-sock-ro "$sock"/libvirt-admin-sock +# Workers refuse to run unless the runtime they reach publishes their accelerator. +printf '%s\n' "$accel" > "$sock/accelerator.tmp" && mv "$sock/accelerator.tmp" "$sock/accelerator" # Firmware on the provisioning bridge may reach this namespace (DHCP) and the # boot Service only. Anything else forwarded from the bridge is dropped. iptables -t mangle -N FLEET-PXE 2>/dev/null || iptables -t mangle -F FLEET-PXE diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 475f3933..54e316d2 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -6,27 +6,37 @@ set -euo pipefail umask 077 state=${1:?private state directory} -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_SITE_PROVIDER=redfish +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} FLEET_SITE_PROVIDER=redfish host="$state/fleet-multiplane-host" ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } +# Scenario group (docs/operations/multiplane.md#ci-mode). Every group runs the +# ungated scenarios and each gated block below that names it; +# all runs every block. +group=${FLEET_MULTIPLANE_GROUP:-all} +runs() { [[ $group == all || $group == "$1" ]]; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" +step import-inert 300 +step staff-access 120 rf baseline 300 rf discovery-faults 600 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 +step tenant-isolation 300 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" step await-delivery 300 rf arm-lost-response 120 step partition 300 +step hold-installer 120 step dispatch 900 rf bmc-interrupt 600 step interrupt-pod 1200 step interrupt-job 600 +step release-installer 120 rf lost-response 1200 step resume 2400 step worker-rbac 120 @@ -35,22 +45,30 @@ step heal 1200 ph install 900 "$host" install --config "$state/acceptance.json" ph install-repeat 900 "$host" install --config "$state/acceptance.json" step lifecycle 900 -flux graph-lifecycle 1200 -flux drift 900 -flux restart 1200 -flux fail-closed 1500 -flux retention 1500 -ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" -ph release 2400 "$host" release --config "$state/acceptance.json" -step release-status-a 120 -ph reuse 900 "$host" reuse --config "$state/acceptance.json" -step reuse-status 120 -step delivery-faults 900 -ph install-b 2400 "$host" install-b --config "$state/acceptance.json" -ph release-b 2400 "$host" release-b --config "$state/acceptance.json" -step release-status-b 120 -step wrong-location 300 -step boot-denials 300 +if runs flux; then + flux graph-lifecycle 1200 + flux drift 900 + flux restart 1200 + flux fail-closed 1500 + flux retention 1500 +fi +if runs release; then + ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" + ph release 2400 "$host" release --config "$state/acceptance.json" + step release-status-a 120 + ph reuse 900 "$host" reuse --config "$state/acceptance.json" + step reuse-status 120 + step delivery-faults 900 + step deadline-admit 1200 + step machine-delete 300 + step deadline-hold 1500 + ph release-b 2400 "$host" release-b --config "$state/acceptance.json" + step deadline-settled 300 + step release-status-b 120 + step rebuild 1200 + step wrong-location 300 + step boot-denials 300 +fi step flux-final 900 rf isolation 600 ph evidence 600 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 8bfc31c3..caa69773 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -4,22 +4,32 @@ set -euo pipefail umask 077 state=${1:?private state directory} -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} host="$state/fleet-multiplane-host" ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } +# Scenario group (docs/operations/multiplane.md#ci-mode). Every group runs the +# ungated scenarios and each gated block below that names it; +# all runs every block. +group=${FLEET_MULTIPLANE_GROUP:-all} +runs() { [[ $group == all || $group == "$1" ]]; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" +step import-inert 300 +step staff-access 120 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 +step tenant-isolation 300 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" step await-delivery 300 step partition 300 +step hold-installer 120 step dispatch 900 step interrupt-pod 1200 step interrupt-job 600 +step release-installer 120 step resume 1800 step worker-rbac 120 step partition-readiness 900 @@ -27,20 +37,29 @@ step heal 1200 ph install 900 "$host" install --config "$state/acceptance.json" ph install-repeat 900 "$host" install --config "$state/acceptance.json" step lifecycle 900 -flux graph-lifecycle 1200 -flux drift 900 -flux restart 1200 -flux fail-closed 1500 -flux retention 1500 -ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" -ph release 1200 "$host" release --config "$state/acceptance.json" -step release-status-a 120 -ph reuse 900 "$host" reuse --config "$state/acceptance.json" -step reuse-status 120 -step delivery-faults 900 -ph release-b 1200 "$host" release-b --config "$state/acceptance.json" -step release-status-b 120 -step wrong-location 300 -step boot-denials 300 +if runs flux; then + flux graph-lifecycle 1200 + flux drift 900 + flux restart 1200 + flux fail-closed 1500 + flux retention 1500 +fi +if runs release; then + ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" + ph release 1200 "$host" release --config "$state/acceptance.json" + step release-status-a 120 + ph reuse 900 "$host" reuse --config "$state/acceptance.json" + step reuse-status 120 + step delivery-faults 900 + step deadline-admit 1200 + step machine-delete 300 + step deadline-hold 1500 + ph release-b 2400 "$host" release-b --config "$state/acceptance.json" + step deadline-settled 300 + step release-status-b 120 + step rebuild 1200 + step wrong-location 300 + step boot-denials 300 +fi step flux-final 900 ph evidence 300 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/coordinator.sh b/hack/multiplane/coordinator.sh index 3e77ed76..802cdfbc 100755 --- a/hack/multiplane/coordinator.sh +++ b/hack/multiplane/coordinator.sh @@ -13,7 +13,16 @@ case $action in echo "coordinator: already running" exit 0 fi - nohup "$state/fleet-multiplane-host" coordinator --config "$state/acceptance.json" >>"$state/coordinator.log" 2>&1 &2; exit 64; } + nohup "$state/fleet-multiplane-host" coordinator --config "$state/acceptance.json" "--skew-margin=$skew" "${@:3}" >>"$state/coordinator.log" 2>&1 "$pidfile" sleep 2 kill -0 "$(cat "$pidfile")" || { echo 'coordinator: exited at start; see coordinator.log in the state directory' >&2; exit 1; } @@ -30,5 +39,9 @@ case $action in fi echo "coordinator: stopped" ;; - *) echo 'usage: coordinator.sh start|stop STATE' >&2; exit 64 ;; + restart) + "$0" stop "$state" + "$0" start "$state" "${@:3}" + ;; + *) echo 'usage: coordinator.sh start|stop|restart STATE [coordinator flags]' >&2; exit 64 ;; esac diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 318f0767..5ef5357f 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -20,7 +20,13 @@ s = pathlib.Path(sys.argv[1]) prefix = (s / 'prefix').read_text().strip() ev = s / 'evidence' -os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' +os.environ['DOCKER_CONTEXT'] = os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT', 'colima-fleet-acceptance-tcg') +# The run parameters; the guest evidence below must show the accelerator. +ACCEL, RUNTIME, GROUP = harness.ACCEL, harness.RUNTIME, harness.GROUP +# The installer prints this with its receipt once it has partitioned the +# disk. A kernel message can still share the line, so it is found mid-line; +# the shell's trace of that printf shows the format, not a receipt. +PARTITIONED = re.compile(r'FLEET-PARTITIONED:([0-9a-f]{64})') REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' @@ -82,52 +88,79 @@ def copy_out(source, destination): 'kro created the worker Job and per-operation RBAC', 'worker-rbac: per-operation ServiceAccount', 'interrupt-pod: worker Pod force-deleted', 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', - 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine Released', + 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine deleted', + 'import-inert: ', 'tenant-isolation: consumer B\'s project has no Device API', 'staff-access: staff read custody', 'contention-custody: custody holds the Device for the one MachineAllocation', + 'deadline-admit: the second installation was admitted', 'release-waits: the Machine is deleting', 'deadline-hold: the installation ended OutcomeUnknown at its deadline', + 'recovery-mismatch: refused', 'deadline-settled: the release wipe was admitted', 'rebuild-unverified: custody rebuilt Unverified', + 'probe-unallocatable: no eligible capacity while custody is Unverified', 'rebuild-verified: custody Verified', 'wrong-location: denied before allocation', 'Flux restored the binding', 'flux-verify: 3 clusters Ready', 'cell Flux applied the dispatch revision', 'Flux restored consumer-a', 'Flux on every cluster Ready at the current revision', 'flux-drift: helm-controller restored kro', 'recreated the shared boot Service at its fixed ClusterIP and restored the observer', 'flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects', 'kro RBAC and admission confine it to per-operation objects', 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in REFLECTION_FAULTS) +# Markers only one scenario group prints. Every group prints the rest. +FLUX_MARKERS = ('flux-drift: helm-controller restored kro', 'recreated the shared boot Service at its fixed ClusterIP and restored the observer', + 'flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects', 'flux-restart: every Flux controller', + 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', 'flux-retention: removing the volume claim') +RELEASE_MARKERS = ('delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', + 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine deleted', + 'deadline-admit: the second installation was admitted', 'release-waits: the Machine is deleting', 'deadline-hold: the installation ended OutcomeUnknown at its deadline', + 'recovery-mismatch: refused', 'deadline-settled: the release wipe was admitted', 'rebuild-unverified: custody rebuilt Unverified', + 'probe-unallocatable: no eligible capacity while custody is Unverified', 'rebuild-verified: custody Verified', + 'wrong-location: denied before allocation') + tuple(m + ': management rejected' for m in REFLECTION_FAULTS) +if not set(FLUX_MARKERS + RELEASE_MARKERS) <= set(markers): + fail('a group marker is not an acceptance marker') +skipped = RELEASE_MARKERS if GROUP == 'flux' else FLUX_MARKERS if GROUP == 'release' else () if REDFISH: markers += ('bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified', 'bmc-self-test: upstream emulator and lab adapter self-test passed', 'redfish-enroll: synthetic per-Device BMC credentials', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', 'redfish-lost-response: On took effect but its response was lost', 'redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install', - 'install-b: verified', 'redfish-isolation: target B never started') + 'a TLS key other than the pin reached no request', 'redfish-isolation: target B never started') for marker in markers: - if marker not in phases: + if marker not in skipped and marker not in phases: fail('missing acceptance phase: ' + marker) def site_operations(raw): """The Device's journaled operations from the copied site store, matched to the provider project's operations by site key: kind, name and fence. Expected order: consumer A's - install, A's release wipe, (Redfish: consumer B's install,) B's release - wipe, with strictly increasing fences, each Succeeded at its fence.""" + install, A's release wipe, consumer B's install, held at its deadline, + and B's release wipe, with strictly increasing fences. Each operation + but the held one Succeeded at its fence; that one is returned apart.""" store = json.loads((raw / 'site' / 'devices' / harness.device_dir().rsplit('/', 1)[1] / 'state.json').read_text()) journaled = harness.sanitized_operations(store, redfish=REDFISH) # Operations by site key; custody and allocations by kind and name. provider = {(i['kind'] + '/' + i['metadata']['name'] if i['kind'] in ('DeviceCustody', 'MachineAllocation') else harness.provider_key(i)): i for i in harness.custody(s)} - ops = [] + held_key = json.loads((s / 'deadline-install.json').read_text())['key'] + ops, held = [], None + if [o['fence'] for o in journaled] != sorted({o['fence'] for o in journaled}): + fail('journaled fences are not strictly increasing: %s' % [o['fence'] for o in journaled]) for o in journaled: p = provider.get(o['operation']) + if o['operation'] == held_key: + st = (p or {}).get('status', {}) + if not p or p['kind'] != 'DeviceInstallation' or o['done'] or st.get('phase') != 'OutcomeUnknown' or st.get('reason') != 'DeadlineExceeded' or st.get('fence') != o['fence']: + fail('the deadline installation is not held OutcomeUnknown at its fence: %s' % {k: st.get(k) for k in ('phase', 'reason', 'fence')}) + held = dict(o, name=p['metadata']['name'], allocation=p['spec']['authority']['allocationRef']['name'], phase=st['phase']) + continue if not p or p['kind'] != o['kind'] or not o['done']: fail('journaled operation %s is not a finished provider %s' % (o['operation'], o['kind'])) st = p.get('status', {}) if st.get('phase') != 'Succeeded' or st.get('fence') != o['fence']: fail('%s %s is %s at fence %s, journaled at fence %s' % (p['kind'], p['metadata']['name'], st.get('phase'), st.get('fence'), o['fence'])) ops.append(dict(o, name=p['metadata']['name'], allocation=p['spec']['authority']['allocationRef']['name'], phase=st['phase'])) - fences = [o['fence'] for o in ops] - if fences != sorted(set(fences)): - fail('operation fences are not strictly increasing: %s' % fences) - return store, ops, provider + if held is None: + fail('the site journal holds no deadline installation') + return store, ops, provider, held -def check_sequence(ops, interrupt): - """Consumer A's allocation holds the interrupted install; the other is B's.""" +def check_sequence(ops, held, interrupt): + """Consumer A's allocation holds the interrupted install; the other is B's, + whose installation was held at its deadline.""" a = next((o['allocation'] for o in ops if o['operation'] == interrupt['operationID']), None) b = next((o['allocation'] for o in ops if o['allocation'] != a), None) - want = [('DeviceInstallation', a), ('DeviceWipe', a)] + ([('DeviceInstallation', b)] if REDFISH else []) + [('DeviceWipe', b)] - if not a or not b or [(o['kind'], o['allocation']) for o in ops] != want: + want = [('DeviceInstallation', a), ('DeviceWipe', a), ('DeviceWipe', b)] + if not a or not b or held['allocation'] != b or [(o['kind'], o['allocation']) for o in ops] != want: fail('expected %s, got %s' % (want, [(o['kind'], o['allocation']) for o in ops])) if any(o['kind'] == 'DeviceWipe' and o['name'] != o['allocation'] + '-wipe-1' for o in ops): fail('a release wiped the Device other than with its first wipe step') @@ -147,10 +180,14 @@ def custody_evidence(store, ops, provider, a, b): spec = custody['spec'] if spec.get('state') != 'Verified' or spec.get('holder', {}).get('type') != 'None' or spec.get('activeOperation') or spec.get('recoveryHold'): fail('final custody is not Verified with no holder, operation or hold: %s' % {k: spec.get(k) for k in ('state', 'holder', 'activeOperation', 'recoveryHold')}) - if spec.get('fence') != ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: - fail('custody fence %s, site fence %s/%s and the last operation fence %s differ' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) - if any(i['kind'] == 'DeviceRecovery' for i in provider.values()): - fail('a DeviceRecovery exists after an uninterrupted lifecycle') + # Custody was rebuilt after the last operation, with a fence above every + # fence the site stored. + rebuilt = json.loads((ev / 'rebuild.json').read_text()) + if spec.get('fence') != rebuilt['verifiedFence'] or spec['fence'] <= ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: + fail('custody fence %s, site fence %s/%s and the last operation fence %s do not follow the rebuild' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) + recoveries = [i for i in provider.values() if i['kind'] == 'DeviceRecovery'] + if len(recoveries) != 1 or recoveries[0].get('status', {}).get('phase') != 'Failed' or recoveries[0]['status'].get('reason') != 'HoldMismatch' or recoveries[0]['status'].get('fence'): + fail('expected only the mismatched recovery, refused for HoldMismatch and never admitted') record = {'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'device': harness.DEVICE, 'custody': {'state': spec['state'], 'holder': spec['holder'], 'fence': spec['fence'], 'activeOperation': None, 'recoveryHold': None, 'rejectedResults': spec.get('rejectedResults')}, @@ -177,9 +214,11 @@ def libvirt_provider(): copy_out('/var/lib/fleet-local', raw) copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') - store, ops, provider = site_operations(raw) + store, ops, provider, held = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) - a, b = check_sequence(ops, interrupt) + if not interrupt.get('installerHold', {}).get('held') or interrupt['installerHold'].get('domain') != interrupt.get('domain'): + fail('the interruptions did not land while the installer guest was held') + a, b = check_sequence(ops, held, interrupt) installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] @@ -190,6 +229,8 @@ def libvirt_provider(): boot = boot_record(raw, 'vmboot', harness.key(uid)) if not boot.get('closed') or boot.get('open') or boot.get('fence') != o['fence']: fail('boot admission not closed at the install fence') + if boot.get('accelerator') != ACCEL: + fail('the journal bound accelerator %s, not %s' % (boot.get('accelerator'), ACCEL)) log = raw / 'boot-evidence' / harness.key(uid) / 'boot-delivery.log' written = log.read_text() if log.exists() else '' for name in ('boot.ipxe', 'kernel', 'installer.gz'): @@ -201,8 +242,9 @@ def libvirt_provider(): if lines.count(marker + boot['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: fail('expected exactly one exact guest receipt in ' + filename) receipts.append({'operation': uid, 'fence': o['fence'], 'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) - if sum(1 for l in (directory / 'installer.log').read_text(errors='replace').splitlines() if re.match(r'^\+ sfdisk /dev/vda', l.strip())) != 1: - fail('installer partitioned the disk other than exactly once') + partitions = PARTITIONED.findall((directory / 'installer.log').read_text(errors='replace')) + if partitions != [boot['receipt']]: + fail('installer partitioned the disk %d times, not exactly once for this operation' % len(partitions)) installer, disk = (directory / 'installer.xml').read_text(), (directory / 'disk.xml').read_text() if "boot dev='network'" not in installer or '' in installer or '' in installer: fail('installer domain is not firmware network boot only') @@ -216,7 +258,13 @@ def libvirt_provider(): blocks = [b for b in re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:]] network = [b for b in blocks if '-netdev' in b and '52:54:00:77:00:02' in b] disk_only = [b for b in blocks if '-netdev' not in b and 'virtio-disk0' in b] - starts[uid] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} + # Every component ran the selected accelerator: both domain definitions + # and every QEMU command line libvirt logged. + domain_types = {re.match(r"=3.12', sys.version_info >= (3, 12), sys.version.split()[0] + ' (evidence extraction uses the tarfile data filter)') + check('runtime-mode', RUNTIME in ('colima', 'ci'), 'FLEET_MULTIPLANE_RUNTIME=%s; colima or ci' % RUNTIME) + if RUNTIME == 'ci': + # The run adjusts host kernel settings and fills the Docker data root: + # only a disposable runner, never a workstation's daemon. + check('ci-runner', os.environ.get('GITHUB_ACTIONS') == 'true' and os.environ.get('RUNNER_ENVIRONMENT') == 'github-hosted', + 'CI mode runs only on a disposable GitHub-hosted runner (GITHUB_ACTIONS=true, RUNNER_ENVIRONMENT=github-hosted)') + check('runtime-parameter:architecture', ARCH in DOCKER_ARCHITECTURES, 'FLEET_MULTIPLANE_ARCH=%s; arm64 or amd64' % ARCH) + # KVM runs the amd64 guest natively, so it needs an amd64 runtime. + accel_ok = ACCEL == 'tcg' or (ACCEL == 'kvm' and ARCH == 'amd64') + check('accelerator', accel_ok, 'FLEET_MULTIPLANE_ACCEL=%s; tcg, or kvm with an amd64 runtime' % ACCEL) + check('scenario-group', GROUP in GROUPS, 'FLEET_MULTIPLANE_GROUP=%s; %s' % (GROUP, ', '.join(GROUPS))) code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) - endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) - if not endpoint_ok and args.bootstrap and shutil.which('colima'): + endpoint_ok = endpoint_matches(code, out) + if not endpoint_ok and RUNTIME == 'colima' and args.bootstrap and shutil.which('colima'): # Only start an existing task-owned profile with its saved configuration. code, out, err = capture(['colima', 'list', '--json'], 30, cwd='/') known = any(json.loads(line).get('name') == PROFILE for line in out.splitlines() if line.strip().startswith('{')) if code == 0 else False @@ -114,16 +148,16 @@ def check(name, ok, detail='', kind='preflight'): code, _, err = capture(['colima', 'start', '--profile', PROFILE], 600, cwd='/') check('bootstrap:colima-start', code == 0, 'started existing profile ' + PROFILE if code == 0 else err.strip()[-300:]) code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) - endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) - check('docker-context', endpoint_ok, CONTEXT + ' must point at the task-owned Colima profile socket; never fleet-e2e-x86') + endpoint_ok = endpoint_matches(code, out) + check('docker-context', endpoint_ok, CONTEXT + (' must point at the runner daemon ' + CI_ENDPOINT if RUNTIME == 'ci' else ' must point at the task-owned Colima profile socket; never fleet-e2e-x86')) info = {} if endpoint_ok: code, out, err = capture(['docker', 'info', '--format', '{{json .}}'], 30) - if check('docker-reachable', code == 0, 'start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if code else 'reachable'): + if check('docker-reachable', code == 0, ('start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if RUNTIME == 'colima' else 'the runner daemon is unreachable') if code else 'reachable'): info = json.loads(out) if info: - check('runtime-architecture', info.get('Architecture') in ('aarch64', 'arm64'), '%s (the Milo image pin is native arm64)' % info.get('Architecture')) + check('runtime-architecture', info.get('Architecture') in DOCKER_ARCHITECTURES.get(ARCH, ()), '%s; FLEET_MULTIPLANE_ARCH=%s' % (info.get('Architecture'), ARCH)) check('runtime-memory', int(info.get('MemTotal', 0)) >= 7_800_000_000, '%.2f GiB; 8 GiB required' % (int(info.get('MemTotal', 0)) / 2**30)) check('runtime-cpus', int(info.get('NCPU', 0)) >= 4, '%s CPUs; 4 required' % info.get('NCPU')) code, out, _ = capture(['docker', 'ps', '--format', '{{.Names}}'], 30) @@ -136,6 +170,9 @@ def check(name, ok, detail='', kind='preflight'): limit = vm_inotify() opted = os.environ.get('FLEET_MULTIPLANE_INOTIFY') == '1024' check('inotify-instances', limit is not None and (limit >= 1024 or opted), 'current %s; requires >=1024 or FLEET_MULTIPLANE_INOTIFY=1024 (reversible task-VM adjustment)' % limit) + if ACCEL == 'kvm': + check('kvm-device', vm_exec('test -c /dev/kvm && test -r /dev/kvm && test -w /dev/kvm && echo present') == 'present', + 'a readable and writable /dev/kvm on the Docker host; no automatic software fallback') root = pathlib.Path(args.root) main = (root / 'cmd/fleet-multiplane/main.go') @@ -152,13 +189,27 @@ def check(name, ok, detail='', kind='preflight'): pre = [c for c in checks if c['kind'] == 'preflight' and not c['ok']] ready = [c for c in checks if c['kind'] == 'readiness' and not c['ok']] code = EXIT_PREFLIGHT if pre else EXIT_BLOCKED if ready else EXIT_PASSED - write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks}) + write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks, + 'runtime': {'mode': RUNTIME, 'dockerContext': CONTEXT, 'architecture': ARCH, 'accelerator': ACCEL}, 'group': GROUP}) for c in checks: print('%-4s %-34s %s' % ('ok' if c['ok'] else 'FAIL', c['name'], c['detail'])) return code +def endpoint_matches(code, out): + """Whether the context reaches exactly the selected runtime's daemon.""" + if code != 0: + return False + if RUNTIME == 'ci': + return out.strip() == CI_ENDPOINT + return RUNTIME == 'colima' and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + + def vm_exec(command, timeout=30): + """A read-only command on the Docker host: the Colima VM, or the runner itself in CI mode.""" + if RUNTIME == 'ci': + code, out, _ = capture(['sh', '-c', command], timeout, cwd='/') + return out.strip() if code == 0 else None if not shutil.which('colima'): return None code, out, _ = capture(['colima', 'ssh', '--profile', PROFILE, '--', 'sh', '-c', command], timeout, cwd='/') @@ -192,56 +243,77 @@ def phase(args): started = time.monotonic() record = {'name': args.name, 'startedAt': now(), 'timeoutSeconds': args.timeout} print('==> %s (bound %ss)' % (args.name, args.timeout), flush=True) + # A signal stops the phase's command and records the phase interrupted. + received = [] + + def on_signal(signum, _frame): + received.append(signum) + raise Interrupted() + for sig in INTERRUPT_SIGNALS: + signal.signal(sig, on_signal) + (state / 'current-phase').write_text(args.name + '\n') with open(log, 'ab') as out, open(state / 'phases.log', 'ab') as markers: p = subprocess.Popen(args.command, stdout=subprocess.PIPE, stderr=out, start_new_session=True) - deadline = started + args.timeout - timed_out = False - import selectors - sel = selectors.DefaultSelector() - os.set_blocking(p.stdout.fileno(), False) - sel.register(p.stdout, selectors.EVENT_READ) - eof = False - while True: - remaining = deadline - time.monotonic() - if remaining <= 0: - timed_out = True - break - if eof: - try: - p.wait(timeout=remaining) - except subprocess.TimeoutExpired: + try: + deadline = started + args.timeout + timed_out = False + import selectors + sel = selectors.DefaultSelector() + os.set_blocking(p.stdout.fileno(), False) + sel.register(p.stdout, selectors.EVENT_READ) + eof = False + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: timed_out = True - break - if sel.select(timeout=min(remaining, 1.0)): - line = os.read(p.stdout.fileno(), 65536) - if not line: - sel.unregister(p.stdout) - eof = True - continue - out.write(line) - markers.write(line) - out.flush() - markers.flush() - if args.echo: - sys.stdout.write(''.join(' ' + l for l in line.decode(errors='replace').splitlines(True))) - sys.stdout.flush() - sel.close() - p.stdout.close() - if timed_out: + break + if eof: + try: + p.wait(timeout=remaining) + except subprocess.TimeoutExpired: + timed_out = True + break + if sel.select(timeout=min(remaining, 1.0)): + line = os.read(p.stdout.fileno(), 65536) + if not line: + sel.unregister(p.stdout) + eof = True + continue + out.write(line) + markers.write(line) + out.flush() + markers.flush() + if args.echo: + sys.stdout.write(''.join(' ' + l for l in line.decode(errors='replace').splitlines(True))) + sys.stdout.flush() + sel.close() + p.stdout.close() + if timed_out: + terminate(p) + code = p.wait(timeout=5) + except Interrupted: + for sig in INTERRUPT_SIGNALS: + signal.signal(sig, signal.SIG_IGN) terminate(p) - code = p.wait(timeout=5) + p.stdout.close() + code = 128 + received[0] record['durationSeconds'] = round(time.monotonic() - started, 1) record['finishedAt'] = now() - if timed_out: + if received: + record.update(status='interrupted', exitCode=code) + elif timed_out: record.update(status='timeout', exitCode=EXIT_TIMEOUT) else: record.update(status='passed' if code == 0 else 'blocked' if code == EXIT_BLOCKED else 'failed', exitCode=code) with open(evidence_dir(state) / 'phases.jsonl', 'a') as f: f.write(json.dumps(record, sort_keys=True) + '\n') + (state / 'current-phase').unlink(missing_ok=True) if record['status'] != 'passed': print('<== %s %s (exit %s); private log: %s' % (args.name, record['status'], record['exitCode'], log), flush=True) tail = log.read_bytes()[-1500:].decode(errors='replace') print('\n'.join(' ' + l for l in tail.splitlines()[-15:]), flush=True) + if received: + return code return EXIT_TIMEOUT if timed_out else (0 if code == 0 else EXIT_BLOCKED if code == EXIT_BLOCKED else EXIT_FAILED) @@ -437,15 +509,17 @@ def secrets(state): def scan(args): values = secrets(args.state) | set(args.extra or []) leaked = [] - for p in evidence_dir(args.state).rglob('*'): + ev = evidence_dir(args.state) + for p in ev.rglob('*'): if p.is_file(): data = p.read_bytes() if any(v.encode() in data for v in values): - leaked.append(p.name) + leaked.append(p) if leaked: - for name in leaked: - (evidence_dir(args.state) / name).write_text('{"redacted":"secret scan matched; see private state"}\n') - print('secret scan matched and redacted: ' + ', '.join(sorted(leaked)), file=sys.stderr) + # Redact the matching file itself, wherever it is under evidence/. + for path in leaked: + path.write_text('{"redacted":"secret scan matched; see private state"}\n') + print('secret scan matched and redacted: ' + ', '.join(sorted(str(p.relative_to(ev)) for p in leaked)), file=sys.stderr) return EXIT_FAILED print('secret scan: %d evidence files clean against %d retained secrets' % (sum(1 for p in evidence_dir(args.state).rglob('*') if p.is_file()), len(values))) return 0 @@ -462,18 +536,57 @@ def result(args): if prefix: code, out, _ = capture(['docker', 'ps', '-a', '--filter', 'name=^' + prefix + '-', '--format', '{{.Names}}\t{{.State}}'], 30) retained = [dict(zip(('name', 'state'), l.split('\t'))) for l in out.splitlines() if code == 0 and l.strip()] + code = args.exit_code + status = STATUS_BY_EXIT.get(code, 'interrupted' if code in [128 + s for s in INTERRUPT_SIGNALS] else 'failed') + # Exit 0 is a pass only if run.sh reached its last line. + if code == EXIT_PASSED: + if (state / COMPLETED).exists(): + status = 'passed' + elif (state / PREFLIGHT_COMPLETED).exists(): + status = 'preflight-passed' + else: + status, code = 'interrupted', EXIT_FAILED failed = next((p for p in phases if p['status'] != 'passed'), None) - status = STATUS_BY_EXIT.get(args.exit_code, 'failed') + running = state / 'current-phase' + if failed is None and status != 'passed' and running.exists(): + failed = {'name': running.read_text().strip()} summary = ev / 'summary.json' - value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': args.exit_code, 'prefix': prefix, + value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': code, 'prefix': prefix, 'group': GROUP, 'failedPhase': failed['name'] if failed else None, 'phases': phases, 'retainedContainers': retained, 'stateDirectory': str(state), 'evidenceDirectory': str(ev), 'summary': 'summary.json' if summary.exists() and status == 'passed' else None, - 'custody': 'released and verified' if status == 'passed' else 'Unknown: inspect private state before any cleanup', + 'custody': ('released and verified' if GROUP != 'flux' else 'allocated at teardown; this group runs no release') if status == 'passed' + else 'Unknown: inspect private state before any cleanup', 'productionAuthority': False} write_json(ev / 'result.json', value) - print('RESULT %s exit=%s evidence=%s' % (status, args.exit_code, ev / 'result.json')) - return 0 + print('RESULT %s exit=%s evidence=%s' % (status, code, ev / 'result.json')) + # run.sh exits with this code, so only a completed run exits 0. + return code + + +def verify(args): + """Whether a recorded result counts as a pass: status passed, every phase + passed, and the run reached teardown. A killed, timed-out or interrupted + run never does, whatever its exit code.""" + path = evidence_dir(args.state) / 'result.json' + try: + value = json.loads(path.read_text()) + except (OSError, ValueError): + print('VERIFY failed: no readable result.json') + return EXIT_FAILED + phases = value.get('phases') or [] + problems = [] + if value.get('status') != 'passed' or value.get('exitCode') != EXIT_PASSED: + problems.append('status %s exit %s' % (value.get('status'), value.get('exitCode'))) + problems += ['phase %s %s' % (p.get('name'), p.get('status')) for p in phases if p.get('status') != 'passed'] + if not any(p.get('name') == 'teardown' and p.get('status') == 'passed' for p in phases): + problems.append('teardown did not pass') + if value.get('retainedContainers'): + problems.append('retained containers: %d' % len(value['retainedContainers'])) + if args.group and value.get('group') != args.group: + problems.append('scenario group %s, expected %s' % (value.get('group'), args.group)) + print('VERIFY %s phases=%d%s' % ('failed' if problems else 'passed', len(phases), (': ' + '; '.join(problems[:8])) if problems else '')) + return EXIT_FAILED if problems else EXIT_PASSED def main(): @@ -505,6 +618,9 @@ def main(): s = sub.add_parser('result') s.add_argument('--state', required=True) s.add_argument('--exit-code', type=int, required=True) + s = sub.add_parser('verify') + s.add_argument('--state', required=True) + s.add_argument('--group', choices=GROUPS, help='the scenario group the run must have recorded') a = p.parse_args() if a.cmd == 'phase': if a.command[:1] == ['--']: @@ -512,7 +628,7 @@ def main(): if not a.command or not re.match(r'^[a-z0-9-]+$', a.name): return EXIT_USAGE return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, 'custody-digest': custody_cmd, - 'scan': scan, 'result': result}[a.cmd](a) + 'scan': scan, 'result': result, 'verify': verify}[a.cmd](a) if __name__ == '__main__': diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 5e5ee1c2..17da267f 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -11,7 +11,8 @@ grants and the metal CRDs inside the project, and in the provider project the inventory and Device custody CRDs. The provider project's Fleet components each get their own token: the Metal provider (management), the - custody coordinator, the release controller and fixture discovery. + custody coordinator, the release controller and fixture discovery. A staff + token creates recoveries. Production uses Milo's own project provisioning, service catalog and IAM; this is not that machinery. """ @@ -19,7 +20,7 @@ p=argparse.ArgumentParser();p.add_argument('state');p.add_argument('prefix');a=p.parse_args() root=pathlib.Path(a.state).resolve();root.mkdir(mode=0o700,parents=True,exist_ok=True) if not a.prefix.startswith('fleet-mp-'):raise SystemExit('task-owned fleet-mp- prefix required') -os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +os.environ['DOCKER_CONTEXT']=os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT','colima-fleet-acceptance-tcg') platform=root/'platform-admin.yaml' ports=json.loads((root/'platform-ports.json').read_text()) def run(*args,**kw):return subprocess.run(args,check=True,text=True,**kw) @@ -38,7 +39,7 @@ def wait(fn,seconds,what): d=root/role;ns='milo-'+role if not d.exists(): d.mkdir(mode=0o700) - who=('bootstrap','management','customer')+(('coordinator','release','discovery') if role=='provider' else ()) + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff') if role=='provider' else ()) tokens={r:secrets.token_hex(32) for r in who} (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k=='bootstrap' else 'fleet-local') for k,v in tokens.items())+'\n') run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) @@ -96,7 +97,10 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], - 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}]} + 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}], + # Staff create recoveries and read inventory and custody, nothing else. + # The coordinator treats every unconfigured creator as staff. + 'staff':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicerecoveries'],'verbs':['get','list','watch','create']}]} for who,component in components.items(): apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-'+who},'rules':component}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-'+who},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-'+who},'subjects':[{'kind':'User','name':who}]}) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index a0aa3941..73cd5453 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -224,9 +224,11 @@ def discovery_faults(s): before = len(audit(s)) cases = [] try: - def probe(name, creds, system, uuid, want): + pin = (d / 'bmc-pin').read_text().strip() + + def probe(name, creds, system, uuid, want, pin=pin): r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'https://127.0.0.1:%d' % port, '--credentials', str(creds), - '--system', system, '--uuid', uuid, '--pin', (d / 'bmc-pin').read_text().strip()], text=True, capture_output=True, timeout=120) + '--system', system, '--uuid', uuid, '--pin', pin], text=True, capture_output=True, timeout=120) line = (r.stdout.strip().splitlines() or [''])[-1] cases.append({'case': name, 'system': system, 'exitCode': r.returncode, 'outcome': line}) if r.returncode != want: @@ -241,6 +243,13 @@ def probe(name, creds, system, uuid, want): probe('ResetType On not advertised (injected)', good, TARGET_A['system'], TARGET_A['uuid'], 11) finally: bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'clear') + # Another key's digest: the TLS handshake fails before any request, + # so the BMC audit gains nothing. + other = pin[:-1] + ('0' if pin[-1] != '0' else '1') + seen = len(audit(s)) + probe('a TLS key other than the pin', good, TARGET_A['system'], TARGET_A['uuid'], 13, pin=other) + if len(audit(s)) != seen: + die('a probe with the wrong pin reached the BMC') probe('target A after the fault is cleared', good, TARGET_A['system'], TARGET_A['uuid'], 0) finally: pf.kill() @@ -255,7 +264,7 @@ def probe(name, creds, system, uuid, want): 'client': 'internal/redfish discovery through fleet-multiplane redfish-probe', 'cases': cases, 'auditRequests': len(window), 'mutatingRequests': 0, 'rejectedRequests': sum(1 for e in window if e['principal'] == 'rejected')}) - print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only') + print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only; a TLS key other than the pin reached no request') def arm_lost_response(s): @@ -349,8 +358,9 @@ def bmc_interrupt(s): write(s / 'evidence' / 'redfish-bmc-interrupt.json', {'observedAt': now(), 'deletedBMCPodUIDs': [o['metadata']['uid'] for o in old], 'replacementBMCPodUID': new['metadata']['uid'], 'operationID': ops[0]['operation'], 'fence': ops[0]['fence'], 'stageAtInterrupt': ops[0]['stage'], 'stageAfter': after[0]['stage'], 'guestRunningAfter': TARGET_A['domain'] in running(s), + 'guestStateAfter': runtime(s, 'virsh', '--connect', LIBVIRT, 'domstate', TARGET_A['domain']).stdout.strip(), 'note': 'the BMC adapter re-reads NVRAM and libvirt state; the worker tolerates a bounded BMC outage while observing'}) - print('redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install and replaced; the guest kept running and the operation stayed unfinished') + print('redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install and replaced; the guest stayed active and the operation stayed unfinished') def isolation(s): @@ -369,16 +379,37 @@ def isolation(s): b, a = record['targetB'], record['targetA'] if b['diskSHA256Before'] != b['diskSHA256After'] or b['qemuStarts'] or b['consoleLines'] != base['targetB']['consoleLines'] or b['mutatingRedfishRequests']: die('target B was touched: %s' % b) - if a['diskSHA256'] != a['zeroDiskSHA256']: + # The flux group runs no release, so target A keeps its installed disk and + # its disk boot; only the groups that wipe it can require it zeroed and off. + released = harness.GROUP != 'flux' + record['targetA']['checkedWiped'] = released + if released and a['diskSHA256'] != a['zeroDiskSHA256']: die('target A disk is not all zeroes after the final verified cleanup') - if record['runningDomains']: + if released and record['runningDomains']: die('a lab target is still running: %s' % record['runningDomains']) + if not released and TARGET_B['domain'] in record['runningDomains']: + die('target B is running: %s' % record['runningDomains']) write(s / 'evidence' / 'redfish-isolation.json', record) (s / 'evidence' / 'redfish-audit.jsonl').write_text(''.join(json.dumps(e, sort_keys=True) + '\n' for e in entries)) - print('redfish-isolation: target B never started, never received a Redfish effect and its disk is unchanged; target A disk independently hashes as all zeroes after the final cleanup') + print('redfish-isolation: target B never started, never received a Redfish effect and its disk is unchanged; ' + + ('target A disk independently hashes as all zeroes after the final cleanup' if released else 'target A stays installed: this group runs no release')) + + +def audit_mark(s): + """Record the BMC audit's length for a later audit-unchanged.""" + (s / 'redfish' / 'audit-mark').write_text('%d\n' % len(audit(s))) + + +def audit_unchanged(s): + """No request after the mark carried an effect.""" + mark = int((s / 'redfish' / 'audit-mark').read_text()) + effects = mutating(audit(s)[mark:]) + if effects: + die('the BMC received an effect: %s' % [{k: e.get(k) for k in ('method', 'path', 'resetType')} for e in effects]) if __name__ == '__main__': step, state = sys.argv[1], pathlib.Path(sys.argv[2]) {'enroll': enroll, 'baseline': baseline, 'discovery-faults': discovery_faults, 'arm-lost-response': arm_lost_response, - 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation}[step](state) + 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation, + 'audit-mark': audit_mark, 'audit-unchanged': audit_unchanged}[step](state) diff --git a/hack/multiplane/roles.py b/hack/multiplane/roles.py index bc79a8a1..3edc7246 100755 --- a/hack/multiplane/roles.py +++ b/hack/multiplane/roles.py @@ -9,7 +9,7 @@ """ import base64,json,os,pathlib,subprocess,sys,time state=pathlib.Path(sys.argv[1]).resolve();prefix=(state/'prefix').read_text().strip() -os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +os.environ['DOCKER_CONTEXT']=os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT','colima-fleet-acceptance-tcg') env=json.loads((state/'gitops-environment.json').read_text()) def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=30s',*args],input=input,text=True,capture_output=True,check=True).stdout def exists(config,*args):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s','get',*args],capture_output=True).returncode==0 diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 46e1e226..a9b1f1e5 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -4,7 +4,8 @@ # and retain exact state as Unknown custody. See docs/operations/multiplane.md. # # Exit codes: 0 passed, 1 failed, 2 preflight failed, 3 blocked by implementation -# readiness, 4 bounded wait expired, 64 usage. +# readiness, 4 bounded wait expired, 64 usage, 128 plus the signal number when +# interrupted. Only a run that reached its last line records passed. set -euo pipefail cd "$(dirname "$0")/../.." umask 077 @@ -23,12 +24,19 @@ for arg in "$@"; do *) usage ;; esac done -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider +# Run parameters (docs/operations/multiplane.md#ci-mode). The defaults are the +# task-owned Colima profile: arm64 runtime, TCG guest. Preflight validates them +# before any resource exists. +export FLEET_MULTIPLANE_RUNTIME=${FLEET_MULTIPLANE_RUNTIME:-colima} FLEET_MULTIPLANE_DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} +export FLEET_MULTIPLANE_ARCH=${FLEET_MULTIPLANE_ARCH:-arm64} FLEET_MULTIPLANE_ACCEL=${FLEET_MULTIPLANE_ACCEL:-tcg} +# Scenario group: all by default; CI shards each suite into flux and release. +export FLEET_MULTIPLANE_GROUP=${FLEET_MULTIPLANE_GROUP:-all} +export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider harness=(python3 hack/multiplane/harness.py) state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") mkdir -m 0700 "$state/evidence" printf '%s\n' "$provider" > "$state/site-provider" -printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\n' "$state" "$state" "$provider" +printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\nScenario group: %s\n' "$state" "$state" "$provider" "$FLEET_MULTIPLANE_GROUP" finish() { code=$1 @@ -42,14 +50,39 @@ finish() { echo "Execution and custody are Unknown. Retained private state: $state. Discard only after inspection: hack/multiplane/teardown.sh $state --discard-unknown" fi [[ $code -eq 0 ]] || "${harness[@]}" scan --state "$state" >/dev/null 2>&1 || true - "${harness[@]}" result --state "$state" --exit-code "$code" - exit "$code" + # The result decides the exit code: exit 0 without the completion marker is + # an interrupted run. + "${harness[@]}" result --state "$state" --exit-code "$code" && exit 0 + exit $? +} +# Every descendant. Parents are signalled before their children, so a phase +# stops its own command and records the interruption; the children are +# listed first, so none is missed when its parent exits. +stop_tree() { + local child children + children=$(pgrep -P "$1" || true) + [[ $1 == "$$" ]] || kill -TERM "$1" 2>/dev/null || true + for child in $children; do stop_tree "$child"; done +} +interrupt() { + trap '' TERM INT HUP + stop_tree $$ + wait || true + finish "$1" } trap 'finish $?' EXIT -ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}"; } +trap 'interrupt 143' TERM +trap 'interrupt 130' INT +trap 'interrupt 129' HUP +# Phases and acceptance scripts run in the background and are waited for, so +# a signal reaches the traps at once rather than after the current phase. +ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}" & wait $!; } -"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" -[[ $preflight_only == 0 ]] || exit 0 +"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" & wait $! +if [[ $preflight_only == 1 ]]; then + : > "$state/preflight-completed" + exit 0 +fi prefix="fleet-mp-$(openssl rand -hex 4)" printf '%s\n' "$prefix" > "$state/prefix" @@ -65,12 +98,12 @@ PY flux=(python3 hack/multiplane/flux.py) # The site binary is built into its own directory: it is the only build context # input besides hack/local-vm, so no private state can enter the image. -ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" +ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH="$FLEET_MULTIPLANE_ARCH" go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" ph site-image 2400 docker build --target site --build-context "fleetbin=$state/site-bin" -t "$prefix-site-image" -f hack/local-vm/Containerfile hack/local-vm ph site-image-verify 120 sh -c ' sum=$(shasum -a 256 "$2/site-bin/fleet-multiplane" | cut -d" " -f1) printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null - docker run --rm -e FLEET_LOCAL_VM_ACCEL=tcg --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" + docker run --rm -e "FLEET_LOCAL_VM_ACCEL=$FLEET_MULTIPLANE_ACCEL" --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" if [[ $provider == redfish ]]; then # The unmodified upstream emulator, verified before extraction, plus the @@ -111,9 +144,9 @@ ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpos ph site-install 900 bash hack/multiplane/site.sh check "$state" ph flux-verify 300 "${flux[@]}" verify "$state" if [[ $provider == redfish ]]; then - bash hack/multiplane/acceptance-redfish.sh "$state" + bash hack/multiplane/acceptance-redfish.sh "$state" & wait $! else - bash hack/multiplane/acceptance.sh "$state" + bash hack/multiplane/acceptance.sh "$state" & wait $! fi ph secret-scan 120 "${harness[@]}" scan --state "$state" if [[ $keep == 1 ]]; then @@ -121,4 +154,6 @@ if [[ $keep == 1 ]]; then else ph teardown 900 bash hack/multiplane/teardown.sh "$state" fi +# The last act of a completed run: only now may the result record passed. +: > "$state/completed" printf 'Local topology/PXE acceptance (%s provider) passed. Production authority and physical hardware remain unqualified.\n' "$provider" diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py new file mode 100644 index 00000000..b83b45c2 --- /dev/null +++ b/hack/multiplane/scenarios.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Evidence checks for the #174 failure scenarios in the multi-plane runs. + +Each command reads the provider project with its bootstrap credential and the +cell with its admin kubeconfig, checks one outcome, and writes a sanitized +record under evidence/. None of them writes custody or an operation. +""" +import datetime +import json +import pathlib +import subprocess +import sys +import time + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout) + +NS, SITE = 'fleet-coordination', 'fleet-site' +PROVIDER_NS, DEVICE = 'fleet-provider', 'synthetic-device-central-01' +ASSIGNMENTS = 'coordination.fleet.datumapis.com/role=assignment' +REDFISH = harness.PROVIDER == 'redfish' +# The Installation UID the tenant-isolation phase's refused installation +# labels (internal/multiplane/scenarios.go). +TENANT_REQUEST = '00000000-0000-4000-8000-000000000174' + + +def die(message): + raise SystemExit(message) + + +def kubectl(s, config, *args, check=True, input=None): + r = subprocess.run(['kubectl', '--kubeconfig', str(s / config), '--request-timeout=20s', *args], text=True, capture_output=True, input=input) + if check and r.returncode: + die('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[:300])) + return r + + +def get(s, config, *args): + return json.loads(kubectl(s, config, *args, '-o', 'json').stdout) + + +def provider(s, *args): + return get(s, 'provider/bootstrap-project.json', '-n', PROVIDER_NS, *args) + + +def custody(s): + return provider(s, 'get', 'devicecustody', DEVICE) + + +def items(s, kind): + return provider(s, 'get', kind)['items'] + + +def write(s, name, record): + record = dict(record, observedAt=datetime.datetime.now(datetime.timezone.utc).isoformat()) + (s / 'evidence' / name).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n') + + +def wait_for(fn, timeout, what, interval=3): + end = time.monotonic() + timeout + while time.monotonic() < end: + value = fn() + if value: + return value + time.sleep(interval) + die('timed out waiting for ' + what) + + +def bmc_effects(s): + """Mutating BMC requests in the lab audit, in Redfish mode.""" + if not REDFISH: + return [] + import redfish_steps + return redfish_steps.mutating(redfish_steps.audit(s)) + + +def admitted_key(op): + """An operation's site key at the fence custody admitted it, or None + before the coordinator recorded the admission.""" + fence = (op.get('status', {}).get('admission') or {}).get('fence') + return harness.operation_key(op['kind'], op['metadata']['name'], fence) if fence else None + + +def handoff_for(s, key): + """The assignment handoff for the operation admission with this site key.""" + for h in get(s, 'cell-admin.yaml', '-n', NS, 'get', 'machineallocationhandoffs', '-l', ASSIGNMENTS)['items']: + a = json.loads(h['spec']['assignmentJSON']) + if harness.operation_key(a['operation']['kind'], a['operation']['name'], a['fence']) == key: + return h['metadata']['name'] + return None + + +def same_admission(ref, key): + """Whether custody's operation reference (kind, name, fence) names the + admission with this site key.""" + return bool(ref) and harness.operation_key(ref.get('kind', ''), ref.get('name', ''), ref.get('fence', 0)) == key + + +def import_inert(s): + """Importing Devices admitted, delivered and sent nothing: no operation, + allocation, assignment, worker Job or journal entry exists, and custody + has no active operation, result or hold.""" + found = {kind: [o['metadata']['name'] for o in items(s, kind)] for kind in ('deviceinstallations', 'devicewipes', 'devicerecoveries', 'machineallocations')} + if any(found.values()): + die('records exist before any allocation: %s' % found) + records = items(s, 'devicecustodies') + devices = sorted(d['metadata']['name'] for d in items(s, 'devices')) + if sorted(c['metadata']['name'] for c in records) != devices: + die('custody does not exist for exactly the imported Devices') + for c in records: + spec = c['spec'] + if spec.get('activeOperation') or spec.get('lastResult') or spec.get('recoveryHold') or spec['holder']['type'] != 'None': + die('imported custody is not idle: %s' % c['metadata']['name']) + if get(s, 'cell-admin.yaml', '-n', NS, 'get', 'machineallocationhandoffs', '-l', ASSIGNMENTS)['items']: + die('an assignment was delivered before any allocation') + if get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'jobs')['items']: + die('a worker Job exists before any allocation') + if harness.journal(s): + die('the site journal holds an operation before any allocation') + effects = bmc_effects(s) + if effects: + die('the BMC received an effect before any allocation: %s' % effects) + write(s, 'import-inert.json', {'devices': devices, 'custody': {c['metadata']['name']: {'state': c['spec']['state'], 'fence': c['spec']['fence']} for c in records}, + 'operations': 0, 'allocations': 0, 'assignments': 0, 'workerJobs': 0, 'journalOperations': 0, + 'bmcEffects': 0 if REDFISH else None}) + print('import-inert: %d imported Devices; no operation, allocation, assignment, worker Job or journal entry%s' + % (len(devices), '; the BMC audit holds no effect' if REDFISH else '')) + + +def staff_access(s): + """The staff identity creates recoveries and reads inventory and custody. + It cannot read Secrets, where a bootstrap payload would be sealed, or + write any other operation, allocation or custody. It holds no consumer + project or hub credential.""" + staff = 'provider/staff-project.json' + probe = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'metadata': {'name': 'staff-probe', 'namespace': PROVIDER_NS}, 'spec': {}} + denied = { + 'get Secrets': ('-n', PROVIDER_NS, 'get', 'secrets'), + 'get Secrets in default': ('-n', 'default', 'get', 'secrets'), + 'create a DeviceInstallation': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, kind='DeviceInstallation'))), + 'create a DeviceWipe': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, kind='DeviceWipe'))), + 'create a MachineAllocation': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, apiVersion='metal.datumapis.com/v1alpha1', kind='MachineAllocation'))), + 'update custody': ('-n', PROVIDER_NS, 'annotate', '--dry-run=server', 'devicecustody', DEVICE, 'probe=staff'), + 'delete custody': ('-n', PROVIDER_NS, 'delete', '--dry-run=server', 'devicecustody', DEVICE), + } + results = {} + for name, args in denied.items(): + stdin = None + if args[-2:-1] == ('-',): + args, stdin = args[:-1], args[-1] + r = kubectl(s, staff, *args, check=False, input=stdin) + if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): + die('staff was not forbidden to %s: %s' % (name, r.stderr.strip()[:200])) + results[name] = 'Forbidden' + for name, args in {'read custody': ('-n', PROVIDER_NS, 'get', 'devicecustody', DEVICE), 'list recoveries': ('-n', PROVIDER_NS, 'get', 'devicerecoveries')}.items(): + if kubectl(s, staff, *args, check=False).returncode: + die('staff cannot ' + name) + results[name] = 'Allowed' + elsewhere = [str(p.relative_to(s)) for p in s.glob('*/staff-project.json') if p.parent.name != 'provider'] + [str(p.relative_to(s)) for p in s.glob('staff*.yaml')] + if elsewhere: + die('staff holds a credential outside the provider project: %s' % elsewhere) + write(s, 'staff-access.json', {'checks': results, 'credentials': ['provider project'], 'bootstrapPayloads': 'refused at admission and at the site'}) + print('staff-access: staff read custody and list recoveries; Secrets, other operations, allocations and custody writes forbidden; no consumer or hub credential') + + +def contention(s): + """Custody names the winner's MachineAllocation, and it is the only one.""" + allocations = [a for a in items(s, 'machineallocations') if a['spec']['deviceRef']['name'] == DEVICE] + winner = get(s, 'consumer-a/management-project.json', '-n', 'default', 'get', 'machine', 'allocation') + # The allocation labels the Machine incarnation it is for. + if len(allocations) != 1 or allocations[0]['metadata'].get('labels', {}).get('fleet.datumapis.com/machine-uid') != winner['metadata']['uid']: + die('expected one MachineAllocation, for consumer-a: %s' % [a['metadata']['name'] for a in allocations]) + holder = custody(s)['spec']['holder'] + if holder['type'] != 'Allocation' or (holder.get('allocationRef') or {}).get('name') != allocations[0]['metadata']['name']: + die('custody does not name the winning allocation: %s' % holder) + write(s, 'contention.json', {'allocations': 1, 'holder': holder['type'], 'holderNamesWinner': True}) + print('contention-custody: custody holds the Device for the one MachineAllocation, consumer-a\'s') + + +def holder_install(s): + """The one installation for the allocation custody holds, ignoring the + tenant-isolation phase's refused installation.""" + allocation = (custody(s)['spec']['holder'].get('allocationRef') or {}).get('name') + ops = [o for o in items(s, 'deviceinstallations') if (o['spec']['authority'].get('allocationRef') or {}).get('name') == allocation + and o['metadata'].get('labels', {}).get('fleet.datumapis.com/installation-uid') != TENANT_REQUEST] + if not allocation or len(ops) != 1: + die('expected one installation for the held allocation %s, found %d' % (allocation, len(ops))) + return ops[0] + + +def wait_installer(s, step): + """Record the held allocation's installation and its handoff, and wait + until it journaled its installer step. It fails at once if the + installation already ended, so a slow start is reported as itself.""" + name = holder_install(s)['metadata']['name'] + # The site keys the operation by kind, name and the fence it was admitted + # at; a same-name installation created later is admitted at another. + key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the installation to be admitted', interval=1) + handoff = wait_for(lambda: handoff_for(s, key), 300, 'the installation to be delivered', interval=1) + (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key, 'handoff': handoff}) + '\n') + + def journaled(): + phase = deadline_op(s)[0].get('status', {}).get('phase') + if phase in ('Succeeded', 'Failed', 'Cancelled', 'OutcomeUnknown'): + die('the installation ended %s before it journaled %s; its deadline left too little time' % (phase, step)) + for o in harness.journal(s) or []: + if o['operation'] == key and any(n == step for n, _ in o['steps']): + return o + return None + wait_for(journaled, 600, 'the second installation to journal %s' % step, interval=1) + + +def deadline_op(s): + ref = json.loads((s / 'deadline-install.json').read_text()) + op = provider(s, 'get', 'deviceinstallation', ref['name']) + if admitted_key(op) != ref['key']: + die('the deadline installation was replaced') + return op, ref['key'] + + +def wipes_for(s, allocation): + return [w for w in items(s, 'devicewipes') if (w['spec'].get('authority', {}).get('allocationRef') or {}).get('name') == allocation] + + +def release_waits(s): + """The Machine is deleted mid-install. Release begins, and waits: custody + holds the Device for release with the installation still active, and no + wipe exists.""" + op, key = deadline_op(s) + phase = op.get('status', {}).get('phase') + if phase in ('Succeeded', 'Failed', 'Cancelled', 'OutcomeUnknown'): + die('the installation ended %s before the release was observed; its deadline (FLEET_MULTIPLANE_INSTALLATION_DEADLINE) left too little time' % phase) + allocation = op['spec']['authority']['allocationRef']['name'] + spec = custody(s)['spec'] + active = spec.get('activeOperation') or {} + if spec['holder']['type'] != 'Release' or not same_admission(active, key): + die('release did not wait for the installation: holder %s, active %s' % (spec['holder']['type'], active.get('kind'))) + if wipes_for(s, allocation): + die('a wipe was created while the installation was active') + machine = kubectl(s, 'consumer-b/management-project.json', '-n', 'default', 'get', 'machine', 'allocation', '-o', 'json') + m = json.loads(machine.stdout) + if not m['metadata'].get('deletionTimestamp'): + die('the Machine is not being deleted') + write(s, 'release-waits.json', {'holder': 'Release', 'activeOperation': 'DeviceInstallation', 'wipes': 0, 'machineDeleting': True, + 'openGates': spec['holder'].get('openGates', [])}) + print('release-waits: the Machine is deleting; custody holds the Device for release with the installation active and no wipe') + + +def deadline_hold(s): + """The installation passes its deadline: it ends OutcomeUnknown with + DeadlineExceeded, custody holds it, and its worker has stopped.""" + def ended(): + op, _ = deadline_op(s) + return op if op.get('status', {}).get('phase') == 'OutcomeUnknown' else None + op = wait_for(ended, 900, 'the installation to end OutcomeUnknown') + key = admitted_key(op) + status = op['status'] + if status.get('reason') != 'DeadlineExceeded': + die('the installation ended OutcomeUnknown for %s, not its deadline' % status.get('reason')) + hold = custody(s)['spec'].get('recoveryHold') or {} + if not same_admission(hold, key) or hold.get('fence') != status.get('fence'): + die('custody does not hold the installation: %s' % hold.get('kind')) + # The handoff was recorded at delivery: its worker Pods must show the + # worker stopped. A missing Pod is a failure, never a pass. + handoff = json.loads((s / 'deadline-install.json').read_text())['handoff'] + + def stopped(): + pods = get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] + ends = [c['state']['terminated']['finishedAt'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] + return ends if pods and len(ends) == len(pods) else None + finished = wait_for(stopped, 300, 'the installation worker to stop') + boots = [b for b in harness.journal(s) or [] if b['operation'] == key] + record = {'phase': 'OutcomeUnknown', 'reason': 'DeadlineExceeded', 'fence': status['fence'], 'deadline': status.get('deadline'), + 'holdFence': hold['fence'], 'workerFinishedAt': max(finished), 'journaledSteps': [n for o in boots for n, _ in o['steps']]} + (s / 'deadline-hold.json').write_text(json.dumps(record) + '\n') + write(s, 'deadline-hold.json', record) + print('deadline-hold: the installation ended OutcomeUnknown at its deadline; custody holds it at fence %d; its worker stopped' % status['fence']) + + +def deadline_settled(s): + """The release's wipe settled the installation hold: admitted above the + held fence after the worker stopped, Succeeded, the hold cleared, the + Device free and the Machine gone.""" + op, _ = deadline_op(s) + held = json.loads((s / 'deadline-hold.json').read_text()) + allocation = op['spec']['authority']['allocationRef']['name'] + wipes = [w for w in wipes_for(s, allocation) if w.get('status', {}).get('phase') == 'Succeeded'] + if len(wipes) != 1: + die('expected one succeeded wipe for the released allocation') + wipe = wipes[0]['status'] + spec = custody(s)['spec'] + if wipe['fence'] <= held['fence'] or spec.get('recoveryHold') or spec['holder']['type'] != 'None': + die('the wipe did not settle the installation hold: wipe fence %s, held fence %s, hold %s' % (wipe['fence'], held['fence'], bool(spec.get('recoveryHold')))) + if wipe['admittedAt'] < held['workerFinishedAt']: + die('the wipe was admitted before the installation worker stopped') + r = kubectl(s, 'consumer-b/management-project.json', '-n', 'default', 'get', 'machine', 'allocation', check=False) + if r.returncode == 0 or 'NotFound' not in r.stderr: + die('the deleted Machine remains') + store, _ = harness.site_store(s) + write(s, 'deadline-settled.json', {'heldFence': held['fence'], 'wipeFence': wipe['fence'], 'wipeAdmittedAt': wipe['admittedAt'], + 'workerFinishedAt': held['workerFinishedAt'], 'siteStopped': (store or {}).get('stopped'), + 'holdCleared': True, 'holder': 'None', 'machineDeleted': True}) + print('deadline-settled: the release wipe was admitted at fence %d after the worker stopped, succeeded and cleared the hold; the Machine is gone' % wipe['fence']) + + +def rebuild_unverified(s): + """Custody was deleted. The coordinator rebuilds it Unverified and keeps + it there while no site reports its fence.""" + def rebuilt(): + r = kubectl(s, 'provider/bootstrap-project.json', '-n', PROVIDER_NS, 'get', 'devicecustody', DEVICE, '-o', 'json', check=False) + return json.loads(r.stdout) if r.returncode == 0 else None + c = wait_for(rebuilt, 300, 'custody to be rebuilt') + old = json.loads((s / 'rebuild-before.json').read_text()) + if c['metadata']['uid'] == old['uid']: + die('custody was not deleted') + if c['spec']['state'] != 'Unverified': + die('rebuilt custody is %s before any site report' % c['spec']['state']) + store, _ = harness.site_store(s) + record = {'oldFence': old['fence'], 'rebuiltState': 'Unverified', 'rebuiltHolder': c['spec']['holder']['type'], 'siteFence': (store or {}).get('fence'), + 'siteStopped': (store or {}).get('stopped')} + (s / 'rebuild-unverified.json').write_text(json.dumps(record) + '\n') + print('rebuild-unverified: custody rebuilt Unverified with holder %s while the site cannot report' % record['rebuiltHolder']) + + +def rebuild_before(s): + c = custody(s) + if c['spec']['state'] != 'Verified' or c['spec']['holder']['type'] != 'None': + die('the rebuild starts from free, Verified custody') + (s / 'rebuild-before.json').write_text(json.dumps({'uid': c['metadata']['uid'], 'fence': c['spec']['fence']}) + '\n') + + +def rebuild_verified(s): + """After the site reports again, custody is Verified with a fence above + every fence the site stored.""" + before = json.loads((s / 'rebuild-unverified.json').read_text()) + c = wait_for(lambda: (lambda c: c if c['spec']['state'] == 'Verified' else None)(custody(s)), 600, 'rebuilt custody to be Verified') + site_fence = max(before['siteFence'] or 0, before['siteStopped'] or 0) + if c['spec']['fence'] <= site_fence or c['spec']['fence'] <= before['oldFence']: + die('rebuilt custody fence %d is not above the site fence %d and the old fence %d' % (c['spec']['fence'], site_fence, before['oldFence'])) + probe = get(s, 'consumer-a/management-project.json', '-n', 'default', 'get', 'machine', 'allocation')['metadata']['uid'] + allocations = items(s, 'machineallocations') + # An allocation labels the Machine incarnation it is for. + probe_allocated = any(a['metadata'].get('labels', {}).get('fleet.datumapis.com/machine-uid') == probe for a in allocations) + if probe_allocated or any(a.get('status', {}).get('phase') != 'Released' for a in allocations): + die('an allocation was recorded during the rebuild') + write(s, 'rebuild.json', dict(before, verifiedFence=c['spec']['fence'], verifiedHolder=c['spec']['holder']['type'], probeAllocated=probe_allocated)) + print('rebuild-verified: custody Verified at fence %d, above the site fence %d; nothing was allocated while Unverified' % (c['spec']['fence'], site_fence)) + + +if __name__ == '__main__': + command, state = sys.argv[1], pathlib.Path(sys.argv[2]) + {'import-inert': import_inert, 'staff-access': staff_access, 'contention': contention, 'release-waits': release_waits, + 'deadline-hold': deadline_hold, 'deadline-settled': deadline_settled, 'rebuild-before': rebuild_before, + 'rebuild-unverified': rebuild_unverified, 'rebuild-verified': rebuild_verified, + 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) diff --git a/hack/multiplane/site.sh b/hack/multiplane/site.sh index d816df6e..1f5b3cc9 100755 --- a/hack/multiplane/site.sh +++ b/hack/multiplane/site.sh @@ -11,7 +11,7 @@ step=${1:?step required} state=${2:?private state directory required} prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} cell="$state/cell-admin.yaml" provider=$(cat "$state/site-provider" 2>/dev/null || echo libvirt) deployments=(fleet-site-runtime fleet-site-boot fleet-site-observer) diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 6af24770..c052d5df 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -8,11 +8,16 @@ step=${1:?step required} state=${2:?private state directory required} prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} harness=(python3 hack/multiplane/harness.py) host="$state/fleet-multiplane-host" ns=fleet-coordination helpers=hack/multiplane/k8s_evidence.py +# Lab-only deadline for the one short-deadline admission. The scenario needs +# time to journal the installer boot and delete the Machine before it +# expires, which takes seconds; production keeps its own deadline. +deadline=${FLEET_MULTIPLANE_INSTALLATION_DEADLINE:-2m} +[[ $deadline =~ ^[1-9][0-9]*[sm]$ ]] || { echo "FLEET_MULTIPLANE_INSTALLATION_DEADLINE must be seconds or minutes, such as 2m" >&2; exit 64; } k() { kubectl --kubeconfig "$1" --request-timeout=20s "${@:2}"; } cell() { k "$state/cell-admin.yaml" "$@"; } @@ -39,14 +44,49 @@ local_phase() { cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o custody_digest() { "${harness[@]}" custody-digest --state "$state"; } # The Device's site store state: its fences and journal. store_state=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import harness; print(harness.STATE_PATH)') +# A store with no state file yet, before any assignment, digests as empty. journal_digest() { - runtime cat "$store_state" | python3 -c ' + runtime sh -c "cat '$store_state' 2>/dev/null || true" | python3 -c ' import hashlib,sys print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' } # The step the install has journaled once its installer boot was requested. installer_step=installer-start [[ $(cat "$state/site-provider" 2>/dev/null) != redfish ]] || installer_step=installer-power-on +scenario() { python3 hack/multiplane/scenarios.py "$@"; } +libvirt='qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' +# The local VM installer hold (hold-installer, release-installer). +hold_file=/tmp/fleet-installer-hold +redfish() { [[ $(cat "$state/site-provider" 2>/dev/null) == redfish ]]; } +# Effects on servers, independent of the site journal: the hypervisor's +# running domains and its append-only QEMU logs, in both modes, and the lab +# BMC audit in Redfish mode. Mark them, then require none after the mark. +server_effects() { + runtime sh -c 'virsh --connect "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock" list --name && { ls -ln /var/log/libvirt/qemu 2>/dev/null || true; }' | python3 -c ' +import hashlib,sys +print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' +} +audit_mark() { + server_effects > "$state/server-effects-mark" + ! redfish || python3 hack/multiplane/redfish_steps.py audit-mark "$state" +} +audit_unchanged() { + [[ $(server_effects) == "$(cat "$state/server-effects-mark")" ]] || { echo 'a domain started or a QEMU log changed' >&2; return 1; } + ! redfish || python3 hack/multiplane/redfish_steps.py audit-unchanged "$state" +} +# A cell site Deployment stopped for a fault. Its Flux layer is suspended +# first, so the harness is never a second writer, and resumed to restore it. +site_stop() { + cell -n flux-system patch kustomization/fleet-site-services --field-manager=fleet-fault-injection --type=merge -p '{"spec":{"suspend":true}}' >/dev/null + site scale "deployment/$1" --replicas=0 >/dev/null + for _ in $(seq 1 120); do [[ -z $(site get pods -l "app.kubernetes.io/name=$1" -o name) ]] && return; sleep 1; done + echo "$1 did not stop" >&2; return 1 +} +site_restore() { + cell -n flux-system patch kustomization/fleet-site-services --field-manager=fleet-fault-injection --type=merge -p '{"spec":{"suspend":false}}' >/dev/null + cell -n flux-system annotate --overwrite kustomization/fleet-site-services "reconcile.fluxcd.io/requestedAt=$(date +%s)" >/dev/null + site wait --for=jsonpath='{.status.availableReplicas}'=1 "deployment/$1" --timeout=300s >/dev/null +} wait_running_pod() { for _ in $(seq 1 "${2:-120}"); do uid=$(py running-pod "$state" "$1") @@ -63,6 +103,95 @@ case "$step" in b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].reason}') [[ $a == Bound/* && $b == Pending/InsufficientCapacity ]] || { echo "unexpected contention status: A=$a B=$b" >&2; exit 1; } printf 'contention: consumer-a %s; consumer-b %s\n' "$a" "$b" + scenario contention "$state" + ;; + tenant-isolation) + # Consumer A holds the Device and consumer B holds nothing. Nothing B's + # side asks for reaches the site or the server. + before=$(journal_digest) + audit_mark + "$host" tenant-isolation --config "$state/acceptance.json" + [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for an unheld tenant' >&2; exit 1; } + [[ -z $(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o name) ]] || { echo 'an assignment was delivered for an unheld tenant' >&2; exit 1; } + audit_unchanged + ;; + import-inert) + scenario import-inert "$state" + ;; + staff-access) + scenario staff-access "$state" + ;; + deadline-admit) + # Consumer B's installation is admitted under a short deadline + # (FLEET_MULTIPLANE_INSTALLATION_DEADLINE, two minutes by default) with + # the lab boot hook armed: the boot service stays Ready, so kro creates + # the worker, and withholds every boot, so the installer never runs and + # the worker waits for its receipt until the deadline. Only this admission + # uses the short deadline. A failure here restores the default + # coordinator and clears the hook, so a rerun starts clean. + trap 'bash hack/multiplane/coordinator.sh restart "$state" >/dev/null; site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR + site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold arm + bash hack/multiplane/coordinator.sh restart "$state" "--installation-deadline=$deadline" >/dev/null + "$host" admit-install-b --config "$state/acceptance.json" >/dev/null + bash hack/multiplane/coordinator.sh restart "$state" >/dev/null + trap 'site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR + scenario wait-installer "$state" "$installer_step" + trap - ERR + printf 'deadline-admit: the second installation was admitted under a %s deadline and journaled its installer boot with the lab boot hook withholding it\n' "$deadline" + ;; + machine-delete) + # The customer deletes Machine B mid-install. One release pass begins the + # release, which must wait for the installation. + k "$state/consumer-b/customer-project.json" -n default delete machine allocation --wait=false >/dev/null + "$host" release-b --config "$state/acceptance.json" --once >/dev/null 2>&1 || true + scenario release-waits "$state" + ;; + deadline-hold) + trap 'site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR + scenario deadline-hold "$state" + # A staff recovery naming the wrong hold is refused before anything is + # delivered or sent. + before=$(journal_digest) + audit_mark + "$host" recovery-mismatch --config "$state/acceptance.json" + [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for a refused recovery' >&2; exit 1; } + audit_unchanged + # The hook withheld the installation's boot: it counted at least one + # denial since it was armed. + denied=$(site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold denied) + [[ $denied =~ ^[0-9]+$ ]] && (( denied > 0 )) || { echo "the lab boot hook denied no boot request: ${denied:-none}" >&2; exit 1; } + # The release's wipe boots normally. + trap - ERR + site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear + printf 'deadline-hold: the lab boot hook denied %s boot requests\n' "$denied" + ;; + deadline-settled) + scenario deadline-settled "$state" + ;; + rebuild) + # Custody of the free Device is deleted while the site cannot report its + # fence: the observer answers fence reports, and the hub accepts none + # older than a minute. + scenario rebuild-before "$state" + # A failure hands the observer back to Flux, so a rerun starts clean. + trap 'site_restore fleet-site-observer' ERR + site_stop fleet-site-observer + sleep 75 + bootstrap="$state/provider/bootstrap-project.json" + k "$bootstrap" -n fleet-provider delete devicecustody synthetic-device-central-01 --wait=false >/dev/null + k "$bootstrap" -n fleet-provider patch devicecustody synthetic-device-central-01 --type=merge -p '{"metadata":{"finalizers":null}}' >/dev/null + scenario rebuild-unverified "$state" + # A new consumer-a Machine finds no eligible capacity while custody is + # Unverified. + customer="$state/consumer-a/customer-project.json" + k "$customer" -n default delete machine allocation --wait --timeout=60s >/dev/null + k "$customer" -n default create -f - >/dev/null <<'JSON' +{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"local"},"powerState":"Off"}} +JSON + "$host" probe-unallocatable --config "$state/acceptance.json" --once + trap - ERR + site_restore fleet-site-observer + scenario rebuild-verified "$state" ;; await-delivery) for _ in $(seq 1 120); do @@ -103,8 +232,52 @@ case "$step" in py worker-rbac "$state" "$name" rm -f "$state/worker-kubeconfig.json" ;; + hold-installer) + # Hold the installer guest paused as soon as its kernel prints, so the + # worker and BMC interruptions below always land mid-install, however fast + # the accelerator. A watcher in the runtime Pod suspends it; a guest that + # printed its receipt first is reported missed, never held. In Redfish mode + # the guest is lab target A, whose console log is append-only, so only + # output after the hold is armed counts. + runtime sh -c "[ ! -e $hold_file.pid ] && rm -f $hold_file" || { echo 'an installer hold is already armed' >&2; exit 1; } + if redfish; then mode=redfish; else mode=libvirt; fi + runtime sh -c 'setsid sh -c "$1" sh "$3" >/dev/null 2>&1 "$2.pid"' sh "$(cat <<'SH' +uri='qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' out=/tmp/fleet-installer-hold mode=$1 +lab=fleet-lab-target-a console=/var/lib/fleet-lab-console/target-a.log +offset=$(( $(wc -c < "$console" 2>/dev/null || echo 0) + 1 )) +since() { tail -c "+$offset" "$1" 2>/dev/null; } +end=$(($(date +%s) + 1500)) +while [ "$(date +%s)" -lt "$end" ]; do + for d in $(virsh --connect "$uri" list --name); do + if [ "$mode" = redfish ]; then + [ "$d" = "$lab" ] && since "$console" | grep -q 'Linux version' || continue + receipt() { since "$console" | grep -q 'FLEET-INSTALLED:'; } + else + case "$d" in fleet-local-*) ;; *) continue ;; esac + log=$(ls /var/lib/fleet-local/vm/*/"${d#fleet-local-}"/installer.log 2>/dev/null | head -1) + [ -n "$log" ] && grep -q 'Linux version' "$log" || continue + receipt() { grep -q 'FLEET-INSTALLED:' "$log"; } + fi + if virsh --connect "$uri" suspend "$d" >/dev/null 2>&1 && [ "$(virsh --connect "$uri" domstate "$d")" = paused ] && ! receipt; then + printf 'held %s %s %s\n' "$d" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$offset" > "$out.tmp" + else + printf 'missed %s\n' "$d" > "$out.tmp" + fi + mv "$out.tmp" "$out"; exit 0 + done + sleep 0.1 +done +echo expired > "$out" +SH +)" "$hold_file" "$mode" + printf 'hold-installer: armed; the installer guest is suspended once its kernel starts and before any receipt\n' + ;; interrupt-pod) name=$(cat "$state/install-handoff") + held= + for _ in $(seq 1 900); do held=$(runtime sh -c "cat $hold_file 2>/dev/null || true"); [[ -z $held ]] || break; sleep 1; done + [[ $held == held\ fleet-local-* || $held == held\ fleet-lab-target-a\ * ]] || { echo "installer guest was not held mid-install: ${held:-no hold}" >&2; exit 1; } + printf '%s\n' "$held" > "$state/installer-hold" "${harness[@]}" wait-stage --state "$state" --stage "$installer_step" --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" before=$(wait_running_pod "$name" 30) py job "$state" "$name" > "$state/interrupt-job-before-pod.json" @@ -122,7 +295,7 @@ case "$step" in py job "$state" "$name" > "$state/interrupt-job-after-pod.json" "${harness[@]}" journal --state "$state" > "$state/interrupt-after.json" py record-pod-interrupt "$state" "$before" "$after" - printf 'interrupt-pod: worker Pod force-deleted after the installer boot was journaled with its domain running; Job controller replaced it; no local result\n' + printf 'interrupt-pod: worker Pod force-deleted after the installer boot was journaled with its domain held paused; Job controller replaced it; no local result\n' ;; interrupt-job) name=$(cat "$state/install-handoff") @@ -147,6 +320,31 @@ case "$step" in py record-job-interrupt "$state" "$old_job" "$new_job" "$(cat "$state/interrupt-job-pod-before")" "$pod" printf 'interrupt-job: running worker Job deleted mid-install; kro recreated it under a new UID for the same operation\n' ;; + release-installer) + # The guest is still paused with no receipt; resume it for the replacement + # worker to observe, and record the hold in the interruption evidence. + read -r _ domain held_at offset < "$state/installer-hold" + [[ $(runtime virsh --connect "$libvirt" domstate "$domain" | head -1) == paused ]] || { echo 'held installer guest is no longer paused' >&2; exit 1; } + if redfish; then + runtime sh -c "! tail -c +$offset /var/lib/fleet-lab-console/target-a.log | grep -q FLEET-INSTALLED:" || { echo 'held installer printed a receipt while paused' >&2; exit 1; } + else + runtime sh -c "! grep -q FLEET-INSTALLED: /var/lib/fleet-local/vm/*/${domain#fleet-local-}/installer.log" || { echo 'held installer printed a receipt while paused' >&2; exit 1; } + fi + runtime virsh --connect "$libvirt" resume "$domain" >/dev/null + [[ $(runtime virsh --connect "$libvirt" domstate "$domain" | head -1) == running ]] || { echo 'held installer guest did not resume' >&2; exit 1; } + python3 - "$state/evidence/interrupt.json" "$domain" "$held_at" <<'PY' +import datetime,json,sys +p,domain,held=sys.argv[1:] +i=json.load(open(p)) +if i.get('domain')!=domain:raise SystemExit('held guest is not the interrupted operation domain') +i['installerHold']={'held':True,'domain':domain,'heldAt':held,'releasedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'domainStateDuringInterruptions':'paused', + 'method':'runtime Pod watcher suspended the guest once its kernel printed and before any receipt; resumed after the Pod and Job interruptions'} +json.dump(i,open(p,'w'),indent=2,sort_keys=True) +PY + runtime rm -f "$hold_file" "$hold_file.pid" + printf 'release-installer: the held installer guest resumed with no receipt printed during the interruptions\n' + ;; resume) name=$(cat "$state/install-handoff") site wait --for=condition=Complete "job/w-$name" --timeout=20m >/dev/null @@ -225,6 +423,7 @@ case "$step" in # duplicate the API refuses, an assignment naming another cell, and a # replay of an admitted operation below the Device's stored fence. before=$(journal_digest) + audit_mark py delivery-faults "$state" create for fault in wrong-cell stale-fence; do job=$(cat "$state/fault-$fault-job") @@ -233,13 +432,20 @@ case "$step" in done after=$(journal_digest) [[ $before == "$after" ]] || { echo 'site store changed during delivery faults' >&2; exit 1; } + audit_unchanged py delivery-faults "$state" verify py delivery-faults "$state" delete printf 'delivery-faults: duplicate refused by the API; wrong-cell and stale-fence deliveries failed their Jobs by podFailurePolicy before effects; site store unchanged; kro pruned them\n' ;; - release-status-a|release-status-b) + release-status-b) + # The customer deleted Machine B; its release removed the finalizer last. + r=$(k "$state/consumer-b/management-project.json" -n default get machine allocation 2>&1 || true) + [[ $r == *NotFound* ]] || { echo "deleted consumer-b Machine remains: $r" >&2; exit 1; } + printf 'release-status-b: consumer-b Machine deleted after its release finished\n' + ;; + release-status-a) # Released claims must not keep public readiness or an installation reference. - project=consumer-a; [[ $step == release-status-a ]] || project=consumer-b + project=consumer-a v=$(k "$state/$project/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}/{.status.conditions[?(@.type=="Ready")].status}/{.status.currentInstallationRef.name}/{.metadata.finalizers}') [[ $v == Released/False/False// ]] || { echo "released $project Machine phase/Bound/Ready/currentInstallationRef/finalizers: $v" >&2; exit 1; } if [[ $step == release-status-a ]]; then diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh index 96ef7fb3..1d9b1934 100755 --- a/hack/multiplane/stop.sh +++ b/hack/multiplane/stop.sh @@ -6,7 +6,7 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || exit 1 # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} # The cell node holds the site runtime, journal volume, kro and worker Jobs; the # platform node holds the Milo APIs and their etcd volumes; the registry holds # the source revisions. Earlier-layout container names are kept for old runs. diff --git a/hack/multiplane/sysctl.py b/hack/multiplane/sysctl.py index 2f2b3658..716bc217 100755 --- a/hack/multiplane/sysctl.py +++ b/hack/multiplane/sysctl.py @@ -1,16 +1,18 @@ #!/usr/bin/env python3 -"""Reversible, explicitly opted-in inotify adjustment in the task Colima VM.""" +"""Reversible, explicitly opted-in inotify adjustment in the task Colima VM, or on the disposable CI runner.""" import json,os,pathlib,subprocess,sys +sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))) +import harness s=pathlib.Path(sys.argv[1]);action=sys.argv[2];prefix=(s/'prefix').read_text().strip() -os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +os.environ['DOCKER_CONTEXT']=harness.CONTEXT def run(*args):return subprocess.check_output(args,text=True).strip() -endpoint=run('docker','context','inspect','colima-fleet-acceptance-tcg','--format','{{.Endpoints.docker.Host}}') -if not endpoint.endswith('/.colima/fleet-acceptance-tcg/docker.sock'):raise SystemExit('unexpected Colima profile') +endpoint=run('docker','context','inspect',harness.CONTEXT,'--format','{{.Endpoints.docker.Host}}') +if not harness.endpoint_matches(0,endpoint):raise SystemExit('unexpected Docker runtime endpoint') node=prefix+'-hub-control-plane';current=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) if action=='set': if (s/'sysctl.json').exists():raise SystemExit('sysctl evidence already exists; do not overwrite original value') if current<1024 and os.environ.get('FLEET_MULTIPLANE_INOTIFY')!='1024':raise SystemExit('Requires fs.inotify.max_user_instances>=1024. Opt into reversible task-VM adjustment with FLEET_MULTIPLANE_INOTIFY=1024') - record={'context':'colima-fleet-acceptance-tcg','setting':'fs.inotify.max_user_instances','original':current,'effective':max(current,1024)} + record={'context':harness.CONTEXT,'setting':'fs.inotify.max_user_instances','original':current,'effective':max(current,1024)} (s/'sysctl.json').write_text(json.dumps(record,indent=2)) if current<1024:run('docker','exec',node,'sysctl','-w','fs.inotify.max_user_instances=1024') record['observedEffective']=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index 8d2ec172..d2aa5ceb 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Delete only this run's exact containers, kind clusters and provider image tag. -# Default: only after evidence/summary.json records passed acceptance (verified -# cleanup and release), then remove private credentials and keep evidence. +# Default: only after evidence/summary.json records verified acceptance evidence +# (verified cleanup and release), then remove private credentials and keep +# evidence. Whether the run passed is recorded only in evidence/result.json. # --discard-unknown is an explicit human decision to abandon an Unknown run; it # deletes the same exact resources, keeps all private state, and never claims release. set -euo pipefail @@ -14,10 +15,10 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo 'unexpected prefix' >&2; exit 1; } # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} KIND_EXPERIMENTAL_PROVIDER=docker if [[ $mode == passed ]]; then - python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="passed")' "$state/evidence/summary.json" 2>/dev/null || { - echo 'No passed acceptance summary; refusing teardown. Use --discard-unknown only after inspection.' >&2; exit 1; } + python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="evidence-verified")' "$state/evidence/summary.json" 2>/dev/null || { + echo 'No verified acceptance evidence; refusing teardown. Use --discard-unknown only after inspection.' >&2; exit 1; } fi hub="$prefix-hub-control-plane" if docker inspect "$hub" >/dev/null 2>&1; then diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index de101577..38f2da5e 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -129,10 +129,16 @@ def render(rev, cluster): for f in (root / layer).glob('*.yaml'): used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) check('substituted variables defined', used and used <= env_keys, str(sorted(used - env_keys))) + check('site accelerator is the run parameter, TCG by default', 'FLEET_LOCAL_VM_ACCEL: tcg\n' in cell3.replace('"', '')) check('graph uses no Flux variables', not re.findall(r'\$\{FLEET_', (root / 'config/site/graph/rgd.yaml').read_text())) check('stage off revision', flux.stage(ns(revision=2, site='off')) == 0 and 'FLEET_SITE_DISPATCH: "false"' in render(2, 'cell')) flux.stage(ns(revision=4, site='dispatch', bad_kro_chart=True)) check('bad chart revision patches only kro', flux.MISSING_DIGEST in render(4, 'cell') and flux.KRO_CHART_DIGEST not in render(4, 'cell')) + def kro_timeout(revision): + docs = [d for d in render(revision, 'cell').split('\n---\n') if 'kind: Kustomization\n' in d and re.search(r'^ name: kro$', d, re.M)] + return re.findall(r'^ timeout: (\S+)$', docs[0], re.M) if len(docs) == 1 else docs + check('bad chart revision shortens only the kro health timeout', kro_timeout(4) == [flux.FAIL_CLOSED_TIMEOUT] and kro_timeout(3) == ['3m'], + '%s %s' % (kro_timeout(4), kro_timeout(3))) flux.stage(ns(revision=6, site='dispatch', drop_site_volume=True)) check('volume removal revision', '$patch: delete' in render(6, 'cell') and 'fleet-site-state' in render(6, 'cell')) sums = (s / 'gitops' / 'r3.SHA256SUMS').read_text() diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 244f8f04..4fb10ac5 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -7,6 +7,7 @@ for f in "$root"/hack/multiplane/*.sh; do bash -n "$f"; done python3 -m py_compile "$root"/hack/multiplane/*.py python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" python3 "$root"/hack/multiplane/test-redfish.py "$root" +python3 "$root"/hack/multiplane/test-interrupt.py "$root" python3 -m py_compile "$root"/hack/redfish-lab/*.py exec python3 - "$root" <<'PY' import json, os, pathlib, re, stat, subprocess, sys, tempfile, time @@ -25,11 +26,12 @@ tool = os.path.basename(sys.argv[0]); a = sys.argv[1:] scenario = os.environ.get('FAKE', '') with open(os.environ['FAKE_TRACE'], 'a') as t: t.write(json.dumps([tool] + a) + '\n') if tool == 'docker': + with open(os.environ['FAKE_TRACE'] + '.context', 'a') as t: t.write(os.environ.get('DOCKER_CONTEXT', '') + '\n') if a[:2] == ['context', 'inspect']: if scenario == 'no-context': sys.exit(1) - print('unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock'); sys.exit(0) + print(os.environ.get('FAKE_ENDPOINT', 'unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock')); sys.exit(0) if a[:1] == ['info']: - print(json.dumps({'Architecture': 'aarch64', 'MemTotal': 8308948992, 'NCPU': 4})); sys.exit(0) + print(json.dumps({'Architecture': os.environ.get('FAKE_ARCH', 'aarch64'), 'MemTotal': 8308948992, 'NCPU': 4})); sys.exit(0) if a[:1] == ['ps']: if '-a' in a: print('fleet-mp-0000aaaa-vm\texited'); sys.exit(0) print('fleet-mp-1234abcd-vm' if scenario == 'busy' else 'unrelated'); sys.exit(0) @@ -45,8 +47,12 @@ if tool == 'kubectl' and 'exec' in a and 'deploy/fleet-site-runtime' in a: if 'virsh' in a: import hashlib print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:16]); sys.exit(0) -if tool == 'colima': - if 'df' in a[-1]: print('/dev/vdb1 41000000 20000000 %d 50%% /var/lib/docker' % (int(os.environ.get('FAKE_FREE_KB', '20000000')))) +# CI mode runs the same read-only host probes on the runner itself (sh -c). +if tool in ('colima', 'sh'): + if 'kvm' in a[-1]: + if os.environ.get('FAKE_KVM') == 'absent': sys.exit(1) + print('present') + elif 'df' in a[-1]: print('/dev/vdb1 41000000 20000000 %d 50%% /var/lib/docker' % (int(os.environ.get('FAKE_FREE_KB', '20000000')))) elif 'inotify' in a[-1]: print(os.environ.get('FAKE_INOTIFY', '1024')) sys.exit(0) sys.exit(0) @@ -59,7 +65,15 @@ with tempfile.TemporaryDirectory() as tmp: p = bin_dir / tool; p.write_text(FAKE.replace('#!/usr/bin/env python3', '#!' + sys.executable)); p.chmod(0o755) trace = tmp / 'trace' base = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_TRACE=str(trace)) - base.pop('FLEET_MULTIPLANE_INOTIFY', None) + for name in ('FLEET_MULTIPLANE_INOTIFY', 'FLEET_MULTIPLANE_RUNTIME', 'FLEET_MULTIPLANE_DOCKER_CONTEXT', 'FLEET_MULTIPLANE_ARCH', + 'FLEET_MULTIPLANE_ACCEL', 'FLEET_SITE_PROVIDER', 'GITHUB_ACTIONS', 'RUNNER_ENVIRONMENT', 'DOCKER_CONTEXT'): + base.pop(name, None) + # CI-mode host probes go through a fake sh, on PATH only for those runs. + ci_bin = tmp / 'ci-bin'; ci_bin.mkdir() + (ci_bin / 'sh').write_text(FAKE.replace('#!/usr/bin/env python3', '#!' + sys.executable)); (ci_bin / 'sh').chmod(0o755) + ci = {'PATH': str(ci_bin) + os.pathsep + base['PATH'], 'FLEET_MULTIPLANE_RUNTIME': 'ci', 'FLEET_MULTIPLANE_DOCKER_CONTEXT': 'default', + 'FLEET_MULTIPLANE_ARCH': 'amd64', 'FLEET_MULTIPLANE_ACCEL': 'kvm', 'GITHUB_ACTIONS': 'true', 'RUNNER_ENVIRONMENT': 'github-hosted', + 'FAKE_ENDPOINT': 'unix:///var/run/docker.sock', 'FAKE_ARCH': 'x86_64'} def run(args, env=None, **kw): return subprocess.run([sys.executable, str(harness), *args], text=True, capture_output=True, env=dict(base, **(env or {})), **kw) @@ -68,8 +82,9 @@ with tempfile.TemporaryDirectory() as tmp: d = pathlib.Path(tempfile.mkdtemp(dir=tmp)); d.chmod(0o700); return d good_root = tmp / 'good'; (good_root / 'cmd/fleet-multiplane').mkdir(parents=True) - markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] - (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed') + markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', + 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable', 'tenant-isolation'] + (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed "redfish-probe" redfish.NewPinnedClient') bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) (bad_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers)) @@ -92,6 +107,56 @@ with tempfile.TemporaryDirectory() as tmp: calls = [json.loads(l) for l in trace.read_text().splitlines()] check('preflight never mutates runtime', not any(c[0] == 'docker' and c[1] in ('rm', 'stop', 'kill', 'network', 'volume', 'system') for c in calls)) check('preflight never starts colima without --bootstrap', not any(c[0] == 'colima' and 'start' in c for c in calls)) + check('default runtime recorded', pre['runtime'] == {'mode': 'colima', 'dockerContext': 'colima-fleet-acceptance-tcg', 'architecture': 'arm64', 'accelerator': 'tcg'}, str(pre.get('runtime'))) + + # Run parameters: CI mode replaces only the Colima-specific probes; every + # combination it cannot honor fails closed before any resource exists. + for name, env, expected in ( + ('ci kvm pass', dict(ci), 0), + ('ci tcg pass', dict(ci, FLEET_MULTIPLANE_ACCEL='tcg'), 0), + ('ci redfish tcg pass', dict(ci, FLEET_MULTIPLANE_ACCEL='tcg', FLEET_SITE_PROVIDER='redfish'), 0), + ('ci outside GitHub Actions', dict(ci, GITHUB_ACTIONS=''), 2), + ('ci on a self-hosted runner', dict(ci, RUNNER_ENVIRONMENT='self-hosted'), 2), + ('ci against a Colima socket', dict(ci, FAKE_ENDPOINT='unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock'), 2), + ('colima against the runner socket', {'FAKE_ENDPOINT': 'unix:///var/run/docker.sock'}, 2), + ('ci architecture mismatch', dict(ci, FAKE_ARCH='aarch64'), 2), + ('ci unknown architecture', dict(ci, FLEET_MULTIPLANE_ARCH='riscv64', FLEET_MULTIPLANE_ACCEL='tcg'), 2), + ('ci without /dev/kvm', dict(ci, FAKE_KVM='absent'), 2), + ('ci low disk', dict(ci, FAKE_FREE_KB='1000'), 2), + ('ci concurrent runtime', dict(ci, FAKE='busy'), 2), + ('ci redfish kvm pass', dict(ci, FLEET_SITE_PROVIDER='redfish'), 0), + ('redfish kvm without /dev/kvm', dict(ci, FLEET_SITE_PROVIDER='redfish', FAKE_KVM='absent'), 2), + ('kvm on an arm64 runtime', {'FLEET_MULTIPLANE_ACCEL': 'kvm'}, 2), + ('unknown accelerator', {'FLEET_MULTIPLANE_ACCEL': 'auto'}, 2), + ('unknown runtime', {'FLEET_MULTIPLANE_RUNTIME': 'lima'}, 2), + ('ci unknown scenario group', dict(ci, FLEET_MULTIPLANE_GROUP='deadline'), 2), + ('ci flux group pass', dict(ci, FLEET_MULTIPLANE_GROUP='flux'), 0)): + s = state(); trace.write_text(''); pathlib.Path(str(trace) + '.context').write_text('') + r = run(['preflight', '--state', str(s), '--root', str(good_root), '--skip-tests'], env) + check('preflight ' + name, r.returncode == expected, 'exit %s: %s' % (r.returncode, r.stdout[-600:])) + if name in ('ci unknown scenario group', 'ci flux group pass'): + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check(name + ' recorded', pre['group'] == env['FLEET_MULTIPLANE_GROUP'] and + [c['ok'] for c in pre['checks'] if c['name'] == 'scenario-group'] == [name.endswith('pass')], str(pre['checks'])) + if name == 'ci kvm pass': + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check('ci runtime recorded', pre['runtime'] == {'mode': 'ci', 'dockerContext': 'default', 'architecture': 'amd64', 'accelerator': 'kvm'}, str(pre['runtime'])) + check('ci checks kvm and keeps the safety checks', {'kvm-device', 'no-concurrent-fleet-runtime', 'runtime-disk', 'runtime-memory', 'runtime-cpus', 'inotify-instances', 'ci-runner', 'amd64-emulation'} + <= {c['name'] for c in pre['checks'] if c['ok']}, str(pre['checks'])) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('ci mode never touches colima', not any(c[0] == 'colima' for c in calls), str(calls)) + check('ci mode uses only the selected context', set(pathlib.Path(str(trace) + '.context').read_text().split()) == {'default'}) + + # run.sh exports the defaults to every step, and passes overrides through. + for name, env, want in ( + ('run.sh defaults', {}, {'mode': 'colima', 'dockerContext': 'colima-fleet-acceptance-tcg', 'architecture': 'arm64', 'accelerator': 'tcg'}), + ('run.sh ci parameters', ci, {'mode': 'ci', 'dockerContext': 'default', 'architecture': 'amd64', 'accelerator': 'kvm'})): + runs = pathlib.Path(tempfile.mkdtemp(dir=tmp)) + r = subprocess.run(['bash', str(root / 'hack/multiplane/run.sh'), '--preflight-only', '--skip-readiness-tests'], text=True, capture_output=True, + env=dict(base, FLEET_MULTIPLANE_STATE_ROOT=str(runs), **env)) + states = list(runs.iterdir()) + pre = json.loads((states[0] / 'evidence/preflight.json').read_text()) if len(states) == 1 else {} + check(name, r.returncode == 0 and pre.get('runtime') == want, 'exit %s %s: %s' % (r.returncode, pre.get('runtime'), (r.stdout + r.stderr)[-600:])) # Bounded phases: pass, fail, blocked passthrough, timeout kills the process group. s = state() @@ -158,16 +223,57 @@ with tempfile.TemporaryDirectory() as tmp: (s / 'evidence/leak.json').write_text('{"v":"%s"}' % secret) check('scan detects ' + secret[0], run(['scan', '--state', str(s)]).returncode == 1) check('scan redacts ' + secret[0], secret not in (s / 'evidence/leak.json').read_text()) + (s / 'evidence/leak.json').unlink() + (s / 'evidence/nested').mkdir() + (s / 'evidence/nested/deep.json').write_text('{"v":"%s"}' % ('w' * 40)) + check('scan detects a nested leak', run(['scan', '--state', str(s)]).returncode == 1) + check('scan redacts the nested file itself', 'w' * 40 not in (s / 'evidence/nested/deep.json').read_text()) + check('scan is clean after redaction', run(['scan', '--state', str(s)]).returncode == 0) - # Result: status mapping and retained owned containers. + # Result: status mapping and retained owned containers. Exit 0 is passed + # only with the completion marker run.sh writes last. s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n') - for code, status in ((0, 'passed'), (1, 'failed'), (2, 'preflight-failed'), (3, 'blocked'), (4, 'timeout')): + (s / 'completed').write_text('') + for code, status in ((0, 'passed'), (1, 'failed'), (2, 'preflight-failed'), (3, 'blocked'), (4, 'timeout'), (143, 'interrupted'), (130, 'interrupted')): run(['result', '--state', str(s), '--exit-code', str(code)]) res = json.loads((s / 'evidence/result.json').read_text()) check('result ' + status, res['status'] == status and res['productionAuthority'] is False) check('result lists retained containers', res['retainedContainers'] == [{'name': 'fleet-mp-0000aaaa-vm', 'state': 'exited'}], str(res['retainedContainers'])) check('result keeps unknown custody', 'Unknown' in res['custody']) + # Verify: a pass needs status passed, every phase passed, teardown passed + # and no retained container, whatever the exit code said. + def verified(result, *args): + s = state(); (s / 'evidence').mkdir(); (s / 'evidence/result.json').write_text(json.dumps(result)) + return run(['verify', '--state', str(s), *args]).returncode + good = {'status': 'passed', 'exitCode': 0, 'group': 'flux', 'retainedContainers': [], 'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'teardown', 'status': 'passed'}]} + check('verify passes a completed run', verified(good) == 0) + check('verify passes the expected scenario group', verified(good, '--group', 'flux') == 0) + check('verify refuses another scenario group', verified(good, '--group', 'release') == 1) + check('verify refuses a run that recorded no group', verified({k: v for k, v in good.items() if k != 'group'}, '--group', 'all') == 1) + for name, change in (('interrupted', {'status': 'interrupted', 'exitCode': 1}), ('timeout', {'status': 'timeout', 'exitCode': 4}), + ('a failed phase', {'phases': [{'name': 'build', 'status': 'timeout'}, {'name': 'teardown', 'status': 'passed'}]}), + ('no teardown', {'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'stop', 'status': 'passed'}]}), + ('retained containers', {'retainedContainers': [{'name': 'fleet-mp-0000aaaa-vm', 'state': 'exited'}]})): + check('verify refuses ' + name, verified(dict(good, **change)) == 1) + s = state() + check('verify refuses a missing result', run(['verify', '--state', str(s)]).returncode == 1) + + # The installer hold: the watcher suspends a guest whose kernel printed and + # reports a guest that printed its receipt first as missed, never held. + steps_text = (root / 'hack/multiplane/steps.sh').read_text() + watcher = steps_text.split("<<'SH'\n", 1)[1].split('\nSH\n', 1)[0] + for name, console, want in (('held', 'Linux version 6.1\n', 'held '), ('missed', 'Linux version 6.1\nFLEET-INSTALLED:' + 'r' * 64 + '\n', 'missed ')): + h = pathlib.Path(tempfile.mkdtemp(dir=tmp)) + (h / 'vm/dev/0123456789abcdef').mkdir(parents=True); (h / 'vm/dev/0123456789abcdef/installer.log').write_text(console) + (h / 'bin').mkdir() + (h / 'bin/virsh').write_text('#!/bin/sh\nfor a; do last=$a; done\ncase "$3" in list) echo fleet-local-0123456789abcdef ;; suspend) echo "$4" > "%s/suspended" ;; domstate) [ -e "%s/suspended" ] && echo paused || echo running ;; esac\n' % (h, h)) + (h / 'bin/virsh').chmod(0o755) + script = watcher.replace('/var/lib/fleet-local/vm', str(h / 'vm')).replace('/tmp/fleet-installer-hold', str(h / 'hold')) + r = subprocess.run(['sh', '-c', script], text=True, capture_output=True, env=dict(os.environ, PATH=str(h / 'bin') + os.pathsep + os.environ['PATH']), timeout=30) + result = (h / 'hold').read_text() if (h / 'hold').exists() else '' + check('installer hold ' + name, r.returncode == 0 and result.startswith(want + 'fleet-local-0123456789abcdef'), repr(result) + r.stderr[-300:]) + # Teardown refuses without passed acceptance, before touching the runtime. s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n'); (s / 'evidence').mkdir() trace.write_text('') @@ -176,6 +282,9 @@ with tempfile.TemporaryDirectory() as tmp: (s / 'evidence/summary.json').write_text('{"acceptance":"failed"}') r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) check('teardown refuses failed summary', r.returncode == 1) + (s / 'evidence/summary.json').write_text('{"acceptance":"passed"}') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) + check('teardown refuses a summary that claims the run passed', r.returncode == 1) check('teardown refusal is effect-free', trace.read_text() == '') (s / 'prefix').write_text('other-prefix\n') r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s), '--discard-unknown'], text=True, capture_output=True, env=base) @@ -184,17 +293,60 @@ with tempfile.TemporaryDirectory() as tmp: check('run usage', r.returncode == 64) # Static guards for runtime-only step code the offline fakes cannot execute. + for f in sorted((root / 'hack/multiplane').glob('*.*')): + if f.suffix in ('.sh', '.py') and not f.name.startswith('test-'): + text = f.read_text() + check('docker context is the run parameter: ' + f.name, 'DOCKER_CONTEXT=colima' not in text and "['DOCKER_CONTEXT']='colima" not in text + and "['DOCKER_CONTEXT'] = 'colima" not in text and "'context','inspect','colima" not in text) + run_text = (root / 'hack/multiplane/run.sh').read_text() + check('site binary built for the selected architecture', 'GOARCH="$FLEET_MULTIPLANE_ARCH"' in run_text and 'GOARCH=arm64' not in run_text) + check('site accelerator is the run parameter', 'FLEET_LOCAL_VM_ACCEL, value: tcg' not in (root / 'config/site/services/services.yaml').read_text() + and '{name: FLEET_LOCAL_VM_ACCEL, value: "${schema.spec.accelerator}"}' in (root / 'config/site/graph/rgd.yaml').read_text() + and 'accelerator: "${FLEET_LOCAL_VM_ACCEL}"' in (root / 'config/site/instance/dispatcher.yaml').read_text()) + runtime_text = (root / 'hack/local-vm/site-runtime').read_text() + bmc_text = (root / 'config/site/redfish/services/bmc.yaml').read_text() + adapter_text = (root / 'hack/redfish-lab/fleet_lab_adapter.py').read_text() + check('lab BMC runs targets only under the runtime accelerator', '{name: FLEET_LAB_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"}' in bmc_text + and adapter_text.count('require_accelerator()') == 3 and "('kvm' if ACCEL == 'kvm' else 'qemu')" in adapter_text) + redfish_suite = (root / 'hack/multiplane/acceptance-redfish.sh').read_text().splitlines() + check('Redfish interruptions land on a held installer', redfish_suite.index('step hold-installer 120') < redfish_suite.index('step dispatch 900') + < redfish_suite.index('step interrupt-job 600') < redfish_suite.index('step release-installer 120') < redfish_suite.index('rf lost-response 1200')) + check('site runtime requires the KVM device and publishes its accelerator', 'kvm) [ -c /dev/kvm ]' in runtime_text and ' *) echo' in runtime_text + and '"$sock/accelerator"' in runtime_text) + check('interrupts land on a held installer in local VM mode', 'step hold-installer' in (root / 'hack/multiplane/acceptance.sh').read_text() + and 'step release-installer' in (root / 'hack/multiplane/acceptance.sh').read_text() and "installerHold" in (root / 'hack/multiplane/evidence.py').read_text()) steps = (root / 'hack/multiplane/steps.sh').read_text() evidence = (root / 'hack/multiplane/evidence.py').read_text() + # The partition marker is counted from real output only: the shell's + # trace of its printf shows the format, and a kernel message may prefix it. + import re as _re + partitioned = _re.compile(_re.search(r"PARTITIONED = re.compile\(r'([^']+)'\)", evidence).group(1)) + receipt = 'ab' * 32 + traced = subprocess.run(['sh', '-xc', "printf 'FLEET-PARTITIONED:%s\\n' \"$1\"", 'sh', receipt], text=True, capture_output=True) + log = traced.stderr + '[ 1.5] vda: vda1\n' + traced.stdout.replace('FLEET-', '[ 1.6] virtio_blk: ok FLEET-', 1) + check('init prints the partition marker after sfdisk', "sfdisk /dev/vda\n# One line" in (root / 'hack/local-vm/init').read_text() + and "printf 'FLEET-PARTITIONED:%s\\n' \"$receipt\"" in (root / 'hack/local-vm/init').read_text()) + check('partition marker ignores its own trace', 'FLEET-PARTITIONED:' in traced.stderr and partitioned.findall(log) == [receipt], log) + check('partition marker counts a second partition', partitioned.findall(log + traced.stdout) == [receipt, receipt]) for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['custody-crd-rules', 'allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', + order = ['custody-crd-rules', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'tenant-isolation', 'admit-install', 'await-delivery', 'partition', 'hold-installer', 'dispatch', 'interrupt-pod', 'interrupt-job', 'release-installer', 'resume', 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', 'reflection-faults', 'release', 'release-status-a', - 'reuse', 'reuse-status', 'delivery-faults', 'release-b', 'release-status-b', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] + 'reuse', 'reuse-status', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', + 'rebuild', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] positions = [sequence.find(' ' + name + ' ') for name in order] check('acceptance phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) + # Each group gates exactly its scenarios in both suites; the rest run in every group. + import re as _re + for suite in ('acceptance.sh', 'acceptance-redfish.sh'): + text = (root / 'hack/multiplane' / suite).read_text() + blocks = {g: [l.split()[1] for l in b.strip().splitlines()] for g, b in _re.findall(r'^if runs (\w+); then\n(.*?)^fi$', text, _re.M | _re.S)} + check(suite + ' flux group', blocks.get('flux') == ['graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'], str(blocks.get('flux'))) + check(suite + ' release group', blocks.get('release') == ['reflection-faults', 'release', 'release-status-a', 'reuse', 'reuse-status', 'delivery-faults', 'deadline-admit', + 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', 'rebuild', 'wrong-location', 'boot-denials'], + str(blocks.get('release'))) for name in order: if name in ('custody-crd-rules', 'allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'): diff --git a/hack/multiplane/test-interrupt.py b/hack/multiplane/test-interrupt.py new file mode 100644 index 00000000..f5b26a47 --- /dev/null +++ b/hack/multiplane/test-interrupt.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""An interrupted run never reports or records passed. + +Runs the real run.sh in a scratch copy of the repository, with the real +harness except for its preflight, which needs a container runtime, and a fake +`go` that keeps the first phase running. Then it interrupts the run mid-phase +and checks the RESULT line, evidence/result.json and the exit code. It also +checks the other exits that end with code 0: a preflight-only run, and a run +that exits 0 before it completed. +""" +import json +import os +import pathlib +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +root = pathlib.Path(sys.argv[1]).resolve() +failures = [] + + +def check(name, condition, detail=''): + if not condition: + failures.append(name + (': ' + detail if detail else '')) + + +SHIM = '''import importlib.util, sys +spec = importlib.util.spec_from_file_location('harness', %r) +harness = importlib.util.module_from_spec(spec) +sys.modules['harness'] = harness +spec.loader.exec_module(harness) +# The preflight needs a container runtime; everything else is the real harness. +harness.preflight = lambda args: 0 +sys.exit(harness.main()) +''' + + +def scratch(tmp): + """A repository copy holding run.sh, a harness shim, and fake tools.""" + repo = tmp / 'repo' + (repo / 'hack/multiplane').mkdir(parents=True) + shutil.copy(root / 'hack/multiplane/run.sh', repo / 'hack/multiplane/run.sh') + (repo / 'hack/multiplane/harness.py').write_text(SHIM % str(root / 'hack/multiplane/harness.py')) + (repo / 'hack/multiplane/stop.sh').write_text('#!/bin/sh\nexit 0\n') + for name in ('go.mod', 'go.sum'): + (repo / name).write_text('') + bin_dir = tmp / 'bin' + bin_dir.mkdir() + # go keeps the build phase running; docker reports no containers. + # The marker names this scratch copy, so the leftover check sees only + # this run's phase command. + for tool, body in (('go', 'exec python3 -c "import time; time.sleep(120)" %s' % tmp.name), ('docker', 'exit 0')): + path = bin_dir / tool + path.write_text('#!/bin/sh\n' + body + '\n') + path.chmod(0o755) + env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FLEET_MULTIPLANE_STATE_ROOT=str(tmp)) + return repo, env + + +def result_of(tmp): + results = list(tmp.glob('fleet-multiplane.*/evidence/result.json')) + return json.loads(results[0].read_text()) if len(results) == 1 else None + + +def default_signals(): + """Give the run default signal dispositions. A parent started under nohup + or as a background job ignores SIGHUP or SIGINT, and bash cannot trap a + signal that was ignored when it started, so the test would then exercise + the parent's dispositions, not run.sh.""" + for sig in (signal.SIGINT, signal.SIGHUP, signal.SIGTERM): + signal.signal(sig, signal.SIG_DFL) + + +def interrupted(sig): + with tempfile.TemporaryDirectory() as t: + tmp = pathlib.Path(t) + repo, env = scratch(tmp) + log = open(tmp / 'run.out', 'w') + p = subprocess.Popen(['bash', str(repo / 'hack/multiplane/run.sh')], cwd=repo, env=env, text=True, + stdout=log, stderr=subprocess.STDOUT, start_new_session=True, preexec_fn=default_signals) + deadline = time.monotonic() + 60 + while time.monotonic() < deadline and not list(tmp.glob('fleet-multiplane.*/logs/build.log')): + time.sleep(0.2) + check(sig.name + ': the build phase started', bool(list(tmp.glob('fleet-multiplane.*/logs/build.log')))) + time.sleep(1) + # Signal only the run itself, as an operator would. It must stop its + # phase promptly and record the interruption. + p.send_signal(sig) + try: + p.wait(timeout=60) + except subprocess.TimeoutExpired: + check(sig.name + ': the run stopped within 60 seconds of the signal', False) + finally: + time.sleep(1) + leftover = subprocess.run(['pgrep', '-f', r'sleep\(120\) %s' % tmp.name], capture_output=True, text=True).stdout.split() + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + log.close() + check(sig.name + ': the phase command was stopped', not leftover, str(leftover)) + out = (tmp / 'run.out').read_text() + lines = [l for l in out.splitlines() if l.startswith('RESULT ')] + result = result_of(tmp) + check(sig.name + ': nonzero exit', p.returncode != 0, str(p.returncode)) + check(sig.name + ': RESULT line is not passed', bool(lines) and not lines[-1].startswith('RESULT passed'), str(lines)) + check(sig.name + ': result.json is not passed', result is not None and result['status'] != 'passed', str(result and result['status'])) + check(sig.name + ': result.json names the interrupted phase', result is not None and result.get('failedPhase') == 'build', + str(result and result.get('failedPhase'))) + check(sig.name + ': result.json exit code is nonzero', result is not None and result['exitCode'] != 0, str(result and result['exitCode'])) + + +for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + interrupted(sig) + +# A preflight-only run that succeeds is not an acceptance pass. +with tempfile.TemporaryDirectory() as t: + tmp = pathlib.Path(t) + repo, env = scratch(tmp) + r = subprocess.run(['bash', str(repo / 'hack/multiplane/run.sh'), '--preflight-only'], cwd=repo, env=env, text=True, capture_output=True, timeout=120) + result = result_of(tmp) + check('preflight-only: exit 0', r.returncode == 0, str(r.returncode) + r.stdout[-300:] + r.stderr[-300:]) + check('preflight-only: not recorded as passed', result is not None and result['status'] == 'preflight-passed', str(result and result['status'])) + +# An exit 0 without the completion marker is never passed. +with tempfile.TemporaryDirectory() as t: + state = pathlib.Path(t) + (state / 'evidence').mkdir() + env = dict(os.environ, PATH=str(state) + os.pathsep + os.environ['PATH']) + docker = state / 'docker' + docker.write_text('#!/bin/sh\nexit 0\n') + docker.chmod(0o755) + r = subprocess.run([sys.executable, str(root / 'hack/multiplane/harness.py'), 'result', '--state', str(state), '--exit-code', '0'], env=env, text=True, capture_output=True) + result = json.loads((state / 'evidence/result.json').read_text()) + check('incomplete exit 0: not passed', result['status'] != 'passed' and not r.stdout.startswith('RESULT passed'), result['status']) + check('incomplete exit 0: nonzero', r.returncode != 0 and result['exitCode'] != 0, str(r.returncode)) + +if failures: + print('FAIL interrupt tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS interrupt tests') diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 846eb322..407dd14c 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -149,12 +149,12 @@ def build(path): sequence = (root / 'hack/multiplane/acceptance-redfish.sh').read_text() steps = (root / 'hack/multiplane/steps.sh').read_text() redfish_steps = (root / 'hack/multiplane/redfish_steps.py').read_text() -for name in re.findall(r'^step (\S+)', sequence, re.M): +for name in re.findall(r'^\s*step (\S+)', sequence, re.M): check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) -for name in re.findall(r'^rf (\S+)', sequence, re.M): +for name in re.findall(r'^\s*rf (\S+)', sequence, re.M): check('redfish step implemented: ' + name, "'%s':" % name in redfish_steps) order = ['baseline', 'discovery-faults', 'allocate', 'arm-lost-response', 'dispatch', 'bmc-interrupt', 'interrupt-pod', 'interrupt-job', 'lost-response', 'resume', 'release', - 'reuse', 'delivery-faults', 'install-b', 'release-b', 'boot-denials', 'isolation', 'evidence'] + 'reuse', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'rebuild', 'boot-denials', 'isolation', 'evidence'] positions = [sequence.find(' ' + n + ' ') for n in order] check('Redfish phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) for path in sorted(list((root / 'internal/redfish').glob('*.go')) + list((root / 'internal/site/redfishwork').glob('*.go'))): @@ -170,6 +170,11 @@ def build(path): check('no OpenStack dependency', not re.search(r'sushy|openstack|ironic', (lock + adapter + (root / 'hack/redfish-lab/Containerfile').read_text()).lower())) run_sh = (root / 'hack/multiplane/run.sh').read_text() +# Isolation runs in every group; only the groups that release target A may +# require its disk zeroed and every target off. +iso = redfish_steps.split('def isolation(s):')[1].split('\ndef ')[0] +check('isolation requires a wiped target A only where a release ran', "released = harness.GROUP != 'flux'" in iso + and "if released and a['diskSHA256']" in iso and "if released and record['runningDomains']" in iso) # $state/provider is the Milo provider project's credential directory. check('site provider marker does not collide with the provider project state', '"$state/site-provider"' in run_sh and '> "$state/provider"' not in run_sh) diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh index d10e43cf..b1093d67 100644 --- a/hack/multiplane/topology.sh +++ b/hack/multiplane/topology.sh @@ -8,7 +8,7 @@ umask 077 state=${1:?private state directory required} prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} KIND_EXPERIMENTAL_PROVIDER=docker node='kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f' registry_image=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import flux; print(flux.REGISTRY_IMAGE)') free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()'; } diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 3782e009..d13884c7 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -46,6 +46,11 @@ BOOT_TARGETS = ('None', 'Pxe', 'Hdd') BOOT_ENABLED = ('Disabled', 'Once') NETWORK = 'fleet-lab-pxe' +# The accelerator the lab targets run under, kvm or tcg. The site runtime that +# hosts libvirt publishes its own beside the socket; the adapter defines and +# starts a target only while the two agree, with no software fallback. +ACCEL = os.environ.get('FLEET_LAB_ACCEL', '') +RUNTIME_ACCELERATOR = os.environ.get('FLEET_LAB_RUNTIME_ACCELERATOR', '/run/fleet-libvirt/accelerator') LOCK = threading.RLock() @@ -108,10 +113,21 @@ class LibvirtError(Exception): pass +def require_accelerator(): + if ACCEL not in ('kvm', 'tcg'): + raise LibvirtError('FLEET_LAB_ACCEL must be kvm or tcg') + try: + published = open(RUNTIME_ACCELERATOR).read().strip() + except OSError: + published = '' + if published != ACCEL: + raise LibvirtError('the site runtime publishes accelerator %r, not %r' % (published, ACCEL)) + + def domain_xml(t, boot): # Persistent lab target: fixed UUID, MAC, disk and console. Only the boot # device changes, from the Redfish boot override at power-on. - return ("{domain}{uuid}20482" + return ("{domain}{uuid}20482" "" "hvm" "destroydestroydestroy" @@ -145,6 +161,7 @@ def __init__(self, targets, state, boot_ip): def ensure(self, sid): """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" t = self.targets[sid] + require_accelerator() try: info = virsh('net-info', NETWORK) if not re.search(r'^Active:\s+yes', info, re.M): @@ -179,6 +196,7 @@ def power_on(self, sid): # Once is consumed by this boot. Persisted before start, like NVRAM. self.nvram[sid] = {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'} self.save() + require_accelerator() virsh('define', '/dev/stdin', input=domain_xml(t, boot)) virsh('start', t['domain']) return boot @@ -379,6 +397,8 @@ def main(): boot_ip = os.environ.get('FLEET_BOOT_IP', '') if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', boot_ip): raise SystemExit('FLEET_BOOT_IP must be the boot Service IPv4 address') + if ACCEL not in ('kvm', 'tcg'): + raise SystemExit('FLEET_LAB_ACCEL must be kvm or tcg') tls = (os.path.join(TLS_DIR, 'tls.crt'), os.path.join(TLS_DIR, 'tls.key')) create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True, ssl_context=tls) elif sys.argv[1:2] == ['fault']: diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index e44926a6..55bbb514 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -18,7 +18,9 @@ (WORK / 'creds').mkdir() (WORK / 'creds' / 'username').write_text('lab-operator\n') (WORK / 'creds' / 'password').write_text('synthetic-test-password\n') -os.environ.update(FLEET_VIRSH=str(HERE / 'fake_virsh.py'), FAKE_VIRSH_STATE=str(WORK / 'virsh.json'), FLEET_BMC_STATE=str(WORK / 'state')) +(WORK / 'accelerator').write_text('tcg\n') +os.environ.update(FLEET_VIRSH=str(HERE / 'fake_virsh.py'), FAKE_VIRSH_STATE=str(WORK / 'virsh.json'), FLEET_BMC_STATE=str(WORK / 'state'), + FLEET_LAB_ACCEL='tcg', FLEET_LAB_RUNTIME_ACCELERATOR=str(WORK / 'accelerator')) sys.path.insert(0, str(HERE)) import fleet_lab_adapter as adapter # noqa: E402 @@ -112,6 +114,28 @@ def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): finally: del os.environ['FAKE_VIRSH_DOWN'] + def test_7_targets_run_only_under_the_runtime_accelerator(self): + target = adapter.load_targets()['System-1'] + self.assertTrue(adapter.domain_xml(target, 'hd').startswith("")) + adapter.ACCEL = 'kvm' + try: + self.assertTrue(adapter.domain_xml(target, 'hd').startswith("")) + # The runtime still publishes tcg: no definition or start, and the + # System reports the hardware unavailable. + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + starts = virsh_state()['domains']['fleet-lab-target-a']['starts'] + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 503) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'], starts) + (WORK / 'accelerator').write_text('kvm\n') + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 204) + self.assertEqual(len(virsh_state()['domains']['fleet-lab-target-a']['starts']), len(starts) + 1) + (WORK / 'accelerator').unlink() + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + finally: + adapter.ACCEL = 'tcg' + (WORK / 'accelerator').write_text('tcg\n') + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/internal/custody/fences_test.go b/internal/custody/fences_test.go new file mode 100644 index 00000000..7c7527bd --- /dev/null +++ b/internal/custody/fences_test.go @@ -0,0 +1,110 @@ +package custody + +import ( + "fmt" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// These tests guard the coordinator's use of site fence reports: a recovery +// applies only once every serving site confirms its fence, the fence it +// records is the lowest any site confirmed, and a Resolve raises custody's +// fence above every fence a site has seen. Each one fails if its guard is +// removed. + +// reportAt stores the stopped fence one named site reports for a Device. +func (s *fakeSites) reportAt(site, device string, fence int64) { + s.mu.Lock() + defer s.mu.Unlock() + s.fences[site+"/"+device] = fence +} + +// serve sets the sites that serve a Device. +func (s *fakeSites) serve(device string, sites ...string) { + s.mu.Lock() + defer s.mu.Unlock() + s.serving[device] = sites +} + +func TestARecoveryOnADeviceNoSiteServesIsNeverConfirmed(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-830", uid(830), fmt.Sprintf("%064x", 830)) + hold := e.holdOn(device) + e.sites.serve(device.Name) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + if status := e.status(retire); status.Phase == ops.PhaseSucceeded { + t.Fatalf("a recovery applied with no serving site: %+v", status) + } + e.clock.Advance(RecoveryDeadline + DefaultSkewMargin) + e.settle(device.Name) + if status := e.status(retire); status.Phase == ops.PhaseSucceeded { + t.Fatalf("a recovery applied with no serving site after its deadline: %+v", status) + } + if custody := e.custody(device.Name); custody.Spec.RecoveryHold == nil || *heldRef(*custody.Spec.RecoveryHold) != *heldRef(hold) || custody.Spec.Holder.Type == ops.HolderRetired { + t.Fatalf("custody after an unconfirmed recovery = %+v", custody.Spec) + } +} + +func TestARecoveryConfirmsTheLowestFenceOfItsSites(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-831", uid(831), fmt.Sprintf("%064x", 831)) + hold := e.holdOn(device) + e.sites.serve(device.Name, testSite, "site-example-b") + e.sites.reportAt("site-example-b", device.Name, hold.Fence) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil { + t.Fatal("the recovery was not admitted") + } + // One site confirms; the other has not stopped its older worker yet. + e.sites.reportAt(testSite, device.Name, active.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseAdmitted, "") + // Both confirm, at different fences: the lower one is recorded. + e.sites.reportAt(testSite, device.Name, active.Fence+3) + e.sites.reportAt("site-example-b", device.Name, active.Fence) + e.settle(device.Name) + status := e.requirePhase(retire, ops.PhaseSucceeded, "") + var evidence ops.RecoveryResultEvidence + if err := jsonUnmarshal(status.Evidence.Raw, &evidence); err != nil || evidence.ConfirmedFence != active.Fence { + t.Fatalf("recovery evidence = %s, want the lowest confirmed fence %d", status.Evidence.Raw, active.Fence) + } +} + +func TestAResolveRaisesTheFenceAboveEverySeenFence(t *testing.T) { + e := startEnv(t) + device := e.device("server-example-832", uid(832), fmt.Sprintf("%064x", 832)) + allocation := "alloc-s-" + device.Name + e.allocation(device, allocation, "Active") + // Two unproven installations make the rebuild need a Resolve. + for index, fence := range []int64{2, 5} { + install := e.installation(device, allocation, fmt.Sprintf("request-%d", index)) + install.Status = ops.OperationStatus{Admission: admitted(fence), Phase: ops.PhaseOutcomeUnknown, Fence: fence, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, install); err != nil { + t.Fatal(err) + } + } + e.sites.report(device.Name, 5) + e.settle(device.Name) + if state := e.custody(device.Name).Spec.State; state != ops.CustodyUnverified { + t.Fatalf("rebuilt custody is %s, want Unverified", state) + } + resolve := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation}}}) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil { + t.Fatal("the Resolve was not admitted") + } + // The site confirms the Resolve's fence, and has seen a higher one from + // an assignment custody never recorded. + e.sites.report(device.Name, active.Fence) + e.sites.reportSeen(device.Name, active.Fence+40) + e.settle(device.Name) + e.requirePhase(resolve, ops.PhaseSucceeded, "") + if custody := e.custody(device.Name); custody.Spec.State != ops.CustodyVerified || custody.Spec.Fence < active.Fence+40 { + t.Fatalf("resolved custody = %+v, want Verified at a fence of at least %d", custody.Spec, active.Fence+40) + } +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index f69aaffa..62be3abd 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -158,18 +158,36 @@ func coordinator(ctx context.Context, c Config, registry *custody.Registry) (*cu return &custody.Coordinator{Client: api, Registry: registry, Sites: sites, Config: custody.Config{Namespace: DeviceNamespace, Principals: p}}, hub, sites, api, nil } +// CoordinatorOptions are the lab coordinator's overrides; zero keeps the +// default. The deadline scenario uses both. +type CoordinatorOptions struct { + // InstallationDeadline replaces the installation kind's deadline for + // operations this process admits. + InstallationDeadline time.Duration + // SkewMargin replaces the margin added to a deadline before it is + // declared exceeded. Only the coordinator daemon declares deadlines + // exceeded; the one-shot phases built by New keep the default margin. + SkewMargin time.Duration +} + // Coordinate is the coordinator process: the custody loop, delivering // through Karmada, and fixture discovery for the cell's Devices under the // discovery identity. -func Coordinate(ctx context.Context, c Config, onError func(error)) error { +func Coordinate(ctx context.Context, c Config, o CoordinatorOptions, onError func(error)) error { registry, err := custody.DefaultRegistry() if err != nil { return err } + if o.InstallationDeadline > 0 { + registry.Kind("DeviceInstallation").Deadline = o.InstallationDeadline + } coord, _, sites, api, err := coordinator(ctx, c, registry) if err != nil { return err } + if o.SkewMargin > 0 { + coord.Config.SkewMargin = o.SkewMargin + } discovery, err := API(filepath.Join(c.State, "provider", "discovery-project.json")) if err != nil { return err @@ -390,7 +408,7 @@ func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet. return nil, nil, nil, nil, err } if current == nil || current.Status.Phase != fleet.AllocationActive { - return nil, nil, nil, nil, errors.New("the consumer has no active allocation") + return nil, nil, nil, nil, errNoActiveAllocation } var install fleet.Installation if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { @@ -418,8 +436,10 @@ var ErrAdmittedUnknown = errors.New("installation admitted; its result remains u // AdmitInstall creates consumer A's installation and returns // ErrAdmittedUnknown once custody admitted it and its handoff exists. -func (r *Runner) AdmitInstall(ctx context.Context) error { - _, _, _, operation, err := r.installation(ctx, 0) +func (r *Runner) AdmitInstall(ctx context.Context) error { return r.admitIndex(ctx, 0) } + +func (r *Runner) admitIndex(ctx context.Context, index int) error { + _, _, _, operation, err := r.installation(ctx, index) if err != nil { return err } @@ -436,10 +456,6 @@ func (r *Runner) AdmitInstall(ctx context.Context) error { func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } -// InstallSecond installs consumer B's Installation after it reused the -// capacity, through the same allocator and federation path. -func (r *Runner) InstallSecond(ctx context.Context) error { return r.InstallIndex(ctx, 1) } - func (r *Runner) InstallIndex(ctx context.Context, index int) error { q, _, install, operation, err := r.installation(ctx, index) if err != nil { @@ -466,6 +482,10 @@ func (r *Runner) InstallIndex(ctx context.Context, index int) error { return r.projectPower(ctx, q) } +// errNoActiveAllocation means the consumer holds no active allocation, so +// the Metal provider installs nothing for it. +var errNoActiveAllocation = errors.New("the consumer has no active allocation") + // errTerminal marks an error that retrying cannot fix. var errTerminal = errors.New("terminal") diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go new file mode 100644 index 00000000..0933c7ad --- /dev/null +++ b/internal/multiplane/scenarios.go @@ -0,0 +1,217 @@ +package multiplane + +import ( + "context" + "errors" + "fmt" + "path/filepath" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + meta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// The failure scenarios of #174's acceptance tests. Each phase checks one +// outcome through the provider project API and never writes custody. + +// AdmitInstallSecond creates consumer B's installation and returns +// ErrAdmittedUnknown once custody admitted it. +func (r *Runner) AdmitInstallSecond(ctx context.Context) error { return r.admitIndex(ctx, 1) } + +// recoveryMismatchLabel marks the staff recovery the mismatch phase +// creates, so a retried phase finds the same one. Recoveries take generated +// names; admission refuses any other. +const recoveryMismatchLabel = "fleet.datumapis.com/acceptance-scenario" + +// RecoveryMismatch creates, as staff, a DeviceRecovery that names the held +// operation at the wrong fence. Admission refuses it before anything is +// delivered: custody's fence and hold stay as they were. +func (r *Runner) RecoveryMismatch(ctx context.Context) error { + staff, err := API(filepath.Join(r.Config.State, "provider", "staff-project.json")) + if err != nil { + return err + } + before := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, before); err != nil { + return err + } + hold := before.Spec.RecoveryHold + if hold == nil { + return fmt.Errorf("%w: the Device has no recovery hold", errTerminal) + } + device := &inventory.Device{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { + return err + } + var existing ops.DeviceRecoveryList + if err := staff.List(ctx, &existing, client.InNamespace(DeviceNamespace), client.MatchingLabels{recoveryMismatchLabel: "recovery-mismatch"}); err != nil { + return err + } + var recovery *ops.DeviceRecovery + switch len(existing.Items) { + case 0: + creator, err := identity(ctx, filepath.Join(r.Config.State, "provider", "staff-project.json")) + if err != nil { + return err + } + recovery = &ops.DeviceRecovery{ + ObjectMeta: metav1.ObjectMeta{GenerateName: Device + "-recovery-", Namespace: DeviceNamespace, Labels: map[string]string{ + recoveryMismatchLabel: "recovery-mismatch", ops.LabelDeviceUID: string(device.UID)}}, + Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "synthetic acceptance: a recovery for another hold"}}}, + Decision: ops.DecisionSettle, + Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence + 1000}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "synthetic acceptance evidence"}, + }, + } + if err := staff.Create(ctx, recovery); err != nil { + return err + } + case 1: + recovery = &existing.Items[0] + default: + return fmt.Errorf("%w: more than one mismatched recovery", errTerminal) + } + switch phase := recovery.Status.Phase; { + case phase == ops.PhaseFailed && recovery.Status.Reason == custody.ReasonHoldMismatch: + case phase == ops.PhaseFailed: + return fmt.Errorf("%w: the mismatched recovery was refused for %s, not the hold", errTerminal, recovery.Status.Reason) + case phase.Ended(): + return fmt.Errorf("%w: the mismatched recovery ended %s: %s", errTerminal, phase, recovery.Status.Reason) + default: + return fmt.Errorf("%w: the mismatched recovery is %q", errPending, phase) + } + after := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, after); err != nil { + return err + } + if after.Spec.Fence != before.Spec.Fence || after.Spec.RecoveryHold == nil || !sameHold(after.Spec.RecoveryHold, hold) || after.Spec.ActiveOperation != nil { + return fmt.Errorf("%w: the refused recovery changed custody", errTerminal) + } + if recovery.Status.Fence != 0 || recovery.Status.AdmittedAt != nil { + return fmt.Errorf("%w: the refused recovery was admitted", errTerminal) + } + fmt.Printf("recovery-mismatch: refused %s; fence %d and the hold unchanged\n", recovery.Status.Reason, after.Spec.Fence) + return nil +} + +// sameHold reports whether two recovery holds name the same operation +// admission: kind, name and fence. +func sameHold(a, b *ops.RecoveryHold) bool { + return a.Kind == b.Kind && a.Name == b.Name && a.Fence == b.Fence +} + +// ProbeUnallocatable tries to allocate consumer A's Machine while custody +// is Unverified. The allocator must find no eligible capacity and record no +// allocation for the Machine. +func (r *Runner) ProbeUnallocatable(ctx context.Context) error { + state := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, state); err != nil { + return fmt.Errorf("%w: custody: %v", errPending, err) + } + if state.Spec.State != ops.CustodyUnverified { + return fmt.Errorf("%w: custody is %s, not Unverified", errTerminal, state.Spec.State) + } + q, err := r.request(ctx, 0) + if err != nil { + return err + } + if _, err := r.Allocator.Allocate(ctx, q.alloc); !errors.Is(err, allocation.ErrInsufficientCapacity) { + return fmt.Errorf("%w: allocation against Unverified custody: %v", errTerminal, err) + } + current, err := r.Allocator.Get(ctx, q.alloc.Machine) + if err != nil { + return err + } + if current != nil && current.Status.Phase != fleet.AllocationReleased { + return fmt.Errorf("%w: an allocation exists for the probe Machine", errTerminal) + } + fmt.Println("probe-unallocatable: no eligible capacity while custody is Unverified; no allocation recorded") + return nil +} + +// TenantIsolation runs while consumer A holds the Device and consumer B +// holds nothing. B's project serves no Device API, and an installation the +// Metal provider names for B's allocation, which never held the Device, is +// refused by custody admission for HolderMismatch before anything is +// delivered, with custody's fence unchanged. The holder check is the guard +// this proves. +func (r *Runner) TenantIsolation(ctx context.Context) error { + if err := r.Consumers[1].API.List(ctx, &ops.DeviceCustodyList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { + return fmt.Errorf("%w: a consumer project serves Device custody: %v", errTerminal, err) + } + if err := r.Consumers[1].API.List(ctx, &ops.DeviceInstallationList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { + return fmt.Errorf("%w: a consumer project serves Device operations: %v", errTerminal, err) + } + q, err := r.request(ctx, 1) + if err != nil { + return err + } + before := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, before); err != nil { + return err + } + if before.Spec.Holder.Type != ops.HolderAllocation { + return fmt.Errorf("%w: consumer A does not hold the Device", errTerminal) + } + var install fleet.Installation + if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + return err + } + device := &inventory.Device{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { + return err + } + unheld := allocation.Name(q.alloc.Machine) + image, err := allocation.ParseImage(install.Spec.ImageRef.Name) + if err != nil { + return err + } + // B's allocation takes this name once B reuses the Device, so the refused + // installation names a synthetic Installation UID to keep its name apart + // from B's later installation. It labels the current Device incarnation, + // as the Metal provider does, so admission reaches the holder check. + const request = "00000000-0000-4000-8000-000000000174" + operation := &ops.DeviceInstallation{} + key := client.ObjectKey{Namespace: DeviceNamespace, Name: custody.InstallationName(unheld, request)} + if err := r.Provider.API.Get(ctx, key, operation); apierrors.IsNotFound(err) { + operation = &ops.DeviceInstallation{ + ObjectMeta: metav1.ObjectMeta{Name: key.Name, Namespace: key.Namespace, Labels: map[string]string{ + ops.LabelDeviceUID: string(device.UID), ops.LabelInstallationUID: request}}, + Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: unheld}}}, + Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + }, + } + if err := r.Provider.API.Create(ctx, operation); err != nil { + return err + } + } else if err != nil { + return err + } + switch phase := operation.Status.Phase; { + case phase == ops.PhaseFailed && operation.Status.Reason == custody.ReasonHolderMismatch: + case phase.Ended() || phase.Running(): + return fmt.Errorf("%w: the unheld installation is %s: %s", errTerminal, phase, operation.Status.Reason) + default: + return fmt.Errorf("%w: the unheld installation is %q", errPending, phase) + } + after := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, after); err != nil { + return err + } + if after.Spec.Fence != before.Spec.Fence || after.Spec.ActiveOperation != nil || operation.Status.Fence != 0 { + return fmt.Errorf("%w: the refused installation changed custody", errTerminal) + } + fmt.Println("tenant-isolation: consumer B's project has no Device API; an installation for its unheld allocation was refused for HolderMismatch with the fence unchanged") + return nil +} diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index 06af2582..e1ed146c 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -194,13 +194,6 @@ func appendEvidence(dir, name, line string) error { return parent.Sync() } -// Serve listens on :8080. The write bound covers emulated firmware fetching -// the initrd through the site's NAT path. -func (b BootServer) Serve(window time.Duration) error { - server := &http.Server{Addr: ":8080", Handler: b.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} - return server.ListenAndServe() -} - // CheckClosedBoot probes a live boot server after every admission closed: // each admission's per-MAC script and capability URLs, other enrolled MACs, // an unsupported and an unguarded artifact, and an unknown identity must diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 19b2a678..f7f207cb 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -249,6 +249,15 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops if err != nil { return nil, err } + // A worker stopped at its deadline closes its admission: nothing can + // resume the operation, so nothing may boot the server from it. A worker + // stopped from outside leaves it open for its replacement. + defer func() { + if mode != "" && site.DeadlinePassed(ctx) && !boot.Closed { + boot.Phase, boot.Closed = "", true + _ = c.saveBoot(work, boot) + } + }() var evidence []ops.StepEvidence for _, ph := range phases { // A phase verified by an earlier worker is done; resume after it. diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 264ecbc5..ebb466c1 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -53,6 +53,8 @@ type lab struct { bootRoot string store *site.Store operation string + // silent keeps the server running with no console receipt. + silent bool } func newLab(t *testing.T) *lab { @@ -130,6 +132,9 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { // boot runs the armed boot, as the server and the boot server would. func (l *lab) boot(target string) { time.Sleep(30 * time.Millisecond) + if l.silent { + return + } var boot Boot if _, err := l.store.GetRecord(device, "boot", l.operation, &boot); err != nil { l.t.Error(err) @@ -292,6 +297,25 @@ func TestAnInterruptedWorkerResumesWithoutASecondOn(t *testing.T) { } } +func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { + l := newLab(t) + l.silent = true + r := runner(t, l) + a := assignment(l, "DeviceInstallation", "00000000-0000-4000-8000-000000000301", 2, installSpec()) + a.Deadline = time.Now().Add(2 * time.Second) + result, err := r.Run(context.Background(), a) + if err != nil || result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonDeadline { + t.Fatalf("install past its deadline = %+v, %v", result, err) + } + var boot Boot + if found, err := r.Store.GetRecord(device, bootRecords, a.Key(), &boot); err != nil || !found || !boot.Closed || boot.Phase != "" { + t.Fatalf("admission after the deadline = %+v, %v, %v", boot, found, err) + } + if _, open, _ := OpenAdmission(r.Store, mac, time.Now()); open { + t.Fatal("a worker stopped at its deadline left its admission open") + } +} + func TestOnlyTheCurrentFenceHasAnOpenBootAdmission(t *testing.T) { l := newLab(t) r := runner(t, l) diff --git a/internal/site/runner.go b/internal/site/runner.go index d8eba1c3..dbdd2731 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -420,6 +420,10 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe var errDeadline = errors.New("the operation's deadline passed") +// DeadlinePassed reports whether ctx ended because the operation's deadline +// passed. No replacement worker can resume such an operation. +func DeadlinePassed(ctx context.Context) bool { return errors.Is(context.Cause(ctx), errDeadline) } + func outcomeReason(ctx context.Context, err error) string { switch cause := context.Cause(ctx); { case errors.Is(err, errSuperseded) || errors.Is(cause, errSuperseded): diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go index 7fa178f1..824d41e4 100644 --- a/internal/site/vmwork/boot.go +++ b/internal/site/vmwork/boot.go @@ -209,13 +209,6 @@ func appendEvidence(dir, line string) error { return syncDir(dir) } -// ServeBoot serves the boot handler. The write bound matches the boot -// window: emulated firmware takes minutes to fetch the installer. -func (c Config) ServeBoot(store *site.Store) error { - server := &http.Server{Addr: ":8080", Handler: c.BootHandler(store), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: c.window(), IdleTimeout: 5 * time.Second} - return server.ListenAndServe() -} - // CheckClosedBoot probes a live boot server with every installation's // closed admission, and with unknown names, and requires each to be denied. // It prints no capability URL. diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 7b2a4ede..559e09c1 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -18,6 +18,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -165,6 +166,9 @@ type Boot struct { Expires time.Time `json:"expires"` Open bool `json:"open,omitempty"` Closed bool `json:"closed,omitempty"` + // Accelerator is the one the installation runs under, fixed before any + // boot, so a replacement worker never resumes it under another. + Accelerator string `json:"accelerator"` } const bootRecords = "vmboot" @@ -184,7 +188,7 @@ func (k Installation) boot(work *site.Work) (Boot, error) { if _, err := rand.Read(token); err != nil { return boot, err } - boot = Boot{Operation: work.Key(), Fence: work.Fence, Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: k.now().Add(k.window())} + boot = Boot{Operation: work.Key(), Fence: work.Fence, Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: k.now().Add(k.window()), Accelerator: k.Accelerator} return boot, k.save(work, boot) } @@ -200,6 +204,9 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { if err != nil { return nil, err } + if boot.Accelerator != k.Accelerator { + return nil, fmt.Errorf("the installation is bound to accelerator %q, not %q", boot.Accelerator, k.Accelerator) + } dir := k.directory(work.Device, work.Key()) var evidence ops.InstallationEvidence record := func(step string) { @@ -246,10 +253,11 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { return nil, err } // A failed network boot closes its admission at once, so the boot - // server stops serving the installer. A worker stopped from outside - // leaves it open for its replacement to resume. + // server stops serving the installer, and so does a worker stopped at + // its deadline, which nothing can resume. A worker stopped from + // outside leaves it open for its replacement to resume. fail := func(err error) error { - if stage == "installer" && k.PXE && boot.Open && ctx.Err() == nil { + if stage == "installer" && k.PXE && boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { boot.Open, boot.Closed = false, true _ = k.save(work, boot) } @@ -428,6 +436,41 @@ func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { if refusal != nil { return nil, refusal } + // Power the guest off first, as a Redfish wipe does: an installation + // stopped at its deadline can leave it running. The local VM serves one + // guest, so every local domain is the Device's, and the fence and run + // lock already stopped every older worker. Sending it again is safe. + running := func(ctx context.Context) ([]string, error) { + names, err := k.virsh(ctx, "list", "--name") + var local []string + for _, name := range strings.Fields(names) { + if strings.HasPrefix(name, "fleet-local-") { + local = append(local, name) + } + } + return local, err + } + if err := work.Step(ctx, site.Step{ + Name: "wipe-power-off", + Send: func(ctx context.Context) error { + names, err := running(ctx) + if err != nil { + return err + } + for _, name := range names { + if _, err := k.virsh(ctx, "destroy", name); err != nil { + // A guest that exited after the list is already off. + if still, lerr := running(ctx); lerr != nil || slices.Contains(still, name) { + return err + } + } + } + return nil + }, + Idempotent: true, + }); err != nil { + return nil, err + } root := filepath.Join(k.Disks, deviceKey(work.Device)) remaining := func() ([]string, error) { paths, err := filepath.Glob(filepath.Join(root, "*", "disk.raw")) diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index ce683991..a32d25dc 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -3,6 +3,7 @@ package vmwork import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -35,6 +36,10 @@ type hypervisor struct { hold bool // noReceipt makes the guest print no receipt. noReceipt bool + // stuck makes destroy leave the domain running. + stuck bool + // exited makes destroy fail because the guest exited first. + exited bool } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -74,6 +79,14 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if !h.hold { delete(h.running, name) } + case "destroy": + if h.exited { + delete(h.running, args[1]) + return "", errors.New("error: domain is not running") + } + if !h.stuck { + delete(h.running, args[1]) + } case "list": var names []string for name := range h.running { @@ -164,14 +177,38 @@ func TestInstallThenWipe(t *testing.T) { } } -// TestAWipeWithARunningDomainIsNotProven keeps a disk in use from counting -// as wiped. -func TestAWipeWithARunningDomainIsNotProven(t *testing.T) { +// TestAWipePowersOffARunningDomain powers off a guest an earlier worker left +// running, then wipes. +func TestAWipePowersOffARunningDomain(t *testing.T) { + r := newRig(t) + r.vm.running["fleet-local-0000000000000000"] = "console" + result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000208", 2, wipeSpec())) + if err != nil || result.Phase != ops.PhaseSucceeded || len(r.vm.running) != 0 { + t.Fatalf("wipe with a running domain = %+v, %v, running %v", result, err, r.vm.running) + } +} + +// TestAWipeToleratesAGuestThatExitsBeforeItsDestroy treats a guest that +// stopped between the list and the destroy as powered off. +func TestAWipeToleratesAGuestThatExitsBeforeItsDestroy(t *testing.T) { + r := newRig(t) + r.vm.running["fleet-local-0000000000000000"] = "console" + r.vm.exited = true + result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000209", 2, wipeSpec())) + if err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe after the guest exited = %+v, %v", result, err) + } +} + +// TestAWipeWithADomainThatKeepsRunningIsNotProven keeps a disk in use from +// counting as wiped. +func TestAWipeWithADomainThatKeepsRunningIsNotProven(t *testing.T) { r := newRig(t) r.vm.running["fleet-local-0000000000000000"] = "console" + r.vm.stuck = true result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000203", 2, wipeSpec())) if err != nil || result.Phase == ops.PhaseSucceeded { - t.Fatalf("wipe with a running domain = %+v, %v", result, err) + t.Fatalf("wipe with a domain that keeps running = %+v, %v", result, err) } } @@ -259,6 +296,27 @@ func TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence(t *testing.T) { } } +// TestAWorkerStoppedAtItsDeadlineClosesItsAdmission stops serving the +// installer once nothing can resume the installation. +func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { + r := newRig(t) + r.config.PXE = true + r.runner.Kinds["DeviceInstallation"] = Installation{r.config} + // The guest keeps running and never prints a receipt, so the worker is + // still waiting when the deadline passes. + r.vm.hold, r.vm.noReceipt = true, true + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000207", 2, installSpec()) + assignment.Deadline = time.Now().Add(time.Second) + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonDeadline { + t.Fatalf("install past its deadline = %+v, %v", result, err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Open || !boot.Closed { + t.Fatalf("admission after the deadline = %+v, %v, %v", boot, found, err) + } +} + // TestAFailedNetworkBootClosesItsAdmission stops serving the installer as // soon as a network-boot installation fails. func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { @@ -277,3 +335,80 @@ func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { t.Fatalf("admission after the failure = %+v, %v, %v", boot, found, err) } } + +// TestAnInstallationResumesOnlyUnderItsBoundAccelerator starts an install +// under TCG; a replacement worker configured for KVM boots nothing, and its +// journaled boot admission still names TCG. +func TestAnInstallationResumesOnlyUnderItsBoundAccelerator(t *testing.T) { + r := newRig(t) + r.vm.hold = true + tcg := r.config + tcg.Accelerator = "tcg" + r.runner.Kinds["DeviceInstallation"] = Installation{tcg} + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000210", 2, installSpec()) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = r.runner.Run(ctx, assignment) + }() + deadline := time.Now().Add(5 * time.Second) + for { + r.vm.mu.Lock() + creates := r.vm.creates + r.vm.mu.Unlock() + if creates == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("the installer never started") + } + time.Sleep(10 * time.Millisecond) + } + cancel() + <-done + r.vm.mu.Lock() + r.vm.hold = false + for name := range r.vm.running { + delete(r.vm.running, name) + } + r.vm.mu.Unlock() + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Accelerator != "tcg" { + t.Fatalf("boot admission = %+v, %v, %v", boot, found, err) + } + kvm := r.config + kvm.Accelerator = "kvm" + r.runner.Kinds["DeviceInstallation"] = Installation{kvm} + // The boot already began under TCG, so the outcome is unknown, never + // a second boot under KVM. + if result, err := r.runner.Run(context.Background(), assignment); err != nil || result.Phase != ops.PhaseOutcomeUnknown { + t.Fatalf("install resumed under another accelerator = %+v, %v", result, err) + } + if r.vm.creates != 1 { + t.Fatalf("boots = %d, want only the TCG installer", r.vm.creates) + } +} + +// TestANewInstallationBindsItsWorkersAccelerator records the accelerator in +// the boot admission and defines the guest with the matching domain type. +func TestANewInstallationBindsItsWorkersAccelerator(t *testing.T) { + for accelerator, domainType := range map[string]string{"kvm": "kvm", "tcg": "qemu"} { + r := newRig(t) + config := r.config + config.Accelerator = accelerator + r.runner.Kinds["DeviceInstallation"] = Installation{config} + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000211", 2, installSpec()) + if result, err := r.runner.Run(context.Background(), assignment); err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("%s install = %+v, %v", accelerator, result, err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Accelerator != accelerator { + t.Fatalf("%s boot admission = %+v, %v, %v", accelerator, boot, found, err) + } + xml, err := os.ReadFile(filepath.Join(config.directory(device, assignment.Key()), "installer.xml")) + if err != nil || !strings.HasPrefix(string(xml), "") { + t.Fatalf("%s installer domain = %.40s, %v", accelerator, xml, err) + } + } +} diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 7301d619..997ceae8 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -34,28 +34,40 @@ result reports every required phase `Passed`. These are the acceptance tests of [#174 at `d4d17f9`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server, and Increment B covers the site side in unit tests. Increment C runs allocation, installation, release and -reuse end to end in the standalone smoke. The multi-plane local VM and Redfish -runs use the same code, and verification of both is pending. The remaining -end-to-end failure scenarios arrive in Increment D. See [device -custody](../../docs/development/device-custody.md#tests). +reuse end to end. Increment D adds the failure scenarios to both multi-plane +runs, the local VM and the Redfish lab, through real Milo project APIs, Karmada, +kro and the site. See [device custody](../../docs/development/device-custody.md#tests) +and the [multi-plane phases](../../docs/operations/multiplane.md#acceptance-phases). + +"Nothing sent" in a phase means the site journal, the hypervisor's running +domains and its QEMU logs are unchanged in both runs, and the lab BMC audit +holds no new effect in the Redfish run. Whether both runs passed every phase +at a given head is recorded in the [device custody +status](../../docs/development/device-custody.md#status). | #174 acceptance test | Executable evidence | Current state | | --- | --- | --- | -| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner` | Envtest verified; the standalone smoke verifies two consumers contending for one server | +| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner`; the `verify-contention` phase | Envtest verified for true concurrency. The phase checks that two consumers contend and custody names the one MachineAllocation | | An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | -| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power | -| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | -| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | -| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | -| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart` | Unit verified; the multi-plane `delivery-faults` phase replays an assignment below the stored fence, and its verification is pending | -| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`, against TLS servers | Unit verified. The Redfish run's lab BMC serves TLS with a per-run key and workers reach it only through the pin, so a mismatch is not injected there; verification of the run is pending | -| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild` | Envtest verified with a fake site; end to end proposed | -| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery` | Envtest verified; end to end proposed | -| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets` | Role definitions verified; bootstrap stays refused | - -The emulator lab cannot cover BMC TLS key rotation, vendor Redfish behavior, -UEFI or real PXE firmware, real disks and wipe assurance, real power reset -evidence, clock skew between coordinator and site, more than one site serving -a Device, or a permanently lost site. The multi-plane Milo registers no creator -webhook, so the multi-plane runs do not prove it. None of these tests qualifies -hardware. +| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power, the first staff kind with an effect | +| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope. The phases below run the same hold and settle mechanism for an installation and a wipe | +| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified for all three. The phase runs one of them: a `DeviceRecovery` naming the held installation at the wrong fence, on a releasing Device, must be refused for `HoldMismatch` with custody unchanged and nothing sent | +| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | The phases check that the installation ends `OutcomeUnknown` with `DeadlineExceeded`, that its worker Pods stopped, and that the settling wipe is admitted only after the worker stopped | +| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart`; the `delivery-faults` phase | Unit verified. The phase checks that an assignment below the stored fence fails its Job before any effect, with nothing sent | +| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`; the `redfish-discovery-faults` phase | Unit verified against TLS servers. The Redfish run's phase checks that a key other than the pin reaches no request, and that a swapped or unknown identity sends only reads | +| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild`; the `rebuild` phase | Envtest verified. The phase checks that custody is rebuilt `Unverified` while the site cannot report, that a new Machine finds no capacity and records no allocation, and that custody is then `Verified` above the site's fence | +| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery`; the `machine-delete`, `deadline-hold` and `deadline-settled` phases | Envtest verified. The phases check that release holds the Device with the installation active and no wipe, that the wipe then settles the hold, and that the Machine is gone | +| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`; the `staff-access` phase | Role definitions verified. The phase checks that staff are forbidden Secrets and every write but recoveries. Bootstrap stays refused, so no payload exists to read | +| A tenant cannot trigger an operation on hardware it does not hold (a review request beside #174's list) | `TestAdmissionPreconditions`; the `tenant-isolation` phase | Envtest verified. While consumer A holds the Device, the phase checks that consumer B's project serves no Device API, that the allocator refuses to install for B because B has no active allocation, and that an installation the Metal provider names for B's unheld allocation is refused for `HolderMismatch`, with the fence unchanged, nothing delivered and nothing sent | +| Importing a Device sends nothing and makes no capacity Available | `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing`; the `import-inert` phase | Envtest verified. The phase checks that no operation, assignment, Job, journal entry or, in the Redfish run, BMC effect exists. The capacity projector is not wired, so the run's fixture writes capacity status itself | + +The emulator lab cannot cover these: + +- BMC TLS key rotation, or one key per server: the lab serves both targets from one BMC with one key, so only target A is a Device; +- vendor Redfish behavior, UEFI or real PXE firmware; +- real disks, wipe assurance or power reset evidence; +- clock skew between the coordinator and a site; +- more than one site serving a Device, or a site lost for good; +- true parallel races between processes, which envtest covers. + +The multi-plane Milo registers no creator webhook, so the multi-plane runs do not prove it. None of these tests qualifies hardware.