From f8301dd93b4dc7dfcc54d02d0cdbf429ea97b949 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:08:49 -0600 Subject: [PATCH 01/10] feat(multiplane): Run acceptance in GitHub Actions Agents queued for one shared Colima VM to run the multi-plane acceptance. This runs both modes on disposable GitHub-hosted runners. Make the runtime, Docker context, site architecture and guest accelerator explicit run parameters whose defaults leave the Colima run unchanged. CI mode requires a GitHub-hosted runner, its own Docker socket and a usable /dev/kvm, probes the runner directly, never calls Colima, and fails closed on any accelerator it cannot honor. Local VM mode runs its guest under KVM. The site runtime refuses KVM without /dev/kvm and publishes its accelerator. A worker runs only against a runtime with its own accelerator, and each installation's journaled boot admission binds it. Evidence requires the domain definitions and every QEMU command line to show it. Redfish lab targets stay on TCG. The Pod and Job interruptions now land on an installer guest held paused once its kernel prints, so they no longer depend on install speed. A guest that printed its receipt first fails the run. The workflow runs on demand, nightly, and when a pull request gets the multiplane-acceptance label. It records the tested commit, rescans and redacts evidence after any outcome, uploads only evidence/, samples runner memory, and passes only when every phase and teardown passed. A redacted secret fails the job. Milo is pinned by its multi-arch index, whose arm64 entry is the previous pin. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 167 ++++++++++++++++++++ cmd/fleet-multiplane/site.go | 24 ++- cmd/fleet-multiplane/site_test.go | 25 +++ config/multiplane/milo/base/milo.yaml | 6 +- config/site/graph/rgd.yaml | 5 +- config/site/instance/dispatcher.yaml | 1 + config/site/services/services.yaml | 6 +- docs/operations/gitops.md | 2 +- docs/operations/multiplane.md | 70 +++++++- docs/operations/redfish-lab.md | 6 + hack/local-vm/site-runtime | 9 +- hack/multiplane/acceptance-redfish.sh | 2 +- hack/multiplane/acceptance.sh | 4 +- hack/multiplane/evidence.py | 24 ++- hack/multiplane/flux.py | 2 +- hack/multiplane/harness.py | 91 +++++++++-- hack/multiplane/milo.py | 2 +- hack/multiplane/roles.py | 2 +- hack/multiplane/run.sh | 11 +- hack/multiplane/site.sh | 2 +- hack/multiplane/steps.sh | 64 +++++++- hack/multiplane/stop.sh | 2 +- hack/multiplane/sysctl.py | 12 +- hack/multiplane/teardown.sh | 2 +- hack/multiplane/test-flux.py | 1 + hack/multiplane/test-harness.sh | 121 +++++++++++++- hack/multiplane/topology.sh | 2 +- internal/site/vmwork/kinds.go | 8 +- internal/site/vmwork/kinds_test.go | 77 +++++++++ 29 files changed, 689 insertions(+), 61 deletions(-) create mode 100644 .github/workflows/multiplane-acceptance.yml create mode 100644 cmd/fleet-multiplane/site_test.go diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml new file mode 100644 index 00000000..a4e00127 --- /dev/null +++ b/.github/workflows/multiplane-acceptance.yml @@ -0,0 +1,167 @@ +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. Local VM mode runs its guest +# under KVM; Redfish mode keeps its lab targets on TCG. 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 }}) + strategy: + fail-fast: false + matrix: + mode: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode != 'both' && format('["{0}"]', inputs.mode) || '["localvm","redfish"]') }} + # 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 }} + 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 + # The Redfish lab adapter defines TCG domains only. + FLEET_MULTIPLANE_ACCEL: ${{ matrix.mode == 'localvm' && 'kvm' || 'tcg' }} + 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: true} + - 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" + - name: Free runner disk and record capacity + run: | + # Preinstalled toolchains this job does not use. The harness needs + # 12 GiB free in the Docker data root. + { + echo "FLEET_MULTIPLANE_STATE_ROOT=$RUNNER_TEMP/fleet-multiplane" + echo "METRICS=$RUNNER_TEMP/runner-metrics" + } >> "$GITHUB_ENV" + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL /usr/local/share/boost + 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 and the run's container memory. 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" + 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))) + 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 "$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" + # 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 }}-${{ 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]}" + # 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 diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index da1c7490..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. 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/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/services/services.yaml b/config/site/services/services.yaml index e5cbac24..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,7 +100,7 @@ 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 @@ -150,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/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/multiplane.md b/docs/operations/multiplane.md index 0e9c2016..e1493202 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -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: @@ -151,6 +151,60 @@ 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, one job per mode. Status: **verified**. +Both modes passed on a hosted runner, local VM mode under KVM. + +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` in local VM mode, `tcg` in Redfish mode | + +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, without `/dev/kvm`, +or with Redfish mode, 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 job passes only if exactly one run recorded `passed` with every phase +passed, teardown passed and no retained container. 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 and swap sampled every +10 seconds, per-container memory, and any kernel OOM events. The job removes +preinstalled toolchains to free disk, and 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 @@ -255,7 +309,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; @@ -264,7 +325,10 @@ 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 no guest; its + TCG installer is slow enough for these interruptions. 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 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 8dc92da5..a9c7ca79 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -35,6 +35,12 @@ 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. The lab adapter defines the targets +as TCG domains, so CI runs them under TCG on an amd64 runner, and preflight +rejects KVM in Redfish mode. TCG 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 | 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 1da7e137..e4b04654 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -6,7 +6,7 @@ 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"; } diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 947d42fc..92364b92 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -4,7 +4,7 @@ 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"; } @@ -20,9 +20,11 @@ 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 diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 8f285242..5bedabc2 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -20,7 +20,9 @@ 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 = harness.ACCEL, harness.RUNTIME REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' @@ -197,6 +199,8 @@ def libvirt_provider(): copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') store, ops, provider, held = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) + 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'] @@ -208,6 +212,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'): @@ -234,7 +240,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. The + # Redfish lab adapter defines TCG domains only. + accel_ok = ACCEL == 'tcg' or (ACCEL == 'kvm' and ARCH == 'amd64' and PROVIDER == 'libvirt') + check('accelerator', accel_ok, 'FLEET_MULTIPLANE_ACCEL=%s; tcg, or kvm with an amd64 runtime and the libvirt provider' % ACCEL) 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 @@ -124,16 +143,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) @@ -146,6 +165,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') @@ -162,13 +184,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}}) 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='/') @@ -468,15 +504,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 @@ -520,6 +558,29 @@ def result(args): 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'])) + 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(): p = argparse.ArgumentParser() sub = p.add_subparsers(dest='cmd', required=True) @@ -549,6 +610,8 @@ 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) a = p.parse_args() if a.cmd == 'phase': if a.command[:1] == ['--']: @@ -556,7 +619,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 13aef413..76ea3849 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -20,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) 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 428de97d..16e63a50 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -24,7 +24,12 @@ 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} +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" @@ -91,12 +96,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 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 4ab95f8c..ba1b1aa2 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -8,7 +8,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} harness=(python3 hack/multiplane/harness.py) host="$state/fleet-multiplane-host" ns=fleet-coordination @@ -49,6 +49,9 @@ print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' 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 @@ -223,8 +226,43 @@ JSON py worker-rbac "$state" "$name" rm -f "$state/worker-kubeconfig.json" ;; + hold-installer) + # Local VM mode: hold the installer guest paused as soon as its kernel + # prints, so the worker 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. + runtime sh -c "[ ! -e $hold_file.pid ] && rm -f $hold_file" || { echo 'an installer hold is already armed' >&2; exit 1; } + runtime sh -c 'setsid sh -c "$1" sh >/dev/null 2>&1 "$2.pid"' sh "$(cat <<'SH' +uri='qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' out=/tmp/fleet-installer-hold +end=$(($(date +%s) + 1500)) +while [ "$(date +%s)" -lt "$end" ]; do + for d in $(virsh --connect "$uri" list --name); do + case "$d" in fleet-local-*) ;; *) continue ;; esac + for log in /var/lib/fleet-local/vm/*/"${d#fleet-local-}"/installer.log; do + [ -f "$log" ] && grep -q 'Linux version' "$log" || continue + if virsh --connect "$uri" suspend "$d" >/dev/null 2>&1 && [ "$(virsh --connect "$uri" domstate "$d")" = paused ] && ! grep -q 'FLEET-INSTALLED:' "$log"; then + printf 'held %s %s\n' "$d" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$out.tmp" + else + printf 'missed %s\n' "$d" > "$out.tmp" + fi + mv "$out.tmp" "$out"; exit 0 + done + done + sleep 0.1 +done +echo expired > "$out" +SH +)" "$hold_file" + 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") + if ! redfish; then + 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-* ]] || { echo "installer guest was not held mid-install: ${held:-no hold}" >&2; exit 1; } + printf '%s\n' "$held" > "$state/installer-hold" + fi "${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" @@ -242,7 +280,8 @@ JSON 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' + if redfish; then state_word=running; else state_word='held paused'; fi + printf 'interrupt-pod: worker Pod force-deleted after the installer boot was journaled with its domain %s; Job controller replaced it; no local result\n' "$state_word" ;; interrupt-job) name=$(cat "$state/install-handoff") @@ -267,6 +306,27 @@ JSON 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 < "$state/installer-hold" + [[ $(runtime virsh --connect "$libvirt" domstate "$domain" | head -1) == paused ]] || { echo 'held installer guest is no longer paused' >&2; exit 1; } + 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; } + 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 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 5b46126e..d2aa5ceb 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -15,7 +15,7 @@ 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")!="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; } diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index de101577..d0750ada 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -129,6 +129,7 @@ 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)) diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 1c4522f7..b2e7502f 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -26,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) @@ -46,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) @@ -60,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) @@ -71,7 +84,7 @@ with tempfile.TemporaryDirectory() as tmp: 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', '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') + (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)) @@ -94,6 +107,49 @@ 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), + ('kvm with the Redfish provider', dict(ci, FLEET_SITE_PROVIDER='redfish'), 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)): + 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 == '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() @@ -160,6 +216,12 @@ 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. Exit 0 is passed # only with the completion marker run.sh writes last. @@ -172,6 +234,36 @@ with tempfile.TemporaryDirectory() as tmp: 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): + s = state(); (s / 'evidence').mkdir(); (s / 'evidence/result.json').write_text(json.dumps(result)) + return run(['verify', '--state', str(s)]).returncode + good = {'status': 'passed', 'exitCode': 0, 'retainedContainers': [], 'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'teardown', 'status': 'passed'}]} + check('verify passes a completed run', verified(good) == 0) + 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('') @@ -191,12 +283,27 @@ 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() + 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() 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', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'tenant-isolation', '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', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', 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/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 09e7ec09..559e09c1 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -166,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" @@ -185,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) } @@ -201,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) { diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 69d0692f..a32d25dc 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -335,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) + } + } +} From f3eb21856d340b342ef242c18414484b363b0500 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 13:03:52 -0600 Subject: [PATCH 02/10] fix(multiplane): Find the partition trace mid-line The installer traces its commands on the serial console that the kernel also prints to, so a kernel message can land at the start of the line that carries the one traced sfdisk command. Evidence counted only lines starting with the trace and failed a run whose install had partitioned the disk exactly once and printed its one receipt: the Redfish job on this branch failed that way. Count the trace wherever it appears in the log, still requiring exactly one, and report the count on failure. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/evidence.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 5bedabc2..72a6c42f 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -23,6 +23,8 @@ 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 = harness.ACCEL, harness.RUNTIME +# The installer's shell trace of its one partitioning command. +PARTITION_TRACE = '+ sfdisk /dev/vda' REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' @@ -225,8 +227,11 @@ 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') + # The installer traces its commands on the serial console the kernel + # also prints to, so a kernel message can share the traced line. + partitions = (directory / 'installer.log').read_text(errors='replace').count(PARTITION_TRACE) + if partitions != 1: + fail('installer partitioned the disk %d times, not exactly once' % 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') @@ -301,8 +306,9 @@ def redfish_provider(): fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): fail('console receipts are out of order or include another operation') - if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 1: - fail('the installer partitioned the target disk other than once for the one finished install') + partitions = sum(l.count(PARTITION_TRACE) for l in console) + if partitions != 1: + fail('the installer partitioned the target disk %d times, not once for the one finished install' % partitions) qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] def network(block): From ae16cc43f5cd90e335d43f2cf58cc8c06acd39a9 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 13:56:19 -0600 Subject: [PATCH 03/10] fix(multiplane): Mark the partition step in one line Counting the sfdisk shell trace anywhere on a line was not enough: a later local VM run found it zero times after an install that printed its one receipt. The shell writes its trace to the serial console in pieces, and the kernel's own messages can land between them. The installer now prints one FLEET-PARTITIONED line, with its receipt, in a single write once sfdisk succeeds, as it already does for the install receipt. Evidence requires exactly one such line, carrying the finished install's receipt, and counts only receipts when it checks their order. Co-Authored-By: Claude Opus 5.5 --- docs/operations/multiplane.md | 2 +- hack/local-vm/init | 3 +++ hack/multiplane/evidence.py | 21 +++++++++++---------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index e1493202..4a2604fa 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -333,7 +333,7 @@ The phases are then: 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. diff --git a/hack/local-vm/init b/hack/local-vm/init index bdb99306..a3e9d0bf 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -58,6 +58,9 @@ if [ "$mode" = burnin ]; 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/multiplane/evidence.py b/hack/multiplane/evidence.py index 72a6c42f..3b9a091b 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -23,8 +23,9 @@ 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 = harness.ACCEL, harness.RUNTIME -# The installer's shell trace of its one partitioning command. -PARTITION_TRACE = '+ sfdisk /dev/vda' +# The installer prints this, then its receipt, once it has partitioned the +# disk. A kernel message can still share the line, so it is found mid-line. +PARTITIONED = 'FLEET-PARTITIONED:' REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' @@ -227,11 +228,10 @@ 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()}) - # The installer traces its commands on the serial console the kernel - # also prints to, so a kernel message can share the traced line. - partitions = (directory / 'installer.log').read_text(errors='replace').count(PARTITION_TRACE) - if partitions != 1: - fail('installer partitioned the disk %d times, not exactly once' % partitions) + log = (directory / 'installer.log').read_text(errors='replace') + partitions = log.count(PARTITIONED) + if partitions != 1 or log.count(PARTITIONED + boot['receipt']) != 1: + fail('installer partitioned the disk %d times, not exactly once for this operation' % 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') @@ -304,10 +304,11 @@ def redfish_provider(): for name in ('boot.ipxe', 'kernel', 'installer.gz'): if 'write-complete ' + name + ' bytes=' not in written: fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) - if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): + if expected != sorted(expected) or sum(1 for l in console if l.startswith(('FLEET-INSTALLED:', 'FLEET-DISK-BOOT:', 'FLEET-WIPED:'))) != len(expected): fail('console receipts are out of order or include another operation') - partitions = sum(l.count(PARTITION_TRACE) for l in console) - if partitions != 1: + installed = [boot_record(raw, 'boot', o['operation'])['receipt'] for o in ops if o['kind'] == 'DeviceInstallation'] + partitions = sum(l.count(PARTITIONED) for l in console) + if partitions != 1 or len(installed) != 1 or sum(l.count(PARTITIONED + installed[0]) for l in console) != 1: fail('the installer partitioned the target disk %d times, not once for the one finished install' % partitions) qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] From a87150ad3b6cf88cd3e5a08b2010bf784e27c00b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 14:00:24 -0600 Subject: [PATCH 04/10] fix(multiplane): Ignore the marker's own shell trace The installer runs with set -x on the console it prints to, so the shell's trace of the FLEET-PARTITIONED printf also contains the marker and a clean install counted it twice. Match the marker followed by a 64-character receipt instead: the trace shows the format at that position, not a receipt, and a kernel message before the real line still matches. Evidence requires the one match to carry the operation's receipt. A harness test runs the printf under a traced shell, prefixes a kernel message, and checks the trace is ignored and a second partition is counted. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/evidence.py | 20 ++++++++++---------- hack/multiplane/test-harness.sh | 11 +++++++++++ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 3b9a091b..c49d9f95 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -23,9 +23,10 @@ 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 = harness.ACCEL, harness.RUNTIME -# The installer prints this, then its receipt, once it has partitioned the -# disk. A kernel message can still share the line, so it is found mid-line. -PARTITIONED = 'FLEET-PARTITIONED:' +# 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' @@ -228,10 +229,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()}) - log = (directory / 'installer.log').read_text(errors='replace') - partitions = log.count(PARTITIONED) - if partitions != 1 or log.count(PARTITIONED + boot['receipt']) != 1: - fail('installer partitioned the disk %d times, not exactly once for this operation' % partitions) + 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') @@ -307,9 +307,9 @@ def redfish_provider(): if expected != sorted(expected) or sum(1 for l in console if l.startswith(('FLEET-INSTALLED:', 'FLEET-DISK-BOOT:', 'FLEET-WIPED:'))) != len(expected): fail('console receipts are out of order or include another operation') installed = [boot_record(raw, 'boot', o['operation'])['receipt'] for o in ops if o['kind'] == 'DeviceInstallation'] - partitions = sum(l.count(PARTITIONED) for l in console) - if partitions != 1 or len(installed) != 1 or sum(l.count(PARTITIONED + installed[0]) for l in console) != 1: - fail('the installer partitioned the target disk %d times, not once for the one finished install' % partitions) + partitions = [r for l in console for r in PARTITIONED.findall(l)] + if len(installed) != 1 or partitions != installed: + fail('the installer partitioned the target disk %d times, not once for the one finished install' % len(partitions)) qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] def network(block): diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index b2e7502f..e9223ab6 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -300,6 +300,17 @@ with tempfile.TemporaryDirectory() as tmp: 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() From d5feb116d8dde11314e9a9298bb8f287a67b12ca Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 17:05:11 -0600 Subject: [PATCH 05/10] fix(multiplane): Give the run registry more memory On a CI runner the kernel killed the run's local registry while it stored the site image: its 128 MiB container limit also counts the page cache of the layers it writes, which a fast runner fills quickly. Raise it to 512 MiB. The topology still fits the documented overcommit. Co-Authored-By: Claude Opus 5.5 --- docs/operations/multiplane.md | 6 ++++-- hack/multiplane/topology.sh | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 4a2604fa..8efaf119 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -137,8 +137,10 @@ 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 -2300 MiB (platform), 2600 MiB (hub), 4400 MiB (cell) and 128 MiB (registry). -They total about 9.2 GiB and deliberately overcommit the 8 GiB VM, because +2300 MiB (platform), 2600 MiB (hub), 4400 MiB (cell) and 512 MiB (registry). +The registry's cap also counts the page cache of the image layers it writes; +at 128 MiB the kernel killed it during a fast runner's site image push. They +total about 9.6 GiB and deliberately overcommit the 8 GiB VM, because actual usage is much lower. In a debug run the cgroup peaks were 1.99 GiB for the platform node (under reclaim pressure at the earlier 1900 MiB cap), 2.06 GiB for the hub and 1.6 GiB for the cell after its restart; VM usage was about 4 GiB diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh index b1093d67..d102338b 100644 --- a/hack/multiplane/topology.sh +++ b/hack/multiplane/topology.sh @@ -14,8 +14,10 @@ registry_image=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()'; } # The source and image registry: plain HTTP on the kind network (local seam). +# Its memory limit also counts the page cache of the layers it writes, so a +# fast runner's push of the site image needs room beyond the process itself. reg_port=$(free_port) -docker run -d --name "$prefix-registry" --network kind --memory 128m --memory-swap 128m --cpus 0.5 \ +docker run -d --name "$prefix-registry" --network kind --memory 512m --memory-swap 512m --cpus 0.5 \ -p "127.0.0.1:$reg_port:5000" "$registry_image" >/dev/null for _ in $(seq 1 30); do curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null 2>&1 && break; sleep 1; done curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null || { echo 'registry did not start' >&2; exit 1; } From 9172b92f15c425a7594df5aae393feb9ec9ac458 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 19:45:53 -0600 Subject: [PATCH 06/10] fix(multiplane): Close the host port race The topology picked free host ports up front and bound them later, so another bind could take one in between: a CI run failed creating the platform cluster with "port is already allocated". Docker now assigns the registry's host port as it binds it, and the harness reads it back. kind resolves every cluster port, including its own API port, before starting the node, so the window there cannot be removed. Each cluster is created through a helper that retries only that failure, deleting this run's own half-created cluster first and choosing fresh ports, at most three times. The failure comes from the node container's start, before anything runs in the cluster, so a retry repeats no effect. Any other error stops at once. A fake-kind test covers the retry, the bound and the immediate stop. Co-Authored-By: Claude Opus 5.5 --- docs/operations/multiplane.md | 6 ++ hack/multiplane/kind_create.py | 79 +++++++++++++++++++++++++ hack/multiplane/test-harness.sh | 1 + hack/multiplane/test-kind-create.py | 89 +++++++++++++++++++++++++++++ hack/multiplane/topology.sh | 50 ++++++++-------- 5 files changed, 200 insertions(+), 25 deletions(-) create mode 100644 hack/multiplane/kind_create.py create mode 100644 hack/multiplane/test-kind-create.py diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 8efaf119..97d189d9 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -153,6 +153,12 @@ 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. +Host ports are loopback only. Docker assigns the registry's port as it binds +it. kind chooses each cluster's ports before it starts the node, so another +process can take one in between. When Docker then reports the port already +allocated, the run deletes that cluster, which has run nothing yet, and creates +it again with fresh ports, at most three times. Any other failure stops the run. + ### CI mode The `multiplane-acceptance` workflow runs the same acceptance on a disposable diff --git a/hack/multiplane/kind_create.py b/hack/multiplane/kind_create.py new file mode 100644 index 00000000..3a12de8f --- /dev/null +++ b/hack/multiplane/kind_create.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Create one kind cluster whose host ports are chosen at creation time. + +kind resolves every host port (its API server port and each extraPortMapping) +before it starts the node container, so another process can bind a port in +between and Docker refuses the start with "port is already allocated". That +failure happens when the node container starts, before anything runs in the +cluster, so this deletes the cluster it was creating and tries again with +fresh ports, a bounded number of times. Any other failure is final. + +The template names each host port as @port:NAME@. Every attempt replaces +them with fresh free ports, writes the kind config, and records the ports +the created cluster bound as {NAME: port} in --ports. +""" +import argparse +import json +import pathlib +import re +import socket +import subprocess +import sys + +TAKEN = 'port is already allocated' +PORT = re.compile(r'@port:([a-z0-9-]+)@') + + +def free_port(): + s = socket.socket() + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + +def kind(*args): + """Run kind, echoing its output, and return (exit code, output).""" + p = subprocess.Popen(['kind', *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + lines = [] + for line in p.stdout: + sys.stdout.write(line) + lines.append(line) + return p.wait(), ''.join(lines) + + +def main(): + a = argparse.ArgumentParser() + a.add_argument('--name', required=True) + a.add_argument('--template', required=True) + a.add_argument('--config', required=True) + a.add_argument('--ports', required=True) + a.add_argument('--kubeconfig', required=True) + a.add_argument('--image', required=True) + a.add_argument('--attempts', type=int, default=3) + args = a.parse_args() + template = pathlib.Path(args.template).read_text() + names = sorted(set(PORT.findall(template))) + for attempt in range(1, args.attempts + 1): + ports = {} + while len(ports) < len(names): + port = free_port() + if port not in ports.values(): + ports[names[len(ports)]] = port + pathlib.Path(args.config).write_text(PORT.sub(lambda m: str(ports[m.group(1)]), template)) + code, out = kind('create', 'cluster', '--name', args.name, '--config', args.config, '--kubeconfig', args.kubeconfig, + '--image', args.image, '--wait', '180s') + if code == 0: + pathlib.Path(args.ports).write_text(json.dumps(ports, sort_keys=True) + '\n') + return 0 + if TAKEN not in out: + return code + # Only this run's own cluster, which failed before any node ran. + kind('delete', 'cluster', '--name', args.name, '--kubeconfig', args.kubeconfig) + print('kind-create: a host port was taken before %s bound it (attempt %d of %d)' % (args.name, attempt, args.attempts), file=sys.stderr) + print('kind-create: %s could not bind fresh host ports in %d attempts' % (args.name, args.attempts), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index e9223ab6..b4d294ef 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -8,6 +8,7 @@ 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 "$root"/hack/multiplane/test-kind-create.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 diff --git a/hack/multiplane/test-kind-create.py b/hack/multiplane/test-kind-create.py new file mode 100644 index 00000000..27abfeb1 --- /dev/null +++ b/hack/multiplane/test-kind-create.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Offline tests for kind_create.py with a fake kind; no container runtime.""" +import json +import os +import pathlib +import stat +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]) +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +tmp = pathlib.Path(tempfile.mkdtemp()) +bin_dir = tmp / 'bin' +bin_dir.mkdir() +# The fake kind records each call and the config it was given, then fails +# create the way FAKE_KIND lists: taken (a bound port), other, or ok. +fake = bin_dir / 'kind' +fake.write_text('''#!/usr/bin/env python3 +import json, os, pathlib, sys +log = pathlib.Path(os.environ['FAKE_KIND_LOG']) +calls = json.loads(log.read_text()) if log.exists() else [] +args = sys.argv[1:] +entry = {'args': args} +if args[:2] == ['create', 'cluster']: + entry['config'] = pathlib.Path(args[args.index('--config') + 1]).read_text() + outcome = os.environ['FAKE_KIND'].split(',')[sum(1 for c in calls if c['args'][:2] == ['create', 'cluster'])] +calls.append(entry) +log.write_text(json.dumps(calls)) +if args[:2] == ['create', 'cluster']: + if outcome == 'taken': + print('ERROR: failed to create cluster: docker run error: Bind for 127.0.0.1:37783 failed: port is already allocated') + sys.exit(1) + if outcome == 'other': + print('ERROR: failed to create cluster: node image pull failed') + sys.exit(1) +''') +fake.chmod(fake.stat().st_mode | stat.S_IEXEC) +template = tmp / 'kind.yaml.template' +template.write_text('ports:\n - {hostPort: @port:a@}\n - {hostPort: @port:b@}\n - {again: @port:a@}\n') + + +def run(outcomes): + log = tmp / ('log-%s.json' % outcomes.replace(',', '-')) + ports = tmp / ('ports-%s.json' % outcomes.replace(',', '-')) + args = [sys.executable, str(root / 'hack/multiplane/kind_create.py'), '--name', 'fleet-mp-0000abcd-hub', '--template', str(template), + '--config', str(tmp / 'kind.yaml'), '--ports', str(ports), '--kubeconfig', str(tmp / 'kubeconfig'), '--image', 'kindest/node:test'] + r = subprocess.run(args, text=True, capture_output=True, + env=dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_KIND=outcomes, FAKE_KIND_LOG=str(log))) + calls = json.loads(log.read_text()) + return r, calls, (json.loads(ports.read_text()) if ports.exists() else None) + + +r, calls, ports = run('ok') +check('creates on the first attempt', r.returncode == 0 and [c['args'][:2] for c in calls] == [['create', 'cluster']], r.stdout + r.stderr) +check('records the ports the config bound', ports and set(ports) == {'a', 'b'} and ports['a'] != ports['b'] + and calls[0]['config'] == 'ports:\n - {hostPort: %d}\n - {hostPort: %d}\n - {again: %d}\n' % (ports['a'], ports['b'], ports['a']), str(ports)) + +r, calls, ports = run('taken,ok') +creates = [c for c in calls if c['args'][:2] == ['create', 'cluster']] +check('retries a taken port with fresh ports', r.returncode == 0 and len(creates) == 2 and creates[0]['config'] != creates[1]['config'], r.stdout + r.stderr) +check('deletes only its own failed cluster before retrying', + [c['args'][:4] for c in calls] == [['create', 'cluster', '--name', 'fleet-mp-0000abcd-hub'], ['delete', 'cluster', '--name', 'fleet-mp-0000abcd-hub'], + ['create', 'cluster', '--name', 'fleet-mp-0000abcd-hub']], str([c['args'] for c in calls])) +check('records the ports of the attempt that bound', ports and creates[1]['config'].startswith('ports:\n - {hostPort: %d}\n - {hostPort: %d}' % (ports['a'], ports['b']))) + +r, calls, ports = run('other,ok') +check('fails at once on any other error', r.returncode != 0 and len(calls) == 1 and ports is None, r.stdout + r.stderr) + +r, calls, ports = run('taken,taken,taken,ok') +check('gives up after a bounded number of attempts', r.returncode != 0 and sum(1 for c in calls if c['args'][:2] == ['create', 'cluster']) == 3 and ports is None, + r.stdout + r.stderr) + +topology = (root / 'hack/multiplane/topology.sh').read_text() +check('every kind cluster is created through the port retry', 'kind create cluster' not in topology and topology.count('kind_create "$prefix-') == 3) +check('Docker assigns the registry host port', '-p "127.0.0.1::5000"' in topology and 'docker port "$prefix-registry" 5000/tcp' in topology + and 'free_port' not in topology) + +if failures: + print('FAIL kind create tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS kind create tests') diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh index d102338b..66a6a1bb 100644 --- a/hack/multiplane/topology.sh +++ b/hack/multiplane/topology.sh @@ -11,52 +11,52 @@ prefix=$(cat "$state/prefix") 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()'; } +# kind resolves host ports before it starts a node, so a port can be taken in +# between; kind_create.py retries only that failure with fresh ports. +kind_create() { python3 hack/multiplane/kind_create.py --name "$1" --template "$2" --config "${2%.template}" --ports "$3" --kubeconfig "$4" --image "$node"; } +port_of() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]])' "$1" "$2"; } # The source and image registry: plain HTTP on the kind network (local seam). # Its memory limit also counts the page cache of the layers it writes, so a # fast runner's push of the site image needs room beyond the process itself. -reg_port=$(free_port) +# Docker assigns its host port as it binds it, so no other bind can take it. docker run -d --name "$prefix-registry" --network kind --memory 512m --memory-swap 512m --cpus 0.5 \ - -p "127.0.0.1:$reg_port:5000" "$registry_image" >/dev/null + -p "127.0.0.1::5000" "$registry_image" >/dev/null +reg_port=$(docker port "$prefix-registry" 5000/tcp | sed -n 's/^127\.0\.0\.1:\([0-9][0-9]*\)$/\1/p' | head -1) +[[ $reg_port =~ ^[0-9]+$ ]] || { echo 'registry has no published host port' >&2; exit 1; } for _ in $(seq 1 30); do curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null 2>&1 && break; sleep 1; done curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null || { echo 'registry did not start' >&2; exit 1; } # Platform: three Milo project APIs, each published on its own NodePort. -api_port=$(free_port) -{ - echo 'kind: Cluster' - echo 'apiVersion: kind.x-k8s.io/v1alpha4' - echo 'nodes:' - echo ' - role: control-plane' - echo ' extraPortMappings:' -} > "$state/platform-kind.yaml" -printf '{' > "$state/platform-ports.json" -sep= -for entry in provider:30441 consumer-a:30442 consumer-b:30443; do - role=${entry%%:*} np=${entry##*:} hp=$(free_port) - printf ' - {containerPort: %s, hostPort: %s, listenAddress: 127.0.0.1}\n' "$np" "$hp" >> "$state/platform-kind.yaml" - printf '%s"%s": %s' "$sep" "$role" "$hp" >> "$state/platform-ports.json"; sep=', ' -done -printf '}\n' >> "$state/platform-ports.json" -kind create cluster --name "$prefix-platform" --config "$state/platform-kind.yaml" --kubeconfig "$state/platform-admin.yaml" --image "$node" --wait 180s +cat > "$state/platform-kind.yaml.template" <<'YAML' +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +nodes: + - role: control-plane + extraPortMappings: + - {containerPort: 30441, hostPort: @port:provider@, listenAddress: 127.0.0.1} + - {containerPort: 30442, hostPort: @port:consumer-a@, listenAddress: 127.0.0.1} + - {containerPort: 30443, hostPort: @port:consumer-b@, listenAddress: 127.0.0.1} +YAML +kind_create "$prefix-platform" "$state/platform-kind.yaml.template" "$state/platform-ports.json" "$state/platform-admin.yaml" docker update --memory 2300m --memory-swap 2300m --cpus 2 "$prefix-platform-control-plane" >/dev/null -cat > "$state/hub-kind.yaml" < "$state/hub-kind.yaml.template" <<'YAML' kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane extraPortMappings: - containerPort: 32443 - hostPort: $api_port + hostPort: @port:karmada@ listenAddress: 127.0.0.1 YAML -kind create cluster --name "$prefix-hub" --config "$state/hub-kind.yaml" --kubeconfig "$state/host.yaml" --image "$node" --wait 180s +kind_create "$prefix-hub" "$state/hub-kind.yaml.template" "$state/hub-ports.json" "$state/host.yaml" +api_port=$(port_of "$state/hub-ports.json" karmada) docker update --memory 2600m --memory-swap 2600m --cpus 2 "$prefix-hub-control-plane" >/dev/null # The cell pulls the site image by digest from the run registry. -cat > "$state/cell-kind.yaml" <<'YAML' +cat > "$state/cell-kind.yaml.template" <<'YAML' kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 containerdConfigPatches: @@ -64,7 +64,7 @@ containerdConfigPatches: [plugins."io.containerd.grpc.v1.cri".registry] config_path = "/etc/containerd/certs.d" YAML -kind create cluster --name "$prefix-cell" --config "$state/cell-kind.yaml" --kubeconfig "$state/cell-admin.yaml" --image "$node" --wait 180s +kind_create "$prefix-cell" "$state/cell-kind.yaml.template" "$state/cell-ports.json" "$state/cell-admin.yaml" docker exec "$prefix-cell-control-plane" mkdir -p "/etc/containerd/certs.d/$prefix-registry:5000" printf '[host."http://%s-registry:5000"]\n capabilities = ["pull", "resolve"]\n' "$prefix" | docker exec -i "$prefix-cell-control-plane" tee "/etc/containerd/certs.d/$prefix-registry:5000/hosts.toml" >/dev/null From 7ceef689b9a1c1826589df1810bab3f70660b08d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:22:30 -0600 Subject: [PATCH 07/10] test(multiplane): Shorten lab timers The deadline and fail-closed scenarios spent about thirteen minutes of each run waiting on timers sized for production: a six-minute deadline plus the coordinator's two-minute skew margin, and kro's three-minute health timeout on the bad revision. Make each a lab setting with a short default. The short-deadline installation gets two minutes, still many times the seconds it needs to journal its boot and lose its Machine; if it runs out, the scenario says so. In CI mode every process reads one Linux kernel clock, so the lab coordinator's skew margin is 30 seconds there; the Colima run keeps two minutes because its VM clock can drift from the workstation's. The scenario still requires the wipe to be admitted after the worker stopped. The bad kro revision also sets a 45-second health timeout, and the recovery revision restores the usual one. Production defaults are unchanged. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 3 ++- docs/development/device-custody.md | 2 +- docs/operations/multiplane.md | 19 ++++++++++++++++--- docs/operations/redfish-lab.md | 2 +- hack/multiplane/coordinator.sh | 12 ++++++++++-- hack/multiplane/flux.py | 20 +++++++++++++++----- hack/multiplane/scenarios.py | 3 +++ hack/multiplane/steps.sh | 12 +++++++++--- hack/multiplane/test-flux.py | 5 +++++ internal/multiplane/runner.go | 23 ++++++++++++++++++----- 10 files changed, 80 insertions(+), 21 deletions(-) diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index baf5142f..72264be3 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -50,6 +50,7 @@ func run() error { 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 } @@ -62,7 +63,7 @@ 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, *installationDeadline, 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", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 67fa281c..e39ccce4 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -393,7 +393,7 @@ phases](../operations/multiplane.md#acceptance-phases) describe each one. | 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 six-minute installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | +| 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 | diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 97d189d9..9f70c298 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -183,6 +183,19 @@ above, unchanged: | `FLEET_MULTIPLANE_ARCH` (site binary and runtime architecture) | `arm64` | `amd64` | | `FLEET_MULTIPLANE_ACCEL` | `tcg` | `kvm` in local VM mode, `tcg` in Redfish mode | +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` | 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. Every +process in a lab run reads one host clock. The deadline scenario still +requires the wipe to be admitted after the worker stopped. + 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` @@ -206,8 +219,8 @@ 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 and swap sampled every -10 seconds, per-container memory, and any kernel OOM events. The job removes -preinstalled toolchains to free disk, and every tool and action is pinned. +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 @@ -413,7 +426,7 @@ The phases are then: 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 a six-minute installation deadline for + and restarts the coordinator with a two-minute 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 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index a9c7ca79..754ed958 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -362,7 +362,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | `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 | -| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a six-minute 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. | +| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a two-minute 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. | diff --git a/hack/multiplane/coordinator.sh b/hack/multiplane/coordinator.sh index a000d468..802cdfbc 100755 --- a/hack/multiplane/coordinator.sh +++ b/hack/multiplane/coordinator.sh @@ -13,8 +13,16 @@ case $action in echo "coordinator: already running" exit 0 fi - # Extra arguments, such as a shorter installation deadline, pass through. - nohup "$state/fleet-multiplane-host" coordinator --config "$state/acceptance.json" "${@:3}" >>"$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; } diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index c1c6a8c4..162a0e8f 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -51,6 +51,12 @@ KARMADA_CHART_SHA256 = '773ab194cb92dad81d479d2199b968a2c6b0b8366306ba47961afd67616834fe' # A well-formed digest that no registry serves: the fail-closed revision. MISSING_DIGEST = 'sha256:' + hashlib.sha256(b'fleet: deliberately absent chart').hexdigest() +# The fail-closed revision also shortens the kro layer's health timeout, so +# kro reports not Ready within a minute rather than after its usual three. +# The recovery revision restores the usual timeout with the chart. +FAIL_CLOSED_TIMEOUT = os.environ.get('FLEET_MULTIPLANE_FAIL_CLOSED_TIMEOUT', '45s') +if not re.fullmatch(r'[1-9][0-9]*[sm]', FAIL_CLOSED_TIMEOUT): + raise SystemExit('FLEET_MULTIPLANE_FAIL_CLOSED_TIMEOUT must be a whole number of seconds or minutes, such as 45s') TAG = 'local' CLUSTERS = ('platform', 'hub', 'cell') KUBECONFIG = {'platform': 'platform-admin.yaml', 'hub': 'host.yaml', 'cell': 'cell-admin.yaml'} @@ -275,7 +281,8 @@ def stage(args): FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false', FLEET_LOCAL_VM_ACCEL=harness.ACCEL) if args.bad_kro_chart: patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, - 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}])) + 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}], + timeout=FAIL_CLOSED_TIMEOUT)) if args.drop_site_volume: patches.append(child_patch('fleet-site-base', [{'patch': '$patch: delete\napiVersion: v1\nkind: PersistentVolumeClaim\n' 'metadata:\n name: fleet-site-state\n namespace: fleet-site\n'}])) @@ -309,10 +316,13 @@ def child_path(name, path): return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: replace\n path: /spec/path\n value: %s\n' % (name, path) -def child_patch(name, patches): - """Patch a child Kustomization's spec.patches: the effect of a source commit.""" - return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: add\n path: /spec/patches\n value: %s\n' % ( - name, json.dumps(patches)) +def child_patch(name, patches, timeout=None): + """Patch a child Kustomization's spec.patches, and optionally its health + timeout: the effect of a source commit.""" + ops = ' - op: add\n path: /spec/patches\n value: %s\n' % json.dumps(patches) + if timeout: + ops += ' - op: replace\n path: /spec/timeout\n value: %s\n' % timeout + return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n%s' % (name, ops) def revisions(state): diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py index 34d31a05..b83b45c2 100644 --- a/hack/multiplane/scenarios.py +++ b/hack/multiplane/scenarios.py @@ -227,6 +227,9 @@ def release_waits(s): 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 {} diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index ba1b1aa2..d739ea88 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -13,6 +13,11 @@ 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" "$@"; } @@ -117,7 +122,8 @@ case "$step" in scenario staff-access "$state" ;; deadline-admit) - # Consumer B's installation is admitted under a six-minute deadline with + # 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 @@ -125,13 +131,13 @@ case "$step" in # 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=6m >/dev/null + 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 six-minute deadline and journaled its installer boot with the lab boot hook withholding it\n' + 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 diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index d0750ada..38f2da5e 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -134,6 +134,11 @@ def render(rev, cluster): 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/internal/multiplane/runner.go b/internal/multiplane/runner.go index 85459efd..254cb92c 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -159,23 +159,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. -// A positive installationDeadline replaces the installation kind's deadline -// for operations this process admits; the deadline scenario uses it. -func Coordinate(ctx context.Context, c Config, installationDeadline time.Duration, 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 installationDeadline > 0 { - registry.Kind("DeviceInstallation").Deadline = installationDeadline + 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 From 82a57a358343676398a5cda33900e391671928c9 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:22:31 -0600 Subject: [PATCH 08/10] ci(multiplane): Cache Go builds per mode Each acceptance job rebuilt the race-instrumented readiness tests and the site binary from scratch, because the shared setup-go cache held another workflow's builds. Give each mode its own Go build cache, keyed by commit and restored from the newest for the same go.sum, else the newest for the mode. Stop deleting preinstalled toolchains: it took one to two minutes, and the runner has far more free disk than the harness requires. The job now samples free disk in the Docker data root every 10 seconds and reports the minimum. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 30 ++++++++++++++++----- docs/operations/multiplane.md | 18 ++++++++----- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml index a4e00127..879b7e25 100644 --- a/.github/workflows/multiplane-acceptance.yml +++ b/.github/workflows/multiplane-acceptance.yml @@ -50,7 +50,20 @@ jobs: 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: true} + 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. + - uses: actions/cache@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 @@ -70,15 +83,14 @@ jobs: mkdir -p "$HOME/.local/bin" mv kubectl "$HOME/.local/bin/kubectl" echo "$HOME/.local/bin" >> "$GITHUB_PATH" - - name: Free runner disk and record capacity + # 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: | - # Preinstalled toolchains this job does not use. The harness needs - # 12 GiB free in the Docker data root. { echo "FLEET_MULTIPLANE_STATE_ROOT=$RUNNER_TEMP/fleet-multiplane" echo "METRICS=$RUNNER_TEMP/runner-metrics" } >> "$GITHUB_ENV" - sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL /usr/local/share/boost nproc free -m df -h / /var/lib/docker @@ -92,12 +104,13 @@ jobs: - name: Sample runner memory run: | mkdir -m 0700 "$METRICS" - # Every 10 s: memory, swap and the run's container memory. Container + # 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" @@ -126,6 +139,9 @@ jobs: 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 @@ -133,7 +149,7 @@ jobs: 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 "$state/evidence/runner/" 2>/dev/null || true + 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" diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 9f70c298..8beb3f12 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -189,12 +189,16 @@ 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` | 2 minutes | The coordinator waits this long past a deadline before declaring it exceeded | +| `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. Every -process in a lab run reads one host clock. The deadline scenario still -requires the wipe to be admitted after the worker stopped. +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 @@ -218,9 +222,9 @@ passed, teardown passed and no retained container. 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 and swap sampled every -10 seconds, per-container memory, and any kernel OOM events. Every tool and action is -pinned. +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 From 486d003c19e34ba6eb5ec335deb86436463c8908 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:29:39 -0600 Subject: [PATCH 09/10] test(multiplane): Run Redfish targets under KVM Redfish mode ran its lab targets under software emulation even on runners with /dev/kvm, so its installs and wipes took several times as long as local VM mode's. The lab adapter now takes the accelerator from the site's run parameter and defines or starts a target only while the site runtime publishes the same one beside the libvirt socket, with no software fallback. Evidence requires every QEMU command line of target A to name it, and preflight accepts KVM in Redfish mode on an amd64 runtime with /dev/kvm. The Pod, Job and BMC interruptions relied on a slow installer to land mid-install. Redfish mode now holds target A paused once its kernel prints, as local VM mode does, reading only console output written after the hold was armed, and evidence fails if the interruptions did not land on the held guest. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 7 +-- config/site/redfish/services/bmc.yaml | 2 + docs/operations/multiplane.md | 14 +++-- docs/operations/redfish-lab.md | 15 +++-- hack/multiplane/acceptance-redfish.sh | 2 + hack/multiplane/evidence.py | 9 +++ hack/multiplane/harness.py | 7 +-- hack/multiplane/redfish_steps.py | 3 +- hack/multiplane/steps.sh | 66 ++++++++++++--------- hack/multiplane/test-harness.sh | 10 +++- hack/redfish-lab/fleet_lab_adapter.py | 22 ++++++- hack/redfish-lab/test_adapter.py | 26 +++++++- 12 files changed, 132 insertions(+), 51 deletions(-) diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml index 879b7e25..72769650 100644 --- a/.github/workflows/multiplane-acceptance.yml +++ b/.github/workflows/multiplane-acceptance.yml @@ -1,8 +1,8 @@ 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. Local VM mode runs its guest -# under KVM; Redfish mode keeps its lab targets on TCG. It runs on demand, +# 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: @@ -39,8 +39,7 @@ jobs: FLEET_MULTIPLANE_RUNTIME: ci FLEET_MULTIPLANE_DOCKER_CONTEXT: default FLEET_MULTIPLANE_ARCH: amd64 - # The Redfish lab adapter defines TCG domains only. - FLEET_MULTIPLANE_ACCEL: ${{ matrix.mode == 'localvm' && 'kvm' || 'tcg' }} + FLEET_MULTIPLANE_ACCEL: kvm steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: {persist-credentials: false} 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/docs/operations/multiplane.md b/docs/operations/multiplane.md index 8beb3f12..aba51552 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -163,7 +163,8 @@ it again with fresh ports, at most three times. Any other failure stops the run. The `multiplane-acceptance` workflow runs the same acceptance on a disposable GitHub-hosted `ubuntu-24.04` runner, one job per mode. Status: **verified**. -Both modes passed on a hosted runner, local VM mode under KVM. +Both modes passed on a hosted runner with local VM mode under KVM. Redfish +mode under KVM is implemented and not yet verified. 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, @@ -181,7 +182,7 @@ above, unchanged: | `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` in local VM mode, `tcg` in Redfish mode | +| `FLEET_MULTIPLANE_ACCEL` | `tcg` | `kvm` | Lab timers shorten the waits the scenarios provoke, in every runtime. Each scenario still proves the same outcome, and production defaults are unchanged: @@ -205,8 +206,8 @@ In CI mode, preflight requires a GitHub-hosted runner (`GITHUB_ACTIONS=true` and 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, without `/dev/kvm`, -or with Redfish mode, and any unknown value. `preflight.json` records the +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 @@ -352,8 +353,9 @@ The phases are then: the replacement exists, still mid-install. kro must recreate the Job under 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 no guest; its - TCG installer is slow enough for these interruptions. + `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 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 754ed958..2edc5628 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -36,10 +36,13 @@ Prerequisites, exit codes, the state and evidence layout, `--keep`, 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. The lab adapter defines the targets -as TCG domains, so CI runs them under TCG on an amd64 runner, and preflight -rejects KVM in Redfish mode. TCG on a cloud runner is its own qualification -target, separate from the Colima runs below and from physical hardware. +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 @@ -102,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) │ @@ -362,7 +365,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | `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 | -| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a two-minute 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. | +| `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. | diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index e4b04654..eb88051b 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -26,10 +26,12 @@ 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 diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index c49d9f95..cb253ddd 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -279,6 +279,8 @@ def redfish_provider(): copy_out('/var/lib/fleet-lab-console', raw / 'lab-console') store, ops, provider, held = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) + 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_alloc, b_alloc = 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'] @@ -321,6 +323,13 @@ def network(block): # was withheld by the lab boot hook), B wipe. if order != ['network', 'disk', 'network', 'network', 'network'] or starts['targetB']: fail('expected target A boots network, disk, network, network, network and no target B start; got %s' % starts) + # Every lab target start ran the selected accelerator: libvirt logs each + # QEMU command line, which names the accelerator it ran. The adapter + # defines a target only while the site runtime publishes the same one. + qemu_accels = [re.findall(r'-accel (\w+)', b) for b in blocks] + if any(x != [ACCEL] for x in qemu_accels): + fail('lab target accelerator is not %s: QEMU accelerators %s' % (ACCEL, qemu_accels)) + starts['accelerator'] = ACCEL audit = [json.loads(l) for l in (ev / 'redfish-audit.jsonl').read_text().splitlines()] effects = [e for e in audit if e['method'] not in ('GET', 'HEAD')] ons = [e for e in effects if e.get('resetType') == 'On'] diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index 185d310c..d9500839 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -128,10 +128,9 @@ def check(name, ok, detail='', kind='preflight'): 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. The - # Redfish lab adapter defines TCG domains only. - accel_ok = ACCEL == 'tcg' or (ACCEL == 'kvm' and ARCH == 'amd64' and PROVIDER == 'libvirt') - check('accelerator', accel_ok, 'FLEET_MULTIPLANE_ACCEL=%s; tcg, or kvm with an amd64 runtime and the libvirt provider' % ACCEL) + # 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) code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) endpoint_ok = endpoint_matches(code, out) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 8460bcf7..7ba3e434 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -358,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): diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index d739ea88..c052d5df 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -233,42 +233,51 @@ JSON rm -f "$state/worker-kubeconfig.json" ;; hold-installer) - # Local VM mode: hold the installer guest paused as soon as its kernel - # prints, so the worker 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. + # 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; } - runtime sh -c 'setsid sh -c "$1" sh >/dev/null 2>&1 "$2.pid"' sh "$(cat <<'SH' -uri='qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' out=/tmp/fleet-installer-hold + 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 - case "$d" in fleet-local-*) ;; *) continue ;; esac - for log in /var/lib/fleet-local/vm/*/"${d#fleet-local-}"/installer.log; do - [ -f "$log" ] && grep -q 'Linux version' "$log" || continue - if virsh --connect "$uri" suspend "$d" >/dev/null 2>&1 && [ "$(virsh --connect "$uri" domstate "$d")" = paused ] && ! grep -q 'FLEET-INSTALLED:' "$log"; then - printf 'held %s %s\n' "$d" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$out.tmp" - else - printf 'missed %s\n' "$d" > "$out.tmp" - fi - mv "$out.tmp" "$out"; exit 0 - done + 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" +)" "$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") - if ! redfish; then - 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-* ]] || { echo "installer guest was not held mid-install: ${held:-no hold}" >&2; exit 1; } - printf '%s\n' "$held" > "$state/installer-hold" - fi + 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" @@ -286,8 +295,7 @@ SH 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" - if redfish; then state_word=running; else state_word='held paused'; fi - printf 'interrupt-pod: worker Pod force-deleted after the installer boot was journaled with its domain %s; Job controller replaced it; no local result\n' "$state_word" + 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") @@ -315,9 +323,13 @@ SH 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 < "$state/installer-hold" + 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; } - 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; } + 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' diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index b4d294ef..679fc978 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -125,7 +125,8 @@ with tempfile.TemporaryDirectory() as tmp: ('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), - ('kvm with the Redfish provider', dict(ci, FLEET_SITE_PROVIDER='redfish'), 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)): @@ -295,6 +296,13 @@ with tempfile.TemporaryDirectory() as tmp: 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() 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) From 11db12e55a81754ab45e79889f3830becf1cc74e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:45:49 -0600 Subject: [PATCH 10/10] ci(multiplane): Shard each suite in two Each suite ran every scenario in sequence on one runner, so a run took as long as all of them together. Add a scenario group setting. Every group builds the same topology and runs the scenarios through the Pod and Job lifecycle checks. The flux group then runs the Flux scenarios, and the release group the reflection, release, reuse, deadline, rebuild, wrong-location and closed-boot scenarios; all, the local default, runs both. Evidence checks what each group produces: the flux group leaves the Device allocated, so the release, wipe and final custody checks run in the release group. The result records the group, and verify requires the expected one. The workflow runs each suite as a flux and a release shard on separate runners, and a new acceptance job passes only if every shard passed. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 49 +++++++++++++-- docs/operations/multiplane.md | 26 ++++++-- docs/operations/redfish-lab.md | 2 +- hack/multiplane/acceptance-redfish.sh | 49 +++++++++------ hack/multiplane/acceptance.sh | 49 +++++++++------ hack/multiplane/evidence.py | 70 ++++++++++++++++----- hack/multiplane/harness.py | 16 ++++- hack/multiplane/redfish_steps.py | 13 +++- hack/multiplane/run.sh | 4 +- hack/multiplane/test-harness.sh | 26 ++++++-- hack/multiplane/test-redfish.py | 9 ++- 11 files changed, 233 insertions(+), 80 deletions(-) diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml index 72769650..41b987f4 100644 --- a/.github/workflows/multiplane-acceptance.yml +++ b/.github/workflows/multiplane-acceptance.yml @@ -22,16 +22,22 @@ permissions: jobs: acceptance: if: github.event_name != 'pull_request' || github.event.label.name == 'multiplane-acceptance' - name: acceptance (${{ matrix.mode }}) + 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 }} + 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 @@ -40,6 +46,7 @@ jobs: 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} @@ -54,7 +61,9 @@ jobs: # 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. - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + # 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 @@ -157,12 +166,22 @@ jobs: 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 }}-${{ github.run_id }}-${{ github.run_attempt }} + 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 @@ -173,10 +192,30 @@ jobs: 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]}" + 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/docs/operations/multiplane.md b/docs/operations/multiplane.md index aba51552..423870f8 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -162,9 +162,10 @@ it again with fresh ports, at most three times. Any other failure stops the run. ### CI mode The `multiplane-acceptance` workflow runs the same acceptance on a disposable -GitHub-hosted `ubuntu-24.04` runner, one job per mode. Status: **verified**. -Both modes passed on a hosted runner with local VM mode under KVM. Redfish -mode under KVM is implemented and not yet verified. +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, @@ -183,6 +184,7 @@ above, unchanged: | `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: @@ -218,8 +220,20 @@ 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 job passes only if exactly one run recorded `passed` with every phase -passed, teardown passed and no retained container. After the run, including +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. @@ -432,7 +446,7 @@ The phases are then: 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 a two-minute installation deadline for + 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 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 2edc5628..7e7cc631 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -367,7 +367,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | `resume` | The recreated Job completes the exact operation with one succeeded Pod | | `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: diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index eb88051b..54e316d2 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -12,6 +12,11 @@ ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --t 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" @@ -40,26 +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 -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 +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 92364b92..caa69773 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -9,6 +9,11 @@ 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" @@ -32,25 +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 -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 +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/evidence.py b/hack/multiplane/evidence.py index cb253ddd..5ef5357f 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -22,7 +22,7 @@ ev = s / 'evidence' 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 = harness.ACCEL, harness.RUNTIME +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. @@ -99,13 +99,26 @@ def copy_out(source, destination): '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', '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): @@ -362,6 +375,43 @@ def network(block): return ops, installs, wipes, custody, interrupt, receipts, starts, denials +FLUX_SCENARIO_FILES = ('flux-drift.json', 'flux-restart.json', 'flux-fail-closed.json', 'flux-retention.json', 'flux-graph-lifecycle.json') +flux_files = ('flux-verify.json', 'flux-initial.json', 'flux-rbac-restore.json', 'flux-final.json', 'flux-ownership-final.json', 'kro-rbac.json') + ( + FLUX_SCENARIO_FILES if GROUP != 'release' else ()) + + +def flux_evidence(): + for name in flux_files: + if not (ev / name).exists(): + fail('missing Flux evidence ' + name) + flux_revisions = json.loads((s / 'flux-revisions.json').read_text()) + final = json.loads((ev / 'flux-final.json').read_text()) + for cluster, snap in final.items(): + if snap['sources']['flux-system/fleet-gitops']['artifactRevision'] != flux_revisions[-1]['fluxRevision']: + fail('%s did not end on the final source revision' % cluster) + if any(k['lastAppliedRevision'] != flux_revisions[-1]['fluxRevision'] or k['suspend'] for n, k in snap['kustomizations'].items()): + fail('%s has a Kustomization not at the final revision' % cluster) + return flux_revisions + + +if GROUP == 'flux': + # The Flux group stops after the core install and the Flux scenarios: the + # Device stays allocated to consumer A, so the release, wipe and custody + # checks belong to the release group, which runs the same core install. + flux_revisions = flux_evidence() + failure_scenarios = {name: json.loads((ev / (name + '.json')).read_text()) for name in ('import-inert', 'staff-access', 'contention')} + summary = {'schemaVersion': 3, 'acceptance': 'evidence-verified', 'group': GROUP, + 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'prefix': prefix, + 'qualification': {'kvm': ACCEL == 'kvm', 'productionAuthority': False, 'productionEquivalence': False}, + 'scenarios': {'gitops': {'sourceRevisions': [{k: r[k] for k in ('revision', 'digest', 'purpose', 'gitHead', 'contentSumsSHA256', 'files')} for r in flux_revisions], + 'evidence': list(flux_files)}, + 'failureScenarios': failure_scenarios, 'custodyCRDRules': custody_rules}, + 'runtimePodMemoryEvents': {key: int(value) for key, value in memory_events.items()}, + 'nodeMemoryEvents': {node: {key: int(value) for key, value in e.items()} for node, e in node_events.items()}} + (ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') + print('evidence: sanitized summary ' + str(ev / 'summary.json') + ' (flux group)') + sys.exit(0) + raw = s / 'provider-private' ops, installs, wipes, custody, interrupt, receipts, starts, denials = (redfish_provider if REDFISH else libvirt_provider)() @@ -438,18 +488,7 @@ def network(block): fail('site volume or Flux-owned shared Deployments not as expected') (ev / 'kubernetes-execution.json').write_text(json.dumps(execution, indent=2, sort_keys=True) + '\n') arch = out('docker', 'info', '--format', '{{.Architecture}}').strip() -flux_files = ('flux-verify.json', 'flux-initial.json', 'flux-rbac-restore.json', 'flux-drift.json', 'flux-restart.json', 'flux-fail-closed.json', 'flux-retention.json', 'flux-final.json', - 'flux-graph-lifecycle.json', 'flux-ownership-final.json', 'kro-rbac.json') -for name in flux_files: - if not (ev / name).exists(): - fail('missing Flux evidence ' + name) -flux_revisions = json.loads((s / 'flux-revisions.json').read_text()) -final = json.loads((ev / 'flux-final.json').read_text()) -for cluster, snap in final.items(): - if snap['sources']['flux-system/fleet-gitops']['artifactRevision'] != flux_revisions[-1]['fluxRevision']: - fail('%s did not end on the final source revision' % cluster) - if any(k['lastAppliedRevision'] != flux_revisions[-1]['fluxRevision'] or k['suspend'] for n, k in snap['kustomizations'].items()): - fail('%s has a Kustomization not at the final revision' % cluster) +flux_revisions = flux_evidence() write_env = json.loads((s / 'gitops-environment.json').read_text()) # The #174 failure scenarios, each written by hack/multiplane/scenarios.py. FAILURE_SCENARIOS = ('import-inert', 'staff-access', 'contention', 'release-waits', 'deadline-hold', 'deadline-settled', 'rebuild') @@ -462,7 +501,7 @@ def network(block): summary = { # The evidence verified; the run is not finished. Only result.json, which # run.sh writes last, records whether the run passed. - 'schemaVersion': 3, 'acceptance': 'evidence-verified', + 'schemaVersion': 3, 'acceptance': 'evidence-verified', 'group': GROUP, 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'prefix': prefix, 'qualification': {'nativeMiloProjectAPIs': True, 'actualKarmadaDeliveryAndReflection': True, 'realLocalPXE': True, 'kubernetesJobExecution': True, 'actualKroController': True, 'fluxReconciledServices': True, @@ -477,6 +516,7 @@ def network(block): 'evidence': list(flux_files), 'siteImage': write_env['siteImage']}, 'installerStarts': starts, 'reflectionRejections': list(REFLECTION_FAULTS), + 'fluxScenarios': GROUP != 'release', 'failureScenarios': failure_scenarios, 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), 'custodyCRDRules': custody_rules, diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index d9500839..6a7cf1d5 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -26,6 +26,11 @@ CONTEXT = os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT', 'colima-' + PROFILE) ARCH = os.environ.get('FLEET_MULTIPLANE_ARCH', 'arm64') ACCEL = os.environ.get('FLEET_MULTIPLANE_ACCEL', 'tcg') +# Scenario group: all runs every scenario in one topology. CI shards a suite +# into flux and release, each on its own runner after the same setup and core +# install scenarios, and requires both to pass. +GROUP = os.environ.get('FLEET_MULTIPLANE_GROUP', 'all') +GROUPS = ('all', 'flux', 'release') DOCKER_ARCHITECTURES = {'arm64': ('aarch64', 'arm64'), 'amd64': ('x86_64', 'amd64')} CI_ENDPOINT = 'unix:///var/run/docker.sock' EXIT_PASSED, EXIT_FAILED, EXIT_PREFLIGHT, EXIT_BLOCKED, EXIT_TIMEOUT, EXIT_USAGE = 0, 1, 2, 3, 4, 64 @@ -131,6 +136,7 @@ def check(name, ok, detail='', kind='preflight'): # 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 = endpoint_matches(code, out) @@ -184,7 +190,7 @@ def check(name, ok, detail='', kind='preflight'): 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, - 'runtime': {'mode': RUNTIME, 'dockerContext': CONTEXT, 'architecture': ARCH, 'accelerator': ACCEL}}) + '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 @@ -545,11 +551,12 @@ def result(args): 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': 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, code, ev / 'result.json')) @@ -576,6 +583,8 @@ def verify(args): 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 @@ -611,6 +620,7 @@ def main(): 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] == ['--']: diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 7ba3e434..73cd5453 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -379,13 +379,20 @@ 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): diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 16e63a50..a9b1f1e5 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -29,12 +29,14 @@ done # 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 diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 679fc978..83b89163 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -129,10 +129,16 @@ with tempfile.TemporaryDirectory() as tmp: ('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)): + ('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'])) @@ -238,11 +244,14 @@ with tempfile.TemporaryDirectory() as tmp: # Verify: a pass needs status passed, every phase passed, teardown passed # and no retained container, whatever the exit code said. - def verified(result): + def verified(result, *args): s = state(); (s / 'evidence').mkdir(); (s / 'evidence/result.json').write_text(json.dumps(result)) - return run(['verify', '--state', str(s)]).returncode - good = {'status': 'passed', 'exitCode': 0, 'retainedContainers': [], 'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'teardown', 'status': 'passed'}]} + 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'}]}), @@ -330,6 +339,15 @@ with tempfile.TemporaryDirectory() as tmp: '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-redfish.py b/hack/multiplane/test-redfish.py index e13f1950..407dd14c 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -149,9 +149,9 @@ 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', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'rebuild', 'boot-denials', 'isolation', 'evidence'] @@ -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)