diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml new file mode 100644 index 00000000..b3a6e001 --- /dev/null +++ b/.github/workflows/multiplane-acceptance.yml @@ -0,0 +1,227 @@ +name: multiplane-acceptance +# The multi-plane acceptance in CI mode (docs/operations/multiplane.md#ci-mode) +# on a disposable GitHub-hosted runner: three kind clusters, Milo, Karmada, kro, +# Flux and a privileged libvirt/QEMU site Pod. Both modes run their guests +# under KVM. It runs on demand, +# nightly, and on a pull request only when the multiplane-acceptance label is +# applied, never on every push. +on: + workflow_dispatch: + inputs: + mode: + description: Site provider + type: choice + options: [both, localvm, redfish, media] + default: both + schedule: + - cron: '23 5 * * *' + pull_request: + types: [labeled] +permissions: + contents: read +jobs: + acceptance: + if: github.event_name != 'pull_request' || github.event.label.name == 'multiplane-acceptance' + name: acceptance (${{ matrix.mode }}, ${{ matrix.group }}) + # Each suite runs as two shards on separate runners, after the same setup + # and core install scenarios: flux runs the Flux scenarios, release the + # reflection, release, reuse, deadline and rebuild scenarios. The + # acceptance job below passes only if every shard passed. A new suite is + # one more mode here and in the task selection below. + strategy: + fail-fast: false + matrix: + # Every suite but virtual media runs as its flux and release shards. + # The virtual media suite (run.sh --redfish --virtual-media) runs as + # one shard: its scenarios are one ordered sequence of installs. + include: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode == 'localvm' && '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"}]' || github.event_name == 'workflow_dispatch' && inputs.mode == 'redfish' && '[{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"}]' || github.event_name == 'workflow_dispatch' && inputs.mode == 'media' && '[{"mode":"media","group":"all"}]' || '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"},{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"},{"mode":"media","group":"all"}]') }} + # A newer labeled run for the same pull request replaces an older one; + # nightly and manual runs never cancel each other. A cancelled run never + # counts as passed. + concurrency: + group: multiplane-acceptance-${{ github.event.pull_request.number || github.run_id }}-${{ matrix.mode }}-${{ matrix.group }} + cancel-in-progress: true + runs-on: ubuntu-24.04 + timeout-minutes: 120 + env: + FLEET_MULTIPLANE_RUNTIME: ci + FLEET_MULTIPLANE_DOCKER_CONTEXT: default + FLEET_MULTIPLANE_ARCH: amd64 + FLEET_MULTIPLANE_ACCEL: kvm + FLEET_MULTIPLANE_GROUP: ${{ matrix.group }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: {persist-credentials: false} + # A pull request run tests GitHub's merge of the head into the base. + - name: Record the tested commits + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: printf 'Tested commit %s for head %s\n' "$(git rev-parse HEAD)" "$HEAD_SHA" | tee -a "$GITHUB_STEP_SUMMARY" + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: {go-version-file: go.mod, cache: false} + # This job's own Go build cache: the readiness tests build with the race + # detector and the site binary without cgo, so a cache saved by another + # workflow holds neither. Keyed by commit, restoring the newest for the + # same go.sum. + # Saved after the build phase even when the run later fails, so a failing + # run still warms the next one. + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}-${{ github.sha }} + restore-keys: | + multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}- + multiplane-go-${{ matrix.mode }}- + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: {python-version: '3.12.12'} + - uses: imranismail/setup-kustomize@2ba527d4d055ab63514ba50a99456fc35684947f # v2 + with: {kustomize-version: 5.8.1} + - name: Install pinned kind, kubectl and task + run: | + set -euo pipefail + go install sigs.k8s.io/kind@v0.31.0 + go install github.com/go-task/task/v3/cmd/task@v3.53.1 + directory=$(mktemp -d) + trap 'rm -rf "$directory"' EXIT + cd "$directory" + curl --fail --location --retry 3 --max-time 60 -o kubectl https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl + curl --fail --location --retry 3 --max-time 60 -o kubectl.sha256 https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl.sha256 + echo "$(cat kubectl.sha256) kubectl" | sha256sum --check + chmod +x kubectl + mkdir -p "$HOME/.local/bin" + mv kubectl "$HOME/.local/bin/kubectl" + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + # The runner's disk has far more free space than the 12 GiB the harness + # requires in the Docker data root, and preflight checks it. + - name: Record runner capacity + run: | + { + echo "FLEET_MULTIPLANE_STATE_ROOT=$RUNNER_TEMP/fleet-multiplane" + echo "METRICS=$RUNNER_TEMP/runner-metrics" + } >> "$GITHUB_ENV" + nproc + free -m + df -h / /var/lib/docker + docker version --format 'docker {{.Server.Version}}' + # Hosted runners restrict /dev/kvm to the kvm group; grant the runner + # access, as GitHub documents for hardware acceleration. + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + ls -l /dev/kvm || true + - name: Sample runner memory + run: | + mkdir -m 0700 "$METRICS" + # Every 10 s: memory, swap, the run's container memory and free disk. Container + # names and byte counts only. The script expands in its own shell. + # shellcheck disable=SC2016 + nohup sh -c 'while :; do + printf "%s %s\n" "$(date -u +%FT%TZ)" "$(awk "/^(MemTotal|MemAvailable|SwapTotal|SwapFree):/ {printf \"%s=%s \", \$1, \$2}" /proc/meminfo)" >> "$1/meminfo.log" + docker stats --no-stream --format "{{.Name}} {{.MemUsage}}" 2>/dev/null | sed "s/^/$(date -u +%FT%TZ) /" >> "$1/containers.log" + printf "%s %s\n" "$(date -u +%FT%TZ)" "$(df -k --output=avail /var/lib/docker | tail -1)" >> "$1/disk.log" + sleep 10 + done' sh "$METRICS" >/dev/null 2>&1 & + echo $! > "$METRICS/sampler.pid" + - name: Run multi-plane acceptance (${{ matrix.mode }}) + timeout-minutes: 100 + env: + TASK: ${{ matrix.mode == 'localvm' && 'multiplane:acceptance' || matrix.mode == 'media' && 'multiplane:media-acceptance' || 'multiplane:redfish-acceptance' }} + # The virtual media suite's lab windows, short enough for KVM guests: + # each held installation waits out both. + FLEET_MULTIPLANE_MEDIA_FETCH: ${{ matrix.mode == 'media' && '2m0s' || '' }} + FLEET_MULTIPLANE_MEDIA_REPORT: ${{ matrix.mode == 'media' && '3m0s' || '' }} + run: | + mkdir -m 0700 "$FLEET_MULTIPLANE_STATE_ROOT" + task "$TASK" + # A timeout or cancellation can stop run.sh before its own scan, so the + # evidence is scanned again here. A match is redacted in place, and the + # second scan must be clean before anything is uploaded. + - name: Record memory and secret-scan evidence + id: scan + if: always() + run: | + kill "$(cat "$METRICS/sampler.pid")" 2>/dev/null || true + sudo dmesg | grep -iE 'out of memory|oom-kill' > "$METRICS/oom.log" || true + python3 - "$METRICS" <<'PY' | tee "$METRICS/summary.txt" >> "$GITHUB_STEP_SUMMARY" + import pathlib, sys + m = pathlib.Path(sys.argv[1]) + rows = [dict(f.split('=') for f in l.split()[1:]) for l in (m / 'meminfo.log').read_text().splitlines()] if (m / 'meminfo.log').exists() else [] + if rows: + total = int(rows[0]['MemTotal:']) / 2**20 + low = min(int(r['MemAvailable:']) for r in rows) / 2**20 + swap = max(int(r['SwapTotal:']) - int(r['SwapFree:']) for r in rows) / 2**20 + print('Runner memory: %.1f GiB total, %.1f GiB peak used, %.1f GiB minimum available, %.2f GiB peak swap, %d samples' % (total, total - low, low, swap, len(rows))) + disk = [int(l.split()[1]) for l in (m / 'disk.log').read_text().splitlines()] if (m / 'disk.log').exists() else [] + if disk: + print('Runner disk: %.1f GiB minimum available in the Docker data root' % (min(disk) / 2**20)) + oom = (m / 'oom.log').read_text().strip().splitlines() if (m / 'oom.log').exists() else [] + print('Kernel OOM events: %d' % len(oom)) + PY + found=false + for state in "$FLEET_MULTIPLANE_STATE_ROOT"/fleet-multiplane.*; do + [ -d "$state/evidence" ] || continue + mkdir -p "$state/evidence/runner" + cp "$METRICS"/meminfo.log "$METRICS"/containers.log "$METRICS"/summary.txt "$METRICS"/oom.log "$METRICS"/disk.log "$state/evidence/runner/" 2>/dev/null || true + if ! python3 hack/multiplane/harness.py scan --state "$state"; then + redacted=true + python3 hack/multiplane/harness.py scan --state "$state" + fi + found=true + done + echo "found=$found" >> "$GITHUB_OUTPUT" + echo "redacted=${redacted:-false}" >> "$GITHUB_OUTPUT" + # Both shards of a mode build the same binaries; one save per commit is + # enough, and a second save of the same key is skipped. + - name: Save the Go build cache + if: always() && matrix.group == 'release' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: multiplane-go-${{ matrix.mode }}-${{ hashFiles('go.mod', 'go.sum') }}-${{ github.sha }} + # Only evidence/ is uploaded, never the private state directory. + - name: Upload sanitized evidence + if: always() && steps.scan.outcome == 'success' && steps.scan.outputs.found == 'true' + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: multiplane-evidence-${{ matrix.mode }}-${{ matrix.group }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/fleet-multiplane/fleet-multiplane.*/evidence/ + if-no-files-found: error + retention-days: 14 + # The job passes only if exactly one run recorded passed with every phase + # passed and teardown passed. A killed, timed-out or cancelled run fails. + - name: Verify the recorded result + if: always() + run: | + states=("$FLEET_MULTIPLANE_STATE_ROOT"/fleet-multiplane.*) + [ "${#states[@]}" -eq 1 ] && [ -d "${states[0]}" ] || { echo "expected exactly one run, found ${#states[@]}"; exit 1; } + python3 hack/multiplane/harness.py verify --state "${states[0]}" --group "$FLEET_MULTIPLANE_GROUP" + # A secret that reached evidence fails the job, even after its redaction. + - name: Fail on redacted evidence + if: always() && steps.scan.outputs.redacted == 'true' + run: | + echo 'evidence matched a retained secret and was redacted; see the scan step' + exit 1 + # The one result for a run: it fails unless every shard of every suite + # passed, including when a shard was skipped or cancelled. + acceptance-result: + name: acceptance + if: always() && (github.event_name != 'pull_request' || github.event.label.name == 'multiplane-acceptance') + needs: acceptance + # A newer labeled run replaces this one too, so a replaced run leaves no + # stale result beside the new one. + concurrency: + group: multiplane-acceptance-${{ github.event.pull_request.number || github.run_id }}-result + cancel-in-progress: true + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require every shard to pass + env: + RESULT: ${{ needs.acceptance.result }} + run: | + [ "$RESULT" = success ] || { echo "a multi-plane acceptance shard did not pass: $RESULT"; exit 1; } + echo 'every multi-plane acceptance shard passed' diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index a17555b2..80ce914a 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -62,6 +62,7 @@ func run() error { relays := fs.String("relays", "", "comma-separated prefixes of the report relays trusted to name a report's source (media-service)") upstream := fs.String("upstream", "", "the media service's PROXY listener, IP:port (report-relay)") clientCA := fs.String("client-ca", "", "CA that signs the site workers' client certificates (media-service)") + 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 } @@ -74,7 +75,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", "media-not-offered", "media-unpinned", "media-install-held", "media-install-download", "media-install-lost", "media-install": diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 359101c6..92584d3b 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -98,15 +98,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() @@ -117,6 +118,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 a63a3515..65c51243 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -27,6 +27,9 @@ spec: dispatch: boolean | default=false # The central media service's certificate, for virtual media workers. mediaCA: string | default="" + # 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} @@ -203,7 +206,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 fdfed945..60c48e61 100644 --- a/config/site/instance/dispatcher.yaml +++ b/config/site/instance/dispatcher.yaml @@ -20,3 +20,4 @@ spec: # empty where no media service runs. It is public; workers verify the # service with it. mediaCA: "${FLEET_MEDIA_CA}" + accelerator: "${FLEET_LOCAL_VM_ACCEL}" diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml index 6b7833e5..459a2955 100644 --- a/config/site/redfish/services/bmc.yaml +++ b/config/site/redfish/services/bmc.yaml @@ -41,6 +41,8 @@ spec: env: - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + # Lab targets run only while the site runtime publishes this accelerator. + - {name: FLEET_LAB_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} - {name: HOME, value: /tmp} ports: - {name: redfish, containerPort: 8443} diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml index 52ae0236..72f25892 100644 --- a/config/site/redfish/services/kustomization.yaml +++ b/config/site/redfish/services/kustomization.yaml @@ -33,7 +33,7 @@ patches: - name: report-relay image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "192.168.5.2:28444"] + command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "${FLEET_MEDIA_HOST}:28444"] securityContext: runAsUser: 65534 runAsNonRoot: true 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/development/device-custody.md b/docs/development/device-custody.md index a437c2e0..18e09b44 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -382,7 +382,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/gitops.md b/docs/operations/gitops.md index 25c219b4..f36fc484 100644 --- a/docs/operations/gitops.md +++ b/docs/operations/gitops.md @@ -129,7 +129,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 da9997f3..5d41b26a 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: @@ -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 @@ -151,6 +153,98 @@ 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 +GitHub-hosted `ubuntu-24.04` runner, two shards per mode. Status: +**verified** for local VM mode under KVM; **implemented, not yet verified** +for Redfish mode under KVM and for the shards. Both modes passed unsharded on +a hosted runner, with Redfish mode under TCG. + +To run it, apply the `multiplane-acceptance` label to a pull request whose +branch contains the workflow. Each application starts one run of both modes, +and a newer run for the same pull request cancels the older one. Pushing to a +labeled pull request does not start a run, so its result goes stale: remove and +reapply the label to test the new head. The workflow +also runs nightly on `main`, and on demand from `main` with a `mode` input +(`both`, `localvm` or `redfish`). It never runs on every push. + +Explicit run parameters select the runtime. Their defaults are the Colima run +above, unchanged: + +| Variable | Default | CI value | +| --- | --- | --- | +| `FLEET_MULTIPLANE_RUNTIME` | `colima` | `ci` | +| `FLEET_MULTIPLANE_DOCKER_CONTEXT` | `colima-fleet-acceptance-tcg` | `default` | +| `FLEET_MULTIPLANE_ARCH` (site binary and runtime architecture) | `arm64` | `amd64` | +| `FLEET_MULTIPLANE_ACCEL` | `tcg` | `kvm` | +| `FLEET_MULTIPLANE_GROUP` (scenario group) | `all` | `flux` or `release`, one per shard | + +Lab timers shorten the waits the scenarios provoke, in every runtime. Each +scenario still proves the same outcome, and production defaults are unchanged: + +| Variable | Default | Production | Scenario | +| --- | --- | --- | --- | +| `FLEET_MULTIPLANE_INSTALLATION_DEADLINE` | `2m` | 40 minutes | The short-deadline installation ends `OutcomeUnknown` | +| `FLEET_MULTIPLANE_SKEW_MARGIN` | `30s` in CI mode, `2m` otherwise | 2 minutes | The coordinator waits this long past a deadline before declaring it exceeded | +| `FLEET_MULTIPLANE_FAIL_CLOSED_TIMEOUT` | `45s` | 3 minutes in the lab topology | The bad kro revision reports not Ready; the recovery revision restores the usual timeout | + +The skew margin covers clock skew between the coordinator and a site. In CI +mode every process reads one Linux kernel clock. A Colima VM's clock can drift +from the workstation's, so that run keeps the production margin. The deadline +scenario still requires the wipe to be admitted after the worker stopped. On a +host too slow to journal the installer boot and delete the Machine within the +deadline, the scenario fails saying so; raise +`FLEET_MULTIPLANE_INSTALLATION_DEADLINE` there. + +In CI mode, preflight requires a GitHub-hosted runner (`GITHUB_ACTIONS=true` and +`RUNNER_ENVIRONMENT=github-hosted`) and a context that points at +exactly `unix:///var/run/docker.sock`. It reads free disk, inotify and a readable, writable `/dev/kvm` +on the runner itself, and memory and CPUs from the runner's daemon. It never +calls Colima. Every other check still applies. Preflight fails closed on an +accelerator it cannot honor: KVM without an amd64 runtime or without +`/dev/kvm`, and any unknown value. `preflight.json` records the +parameters. + +Every component must agree on the accelerator. The site runtime refuses KVM +without `/dev/kvm`, with no software fallback, and publishes the accelerator it +runs. A worker runs only against a runtime that published its own accelerator, +and each installation's journaled boot admission binds it, so a replacement +worker never resumes an installation under another. Evidence then requires both +domain definitions and every QEMU command line to show the selected accelerator, +and `summary.json` records it. + +The workflow runs each suite as two shards on separate runners. Both shards +build the same topology and run the same scenarios up to the Pod and Job +lifecycle checks. The `flux` shard then runs the Flux scenarios: graph +lifecycle, drift, restart, fail-closed and retention. The `release` shard runs +the reflection faults, release, reuse, deadline, rebuild, wrong-location and +closed-boot scenarios. Each shard checks the evidence its scenarios produce: +the `flux` shard leaves the Device allocated, so the release, wipe and final +custody checks run in the `release` shard. A local run defaults to `all` and +runs every scenario in one topology. + +A shard passes only if exactly one run recorded `passed` with every phase +passed, teardown passed, the expected scenario group and no retained +container. The workflow's `acceptance` result passes only if every shard of +every suite passed. After the run, including +after a timeout or cancellation, the job scans the evidence for secrets again +and redacts any match. It uploads only `evidence/`, and only after a clean scan. +A match fails the job even after its redaction. +The evidence includes `runner/`, the runner's memory, swap and free disk in +the Docker data root sampled every 10 seconds, per-container memory, and any +kernel OOM events. Every tool and action is pinned. + +KVM on a GitHub-hosted runner is nested virtualization in a cloud VM. It is a +qualification target of its own, separate from the Colima TCG runs and from +physical hardware, and a pass in one qualifies neither of the others. + ### State and evidence layout All containers have one fresh `fleet-mp-` prefix. The command prints a @@ -255,7 +349,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,12 +365,16 @@ The phases are then: - the same unfinished operation. 6. **Job interruption.** `interrupt-job` deletes the whole worker Job as soon as the replacement exists, still mid-install. kro must recreate the Job under - a new UID for the same operation. + a new UID for the same operation. `release-installer` then resumes the + guest, which still has printed no receipt, and records the hold in + `interrupt.json`. Evidence fails without it. Redfish mode holds lab target A + the same way, from its append-only console, through the BMC interruption + as well. 7. **Exact resume.** `resume` requires the recreated Job to be `Complete` with one succeeded Pod, and the observer to publish the stored `Succeeded` result. The Device's journal must show the installer boot requested exactly once. Evidence later proves exactly one firmware-network installer start followed by exactly one disk-only start. - It uses libvirt's append-only QEMU log, plus one `sfdisk`, one installer + It uses libvirt's append-only QEMU log, plus one partition marker, one installer receipt and one disk-boot receipt in the guest serial logs. `worker-rbac` then proves the worker token can read only its own handoff: no list, no other names, no status or spec writes, no Secrets, no site writes. @@ -341,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 six-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 60752084..e2f3c9af 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -35,6 +35,15 @@ Prerequisites, exit codes, the state and evidence layout, `--keep`, [multi-plane harness](multiplane.md#run). Redfish mode also needs network access to GitHub release archives, Docker Hub and PyPI to build the lab BMC image. +Redfish mode also runs in [CI mode](multiplane.md#ci-mode), as the `redfish` +job of the `multiplane-acceptance` workflow, with the lab targets under KVM. +Status: implemented, not yet verified under KVM. +The lab adapter defines and starts a target only while the site runtime +publishes the accelerator the adapter was given, and evidence requires every +QEMU command line of target A to show it. KVM on a cloud runner is its own +qualification target, separate from the Colima runs below and from physical +hardware. + ## Upstream emulator and provenance | Item | Pin | @@ -96,7 +105,7 @@ upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. ```text cell Flux layers (Redfish overlays of config/site) fleet-site-runtime (privileged) fleet-site-bmc (unprivileged, all caps dropped) - libvirtd + QEMU TCG ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter + libvirtd + QEMU ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter lab-target-a lab-target-b ▲ Redfish over TLS (pinned key), Basic auth (persistent disks, serial capture) │ Service 10.96.0.81:8443 │ firmware DHCP/iPXE (static) │ @@ -484,9 +493,9 @@ 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 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/local-vm/init b/hack/local-vm/init index 153cee4a..8f2994ab 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -86,6 +86,9 @@ if [ "$mode" = wipe ]; then fi [ "$mode" = install ] || /bin/busybox poweroff -f printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda +# One line, in one write, once the disk is partitioned: the shell trace above +# reaches the console in pieces the kernel's own messages can split. +printf 'FLEET-PARTITIONED:%s\n' "$receipt" mkfs.ext4 -F /dev/vda1 mkdir -p /target mount /dev/vda1 /target diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index d2a05481..5efb8f1e 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-media.sh b/hack/multiplane/acceptance-media.sh index 292267cf..85b01421 100755 --- a/hack/multiplane/acceptance-media.sh +++ b/hack/multiplane/acceptance-media.sh @@ -8,7 +8,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}"; } rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index b7a46240..b6875835 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"; } @@ -20,6 +20,11 @@ if [[ ${FLEET_LAB_DHCP:-static} == synced ]]; then watcher=$! trap 'kill "$watcher" 2>/dev/null || true' EXIT fi +# 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" @@ -34,10 +39,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 @@ -46,26 +53,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 # Synchronized lab DHCP (run.sh --synced-dhcp): every boot's reservation came # from its own IPAM claim and Kea served it only while the boot was open. [[ ${FLEET_LAB_DHCP:-static} != synced ]] || rf dhcp-synced 300 diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 947d42fc..caa69773 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -4,11 +4,16 @@ set -euo pipefail umask 077 state=${1:?private state directory} -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} host="$state/fleet-multiplane-host" ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } +# Scenario group (docs/operations/multiplane.md#ci-mode). Every group runs the +# ungated scenarios and each gated block below that names it; +# all runs every block. +group=${FLEET_MULTIPLANE_GROUP:-all} +runs() { [[ $group == all || $group == "$1" ]]; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" @@ -20,9 +25,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 @@ -30,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/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/evidence.py b/hack/multiplane/evidence.py index 19ca3465..881ff340 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -20,7 +20,13 @@ s = pathlib.Path(sys.argv[1]) prefix = (s / 'prefix').read_text().strip() ev = s / 'evidence' -os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' +os.environ['DOCKER_CONTEXT'] = os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT', 'colima-fleet-acceptance-tcg') +# The run parameters; the guest evidence below must show the accelerator. +ACCEL, RUNTIME, GROUP = harness.ACCEL, harness.RUNTIME, harness.GROUP +# The installer prints this with its receipt once it has partitioned the +# disk. A kernel message can still share the line, so it is found mid-line; +# the shell's trace of that printf shows the format, not a receipt. +PARTITIONED = re.compile(r'FLEET-PARTITIONED:([0-9a-f]{64})') REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' SYNCED = (s / 'lab-dhcp').exists() and (s / 'lab-dhcp').read_text().strip() == 'synced' @@ -108,13 +114,26 @@ def copy_out(source, destination): fail('an operation booted without IPAM allocating its address to its own claim') if dhcp.get('claimsRemaining') != 0 or dhcp.get('allocationsRemaining') != 0: fail('IPAM still held boot address claims or allocations after the run') +# 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): @@ -216,6 +235,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'] @@ -227,6 +248,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'): @@ -238,8 +261,9 @@ def libvirt_provider(): if lines.count(marker + boot['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: fail('expected exactly one exact guest receipt in ' + filename) receipts.append({'operation': uid, 'fence': o['fence'], 'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) - if sum(1 for l in (directory / 'installer.log').read_text(errors='replace').splitlines() if re.match(r'^\+ sfdisk /dev/vda', l.strip())) != 1: - fail('installer partitioned the disk other than exactly once') + partitions = PARTITIONED.findall((directory / 'installer.log').read_text(errors='replace')) + if partitions != [boot['receipt']]: + fail('installer partitioned the disk %d times, not exactly once for this operation' % len(partitions)) installer, disk = (directory / 'installer.xml').read_text(), (directory / 'disk.xml').read_text() if "boot dev='network'" not in installer or '' in installer or '' in installer: fail('installer domain is not firmware network boot only') @@ -253,7 +277,13 @@ def libvirt_provider(): blocks = [b for b in re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:]] network = [b for b in blocks if '-netdev' in b and '52:54:00:77:00:02' in b] disk_only = [b for b in blocks if '-netdev' not in b and 'virtio-disk0' in b] - starts[uid] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} + # Every component ran the selected accelerator: both domain definitions + # and every QEMU command line libvirt logged. + domain_types = {re.match(r"=3.12', sys.version_info >= (3, 12), sys.version.split()[0] + ' (evidence extraction uses the tarfile data filter)') + check('runtime-mode', RUNTIME in ('colima', 'ci'), 'FLEET_MULTIPLANE_RUNTIME=%s; colima or ci' % RUNTIME) + if RUNTIME == 'ci': + # The run adjusts host kernel settings and fills the Docker data root: + # only a disposable runner, never a workstation's daemon. + check('ci-runner', os.environ.get('GITHUB_ACTIONS') == 'true' and os.environ.get('RUNNER_ENVIRONMENT') == 'github-hosted', + 'CI mode runs only on a disposable GitHub-hosted runner (GITHUB_ACTIONS=true, RUNNER_ENVIRONMENT=github-hosted)') + check('runtime-parameter:architecture', ARCH in DOCKER_ARCHITECTURES, 'FLEET_MULTIPLANE_ARCH=%s; arm64 or amd64' % ARCH) + # KVM runs the amd64 guest natively, so it needs an amd64 runtime. + accel_ok = ACCEL == 'tcg' or (ACCEL == 'kvm' and ARCH == 'amd64') + check('accelerator', accel_ok, 'FLEET_MULTIPLANE_ACCEL=%s; tcg, or kvm with an amd64 runtime' % ACCEL) + check('scenario-group', GROUP in GROUPS, 'FLEET_MULTIPLANE_GROUP=%s; %s' % (GROUP, ', '.join(GROUPS))) code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) - endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) - if not endpoint_ok and args.bootstrap and shutil.which('colima'): + endpoint_ok = endpoint_matches(code, out) + if not endpoint_ok and RUNTIME == 'colima' and args.bootstrap and shutil.which('colima'): # Only start an existing task-owned profile with its saved configuration. code, out, err = capture(['colima', 'list', '--json'], 30, cwd='/') known = any(json.loads(line).get('name') == PROFILE for line in out.splitlines() if line.strip().startswith('{')) if code == 0 else False @@ -124,16 +148,16 @@ def check(name, ok, detail='', kind='preflight'): code, _, err = capture(['colima', 'start', '--profile', PROFILE], 600, cwd='/') check('bootstrap:colima-start', code == 0, 'started existing profile ' + PROFILE if code == 0 else err.strip()[-300:]) code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) - endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) - check('docker-context', endpoint_ok, CONTEXT + ' must point at the task-owned Colima profile socket; never fleet-e2e-x86') + endpoint_ok = endpoint_matches(code, out) + check('docker-context', endpoint_ok, CONTEXT + (' must point at the runner daemon ' + CI_ENDPOINT if RUNTIME == 'ci' else ' must point at the task-owned Colima profile socket; never fleet-e2e-x86')) info = {} if endpoint_ok: code, out, err = capture(['docker', 'info', '--format', '{{json .}}'], 30) - if check('docker-reachable', code == 0, 'start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if code else 'reachable'): + if check('docker-reachable', code == 0, ('start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if RUNTIME == 'colima' else 'the runner daemon is unreachable') if code else 'reachable'): info = json.loads(out) if info: - check('runtime-architecture', info.get('Architecture') in ('aarch64', 'arm64'), '%s (the Milo image pin is native arm64)' % info.get('Architecture')) + check('runtime-architecture', info.get('Architecture') in DOCKER_ARCHITECTURES.get(ARCH, ()), '%s; FLEET_MULTIPLANE_ARCH=%s' % (info.get('Architecture'), ARCH)) check('runtime-memory', int(info.get('MemTotal', 0)) >= 7_800_000_000, '%.2f GiB; 8 GiB required' % (int(info.get('MemTotal', 0)) / 2**30)) check('runtime-cpus', int(info.get('NCPU', 0)) >= 4, '%s CPUs; 4 required' % info.get('NCPU')) code, out, _ = capture(['docker', 'ps', '--format', '{{.Names}}'], 30) @@ -146,6 +170,9 @@ def check(name, ok, detail='', kind='preflight'): limit = vm_inotify() opted = os.environ.get('FLEET_MULTIPLANE_INOTIFY') == '1024' check('inotify-instances', limit is not None and (limit >= 1024 or opted), 'current %s; requires >=1024 or FLEET_MULTIPLANE_INOTIFY=1024 (reversible task-VM adjustment)' % limit) + if ACCEL == 'kvm': + check('kvm-device', vm_exec('test -c /dev/kvm && test -r /dev/kvm && test -w /dev/kvm && echo present') == 'present', + 'a readable and writable /dev/kvm on the Docker host; no automatic software fallback') root = pathlib.Path(args.root) main = (root / 'cmd/fleet-multiplane/main.go') @@ -162,13 +189,27 @@ def check(name, ok, detail='', kind='preflight'): pre = [c for c in checks if c['kind'] == 'preflight' and not c['ok']] ready = [c for c in checks if c['kind'] == 'readiness' and not c['ok']] code = EXIT_PREFLIGHT if pre else EXIT_BLOCKED if ready else EXIT_PASSED - write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks}) + write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks, + 'runtime': {'mode': RUNTIME, 'dockerContext': CONTEXT, 'architecture': ARCH, 'accelerator': ACCEL}, 'group': GROUP}) for c in checks: print('%-4s %-34s %s' % ('ok' if c['ok'] else 'FAIL', c['name'], c['detail'])) return code +def endpoint_matches(code, out): + """Whether the context reaches exactly the selected runtime's daemon.""" + if code != 0: + return False + if RUNTIME == 'ci': + return out.strip() == CI_ENDPOINT + return RUNTIME == 'colima' and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + + def vm_exec(command, timeout=30): + """A read-only command on the Docker host: the Colima VM, or the runner itself in CI mode.""" + if RUNTIME == 'ci': + code, out, _ = capture(['sh', '-c', command], timeout, cwd='/') + return out.strip() if code == 0 else None if not shutil.which('colima'): return None code, out, _ = capture(['colima', 'ssh', '--profile', PROFILE, '--', 'sh', '-c', command], timeout, cwd='/') @@ -460,15 +501,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 @@ -500,11 +543,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')) @@ -512,6 +556,31 @@ 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'])) + if args.group and value.get('group') != args.group: + problems.append('scenario group %s, expected %s' % (value.get('group'), args.group)) + print('VERIFY %s phases=%d%s' % ('failed' if problems else 'passed', len(phases), (': ' + '; '.join(problems[:8])) if problems else '')) + return EXIT_FAILED if problems else EXIT_PASSED + + def main(): p = argparse.ArgumentParser() sub = p.add_subparsers(dest='cmd', required=True) @@ -541,6 +610,9 @@ def main(): s = sub.add_parser('result') s.add_argument('--state', required=True) s.add_argument('--exit-code', type=int, required=True) + s = sub.add_parser('verify') + s.add_argument('--state', required=True) + s.add_argument('--group', choices=GROUPS, help='the scenario group the run must have recorded') a = p.parse_args() if a.cmd == 'phase': if a.command[:1] == ['--']: @@ -548,7 +620,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/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/media-central.sh b/hack/multiplane/media-central.sh index b7bd5562..5005f1e1 100755 --- a/hack/multiplane/media-central.sh +++ b/hack/multiplane/media-central.sh @@ -27,12 +27,21 @@ case $action in docker rm "$id" >/dev/null fi mkdir -p "$state/media-central" && chmod 0700 "$state/media-central" - # Clients: lab Pods arrive on loopback, and installed servers' reports - # through the relay with their own lab network addresses. - nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "127.0.0.1:28443,[::1]:28443" \ - --proxy-listen 127.0.0.1:28444 --relays 127.0.0.0/8 \ + # Lab Pods reach the service at the runtime's host address: under Colima + # its gateway, which arrives on loopback; on a CI runner the kind network's + # gateway, from the kind nodes' addresses. + listen="127.0.0.1:28443,[::1]:28443" relay_listen=127.0.0.1:28444 + if [[ ${FLEET_MULTIPLANE_RUNTIME:-colima} == ci ]]; then + host=$(cat "$state/media-host") + listen="$listen,$host:28443" relay_listen="$relay_listen,$host:28444" + fi + # Clients: lab Pods, and installed servers' reports through the relay + # with their own lab network addresses. + clients=$(cat "$state/media-clients") + nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "$listen" \ + --proxy-listen "$relay_listen" --relays "127.0.0.0/8,$clients" \ --tls-cert "$state/redfish/media-tls.crt" --tls-key "$state/redfish/media-tls.key" --client-ca "$state/redfish/media-worker-ca.crt" \ - --state-dir "$state/media-central" --artifacts "$artifacts" --clients 127.0.0.0/8,::1/128,192.168.77.0/24 >>"$state/media-central.log" 2>&1 >"$state/media-central.log" 2>&1 "$pidfile" sleep 2 kill -0 "$(cat "$pidfile")" || { echo 'media-central: exited at start; see media-central.log in the state directory' >&2; exit 1; } diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 7672c7f2..4a3486b6 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -381,7 +381,7 @@ def release_proof(s): denials = [] for op in ops: w = window_record(s, op['metadata']['uid']) - url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.MEDIA_HOST, rf.MEDIA_PORT, key(op['metadata']['uid']), w['bootDigest']) + url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.media_host(s), rf.MEDIA_PORT, key(op['metadata']['uid']), w['bootDigest']) probe = ("import ssl,sys,urllib.request,urllib.error\nc=ssl.create_default_context(cafile='/etc/fleet-bmc-media-ca/ca.crt')\n" "try:\n urllib.request.urlopen(sys.argv[1],context=c,timeout=20); print(200)\nexcept urllib.error.HTTPError as e: print(e.code)\n") answer = rf.bmc(s, 'python3', '-c', probe, url).stdout.strip() diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 0bf0c901..5319e242 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -25,7 +25,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' with_ipam=os.environ.get('FLEET_LAB_DHCP')=='synced' or os.environ.get('FLEET_LAB_IPAM')=='1' ports=json.loads((root/'platform-ports.json').read_text()) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 2b3abab8..3607fb75 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -51,7 +51,10 @@ BOOT_IP = '10.96.0.80' # The workstation as lab Pods and guests reach it (the Colima host gateway), # where the central media service listens on loopback. -MEDIA_HOST = '192.168.5.2' +def media_host(s): + """Where lab Pods reach the central media service, as run.sh recorded + it for the runtime.""" + return (s / 'media-host').read_text().strip() # The report relay on the lab bridge, where guests post their reports. REPORT_RELAY = '192.168.77.1' MEDIA_PORT = 28443 @@ -183,7 +186,7 @@ def enroll(s): # gateway. The lab BMC, the workers and the installed OS verify it # against this certificate. subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'media-tls.key'), - '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:%s,IP:127.0.0.1,IP:::1' % (MEDIA_HOST, REPORT_RELAY)], + '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:%s,IP:127.0.0.1,IP:::1' % (media_host(s), REPORT_RELAY)], check=True, capture_output=True) # Site workers authenticate to the central media service with client # certificates from a CA generated per run: the cell's workers, and one @@ -437,8 +440,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): @@ -457,13 +461,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')) # What the lab IPAM pool can allocate: 192.168.77.0/24 less 100 leading and 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 6a7bc9d6..fe65d8b6 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -38,13 +38,20 @@ done # media suite, for each install's report address. lab_ipam=0 [[ $lab_dhcp == static && $media == 0 ]] || lab_ipam=1 -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider FLEET_LAB_DHCP=$lab_dhcp FLEET_LAB_IPAM=$lab_ipam +# Run parameters (docs/operations/multiplane.md#ci-mode). The defaults are the +# task-owned Colima profile: arm64 runtime, TCG guest. Preflight validates them +# before any resource exists. +export FLEET_MULTIPLANE_RUNTIME=${FLEET_MULTIPLANE_RUNTIME:-colima} FLEET_MULTIPLANE_DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} +export FLEET_MULTIPLANE_ARCH=${FLEET_MULTIPLANE_ARCH:-arm64} FLEET_MULTIPLANE_ACCEL=${FLEET_MULTIPLANE_ACCEL:-tcg} +# Scenario group: all by default; CI shards each suite into flux and release. +export FLEET_MULTIPLANE_GROUP=${FLEET_MULTIPLANE_GROUP:-all} +export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider FLEET_LAB_DHCP=$lab_dhcp FLEET_LAB_IPAM=$lab_ipam 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 '%s\n' "$lab_dhcp" > "$state/lab-dhcp" -printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\nLab DHCP: %s\n' "$state" "$state" "$provider" "$lab_dhcp" +printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\nLab DHCP: %s\nScenario group: %s\n' "$state" "$state" "$provider" "$lab_dhcp" "$FLEET_MULTIPLANE_GROUP" finish() { code=$1 @@ -106,13 +113,13 @@ 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 && CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "$1/site-bin/fleet-dhcp-sync" ./cmd/fleet-dhcp-sync && 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 && CGO_ENABLED=0 GOOS=linux GOARCH="$FLEET_MULTIPLANE_ARCH" go build -o "$1/site-bin/fleet-dhcp-sync" ./cmd/fleet-dhcp-sync && 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) sync=$(shasum -a 256 "$2/site-bin/fleet-dhcp-sync" | cut -d" " -f1) printf "%s /usr/local/bin/fleet-multiplane\n%s /usr/local/bin/fleet-dhcp-sync\n" "$sum" "$sync" | 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 @@ -125,6 +132,17 @@ ph flux-tools 300 "${flux[@]}" tools "$state" docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null # Disposable infrastructure only: registry and three kind clusters, no services. ph topology 900 bash hack/multiplane/topology.sh "$state" +# Where lab Pods reach this host's central media service, and the network +# their connections arrive from: Colima's host gateway, which arrives on +# loopback, or on a CI runner the kind network's gateway and subnet. +if [[ $FLEET_MULTIPLANE_RUNTIME == ci ]]; then + docker network inspect kind -f '{{range .IPAM.Config}}{{.Gateway}} {{.Subnet}}{{"\n"}}{{end}}' | + awk -v host="$state/media-host" -v clients="$state/media-clients" '$1 ~ /^[0-9.]+$/ {print $1 > host; print $2 > clients; exit}' + [[ -s $state/media-host && -s $state/media-clients ]] || { echo 'the kind network has no IPv4 gateway' >&2; exit 1; } +else + printf '192.168.5.2\n' > "$state/media-host" + printf '127.0.0.0/8\n' > "$state/media-clients" +fi ph site-image-push 600 bash hack/multiplane/site.sh push "$state" # Revision 1: platform services only. The bootstrap boundary applies each # cluster's Flux components and sync objects once; Flux then owns them too. @@ -148,7 +166,7 @@ c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix # virtual media suite adds virtual media as an operator would. 'DeliveryMethods':[{'method':'NetworkBoot'}], # The central media service, as lab Pods and guests reach the workstation. - 'MediaService':'https://192.168.5.2:28443'} + 'MediaService':'https://%s:28443'%(s/'media-host').read_text().strip()} if sys.argv[3]=='1':c['BootAddressClass']='lab-provisioning' (s/'acceptance.json').write_text(json.dumps(c)) PY diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py index c5ada4a7..033593dc 100644 --- a/hack/multiplane/scenarios.py +++ b/hack/multiplane/scenarios.py @@ -208,6 +208,9 @@ def release_waits(s): holds the Device for release with the installation still active, and no wipe exists.""" op = 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/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 8bd52f43..f165d5c3 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -8,11 +8,16 @@ step=${1:?step required} state=${2:?private state directory required} prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} harness=(python3 hack/multiplane/harness.py) host="$state/fleet-multiplane-host" ns=fleet-coordination helpers=hack/multiplane/k8s_evidence.py +# Lab-only deadline for the one short-deadline admission. The scenario needs +# time to journal the installer boot and delete the Machine before it +# expires, which takes seconds; production keeps its own deadline. +deadline=${FLEET_MULTIPLANE_INSTALLATION_DEADLINE:-2m} +[[ $deadline =~ ^[1-9][0-9]*[sm]$ ]] || { echo "FLEET_MULTIPLANE_INSTALLATION_DEADLINE must be seconds or minutes, such as 2m" >&2; exit 64; } k() { kubectl --kubeconfig "$1" --request-timeout=20s "${@:2}"; } cell() { k "$state/cell-admin.yaml" "$@"; } @@ -49,6 +54,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 @@ -114,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 @@ -122,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 @@ -218,8 +227,52 @@ JSON py worker-rbac "$state" "$name" rm -f "$state/worker-kubeconfig.json" ;; + hold-installer) + # Hold the installer guest paused as soon as its kernel prints, so the + # worker and BMC interruptions below always land mid-install, however fast + # the accelerator. A watcher in the runtime Pod suspends it; a guest that + # printed its receipt first is reported missed, never held. In Redfish mode + # the guest is lab target A, whose console log is append-only, so only + # output after the hold is armed counts. + runtime sh -c "[ ! -e $hold_file.pid ] && rm -f $hold_file" || { echo 'an installer hold is already armed' >&2; exit 1; } + if redfish; then mode=redfish; else mode=libvirt; fi + runtime sh -c 'setsid sh -c "$1" sh "$3" >/dev/null 2>&1 "$2.pid"' sh "$(cat <<'SH' +uri='qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' out=/tmp/fleet-installer-hold mode=$1 +lab=fleet-lab-target-a console=/var/lib/fleet-lab-console/target-a.log +offset=$(( $(wc -c < "$console" 2>/dev/null || echo 0) + 1 )) +since() { tail -c "+$offset" "$1" 2>/dev/null; } +end=$(($(date +%s) + 1500)) +while [ "$(date +%s)" -lt "$end" ]; do + for d in $(virsh --connect "$uri" list --name); do + if [ "$mode" = redfish ]; then + [ "$d" = "$lab" ] && since "$console" | grep -q 'Linux version' || continue + receipt() { since "$console" | grep -q 'FLEET-INSTALLED:'; } + else + case "$d" in fleet-local-*) ;; *) continue ;; esac + log=$(ls /var/lib/fleet-local/vm/*/"${d#fleet-local-}"/installer.log 2>/dev/null | head -1) + [ -n "$log" ] && grep -q 'Linux version' "$log" || continue + receipt() { grep -q 'FLEET-INSTALLED:' "$log"; } + fi + if virsh --connect "$uri" suspend "$d" >/dev/null 2>&1 && [ "$(virsh --connect "$uri" domstate "$d")" = paused ] && ! receipt; then + printf 'held %s %s %s\n' "$d" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$offset" > "$out.tmp" + else + printf 'missed %s\n' "$d" > "$out.tmp" + fi + mv "$out.tmp" "$out"; exit 0 + done + sleep 0.1 +done +echo expired > "$out" +SH +)" "$hold_file" "$mode" + printf 'hold-installer: armed; the installer guest is suspended once its kernel starts and before any receipt\n' + ;; interrupt-pod) name=$(cat "$state/install-handoff") + held= + for _ in $(seq 1 900); do held=$(runtime sh -c "cat $hold_file 2>/dev/null || true"); [[ -z $held ]] || break; sleep 1; done + [[ $held == held\ fleet-local-* || $held == held\ fleet-lab-target-a\ * ]] || { echo "installer guest was not held mid-install: ${held:-no hold}" >&2; exit 1; } + printf '%s\n' "$held" > "$state/installer-hold" "${harness[@]}" wait-stage --state "$state" --stage "$installer_step" --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" before=$(wait_running_pod "$name" 30) py job "$state" "$name" > "$state/interrupt-job-before-pod.json" @@ -237,7 +290,7 @@ 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' + 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") @@ -262,6 +315,31 @@ 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 offset < "$state/installer-hold" + [[ $(runtime virsh --connect "$libvirt" domstate "$domain" | head -1) == paused ]] || { echo 'held installer guest is no longer paused' >&2; exit 1; } + if redfish; then + runtime sh -c "! tail -c +$offset /var/lib/fleet-lab-console/target-a.log | grep -q FLEET-INSTALLED:" || { echo 'held installer printed a receipt while paused' >&2; exit 1; } + else + runtime sh -c "! grep -q FLEET-INSTALLED: /var/lib/fleet-local/vm/*/${domain#fleet-local-}/installer.log" || { echo 'held installer printed a receipt while paused' >&2; exit 1; } + fi + runtime virsh --connect "$libvirt" resume "$domain" >/dev/null + [[ $(runtime virsh --connect "$libvirt" domstate "$domain" | head -1) == running ]] || { echo 'held installer guest did not resume' >&2; exit 1; } + python3 - "$state/evidence/interrupt.json" "$domain" "$held_at" <<'PY' +import datetime,json,sys +p,domain,held=sys.argv[1:] +i=json.load(open(p)) +if i.get('domain')!=domain:raise SystemExit('held guest is not the interrupted operation domain') +i['installerHold']={'held':True,'domain':domain,'heldAt':held,'releasedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'domainStateDuringInterruptions':'paused', + 'method':'runtime Pod watcher suspended the guest once its kernel printed and before any receipt; resumed after the Pod and Job interruptions'} +json.dump(i,open(p,'w'),indent=2,sort_keys=True) +PY + runtime rm -f "$hold_file" "$hold_file.pid" + printf 'release-installer: the held installer guest resumed with no receipt printed during the interruptions\n' + ;; resume) name=$(cat "$state/install-handoff") site wait --for=condition=Complete "job/w-$name" --timeout=20m >/dev/null diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh index 71d76ea7..5b2a90bf 100755 --- a/hack/multiplane/stop.sh +++ b/hack/multiplane/stop.sh @@ -7,7 +7,7 @@ prefix=$(cat "$state/prefix") # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null bash hack/multiplane/media-central.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 e5bf269a..e40a3476 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -16,7 +16,7 @@ prefix=$(cat "$state/prefix") # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null bash hack/multiplane/media-central.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 260762fc..7c0091e5 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -134,10 +134,16 @@ def render(rev, cluster): for f in (root / layer).glob('*.yaml'): used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) check('substituted variables defined', used and used <= env_keys, str(sorted(used - env_keys))) + check('site accelerator is the run parameter, TCG by default', 'FLEET_LOCAL_VM_ACCEL: tcg\n' in cell3.replace('"', '')) check('graph uses no Flux variables', not re.findall(r'\$\{FLEET_', (root / 'config/site/graph/rgd.yaml').read_text())) check('stage off revision', flux.stage(ns(revision=2, site='off')) == 0 and 'FLEET_SITE_DISPATCH: "false"' in render(2, 'cell')) flux.stage(ns(revision=4, site='dispatch', bad_kro_chart=True)) check('bad chart revision patches only kro', flux.MISSING_DIGEST in render(4, 'cell') and flux.KRO_CHART_DIGEST not in render(4, 'cell')) + def kro_timeout(revision): + docs = [d for d in render(revision, 'cell').split('\n---\n') if 'kind: Kustomization\n' in d and re.search(r'^ name: kro$', d, re.M)] + return re.findall(r'^ timeout: (\S+)$', docs[0], re.M) if len(docs) == 1 else docs + check('bad chart revision shortens only the kro health timeout', kro_timeout(4) == [flux.FAIL_CLOSED_TIMEOUT] and kro_timeout(3) == ['3m'], + '%s %s' % (kro_timeout(4), kro_timeout(3))) flux.stage(ns(revision=6, site='dispatch', drop_site_volume=True)) check('volume removal revision', '$patch: delete' in render(6, 'cell') and 'fleet-site-state' in render(6, 'cell')) sums = (s / 'gitops' / 'r3.SHA256SUMS').read_text() diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 9b3c9aee..46683bcf 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 @@ -26,11 +27,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 +48,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 +66,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 +85,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 +108,56 @@ with tempfile.TemporaryDirectory() as tmp: calls = [json.loads(l) for l in trace.read_text().splitlines()] check('preflight never mutates runtime', not any(c[0] == 'docker' and c[1] in ('rm', 'stop', 'kill', 'network', 'volume', 'system') for c in calls)) check('preflight never starts colima without --bootstrap', not any(c[0] == 'colima' and 'start' in c for c in calls)) + check('default runtime recorded', pre['runtime'] == {'mode': 'colima', 'dockerContext': 'colima-fleet-acceptance-tcg', 'architecture': 'arm64', 'accelerator': 'tcg'}, str(pre.get('runtime'))) + + # Run parameters: CI mode replaces only the Colima-specific probes; every + # combination it cannot honor fails closed before any resource exists. + for name, env, expected in ( + ('ci kvm pass', dict(ci), 0), + ('ci tcg pass', dict(ci, FLEET_MULTIPLANE_ACCEL='tcg'), 0), + ('ci redfish tcg pass', dict(ci, FLEET_MULTIPLANE_ACCEL='tcg', FLEET_SITE_PROVIDER='redfish'), 0), + ('ci outside GitHub Actions', dict(ci, GITHUB_ACTIONS=''), 2), + ('ci on a self-hosted runner', dict(ci, RUNNER_ENVIRONMENT='self-hosted'), 2), + ('ci against a Colima socket', dict(ci, FAKE_ENDPOINT='unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock'), 2), + ('colima against the runner socket', {'FAKE_ENDPOINT': 'unix:///var/run/docker.sock'}, 2), + ('ci architecture mismatch', dict(ci, FAKE_ARCH='aarch64'), 2), + ('ci unknown architecture', dict(ci, FLEET_MULTIPLANE_ARCH='riscv64', FLEET_MULTIPLANE_ACCEL='tcg'), 2), + ('ci without /dev/kvm', dict(ci, FAKE_KVM='absent'), 2), + ('ci low disk', dict(ci, FAKE_FREE_KB='1000'), 2), + ('ci concurrent runtime', dict(ci, FAKE='busy'), 2), + ('ci redfish kvm pass', dict(ci, FLEET_SITE_PROVIDER='redfish'), 0), + ('redfish kvm without /dev/kvm', dict(ci, FLEET_SITE_PROVIDER='redfish', FAKE_KVM='absent'), 2), + ('kvm on an arm64 runtime', {'FLEET_MULTIPLANE_ACCEL': 'kvm'}, 2), + ('unknown accelerator', {'FLEET_MULTIPLANE_ACCEL': 'auto'}, 2), + ('unknown runtime', {'FLEET_MULTIPLANE_RUNTIME': 'lima'}, 2), + ('ci unknown scenario group', dict(ci, FLEET_MULTIPLANE_GROUP='deadline'), 2), + ('ci flux group pass', dict(ci, FLEET_MULTIPLANE_GROUP='flux'), 0)): + s = state(); trace.write_text(''); pathlib.Path(str(trace) + '.context').write_text('') + r = run(['preflight', '--state', str(s), '--root', str(good_root), '--skip-tests'], env) + check('preflight ' + name, r.returncode == expected, 'exit %s: %s' % (r.returncode, r.stdout[-600:])) + if name in ('ci unknown scenario group', 'ci flux group pass'): + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check(name + ' recorded', pre['group'] == env['FLEET_MULTIPLANE_GROUP'] and + [c['ok'] for c in pre['checks'] if c['name'] == 'scenario-group'] == [name.endswith('pass')], str(pre['checks'])) + if name == 'ci kvm pass': + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check('ci runtime recorded', pre['runtime'] == {'mode': 'ci', 'dockerContext': 'default', 'architecture': 'amd64', 'accelerator': 'kvm'}, str(pre['runtime'])) + check('ci checks kvm and keeps the safety checks', {'kvm-device', 'no-concurrent-fleet-runtime', 'runtime-disk', 'runtime-memory', 'runtime-cpus', 'inotify-instances', 'ci-runner', 'amd64-emulation'} + <= {c['name'] for c in pre['checks'] if c['ok']}, str(pre['checks'])) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('ci mode never touches colima', not any(c[0] == 'colima' for c in calls), str(calls)) + check('ci mode uses only the selected context', set(pathlib.Path(str(trace) + '.context').read_text().split()) == {'default'}) + + # run.sh exports the defaults to every step, and passes overrides through. + for name, env, want in ( + ('run.sh defaults', {}, {'mode': 'colima', 'dockerContext': 'colima-fleet-acceptance-tcg', 'architecture': 'arm64', 'accelerator': 'tcg'}), + ('run.sh ci parameters', ci, {'mode': 'ci', 'dockerContext': 'default', 'architecture': 'amd64', 'accelerator': 'kvm'})): + runs = pathlib.Path(tempfile.mkdtemp(dir=tmp)) + r = subprocess.run(['bash', str(root / 'hack/multiplane/run.sh'), '--preflight-only', '--skip-readiness-tests'], text=True, capture_output=True, + env=dict(base, FLEET_MULTIPLANE_STATE_ROOT=str(runs), **env)) + states = list(runs.iterdir()) + pre = json.loads((states[0] / 'evidence/preflight.json').read_text()) if len(states) == 1 else {} + check(name, r.returncode == 0 and pre.get('runtime') == want, 'exit %s %s: %s' % (r.returncode, pre.get('runtime'), (r.stdout + r.stderr)[-600:])) # Bounded phases: pass, fail, blocked passthrough, timeout kills the process group. s = state() @@ -160,6 +224,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 +242,39 @@ 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, *args): + s = state(); (s / 'evidence').mkdir(); (s / 'evidence/result.json').write_text(json.dumps(result)) + return run(['verify', '--state', str(s), *args]).returncode + good = {'status': 'passed', 'exitCode': 0, 'group': 'flux', 'retainedContainers': [], 'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'teardown', 'status': 'passed'}]} + check('verify passes a completed run', verified(good) == 0) + check('verify passes the expected scenario group', verified(good, '--group', 'flux') == 0) + check('verify refuses another scenario group', verified(good, '--group', 'release') == 1) + check('verify refuses a run that recorded no group', verified({k: v for k, v in good.items() if k != 'group'}, '--group', 'all') == 1) + for name, change in (('interrupted', {'status': 'interrupted', 'exitCode': 1}), ('timeout', {'status': 'timeout', 'exitCode': 4}), + ('a failed phase', {'phases': [{'name': 'build', 'status': 'timeout'}, {'name': 'teardown', 'status': 'passed'}]}), + ('no teardown', {'phases': [{'name': 'build', 'status': 'passed'}, {'name': 'stop', 'status': 'passed'}]}), + ('retained containers', {'retainedContainers': [{'name': 'fleet-mp-0000aaaa-vm', 'state': 'exited'}]})): + check('verify refuses ' + name, verified(dict(good, **change)) == 1) + s = state() + check('verify refuses a missing result', run(['verify', '--state', str(s)]).returncode == 1) + + # The installer hold: the watcher suspends a guest whose kernel printed and + # reports a guest that printed its receipt first as missed, never held. + steps_text = (root / 'hack/multiplane/steps.sh').read_text() + watcher = steps_text.split("<<'SH'\n", 1)[1].split('\nSH\n', 1)[0] + for name, console, want in (('held', 'Linux version 6.1\n', 'held '), ('missed', 'Linux version 6.1\nFLEET-INSTALLED:' + 'r' * 64 + '\n', 'missed ')): + h = pathlib.Path(tempfile.mkdtemp(dir=tmp)) + (h / 'vm/dev/0123456789abcdef').mkdir(parents=True); (h / 'vm/dev/0123456789abcdef/installer.log').write_text(console) + (h / 'bin').mkdir() + (h / 'bin/virsh').write_text('#!/bin/sh\nfor a; do last=$a; done\ncase "$3" in list) echo fleet-local-0123456789abcdef ;; suspend) echo "$4" > "%s/suspended" ;; domstate) [ -e "%s/suspended" ] && echo paused || echo running ;; esac\n' % (h, h)) + (h / 'bin/virsh').chmod(0o755) + script = watcher.replace('/var/lib/fleet-local/vm', str(h / 'vm')).replace('/tmp/fleet-installer-hold', str(h / 'hold')) + r = subprocess.run(['sh', '-c', script], text=True, capture_output=True, env=dict(os.environ, PATH=str(h / 'bin') + os.pathsep + os.environ['PATH']), timeout=30) + result = (h / 'hold').read_text() if (h / 'hold').exists() else '' + check('installer hold ' + name, r.returncode == 0 and result.startswith(want + 'fleet-local-0123456789abcdef'), repr(result) + r.stderr[-300:]) + # Teardown refuses without passed acceptance, before touching the runtime. s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n'); (s / 'evidence').mkdir() trace.write_text('') @@ -191,18 +294,60 @@ with tempfile.TemporaryDirectory() as tmp: check('run usage', r.returncode == 64) # Static guards for runtime-only step code the offline fakes cannot execute. + for f in sorted((root / 'hack/multiplane').glob('*.*')): + if f.suffix in ('.sh', '.py') and not f.name.startswith('test-'): + text = f.read_text() + check('docker context is the run parameter: ' + f.name, 'DOCKER_CONTEXT=colima' not in text and "['DOCKER_CONTEXT']='colima" not in text + and "['DOCKER_CONTEXT'] = 'colima" not in text and "'context','inspect','colima" not in text) + run_text = (root / 'hack/multiplane/run.sh').read_text() + check('site binary built for the selected architecture', 'GOARCH="$FLEET_MULTIPLANE_ARCH"' in run_text and 'GOARCH=arm64' not in run_text) + check('site accelerator is the run parameter', 'FLEET_LOCAL_VM_ACCEL, value: tcg' not in (root / 'config/site/services/services.yaml').read_text() + and '{name: FLEET_LOCAL_VM_ACCEL, value: "${schema.spec.accelerator}"}' in (root / 'config/site/graph/rgd.yaml').read_text() + and 'accelerator: "${FLEET_LOCAL_VM_ACCEL}"' in (root / 'config/site/instance/dispatcher.yaml').read_text()) + runtime_text = (root / 'hack/local-vm/site-runtime').read_text() + bmc_text = (root / 'config/site/redfish/services/bmc.yaml').read_text() + adapter_text = (root / 'hack/redfish-lab/fleet_lab_adapter.py').read_text() + check('lab BMC runs targets only under the runtime accelerator', '{name: FLEET_LAB_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"}' in bmc_text + and adapter_text.count('require_accelerator()') == 3 and "('kvm' if ACCEL == 'kvm' else 'qemu')" in adapter_text) + redfish_suite = (root / 'hack/multiplane/acceptance-redfish.sh').read_text().splitlines() + check('Redfish interruptions land on a held installer', redfish_suite.index('step hold-installer 120') < redfish_suite.index('step dispatch 900') + < redfish_suite.index('step interrupt-job 600') < redfish_suite.index('step release-installer 120') < redfish_suite.index('rf lost-response 1200')) + check('site runtime requires the KVM device and publishes its accelerator', 'kvm) [ -c /dev/kvm ]' in runtime_text and ' *) echo' in runtime_text + and '"$sock/accelerator"' in runtime_text) + check('interrupts land on a held installer in local VM mode', 'step hold-installer' in (root / 'hack/multiplane/acceptance.sh').read_text() + and 'step release-installer' in (root / 'hack/multiplane/acceptance.sh').read_text() and "installerHold" in (root / 'hack/multiplane/evidence.py').read_text()) steps = (root / 'hack/multiplane/steps.sh').read_text() evidence = (root / 'hack/multiplane/evidence.py').read_text() + # The partition marker is counted from real output only: the shell's + # trace of its printf shows the format, and a kernel message may prefix it. + import re as _re + partitioned = _re.compile(_re.search(r"PARTITIONED = re.compile\(r'([^']+)'\)", evidence).group(1)) + receipt = 'ab' * 32 + traced = subprocess.run(['sh', '-xc', "printf 'FLEET-PARTITIONED:%s\\n' \"$1\"", 'sh', receipt], text=True, capture_output=True) + log = traced.stderr + '[ 1.5] vda: vda1\n' + traced.stdout.replace('FLEET-', '[ 1.6] virtio_blk: ok FLEET-', 1) + check('init prints the partition marker after sfdisk', "sfdisk /dev/vda\n# One line" in (root / 'hack/local-vm/init').read_text() + and "printf 'FLEET-PARTITIONED:%s\\n' \"$receipt\"" in (root / 'hack/local-vm/init').read_text()) + check('partition marker ignores its own trace', 'FLEET-PARTITIONED:' in traced.stderr and partitioned.findall(log) == [receipt], log) + check('partition marker counts a second partition', partitioned.findall(log + traced.stdout) == [receipt, receipt]) for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['custody-crd-rules', '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', '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-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/test-redfish.py b/hack/multiplane/test-redfish.py index 26c44805..aece0f19 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -291,9 +291,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'] @@ -312,6 +312,11 @@ def build(path): check('no OpenStack dependency', not re.search(r'sushy|openstack|ironic', (lock + adapter + (root / 'hack/redfish-lab/Containerfile').read_text()).lower())) run_sh = (root / 'hack/multiplane/run.sh').read_text() +# Isolation runs in every group; only the groups that release target A may +# require its disk zeroed and every target off. +iso = redfish_steps.split('def isolation(s):')[1].split('\ndef ')[0] +check('isolation requires a wiped target A only where a release ran', "released = harness.GROUP != 'flux'" in iso + and "if released and a['diskSHA256']" in iso and "if released and record['runningDomains']" in iso) # $state/provider is the Milo provider project's credential directory. check('site provider marker does not collide with the provider project state', '"$state/site-provider"' in run_sh and '> "$state/provider"' not in run_sh) diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh index bf852b56..81a293b9 100644 --- a/hack/multiplane/topology.sh +++ b/hack/multiplane/topology.sh @@ -8,57 +8,59 @@ 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()'; } +# 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). -reg_port=$(free_port) -docker run -d --name "$prefix-registry" --network kind --memory 128m --memory-swap 128m --cpus 0.5 \ - -p "127.0.0.1:$reg_port:5000" "$registry_image" >/dev/null +# 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. +# 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::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" # IPAM (synchronized DHCP or virtual media) adds its PostgreSQL beside the # Milo APIs. platform_memory=2300m [[ ${FLEET_LAB_IPAM:-0} != 1 ]] || platform_memory=2800m docker update --memory "$platform_memory" --memory-swap "$platform_memory" --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: @@ -66,7 +68,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 diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index fe64acb6..b6f25a70 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -66,6 +66,11 @@ # synced: the network has no DHCP of its own, and the site's Kea, fed by # Fleet's reservation feed, is the only DHCP server on the bridge. LAB_DHCP = os.environ.get('FLEET_LAB_DHCP', 'static') +# 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() @@ -128,6 +133,17 @@ 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 media_xml(media): return ''.join("" % (media[dev]['file'], target) for dev, target in MEDIA_DEVICES if media.get(dev, {}).get('Inserted')) @@ -136,7 +152,7 @@ def media_xml(media): def domain_xml(t, boot, media=None): # 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" @@ -181,6 +197,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): @@ -216,6 +233,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, self.media[sid])) virsh('start', t['domain']) return boot @@ -590,6 +608,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 0d6dc8b4..b403d47f 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'), FLEET_BMC_MEDIA=str(WORK / 'media')) +(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_BMC_MEDIA=str(WORK / 'media'), + 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 @@ -200,6 +202,28 @@ def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): finally: del os.environ['FAKE_VIRSH_DOWN'] + def test_7_targets_run_only_under_the_runtime_accelerator(self): + target = adapter.load_targets()['System-1'] + self.assertTrue(adapter.domain_xml(target, 'hd').startswith("")) + adapter.ACCEL = 'kvm' + try: + self.assertTrue(adapter.domain_xml(target, 'hd').startswith("")) + # The runtime still publishes tcg: no definition or start, and the + # System reports the hardware unavailable. + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + starts = virsh_state()['domains']['fleet-lab-target-a']['starts'] + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 503) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'], starts) + (WORK / 'accelerator').write_text('kvm\n') + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 204) + self.assertEqual(len(virsh_state()['domains']['fleet-lab-target-a']['starts']), len(starts) + 1) + (WORK / 'accelerator').unlink() + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + finally: + adapter.ACCEL = 'tcg' + (WORK / 'accelerator').write_text('tcg\n') + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 069df90d..c95217de 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -169,23 +169,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 diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index ed39e969..0748a8bb 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -172,6 +172,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" @@ -191,7 +194,7 @@ func (k Installation) boot(work *site.Work) (Boot, error) { if _, err := rand.Read(token); err != nil { return boot, err } - boot = Boot{Operation: work.Operation.UID, Fence: work.Fence, Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: k.now().Add(k.window())} + boot = Boot{Operation: work.Operation.UID, 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) } @@ -207,6 +210,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.Operation.UID) 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 b5a35d10..35ced874 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.Operation.UID), &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.Operation.UID), &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.Operation.UID), "installer.xml")) + if err != nil || !strings.HasPrefix(string(xml), "") { + t.Fatalf("%s installer domain = %.40s, %v", accelerator, xml, err) + } + } +}