diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 848551a1..426830bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,32 +5,173 @@ on: branches: [main] permissions: contents: read +# The checks run as parallel jobs, so wall time is the slowest job rather than +# their sum. Each job restores its own Go build cache: the race-instrumented +# test builds and the plain vet and tool builds never share compiled packages, +# so one shared cache would hold only whichever job saved first. A cache key +# changes with go.sum; a miss restores the newest older cache for the job. jobs: - validate: + # Every Go test runs once, with the race detector. No package is excluded + # from race runs by a build tag. The shards partition `go list ./...`: the + # rest shard takes every package the others do not name, so a new package + # is always tested. The custody and allocation packages run their + # envtest-backed tests one after another, so their tests are dealt + # round-robin across shards: three for custody and two for allocation, + # whose tests together come near go test's ten-minute package timeout. + # -count=1 keeps a restored cache from replaying results, and a skipped test + # fails the shard: every skip in this repository means a missing tool or + # envtest assets. + go-test: + name: go-test (${{ matrix.shard }}) runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - {shard: custody-1, packages: custody, part: 1, parts: 3} + - {shard: custody-2, packages: custody, part: 2, parts: 3} + - {shard: custody-3, packages: custody, part: 3, parts: 3} + - {shard: allocation-1, packages: allocation, part: 1, parts: 2} + - {shard: allocation-2, packages: allocation, part: 2, parts: 2} + - {shard: api, packages: api, part: 1, parts: 1} + - {shard: rest, packages: rest, part: 1, parts: 1} steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 - with: {go-version-file: go.mod, cache: true} + with: {go-version-file: go.mod, cache: false} + - uses: actions/cache@v6 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: go-test-${{ matrix.packages }}-${{ runner.os }}-${{ hashFiles('go.mod', 'go.sum') }}-${{ github.sha }} + restore-keys: | + go-test-${{ matrix.packages }}-${{ runner.os }}-${{ hashFiles('go.mod', 'go.sum') }}- + go-test-${{ matrix.packages }}-${{ runner.os }}- + - uses: actions/cache@v6 + with: + path: ~/.local/share/kubebuilder-envtest + key: envtest-${{ runner.os }}-v0.25.2-1.37.0 + # One registration test renders the published bundle with kustomize. - uses: imranismail/setup-kustomize@v2 with: {kustomize-version: 5.8.1} - # Runs the manager's multi-project end-to-end test against real API - # servers; without these assets it is skipped. + # Runs the envtest-based tests against real API servers. - name: Install envtest assets - run: echo "KUBEBUILDER_ASSETS=$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" >> "$GITHUB_ENV" - - run: go test ./... - - run: go test -race ./... + run: | + assets=$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path) + test -x "$assets/kube-apiserver" && test -x "$assets/etcd" + echo "KUBEBUILDER_ASSETS=$assets" >> "$GITHUB_ENV" + - name: go test -race (${{ matrix.shard }}) + shell: bash + env: + PACKAGES: ${{ matrix.packages }} + PART: ${{ matrix.part }} + PARTS: ${{ matrix.parts }} + run: | + module=$(go list -m) + all=$(go list ./...) + case "$PACKAGES" in + custody) packages=$(grep -x "$module/internal/custody" <<<"$all") ;; + allocation) packages=$(grep -x "$module/internal/allocation" <<<"$all") ;; + api) packages=$(grep "^$module/internal/api/" <<<"$all") ;; + rest) packages=$(grep -vx -e "$module/internal/custody" -e "$module/internal/allocation" -e "$module/internal/api/.*" <<<"$all") ;; + esac + [ -n "$packages" ] || { echo "shard $PACKAGES has no packages"; exit 1; } + run=() + if [ "$PARTS" -gt 1 ]; then + # shellcheck disable=SC2086 + tests=$(go test -race -list '.*' $packages | grep -E '^(Test|Example|Fuzz)') + mine=$(awk -v part="$PART" -v parts="$PARTS" '(NR - 1) % parts == part - 1' <<<"$tests" | paste -sd '|' -) + [ -n "$mine" ] || { echo "shard $PART of $PARTS has no tests"; exit 1; } + run=(-run "^($mine)\$") + fi + # shellcheck disable=SC2086 + go test -race -count=1 -v "${run[@]}" $packages > "$RUNNER_TEMP/go-test.log" 2>&1 || status=$? + grep -E '^(ok|FAIL|panic:|--- FAIL|--- SKIP)|^\s+--- (FAIL|SKIP)' "$RUNNER_TEMP/go-test.log" || true + if [ "${status:-0}" -ne 0 ]; then + grep -v -E '^\s*(=== (RUN|PAUSE|CONT|NAME)|--- PASS)' "$RUNNER_TEMP/go-test.log" | tail -n 400 + exit "$status" + fi + ! grep -qE '^\s*--- SKIP' "$RUNNER_TEMP/go-test.log" || { echo 'a test skipped'; exit 1; } + checks: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: {go-version-file: go.mod, cache: false} + - uses: actions/cache@v6 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: go-checks-${{ runner.os }}-${{ hashFiles('go.mod', 'go.sum') }} + restore-keys: go-checks-${{ runner.os }}- + - uses: imranismail/setup-kustomize@v2 + with: {kustomize-version: 5.8.1} - run: go vet ./... - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null + - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null + - run: kustomize build config/inventory >/dev/null - run: ./hack/validate-synthetic-staging-render.sh - run: ./hack/validate-overlay-isolation.sh - run: ./hack/test-overlay-isolation.sh + - run: ./hack/validate-bmc-credential-namespace.sh + - run: ./hack/test-bmc-credential-namespace.sh - run: ./hack/validate-standalone-render.sh - run: ./hack/test-standalone-source-id.sh - run: ./hack/test-standalone-preflight.sh - run: ./hack/test-standalone-build-context.sh + - name: Build commissioning member image + if: github.event_name == 'pull_request' + run: docker build -f build/commissioning-member.Dockerfile . + # Script self-tests, shell lint and documentation links. None of them builds + # Go code. + harness: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + - uses: imranismail/setup-kustomize@v2 + with: {kustomize-version: 5.8.1} + - name: Install ripgrep for the link check + run: sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ripgrep + - run: ./hack/test-run-standalone-smoke.sh + - run: ./hack/validate-site-dhcp-render.sh + - run: bash hack/dhcp/validate-producer.sh + - run: python3 hack/dhcp/staging-proof-test.py + - run: ./hack/validate-network-boot-inactive.sh - run: ./hack/validate-doc-links.sh + - run: ./hack/multiplane/test-harness.sh + - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime + standalone-smoke: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: {go-version-file: go.mod, cache: true} + - uses: imranismail/setup-kustomize@v2 + with: {kustomize-version: 5.8.1} + - name: Install pinned kind and kubectl + shell: bash + run: | + set -euo pipefail + go install sigs.k8s.io/kind@v0.31.0 + directory=$(mktemp -d) + trap 'rm -rf "$directory"' EXIT + cd "$directory" + curl --fail --location --retry 3 --max-time 60 -o kubectl https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl + curl --fail --location --retry 3 --max-time 60 -o kubectl.sha256 https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl.sha256 + echo "$(cat kubectl.sha256) kubectl" | sha256sum --check + chmod +x kubectl + mkdir -p "$HOME/.local/bin" + mv kubectl "$HOME/.local/bin/kubectl" + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Run disposable standalone smoke + run: ./hack/run-standalone-smoke.sh diff --git a/.github/workflows/dhcp-isolated.yml b/.github/workflows/dhcp-isolated.yml new file mode 100644 index 00000000..c6a3a72c --- /dev/null +++ b/.github/workflows/dhcp-isolated.yml @@ -0,0 +1,30 @@ +name: Isolated DHCP consumer +on: + pull_request: + paths: + - config/site/dhcp/isolated/** + - config/site/dhcp/isolated-example/** + - hack/dhcp/** + - .github/workflows/dhcp-isolated.yml + push: + branches: [main, feat/manual-inventory-records] + paths: + - config/site/dhcp/isolated/** + - config/site/dhcp/isolated-example/** + - hack/dhcp/** + - .github/workflows/dhcp-isolated.yml +permissions: + contents: read +jobs: + consumer: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: {go-version-file: go.mod, cache: false} + - uses: imranismail/setup-kustomize@v2 + with: {kustomize-version: 5.8.1} + - run: go install github.com/mikefarah/yq/v4@v4.54.3 + - run: shellcheck hack/dhcp/*.sh + - run: bash hack/dhcp/test-transport.sh diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml new file mode 100644 index 00000000..2565eb25 --- /dev/null +++ b/.github/workflows/multiplane-acceptance.yml @@ -0,0 +1,240 @@ +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 + groups: + description: Scenario groups + type: choice + options: [all, split] + default: all + 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 }}) + # A labeled pull request run splits each suite into 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 nightly run, and a manual run unless + # it asks for split, runs the all group: every scenario in one topology, + # so the release scenarios run after the Flux disruptions + # (docs/operations/multiplane.md#ci-mode). 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: + # Each shard is one suite in one scenario group. A labeled pull request + # run, or a manual run that asks for split, runs the local VM and + # Redfish suites as their flux and release shards; the nightly run, and + # a manual run unless it asks for split, runs each in the all group. The + # virtual media suite (run.sh --redfish --virtual-media) always runs as + # one all shard: its scenarios are one ordered sequence of installs. + # Both selects every suite. + include: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode == 'media' && '[{"mode":"media","group":"all"}]' || github.event_name == 'workflow_dispatch' && inputs.mode == 'localvm' && (inputs.groups == 'split' && '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"}]' || '[{"mode":"localvm","group":"all"}]') || github.event_name == 'workflow_dispatch' && inputs.mode == 'redfish' && (inputs.groups == 'split' && '[{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"}]' || '[{"mode":"redfish","group":"all"}]') || (github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.groups == 'split')) && '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"},{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"},{"mode":"media","group":"all"}]' || '[{"mode":"localvm","group":"all"},{"mode":"redfish","group":"all"},{"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 split run build the same binaries, so only the release + # shard saves, as does an all run; a second save of a key is skipped. + - name: Save the Go build cache + if: always() && matrix.group != 'flux' + 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/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2ada75ca..87c94e73 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,6 +18,30 @@ jobs: platforms: linux/amd64,linux/arm64 secrets: inherit + publish-site-runtime-image: + permissions: + id-token: write + contents: read + packages: write + uses: datum-cloud/actions/.github/workflows/publish-docker.yaml@v1.21.0 + with: + image-name: fleet-site-runtime + dockerfile-path: build/site-runtime.Dockerfile + platforms: linux/amd64,linux/arm64 + secrets: inherit + + publish-commissioning-member-image: + permissions: + id-token: write + contents: read + packages: write + uses: datum-cloud/actions/.github/workflows/publish-docker.yaml@v1.21.0 + with: + image-name: fleet-commissioning-member + dockerfile-path: build/commissioning-member.Dockerfile + platforms: linux/amd64,linux/arm64 + secrets: inherit + # The plugin images are deployed by config/components/{consumer,provider}-ui-plugin # in the same kustomize bundle. publish-consumer-ui-plugin-image: @@ -63,6 +87,8 @@ jobs: bundle-path: config images: | - { path: config/base/manager, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } + - { path: config/base/registration, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } + - { path: config/base/bmc-discovery, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/overlays/synthetic-staging, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/components/consumer-ui-plugin, name: ghcr.io/datum-cloud/fleet-consumer-ui-plugin, tag: "${{ needs.publish-consumer-ui-plugin-image.outputs.tag }}" } - { path: config/components/provider-ui-plugin, name: ghcr.io/datum-cloud/fleet-provider-ui-plugin, tag: "${{ needs.publish-provider-ui-plugin-image.outputs.tag }}" } diff --git a/.gitignore b/.gitignore index d105526d..217d5f65 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,6 @@ /kubeconfig /kubeconfig.* /talosconfig -/netbox.txt /servers.com.txt # Local outputs and scratch work @@ -27,3 +26,17 @@ # Local agent settings .claude/settings.local.json .claude/worktrees/ + +# Python tooling caches +__pycache__/ +*.py[cod] + +# Flux install manifest downloaded and verified by hack/multiplane/flux.py; never committed. +config/multiplane/flux/gotk-components.yaml + +# Locally built binaries +/fleet-multiplane +/fleet-manager +/fleet-registration +/fleet-simulator +/fleet-standalone-smoke diff --git a/README.md b/README.md index 778018b3..8551f915 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,9 @@ services. Each subsystem owns its resources and controls changes to them. Fleet is under development. This repository contains the service design, alpha APIs, lifecycle libraries, and synthetic validation environments. Production -integration and real provider support are not complete; the production manager -rejects work that requires those integrations and makes no provider changes. See the +integration and real provider support are not complete. By default the manager +makes no provider changes. A placement-resolved [physical site route](docs/operations/site-execution.md#routing-a-providers-physical-devices) +can deliver admitted provider operations through Karmada without enabling customer allocation. See the [implementation status](docs/development/README.md) for the implemented subset and remaining gaps. @@ -31,6 +32,11 @@ The first bare-metal release must exercise a standalone customer workload on a qualified OS other than Talos, without requiring a managed cluster or an ongoing guest agent. Provisioning engines and provider integrations remain pluggable. +The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) +proposes managed images and bounded delegation to customer PXE. The +[boot network enhancement](docs/enhancements/boot-network/README.md) proposes +DHCP reservations that exist only while a machine's network boot is admitted. + ## Learn more Start with the [product overview and documentation guide](docs/README.md) to diff --git a/Taskfile.yaml b/Taskfile.yaml index 1765d7b0..a3bf1346 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,69 @@ version: '3' tasks: + standalone:test: + desc: Run the synthetic lifecycle in a disposable local kind cluster. + cmds: + - ./hack/run-standalone-smoke.sh + + boot-network:kea-lab: + desc: Prove the site DHCP path with real Kea, the synchronizer and the feed on one container bridge. + cmds: + - ./hack/boot-network/kea-lab.sh + + multiplane:acceptance: + desc: Fresh local Milo/Karmada/kro/PXE acceptance, every service installed by per-cluster Flux from the checkout, in the task-owned Colima profile (exit 0 pass, 1 fail, 2 preflight, 3 blocked, 4 timeout). + env: + # Explicit opt-in for the documented reversible inotify adjustment inside the task VM only. + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh {{.CLI_ARGS}} + + multiplane:redfish-acceptance: + desc: "The multi-plane acceptance in Redfish mode: workers drive two persistent lab VMs only through the DMTF Redfish Interface Emulator and its lab adapter (same exit codes)." + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --redfish {{.CLI_ARGS}} + + multiplane:flux-qualification: + desc: "The Flux qualification suite: the same fresh topology and Flux bootstrap, one completed installation, then the GitOps behavior scenarios (graph lifecycle, drift, restart, fail-closed) the acceptance runs no longer repeat (same exit codes)." + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --suite flux-qualification {{.CLI_ARGS}} + + multiplane:media-acceptance: + desc: "The Redfish-mode virtual media suite: the worker installs a lab VM over Redfish VirtualMedia from the site's media service, then proves release (same exit codes)." + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --redfish --virtual-media {{.CLI_ARGS}} + + multiplane:preflight: + desc: Check local prerequisites and implementation readiness without creating resources. + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --preflight-only {{.CLI_ARGS}} + + multiplane:stop: + desc: Stop (never delete) one retained run's exact containers; custody stays Unknown. + requires: + vars: [STATE] + cmds: + - ./hack/multiplane/stop.sh "{{.STATE}}" + + multiplane:cleanup: + desc: Remove the stopped containers, image tags and state of finished runs older than FLEET_MULTIPLANE_CLEANUP_AGE_HOURS (default 12); never an active, locked or queued run. Pass --dry-run to list only. + cmds: + - python3 hack/multiplane/harness.py cleanup --verbose {{.CLI_ARGS}} + + multiplane:test-harness: + desc: Offline tests for the multi-plane harness with fake runtime tools. + cmds: + - ./hack/multiplane/test-harness.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/build/commissioning-member.Dockerfile b/build/commissioning-member.Dockerfile new file mode 100644 index 00000000..66e23d95 --- /dev/null +++ b/build/commissioning-member.Dockerfile @@ -0,0 +1,13 @@ +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine@sha256:3ad57304ad93bbec8548a0437ad9e06a455660655d9af011d58b993f6f615648 AS build +ARG TARGETOS TARGETARCH +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w -X main.memberProfile=commissioning' -o /out/member ./cmd/fleet-multiplane + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +COPY --from=build /out/member /usr/local/bin/member +ENV FLEET_SITE_PROVIDER=redfish +ENTRYPOINT ["/usr/local/bin/member"] diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 568e18a9..d6af25cd 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -6,9 +6,15 @@ RUN go mod download COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ - && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-registration ./cmd/fleet-registration \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager +COPY --from=build /out/fleet-registration /fleet-registration COPY --from=build /out/fleet-simulator /fleet-simulator +COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync +COPY --from=build /out/fleet-bmc-discovery /fleet-bmc-discovery ENTRYPOINT ["/fleet-manager"] diff --git a/build/site-runtime.Dockerfile b/build/site-runtime.Dockerfile new file mode 100644 index 00000000..a2fcfd54 --- /dev/null +++ b/build/site-runtime.Dockerfile @@ -0,0 +1,13 @@ +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine@sha256:3ad57304ad93bbec8548a0437ad9e06a455660655d9af011d58b993f6f615648 AS build +ARG TARGETOS TARGETARCH +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-multiplane ./cmd/fleet-multiplane + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +COPY --from=build /out/fleet-multiplane /usr/local/bin/fleet-multiplane +ENV FLEET_SITE_PROVIDER=redfish +ENTRYPOINT ["/usr/local/bin/fleet-multiplane"] diff --git a/cmd/fleet-bmc-discovery/main.go b/cmd/fleet-bmc-discovery/main.go new file mode 100644 index 00000000..100d58dd --- /dev/null +++ b/cmd/fleet-bmc-discovery/main.go @@ -0,0 +1,79 @@ +// fleet-bmc-discovery reads what each Device's BMC reports over read-only +// Redfish GETs and writes it into Device status in one Milo project. It runs +// where the BMC network is reachable, as one replica without leader election. +// With --once it contacts each BMC once and prints the statuses it would +// write, writing nothing to Milo. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + "go.datum.net/fleet/internal/bmcdiscovery" +) + +func main() { + var configPath string + var once bool + flag.StringVar(&configPath, "config", "/etc/fleet/bmc-discovery/config.yaml", "discovery configuration file") + flag.BoolVar(&once, "once", false, "contact each BMC once, print the statuses that would be written, and write nothing to Milo") + zapOptions := zap.Options{Development: false} + zapOptions.BindFlags(flag.CommandLine) + flag.Parse() + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zapOptions))) + if err := run(ctrl.SetupSignalHandler(), configPath, once); err != nil && !errors.Is(err, context.Canceled) { + fmt.Fprintln(os.Stderr, "fleet-bmc-discovery:", err) + os.Exit(1) + } +} + +func run(ctx context.Context, configPath string, once bool) error { + config, err := bmcdiscovery.LoadConfig(configPath) + if err != nil { + return err + } + milo, err := clientcmd.BuildConfigFromFlags("", config.MiloKubeconfig) + if err != nil { + return fmt.Errorf("Milo project kubeconfig: %w", err) + } + var local *rest.Config + if config.LocalKubeconfig != "" { + local, err = clientcmd.BuildConfigFromFlags("", config.LocalKubeconfig) + } else { + local, err = rest.InClusterConfig() + } + if err != nil { + return fmt.Errorf("local cluster config: %w", err) + } + scheme, err := bmcdiscovery.NewScheme() + if err != nil { + return err + } + bmc := bmcdiscovery.RedfishBMC{Timeout: config.RequestTimeout.Duration} + if once { + devices, err := client.New(milo, client.Options{Scheme: scheme}) + if err != nil { + return err + } + secrets, err := client.New(local, client.Options{Scheme: scheme}) + if err != nil { + return err + } + // Reads only: RunOnce takes readers, so no write can reach Milo. + return bmcdiscovery.RunOnce(ctx, config, client.Reader(devices), client.Reader(secrets), bmc, os.Stdout) + } + mgr, err := bmcdiscovery.NewManager(config, milo, local, scheme, bmc) + if err != nil { + return err + } + return mgr.Start(ctx) +} diff --git a/cmd/fleet-dhcp-sync/main.go b/cmd/fleet-dhcp-sync/main.go new file mode 100644 index 00000000..e52e468d --- /dev/null +++ b/cmd/fleet-dhcp-sync/main.go @@ -0,0 +1,73 @@ +// fleet-dhcp-sync runs beside one Kea DHCPv4 instance. It applies a site's +// boot-reservation feed through Kea's control socket and reports each applied +// revision back to the site, which retains it as boot and revocation evidence. +package main + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "flag" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "go.datum.net/fleet/internal/dhcpsync" +) + +func main() { + var feed, tokenPath, caPath, instance, socket, base string + var interval, refresh time.Duration + flag.StringVar(&feed, "feed", "", "site DHCP feed origin, https://host[:port]") + flag.StringVar(&tokenPath, "token-file", "", "file holding the synchronizer bearer token") + flag.StringVar(&caPath, "ca-file", "", "PEM CA bundle the feed's certificate must chain to; default the system roots") + flag.StringVar(&instance, "instance", os.Getenv("POD_NAME"), "stable name of this Kea instance") + flag.StringVar(&socket, "kea-socket", "/var/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket; Kea 2.6 allows only /var/run/kea") + flag.StringVar(&base, "base-config", "/etc/kea/kea-dhcp4.conf", "Kea configuration without Fleet reservations") + flag.DurationVar(&interval, "interval", 5*time.Second, "feed poll interval") + flag.DurationVar(&refresh, "refresh", dhcpsync.DefaultRefresh, "least time between two reports of an unchanged applied feed") + flag.Parse() + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + if err := run(logger, feed, tokenPath, caPath, instance, socket, base, interval, refresh); err != nil && !errors.Is(err, context.Canceled) { + logger.Error("dhcp sync stopped", "error", err) + os.Exit(1) + } +} + +func run(logger *slog.Logger, feed, tokenPath, caPath, instance, socket, base string, interval, refresh time.Duration) error { + u, err := url.Parse(feed) + if err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.User != nil { + return errors.New("feed must be an https origin") + } + token, err := os.ReadFile(tokenPath) + if err != nil { + return fmt.Errorf("token: %w", err) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + if caPath != "" { + pem, err := os.ReadFile(caPath) + if err != nil { + return fmt.Errorf("CA bundle: %w", err) + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(pem) { + return errors.New("CA bundle holds no certificate") + } + transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} + } + s := &dhcpsync.Syncer{ + Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, Refresh: refresh, + HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + return s.Run(ctx, interval, func(err error) { logger.Warn("sync cycle failed", "error", err) }) +} diff --git a/cmd/fleet-manager/clientcert_test.go b/cmd/fleet-manager/clientcert_test.go new file mode 100644 index 00000000..375bdfdc --- /dev/null +++ b/cmd/fleet-manager/clientcert_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "k8s.io/client-go/rest" +) + +// clientCertDir writes a cert-manager style Secret directory, tls.crt and +// tls.key, holding a client certificate for commonName signed by ca. +func clientCertDir(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, commonName string) string { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: commonName}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}} + der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for name, block := range map[string]*pem.Block{"tls.crt": {Type: "CERTIFICATE", Bytes: der}, "tls.key": {Type: "EC PRIVATE KEY", Bytes: keyDER}} { + if err := os.WriteFile(filepath.Join(dir, name), pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + } + return dir +} + +// TestEachComponentAuthenticatesToMiloWithItsOwnClientCertificate builds +// the coordinator's connection from the manager's: the same endpoint and +// server CA, but only the coordinator's client certificate, and none of the +// manager's credentials. +func TestEachComponentAuthenticatesToMiloWithItsOwnClientCertificate(t *testing.T) { + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + caTemplate := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "synthetic-client-ca"}, IsCA: true, BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour)} + caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + ca, err := x509.ParseCertificate(caDER) + if err != nil { + t.Fatal(err) + } + pool := x509.NewCertPool() + pool.AddCert(ca) + type seen struct { + commonName string + authorization string + } + requests := make(chan seen, 1) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got := seen{authorization: r.Header.Get("Authorization")} + if len(r.TLS.PeerCertificates) == 1 { + got.commonName = r.TLS.PeerCertificates[0].Subject.CommonName + } + requests <- got + })) + server.TLS = &tls.Config{ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool} + server.StartTLS() + defer server.Close() + serverCA := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}) + + manager := clientCertDir(t, ca, caKey, "fleet-manager") + provider := &rest.Config{Host: server.URL, BearerToken: "manager-token", TLSClientConfig: rest.TLSClientConfig{ + CAData: serverCA, CertFile: filepath.Join(manager, "tls.crt"), KeyFile: filepath.Join(manager, "tls.key")}} + config, err := withClientCert(provider, clientCertDir(t, ca, caKey, "custody-coordinator")) + if err != nil { + t.Fatal(err) + } + client, err := rest.HTTPClientFor(config) + if err != nil { + t.Fatal(err) + } + response, err := client.Get(config.Host + "/readyz") + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if got := <-requests; got.commonName != "custody-coordinator" || got.authorization != "" { + t.Fatalf("Milo saw client certificate %q and authorization %q, want only the coordinator's certificate", got.commonName, got.authorization) + } + if _, err := withClientCert(provider, t.TempDir()); err == nil { + t.Fatal("a directory without a client certificate was accepted") + } +} diff --git a/cmd/fleet-manager/main.go b/cmd/fleet-manager/main.go index 73d378c4..33742c2a 100644 --- a/cmd/fleet-manager/main.go +++ b/cmd/fleet-manager/main.go @@ -4,9 +4,7 @@ import ( "context" "errors" "flag" - "net/http" "os" - "time" "golang.org/x/sync/errgroup" "k8s.io/apimachinery/pkg/runtime" @@ -16,11 +14,13 @@ import ( ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" ctrlcluster "sigs.k8s.io/controller-runtime/pkg/cluster" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" eventmanager "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/projectdiscovery" "go.datum.net/fleet/internal/staging" @@ -35,23 +35,32 @@ import ( const leaseName = "fleet-manager.fleet.datumapis.com" type managerFlags struct { - configPath, privateNamespace, leaderElectionNamespace string + configPath, leaderElectionNamespace string + physicalConfig string syntheticStaging bool syntheticProviderURL, syntheticTokenFile, syntheticLocation string syntheticConsumerProjectName string syntheticProviderProjectName, syntheticPublishedClassName string syntheticPublishedProfileName string + syntheticCoordinatorCertDir, syntheticReleaseCertDir string + syntheticProjectorCertDir string + syntheticEnrollmentFile, syntheticDeviceNamespace string } func bindFlags(flags *flag.FlagSet) *managerFlags { f := &managerFlags{} + flags.StringVar(&f.physicalConfig, "physical-site-config", "", "provider custody route to a physical Karmada member") flags.StringVar(&f.configPath, "config", "", "path to the FleetManager configuration file (authority and project discovery)") - flags.StringVar(&f.privateNamespace, "private-namespace", "", "service-controlled private record namespace") flags.StringVar(&f.leaderElectionNamespace, "leader-election-namespace", "", "management-cluster namespace for the leader lease") flags.BoolVar(&f.syntheticStaging, "synthetic-staging", false, "enable the explicit non-production synthetic allocation integration for one consumer project") flags.StringVar(&f.syntheticProviderURL, "synthetic-provider-url", "http://127.0.0.1:8080", "synthetic provider runtime URL") - flags.StringVar(&f.syntheticTokenFile, "synthetic-provider-token-file", "", "file containing the synthetic provider bearer token") + flags.StringVar(&f.syntheticTokenFile, "synthetic-provider-token-file", "", "file containing the synthetic provider site's bearer token") + flags.StringVar(&f.syntheticCoordinatorCertDir, "synthetic-coordinator-client-cert-dir", "", "directory holding the custody coordinator's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticReleaseCertDir, "synthetic-release-client-cert-dir", "", "directory holding the release controller's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticProjectorCertDir, "synthetic-projector-client-cert-dir", "", "directory holding the capacity projector's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticEnrollmentFile, "synthetic-site-enrollment-file", "", "JSON enrollment of the Devices the synthetic provider site serves") + flags.StringVar(&f.syntheticDeviceNamespace, "synthetic-device-namespace", "default", "namespace of the Devices, capacities and allocations in the provider project") flags.StringVar(&f.syntheticLocation, "synthetic-location", "us-central-1", "only location accepted by synthetic staging") flags.StringVar(&f.syntheticConsumerProjectName, "synthetic-consumer-project-name", "", "the one engaged consumer project synthetic staging allocates for and publishes into") flags.StringVar(&f.syntheticProviderProjectName, "synthetic-provider-project-name", "", "provider project used by synthetic cross-project staging") @@ -64,17 +73,17 @@ var errFlags = errors.New("invalid fleet-manager flags") // validate checks flag combinations before any cluster is contacted. func (f *managerFlags) validate() error { - if f.configPath == "" || f.privateNamespace == "" || f.leaderElectionNamespace == "" { - return errors.Join(errFlags, errors.New("--config, --private-namespace, and --leader-election-namespace are required")) + if f.configPath == "" || f.leaderElectionNamespace == "" { + return errors.Join(errFlags, errors.New("--config and --leader-election-namespace are required")) } if !f.syntheticStaging { - if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" { + if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" || f.syntheticCoordinatorCertDir != "" || f.syntheticReleaseCertDir != "" || f.syntheticProjectorCertDir != "" || f.syntheticEnrollmentFile != "" { return errors.Join(errFlags, errors.New("synthetic flags require --synthetic-staging")) } return nil } - if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" { - return errors.Join(errFlags, errors.New("--synthetic-staging requires --synthetic-provider-token-file and --synthetic-consumer-project-name")) + if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" || f.syntheticCoordinatorCertDir == "" || f.syntheticReleaseCertDir == "" || f.syntheticProjectorCertDir == "" || f.syntheticEnrollmentFile == "" { + return errors.Join(errFlags, errors.New("--synthetic-staging requires the provider site token, the coordinator, release controller and capacity projector client certificates, the site enrollment, and --synthetic-consumer-project-name")) } if f.syntheticProviderProjectName != "" && (f.syntheticPublishedClassName == "" || f.syntheticPublishedProfileName == "") { return errors.Join(errFlags, errors.New("--synthetic-provider-project-name requires the published class and profile names")) @@ -98,6 +107,8 @@ func main() { scheme := runtime.NewScheme() must(clientgoscheme.AddToScheme(scheme)) must(fleetv1.AddToScheme(scheme)) + must(inventory.AddToScheme(scheme)) + must(ops.AddToScheme(scheme)) must(networkingv1.AddToScheme(scheme)) must(locationsv1alpha1.AddToScheme(scheme)) must(quotav1alpha1.AddToScheme(scheme)) @@ -131,53 +142,61 @@ func main() { for _, runnable := range selection.LocalRunnables { must(mgr.GetLocalManager().Add(runnable)) } - privateCluster, err := ctrlcluster.New(hostConfig, func(options *ctrlcluster.Options) { - options.Scheme = scheme - options.Cache = eventmanager.PrivateCacheOptions(flags.privateNamespace) - }) - must(err) - setupOptions := eventmanager.SetupOptions{PrivateNamespace: flags.privateNamespace, PrivateCluster: privateCluster, HandlersFor: eventmanager.DefaultHandlers} - - // Without --synthetic-staging every project gets blocked lifecycle - // handlers: no allocation, installation, provider call, or custody write. - // Only the requested-hardware projector writes. - if flags.syntheticStaging { - // Private lifecycle records are retained authority, not eventually - // consistent projections. Coordinator reads observe API-server state - // directly; the private cluster cache only delivers events. - privateRecordClient, err := ctrlclient.New(hostConfig, ctrlclient.Options{Scheme: scheme}) + setupOptions := eventmanager.SetupOptions{HandlersFor: eventmanager.DefaultHandlers} + + var physical *physicalSite + if flags.physicalConfig != "" { + physical, err = readPhysicalSite(flags.physicalConfig) must(err) - provider, err := executor.NewHTTPClientFromTokenFile(flags.syntheticProviderURL, flags.syntheticTokenFile, &http.Client{Timeout: 30 * time.Second}) + } + if flags.syntheticStaging || physical != nil { + providerName := flags.syntheticProviderProjectName + if providerName == "" { + providerName = flags.syntheticConsumerProjectName + } + if physical != nil { + must(physical.checkScope(flags, providerName)) + providerName = physical.ProviderProject + } + providerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, providerName) must(err) - coordinator, err := controller.NewCoordinator(privateRecordClient, flags.privateNamespace, provider, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) + providerConfig, err := projectdiscovery.ProjectRESTConfig(selection.ProjectConfig, providerProject.RouteName) must(err) - consumerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticConsumerProjectName) + allocator, loop, discover, err := providerCustody(ctx, scheme, providerConfig, flags, physical) must(err) - template := staging.Handler{Coordinator: coordinator, Location: flags.syntheticLocation} - if flags.syntheticProviderProjectName != "" { - providerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticProviderProjectName) + // Both need the leader lease: one coordinator writes custody. + if physical != nil { + loop.VerifyProvider = func(ctx context.Context) error { + return verifierFor(providerProject).VerifyProject(ctx, providerProject) + } + } + must(mgr.GetLocalManager().Add(manager.RunnableFunc(loop.Run))) + if flags.syntheticStaging { + consumerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticConsumerProjectName) must(err) - if providerProject.SameLifetime(consumerProject) { + if flags.syntheticProviderProjectName != "" && providerProject.SameLifetime(consumerProject) { must(eventmanager.ErrEventWiringUnavailable) } - providerConfig, err := projectdiscovery.ProjectRESTConfig(selection.ProjectConfig, providerProject.RouteName) - must(err) - providerCluster, err := ctrlcluster.New(providerConfig, func(options *ctrlcluster.Options) { - options.Scheme = scheme - options.Cache = eventmanager.ProjectCacheOptions() - }) - must(err) - template.Provider, template.ProviderProject = providerCluster.GetClient(), providerProject - setupOptions.ProviderProject, setupOptions.ProviderCluster, setupOptions.ProviderVerifier = providerProject, providerCluster, verifierFor(providerProject) - setupOptions.ProviderConsumer = multicluster.ClusterName(consumerProject.RouteName) - must(staging.SetupPublisher(mgr, projects, providerCluster, staging.PublisherOptions{ConsumerProject: consumerProject, ProviderProject: providerProject, ClassName: flags.syntheticPublishedClassName, ProfileName: flags.syntheticPublishedProfileName})) + must(mgr.GetLocalManager().Add(manager.RunnableFunc(discover))) + template := staging.Handler{Allocator: allocator, Location: flags.syntheticLocation} + if flags.syntheticProviderProjectName != "" { + providerCluster, err := ctrlcluster.New(providerConfig, func(options *ctrlcluster.Options) { + options.Scheme = scheme + options.Cache = eventmanager.ProjectCacheOptions() + }) + must(err) + template.Provider, template.ProviderProject = providerCluster.GetClient(), providerProject + setupOptions.ProviderProject, setupOptions.ProviderCluster, setupOptions.ProviderVerifier = providerProject, providerCluster, verifierFor(providerProject) + setupOptions.ProviderConsumer = multicluster.ClusterName(consumerProject.RouteName) + must(staging.SetupPublisher(mgr, projects, providerCluster, staging.PublisherOptions{ConsumerProject: consumerProject, ProviderProject: providerProject, ClassName: flags.syntheticPublishedClassName, ProfileName: flags.syntheticPublishedProfileName})) + } + setupOptions.HandlersFor = staging.ConsumerHandlers(eventmanager.DefaultHandlers, consumerProject, template) } - setupOptions.HandlersFor = staging.ConsumerHandlers(eventmanager.DefaultHandlers, consumerProject, template) } must(eventmanager.Setup(ctx, mgr, projects, setupOptions)) // Readiness reflects discovery and cache health only. It never depends on // a provider integration, and passing it enables no lifecycle effect. - must(projectdiscovery.AddHealthChecks(mgr, selection.Discovery, tracker, projectdiscovery.NamedCache{Name: "private-records", Cache: privateCluster.GetCache()})) + must(projectdiscovery.AddHealthChecks(mgr, selection.Discovery, tracker)) group, ctx := errgroup.WithContext(ctx) for _, runnable := range selection.SideRunnables { diff --git a/cmd/fleet-manager/main_test.go b/cmd/fleet-manager/main_test.go index 5341a6cf..04e793f0 100644 --- a/cmd/fleet-manager/main_test.go +++ b/cmd/fleet-manager/main_test.go @@ -18,7 +18,7 @@ func parse(t *testing.T, args ...string) error { return f.validate() } -var required = []string{"--config=/etc/fleet/manager/config.yaml", "--private-namespace=fleet-system-private", "--leader-election-namespace=fleet-system"} +var required = []string{"--config=/etc/fleet/manager/config.yaml", "--leader-election-namespace=fleet-system"} func TestDefaultConfigurationHasNoSyntheticIntegration(t *testing.T) { if err := parse(t, required...); err != nil { @@ -38,7 +38,7 @@ func TestDefaultConfigurationHasNoSyntheticIntegration(t *testing.T) { } func TestRemovedSingleProjectFlagsAreRejected(t *testing.T) { - for _, removed := range []string{"--project-name=consumer", "--authority-id=milo", "--project-kubeconfig=/k", "--enable-requested-hardware-projector=false"} { + for _, removed := range []string{"--project-name=consumer", "--authority-id=milo", "--project-kubeconfig=/k", "--enable-requested-hardware-projector=false", "--private-namespace=fleet-system-private"} { if err := parse(t, append(required, removed)...); err == nil { t.Fatalf("%s was accepted", removed) } @@ -52,10 +52,27 @@ func TestSyntheticFlagsRequireAndScopeStaging(t *testing.T) { if err := parse(t, append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t")...); !errors.Is(err, errFlags) { t.Fatalf("staging without a consumer project: %v", err) } - staging := append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t", "--synthetic-consumer-project-name=consumer") + components := []string{"--synthetic-coordinator-client-cert-dir=/c", "--synthetic-release-client-cert-dir=/r", "--synthetic-projector-client-cert-dir=/p", "--synthetic-site-enrollment-file=/e"} + staging := append(append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t", "--synthetic-consumer-project-name=consumer"), components...) if err := parse(t, staging...); err != nil { t.Fatal(err) } + // Each component authenticates as itself, and the site's Devices are + // configuration: staging refuses to start without any of them. + for _, missing := range components { + var args []string + for _, arg := range staging { + if arg != missing { + args = append(args, arg) + } + } + if err := parse(t, args...); !errors.Is(err, errFlags) { + t.Fatalf("staging without %s: %v", missing, err) + } + if err := parse(t, append(required, missing)...); !errors.Is(err, errFlags) { + t.Fatalf("%s without --synthetic-staging: %v", missing, err) + } + } if err := parse(t, append(staging, "--synthetic-provider-project-name=provider-project")...); !errors.Is(err, errFlags) { t.Fatalf("provider project without publication names: %v", err) } diff --git a/cmd/fleet-manager/physical.go b/cmd/fleet-manager/physical.go new file mode 100644 index 00000000..59d3a730 --- /dev/null +++ b/cmd/fleet-manager/physical.go @@ -0,0 +1,147 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/yaml" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/delivery" +) + +type physicalSite struct { + ProviderProject string `json:"providerProject"` + DeviceNamespace string `json:"deviceNamespace"` + Cell string `json:"cell"` + HubKubeconfig string `json:"hubKubeconfig"` + CoordinatorCertDir string `json:"coordinatorCertDir"` + ReleaseCertDir string `json:"releaseCertDir"` + ProjectorCertDir string `json:"projectorCertDir"` + Site string `json:"site"` + Commissioning bool `json:"commissioning,omitempty"` +} + +func readPhysicalSite(path string) (*physicalSite, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var config physicalSite + if err := yaml.UnmarshalStrict(data, &config); err != nil { + return nil, err + } + if len(validation.IsDNS1123Label(config.DeviceNamespace)) != 0 || len(validation.IsDNS1123Subdomain(config.ProviderProject)) != 0 || + len(validation.IsDNS1123Label(config.Cell)) != 0 || config.Cell == syntheticSite || len(validation.IsDNS1123Subdomain(config.Site)) != 0 { + return nil, errors.New("physical site needs an explicit provider project, namespace, member and inventory Site") + } + for _, mount := range []string{config.HubKubeconfig, config.CoordinatorCertDir, config.ReleaseCertDir, config.ProjectorCertDir} { + if !filepath.IsAbs(mount) { + return nil, errors.New("physical site credential mounts must be absolute paths") + } + } + return &config, nil +} + +func (config *physicalSite) attach(sites *delivery.Sites, api dynamic.Interface, reader client.Reader) error { + if config.Commissioning && len(sites.Devices) != 0 { + return errors.New("commissioning site cannot share synthetic enrollment") + } + sites.Sites[config.Cell] = &coordination.Hub{API: api, Namespace: "fleet-coordination", Cell: config.Cell, ProviderProject: config.ProviderProject, MaxAge: time.Minute} + sites.PhysicalCell = config.Cell + sites.Commissioning = config.Commissioning + sites.Resolve = func(ctx context.Context, device *inventory.Device) string { + return config.placement(ctx, reader, device) + } + return nil +} + +func (config *physicalSite) connect(sites *delivery.Sites, reader client.Reader) error { + hub, err := clientcmd.BuildConfigFromFlags("", config.HubKubeconfig) + if err != nil { + return err + } + if !strings.HasPrefix(hub.Host, "https://") || hub.Insecure { + return errors.New("physical hub kubeconfig requires verified HTTPS") + } + hub.Timeout = 30 * time.Second + api, err := dynamic.NewForConfig(hub) + if err != nil { + return err + } + return config.attach(sites, api, reader) +} + +func (config *physicalSite) checkScope(flags *managerFlags, provider string) error { + if flags.syntheticStaging && (provider != config.ProviderProject || flags.syntheticDeviceNamespace != config.DeviceNamespace || flags.syntheticCoordinatorCertDir != config.CoordinatorCertDir || flags.syntheticProjectorCertDir != config.ProjectorCertDir || flags.syntheticReleaseCertDir != config.ReleaseCertDir) { + return errors.New("mixed routes require one provider project, Device namespace and set of coordinator, release and projector identities") + } + return nil +} + +func (config *physicalSite) placement(ctx context.Context, reader client.Reader, device *inventory.Device) string { + if device.Namespace != config.DeviceNamespace || device.UID == "" || !device.DeletionTimestamp.IsZero() || device.Spec.ClaimRef.Name == "" { + return "" + } + get := func(name string, obj client.Object) bool { + return name != "" && reader.Get(ctx, client.ObjectKey{Namespace: device.Namespace, Name: name}, obj) == nil && obj.GetUID() != "" && obj.GetDeletionTimestamp().IsZero() + } + claim := &inventory.DeviceClaim{} + if !get(device.Spec.ClaimRef.Name, claim) { + return "" + } + claimFacility := claim.Spec.Placement.FacilityRef + var claimRack inventory.Rack + if plannedRack := claim.Spec.Placement.RackRef; plannedRack != nil { + if claimFacility != nil || !get(plannedRack.Name, &claimRack) { + return "" + } + claimFacility = &claimRack.Spec.FacilityRef + } + facilityRef, rackRef := claim.Spec.Placement.FacilityRef, claim.Spec.Placement.RackRef + if report := device.Spec.ReportedPlacement; report != nil { + facilityRef, rackRef = report.FacilityRef, report.RackRef + } + var rack inventory.Rack + if rackRef != nil { + if rackRef.Name == claimRack.Name && claimRack.UID != "" { + rack = claimRack + } else if !get(rackRef.Name, &rack) { + return "" + } + if facilityRef != nil && facilityRef.Name != rack.Spec.FacilityRef.Name { + return "" + } + facilityRef = &rack.Spec.FacilityRef + } + var facility inventory.Facility + if facilityRef == nil || claimFacility == nil || facilityRef.Name != claimFacility.Name || !get(facilityRef.Name, &facility) { + return "" + } + var list inventory.SiteList + if reader.List(ctx, &list, client.InNamespace(device.Namespace)) != nil { + return "" + } + var key string + for _, site := range list.Items { + for _, ref := range site.Spec.FacilityRefs { + if ref.Name == facility.Name { + if key != "" || site.Name != config.Site || site.UID == "" || !site.DeletionTimestamp.IsZero() { + return "" + } + key = fmt.Sprintf("%s/%s/%d/%s/%d/%s/%d/%s/%d/%s/%s/%d", config.Cell, device.UID, device.Generation, claim.UID, claim.Generation, claimRack.UID, claimRack.Generation, rack.UID, rack.Generation, facility.UID, site.UID, site.Generation) + } + } + } + return key +} diff --git a/cmd/fleet-manager/physical_test.go b/cmd/fleet-manager/physical_test.go new file mode 100644 index 00000000..1b0e1b00 --- /dev/null +++ b/cmd/fleet-manager/physical_test.go @@ -0,0 +1,267 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "sigs.k8s.io/controller-runtime/pkg/client" + crfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic/fake" + ktesting "k8s.io/client-go/testing" +) + +const exampleRoute = `providerProject: provider-example +deviceNamespace: inventory +coordinatorCertDir: /credentials/coordinator +releaseCertDir: /credentials/release +projectorCertDir: /credentials/projector +hubKubeconfig: /credentials/hub/config +cell: cell-example +site: site-example +` + +func routeFile(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "route.yaml") + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + return path +} + +type confirmedPlacementSite struct{ delivery.Site } + +func (confirmedPlacementSite) PhysicalFence(context.Context, string, types.UID) (custody.SiteFence, bool, error) { + return custody.SiteFence{}, true, nil +} + +func TestPhysicalPlacement(t *testing.T) { + route, err := readPhysicalSite(routeFile(t, exampleRoute)) + if err != nil { + t.Fatal(err) + } + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + meta := func(name string) metav1.ObjectMeta { + return metav1.ObjectMeta{Name: name, Namespace: "inventory", UID: types.UID(name)} + } + ref := func(name string) inventory.LocalReference { return inventory.LocalReference{Name: name} } + facility := &inventory.Facility{ObjectMeta: meta("facility")} + rack := &inventory.Rack{ObjectMeta: meta("rack"), Spec: inventory.RackSpec{FacilityRef: ref("facility")}} + rackRef := ref("rack") + claim := &inventory.DeviceClaim{ObjectMeta: meta("claim"), Spec: inventory.DeviceClaimSpec{Placement: inventory.Placement{RackRef: &rackRef}}} + site := &inventory.Site{ObjectMeta: meta(route.Site), Spec: inventory.SiteSpec{FacilityRefs: []inventory.LocalReference{ref("facility")}}} + device := &inventory.Device{ObjectMeta: meta("existing"), Spec: inventory.DeviceSpec{ClaimRef: ref("claim")}} + ctx := context.Background() + reader := crfake.NewClientBuilder().WithScheme(scheme).WithObjects(device, facility, claim, site, rack).Build() + api := fake.NewSimpleDynamicClient(runtime.NewScheme()) + sites := &delivery.Sites{Sites: map[string]delivery.Site{}, Devices: map[string][]string{"fixture": {syntheticSite}}} + if err := route.attach(sites, api, reader); err != nil { + t.Fatal(err) + } + for _, name := range []string{"existing", "new"} { + if name == "new" { + device.ObjectMeta = meta(name) + if err := reader.Create(ctx, device); err != nil { + t.Fatal(err) + } + } + if err := reader.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if route.placement(ctx, reader, device) == "" { + t.Fatalf("no route for %s", name) + } + if _, allowed := sites.AdmissionRoute(ctx, device, &ops.DeviceWipe{}); allowed { + t.Fatal("missing fence accepted") + } + } + other := site.DeepCopyObject().(*inventory.Site) + fixture := &inventory.Device{ObjectMeta: meta("fixture"), Spec: device.Spec} + sites.Sites[syntheticSite] = nil + serving := sites.Serving(fixture) + if len(serving) != 1 || serving[0] != syntheticSite { + t.Fatalf("fixture escaped synthetic site: %v", serving) + } + device.Spec.ReportedPlacement = &inventory.ReportedPlacement{FacilityRef: &inventory.LocalReference{Name: "different"}, RackRef: &rackRef} + if route.placement(ctx, reader, device) != "" { + t.Fatal("conflicting reported rack and facility accepted") + } + device.Spec.ReportedPlacement = nil + observedRack := &inventory.Rack{ObjectMeta: meta("reported-rack"), Spec: rack.Spec} + if err := reader.Create(ctx, observedRack); err != nil { + t.Fatal(err) + } + for _, reportedRack := range []*inventory.LocalReference{nil, {Name: observedRack.Name}} { + device.Spec.ReportedPlacement = &inventory.ReportedPlacement{FacilityRef: &inventory.LocalReference{Name: facility.Name}, RackRef: reportedRack} + sites.Sites[route.Cell] = confirmedPlacementSite{} + sites.Reader, sites.Registry = reader, &custody.Registry{} + operation := &ops.DevicePowerOperation{ObjectMeta: meta("power")} + token, ok := sites.AdmissionRoute(ctx, device, operation) + snapshot := ops.DeviceSnapshot{Extra: map[string]string{custody.PhysicalRouteKey: token, custody.PhysicalDeviceUIDKey: string(device.UID)}} + if !ok || !sites.Current(ctx, device, snapshot) { + t.Fatal("expected current admission before rack replacement") + } + if err := reader.Delete(ctx, rack); err != nil { + t.Fatal(err) + } + rack.UID += "-replacement" + rack.ResourceVersion = "" + if err := reader.Create(ctx, rack); err != nil { + t.Fatal(err) + } + if route.placement(ctx, reader, device) == "" || sites.Current(ctx, device, snapshot) { + t.Fatal("same-facility rack replacement must leave placement valid but invalidate old admission") + } + } + device.Spec.ReportedPlacement = nil + other.ObjectMeta = meta("other") + if err := reader.Create(ctx, other); err != nil { + t.Fatal(err) + } + if route.placement(ctx, reader, device) != "" { + t.Fatal("overlapping Sites accepted") + } + for _, action := range api.Actions() { + if action.GetVerb() == "create" { + obj := action.(ktesting.CreateAction).GetObject().(metav1.Object) + if !strings.HasPrefix(obj.GetName(), "fence-") { + t.Fatal("unexpected executable handoff") + } + } + } +} + +func TestCommissioningNeverFallsBackToSynthetic(t *testing.T) { + config := &physicalSite{Commissioning: true} + sites := &delivery.Sites{Devices: map[string][]string{"server": {syntheticSite}}} + if config.attach(sites, nil, nil) == nil { + t.Fatal("synthetic collision accepted") + } +} + +func TestCommissioningSiteRoutesTwoDevices(t *testing.T) { + ctx := context.Background() + route, err := readPhysicalSite(routeFile(t, exampleRoute+"commissioning: true\n")) + if err != nil { + t.Fatal(err) + } + meta := func(name string) metav1.ObjectMeta { + return metav1.ObjectMeta{Name: name, Namespace: route.DeviceNamespace, UID: types.UID(name + "-uid")} + } + facility := &inventory.Facility{ObjectMeta: meta("facility")} + facilityRef := inventory.LocalReference{Name: facility.Name} + claim := &inventory.DeviceClaim{ObjectMeta: meta("claim"), Spec: inventory.DeviceClaimSpec{Placement: inventory.Placement{FacilityRef: &facilityRef}}} + location := &inventory.Site{ObjectMeta: meta(route.Site), Spec: inventory.SiteSpec{FacilityRefs: []inventory.LocalReference{facilityRef}}} + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + otherFacility := &inventory.Facility{ObjectMeta: meta("elsewhere")} + otherRef := inventory.LocalReference{Name: otherFacility.Name} + otherClaim := &inventory.DeviceClaim{ObjectMeta: meta("other-claim"), Spec: inventory.DeviceClaimSpec{Placement: inventory.Placement{FacilityRef: &otherRef}}} + otherSite := &inventory.Site{ObjectMeta: meta("other-site"), Spec: inventory.SiteSpec{FacilityRefs: []inventory.LocalReference{otherRef}}} + if err := ops.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + reader := crfake.NewClientBuilder().WithScheme(scheme).WithObjects(facility, claim, location, otherFacility, otherSite, otherClaim).Build() + api := fake.NewSimpleDynamicClient(runtime.NewScheme()) + registry, err := custody.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + sites := &delivery.Sites{Sites: map[string]delivery.Site{}, Registry: registry, Reader: reader} + if err := route.attach(sites, api, reader); err != nil { + t.Fatal(err) + } + for _, name := range []string{"alpha", "beta"} { + device := &inventory.Device{ObjectMeta: meta(name)} + device.Spec.ClaimRef.Name = claim.Name + device.Spec.Identity.SystemUUID = "system-" + name + device.Status.Discovery = &inventory.DeviceDiscovery{TLS: &inventory.ObservedTLS{PublicKeySHA256: "pin-" + name}} + request := &ops.DeviceCommissioning{ObjectMeta: meta("request-" + name)} + request.Spec.DeviceRef.Name = name + request.Labels = map[string]string{ops.LabelDeviceUID: string(device.UID)} + check := func(want bool) { + t.Helper() + if _, ok := sites.AdmissionRoute(ctx, device, request); ok != want { + t.Fatalf("%s: route eligibility %v, want %v", name, ok, want) + } + } + check(false) + target := device.Namespace + "/" + name + report := &unstructured.Unstructured{} + report.SetAPIVersion(coordination.Resource.GroupVersion().String()) + report.SetKind(coordination.Kind) + report.SetName(coordination.ReportName(target)) + report.SetNamespace("fleet-coordination") + report.SetLabels(map[string]string{coordination.CellLabel: route.Cell, coordination.RoleLabel: coordination.RoleReport}) + report.Object["spec"] = map[string]any{"cell": route.Cell, "device": target} + now := time.Now().UTC().Format(time.RFC3339Nano) + boot := map[string]any{"target": "Pxe", "enabled": "Once", "systemUUID": device.Spec.Identity.SystemUUID, "bmcPublicKeySHA256": device.Status.Discovery.TLS.PublicKeySHA256, "observedAt": now} + obs := map[string]any{"cell": route.Cell, "providerProject": route.ProviderProject, "deviceUID": string(device.UID), "observedAt": now, "fence": map[string]any{"seen": int64(4), "stopped": int64(4)}, "commissioningBoot": boot} + report.Object["status"] = map[string]any{"reflected": []any{map[string]any{"clusterName": route.Cell, "observation": obs}}} + if _, err := api.Resource(coordination.Resource).Namespace(report.GetNamespace()).Create(ctx, report, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + check(true) + request.Spec.DeviceRef.Name = "other" + check(false) + request.Spec.DeviceRef.Name = name + request.Labels[ops.LabelDeviceUID] = "other" + check(false) + request.Labels[ops.LabelDeviceUID] = string(device.UID) + device.Status.Discovery.TLS.PublicKeySHA256 = "mismatched" + check(false) + device.Status.Discovery.TLS.PublicKeySHA256 = "pin-" + name + device.Spec.ClaimRef.Name = otherClaim.Name + check(false) + device.Spec.ClaimRef.Name = claim.Name + device.UID = "replacement" + request.Labels[ops.LabelDeviceUID] = string(device.UID) + check(false) + } +} + +func TestPhysicalConfigRejectsAmbiguousRoutes(t *testing.T) { + for _, bad := range []string{exampleRoute + "cel: elsewhere\n", exampleRoute + "cell: other\n", strings.Replace(exampleRoute, "cell-example", syntheticSite, 1), exampleRoute + "devices: {}\n", exampleRoute + "commissioningDeviceUID: old\n", exampleRoute + "commissioningDeviceName: old\n", strings.Replace(exampleRoute, "/credentials/hub/config", "''", 1)} { + if _, err := readPhysicalSite(routeFile(t, bad)); err == nil { + t.Fatal("accepted invalid config") + } + } + route, err := readPhysicalSite(routeFile(t, exampleRoute)) + if err != nil { + t.Fatal(err) + } + flags := &managerFlags{} + if err := route.checkScope(flags, ""); err != nil { + t.Fatal(err) + } + flags.syntheticStaging = true + if err := route.checkScope(flags, "other"); err == nil { + t.Fatal("mixed provider scopes accepted") + } + flags.syntheticDeviceNamespace = route.DeviceNamespace + flags.syntheticCoordinatorCertDir = route.CoordinatorCertDir + flags.syntheticProjectorCertDir = route.ProjectorCertDir + flags.syntheticReleaseCertDir = route.ReleaseCertDir + if err := route.checkScope(flags, route.ProviderProject); err != nil { + t.Fatal(err) + } +} diff --git a/cmd/fleet-manager/rbac_test.go b/cmd/fleet-manager/rbac_test.go new file mode 100644 index 00000000..afee5b83 --- /dev/null +++ b/cmd/fleet-manager/rbac_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + appsv1 "k8s.io/api/apps/v1" + rbacv1 "k8s.io/api/rbac/v1" + "sigs.k8s.io/yaml" +) + +func readManifest(t *testing.T, name string, into any) { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "config", "base", "manager", name)) + if err != nil { + t.Fatal(err) + } + if err := yaml.UnmarshalStrict(data, into); err != nil { + t.Fatalf("%s: %v", name, err) + } +} + +// TestLeaderElectionCanRecordEvents requires the manager's service account, +// in the namespace that holds its lease, to manage the lease and to create +// and patch the core Events leader election records there. +func TestLeaderElectionCanRecordEvents(t *testing.T) { + var deployment appsv1.Deployment + readManifest(t, "deployment.yaml", &deployment) + account := deployment.Spec.Template.Spec.ServiceAccountName + var namespace string + for _, arg := range deployment.Spec.Template.Spec.Containers[0].Args { + if value, ok := strings.CutPrefix(arg, "--leader-election-namespace="); ok { + namespace = value + } + } + if account == "" || namespace == "" { + t.Fatalf("service account %q, leader-election namespace %q", account, namespace) + } + + var binding rbacv1.RoleBinding + readManifest(t, "leader-election-role-binding.yaml", &binding) + var role rbacv1.Role + readManifest(t, "leader-election-role.yaml", &role) + subject := rbacv1.Subject{Kind: rbacv1.ServiceAccountKind, Name: account, Namespace: deployment.Namespace} + if binding.Namespace != namespace || binding.RoleRef.Kind != "Role" || binding.RoleRef.Name != role.Name || !slices.Contains(binding.Subjects, subject) { + t.Fatalf("binding = %+v, want %s bound to %s in %s", binding, account, role.Name, namespace) + } + if role.Namespace != namespace { + t.Fatalf("role namespace = %s, want %s", role.Namespace, namespace) + } + allows := func(group, resource, verb string) bool { + return slices.ContainsFunc(role.Rules, func(rule rbacv1.PolicyRule) bool { + return slices.Contains(rule.APIGroups, group) && slices.Contains(rule.Resources, resource) && slices.Contains(rule.Verbs, verb) && len(rule.ResourceNames) == 0 + }) + } + for _, verb := range []string{"get", "create", "update"} { + if !allows("coordination.k8s.io", "leases", verb) { + t.Errorf("the role cannot %s leases", verb) + } + } + for _, verb := range []string{"create", "patch"} { + if !allows("", "events", verb) { + t.Errorf("the role cannot %s core events", verb) + } + } +} diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go new file mode 100644 index 00000000..78aea873 --- /dev/null +++ b/cmd/fleet-manager/synthetic.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/allocation" + "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/siteapi" +) + +// syntheticSite is the synthetic provider: the simulator site. +const syntheticSite = "synthetic-provider" + +func providerCustody(ctx context.Context, scheme *runtime.Scheme, providerConfig *rest.Config, flags *managerFlags, physical *physicalSite) (*allocation.Allocator, *delivery.Loop, func(context.Context) error, error) { + namespace, coordinatorDir, releaseDir, projectorDir := flags.syntheticDeviceNamespace, flags.syntheticCoordinatorCertDir, flags.syntheticReleaseCertDir, flags.syntheticProjectorCertDir + if physical != nil { + namespace, coordinatorDir, releaseDir, projectorDir = physical.DeviceNamespace, physical.CoordinatorCertDir, physical.ReleaseCertDir, physical.ProjectorCertDir + } + coordinatorConfig, err := withClientCert(providerConfig, coordinatorDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("custody coordinator credential: %w", err) + } + releaseConfig, err := withClientCert(providerConfig, releaseDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("release controller credential: %w", err) + } + projectorConfig, err := withClientCert(providerConfig, projectorDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("capacity projector credential: %w", err) + } + clients := make([]ctrlclient.Client, 4) + for index, config := range []*rest.Config{providerConfig, coordinatorConfig, releaseConfig, projectorConfig} { + // Decisions read through to the API server, never a cache. + if clients[index], err = ctrlclient.New(config, ctrlclient.Options{Scheme: scheme}); err != nil { + return nil, nil, nil, err + } + } + provider, coordinatorClient, releaseClient, projectorClient := clients[0], clients[1], clients[2], clients[3] + providerCreator, err := allocation.Creator(ctx, providerConfig) + if err != nil { + return nil, nil, nil, fmt.Errorf("identify the Metal provider: %w", err) + } + releaseCreator, err := allocation.Creator(ctx, releaseConfig) + if err != nil { + return nil, nil, nil, fmt.Errorf("identify the release controller: %w", err) + } + registry, err := custody.DefaultRegistry() + if err != nil { + return nil, nil, nil, err + } + sites := &delivery.Sites{Registry: registry, Reader: coordinatorClient, Sites: map[string]delivery.Site{}, Devices: map[string][]string{}} + var enrollment fixture.Enrollment + if flags.syntheticStaging { + enrollment, err = readEnrollment(flags.syntheticEnrollmentFile) + if err != nil { + return nil, nil, nil, err + } + remote, err := siteapi.NewClient(flags.syntheticProviderURL, func() (string, error) { return readToken(flags.syntheticTokenFile) }, &http.Client{Timeout: 30 * time.Second}) + if err != nil { + return nil, nil, nil, err + } + sites.Sites[syntheticSite] = remote + for device := range enrollment { + deviceNamespace, name, _ := strings.Cut(device, "/") + if deviceNamespace != namespace { + return nil, nil, nil, fmt.Errorf("enrolled Device %s is outside %s", device, namespace) + } + sites.Devices[name] = []string{syntheticSite} + } + } + if physical != nil { + if err := physical.connect(sites, coordinatorClient); err != nil { + return nil, nil, nil, err + } + } + principals := custody.Principals{ + custody.CreatorMetalProvider: {{Username: providerCreator.Username, UID: providerCreator.UID}}, + custody.CreatorReleaseController: {{Username: releaseCreator.Username, UID: releaseCreator.UID}}, + } + if err := principals.Validate(); err != nil { + return nil, nil, nil, err + } + coordinator := &custody.Coordinator{Client: coordinatorClient, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals}} + log := ctrl.Log.WithName("custody") + + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: capacity.Policies(projectorClient, namespace)} + loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, Capacity: projector, + Courier: &delivery.Courier{Client: coordinatorClient, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, + OnError: func(err error) { log.Info("coordinator pass incomplete", "error", err.Error()) }} + if !flags.syntheticStaging { + return nil, loop, nil, nil + } + allocator := &allocation.Allocator{ + AllowsDevice: func(name string) bool { _, ok := enrollment[namespace+"/"+name]; return ok }, + Provider: provider, ProviderCreator: providerCreator, + Releaser: releaseClient, ReleaseCreator: releaseCreator, + Custody: coordinator, Namespace: namespace, + Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: capacity.Policies(provider, namespace)}, + // The synthetic site enrolls one boot NIC and one disk per Device. + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Sites: sites, + } + // Synthetic staging has no BMC discovery. The manager writes fixture + // discovery for the synthetic site's Devices instead. + discover := func(ctx context.Context) error { + fixture.Run(ctx, provider, enrollment, time.Minute, func(err error) { log.Info("fixture discovery incomplete", "error", err.Error()) }) + return nil + } + return allocator, loop, discover, nil +} + +// withClientCert is the Milo connection of config, the same endpoint and +// server CA, authenticated only by the client certificate in dir. The +// directory holds a cert-manager certificate Secret's tls.crt and tls.key. +// client-go rereads both files, so a renewed certificate is used without a +// restart; mount the whole Secret, never a subPath. +func withClientCert(config *rest.Config, dir string) (*rest.Config, error) { + certFile, keyFile := filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key") + if _, err := tls.LoadX509KeyPair(certFile, keyFile); err != nil { + return nil, fmt.Errorf("load the client certificate in %s: %w", dir, err) + } + copied := rest.AnonymousClientConfig(config) + copied.CertFile, copied.KeyFile = certFile, keyFile + return copied, nil +} + +func readToken(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(data)) + if token == "" || strings.ContainsAny(token, "\r\n") { + return "", errors.New("the token must be one nonempty line") + } + return token, nil +} + +func readEnrollment(path string) (fixture.Enrollment, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var enrollment fixture.Enrollment + decoder := json.NewDecoder(strings.NewReader(string(data))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&enrollment); err != nil { + return nil, err + } + if len(enrollment) == 0 { + return nil, errors.New("the synthetic site enrolls no Device") + } + return enrollment, nil +} diff --git a/cmd/fleet-member-enroll/main.go b/cmd/fleet-member-enroll/main.go new file mode 100644 index 00000000..05ca0413 --- /dev/null +++ b/cmd/fleet-member-enroll/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "flag" + "fmt" + "go.datum.net/fleet/internal/site" + "os" + "path/filepath" +) + +func main() { + ledger := flag.String("ledger", "", "site-owner ledger directory") + root := flag.String("journal", "", "retained site store") + flag.Parse() + if !filepath.IsAbs(*ledger) || !filepath.IsAbs(*root) || flag.NArg() != 0 { + flag.Usage() + os.Exit(2) + } + decision, err := site.ParseMemberDecision(os.Stdin) + if err == nil { + err = site.ConfirmMember(*ledger, *root, decision) + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go new file mode 100644 index 00000000..ffe0813e --- /dev/null +++ b/cmd/fleet-multiplane/main.go @@ -0,0 +1,351 @@ +// fleet-multiplane is an opt-in local acceptance binary. Production managers do +// not import its synthetic admission, quota or discovery fixtures. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "net/netip" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/multiplane" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +var memberProfile string + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "multi-plane command failed:", err) + os.Exit(1) + } +} + +func run() error { + if len(os.Args) < 2 { + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|media-stale|media-service|boot-denials|dhcp-feed|redfish-probe| [flags]") + } + fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) + once := fs.Bool("once", false, "one attempt, for fault injection") + handoff := fs.String("handoff", "", "exact delivered handoff name (site-worker)") + origin := fs.String("origin", "", "boot listener origin to probe, http://IPv4:port (boot-denials; required)") + interval := fs.Duration("interval", 10*time.Second, "observation refresh interval (site-observer)") + deliveryFile := fs.String("delivery-methods", "", "the site enrollment's delivery declaration, a JSON list of offers (site-observer, dhcp-feed)") + configPath := fs.String("config", "", "private acceptance config JSON") + kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") + cell := fs.String("cell", "", "exact Karmada member name") + extraMAC := fs.String("extra-mac", "", "another enrolled NIC whose boot script must be denied (boot-denials, Redfish mode)") + endpoint := fs.String("endpoint", "", "Redfish endpoint (redfish-probe)") + credentials := fs.String("credentials", "", "directory holding username and password files (redfish-probe)") + system := fs.String("system", "", "enrolled Redfish System Id (redfish-probe)") + uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") + pin := fs.String("pin", "", "the BMC's approved key digest; the probe connects only to that key (redfish-probe)") + clientID := fs.String("client-id", "", "identity the probe's requests carry as their User-Agent, so the lab BMC audit can tell them apart (redfish-probe)") + syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") + installationDeadline := fs.Duration("installation-deadline", 0, "replace the installation deadline for operations this coordinator admits (coordinator)") + skewMargin := fs.Duration("skew-margin", 0, "replace the margin after a deadline before the coordinator declares it exceeded (coordinator)") + tlsCert := fs.String("tls-cert", "", "TLS certificate the DHCP feed or media service serves (dhcp-feed, media-service)") + tlsKey := fs.String("tls-key", "", "TLS key of the DHCP feed or media service (dhcp-feed, media-service)") + deviceName := fs.String("device", "", "exact / Device (media-stale)") + listen := fs.String("listen", "127.0.0.1:18443", "listen address (media-service)") + mediaRoot := fs.String("state-dir", "", "the media service's own state directory (media-service)") + mediaArtifacts := fs.String("artifacts", "", "directory of the image's pinned artifacts (media-service)") + mediaClients := fs.String("clients", "", "comma-separated IPv4 prefixes the media service serves (media-service)") + proxyListen := fs.String("proxy-listen", "", "comma-separated addresses where report relays connect with a PROXY header (media-service)") + 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)") + if err := fs.Parse(os.Args[2:]); err != nil { + return err + } + ledger := os.Getenv("FLEET_MEMBER_LEDGER") + if memberProfile != "" && (memberProfile != "commissioning" || (os.Args[1] != "site-worker" && os.Args[1] != "site-observer") || !redfishMode() || *kubeconfig != "" || ledger == "" || *handoff == "" || *cell == "" || *cell != os.Getenv("FLEET_COMMISSIONING_CELL")) { + return errors.New("unsupported member command or enrollment") + } + switch os.Args[1] { + case "coordinator": + config, err := multiplane.ReadConfig(*configPath) + if err != nil { + return err + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + fmt.Println("coordinator: custody coordinator running") + 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", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation", "media-not-offered", "media-offered", "media-unpinned", "media-install-held", "media-install-download", "media-install-lost", "media-install": + return phase(os.Args[1], *configPath, *once) + case "redfish-probe": + return probe(*endpoint, *credentials, *system, *uuid, *pin, *clientID) + case "image": + image, err := siteImage() + if err != nil { + return err + } + fmt.Println(image) + return nil + case "boot-service", "boot-denials", "dhcp-feed": + return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey, *deliveryFile) + case "boot-withhold": + return armWithhold(fs.Arg(0)) + case "media-stale": + return mediaStale(*deviceName) + case "media-service": + config, err := multiplane.ReadConfig(*configPath) + if err != nil { + return err + } + var clients, trusted []netip.Prefix + for _, value := range strings.Split(*mediaClients, ",") { + prefix, err := netip.ParsePrefix(strings.TrimSpace(value)) + if err != nil { + return fmt.Errorf("media-service: -clients must list IPv4 prefixes") + } + clients = append(clients, prefix.Masked()) + } + for _, value := range strings.Split(*relays, ",") { + if value = strings.TrimSpace(value); value == "" { + continue + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return fmt.Errorf("media-service: -relays must list prefixes") + } + trusted = append(trusted, prefix.Masked()) + } + if *proxyListen != "" && len(trusted) == 0 { + return fmt.Errorf("media-service: -proxy-listen needs -relays") + } + if *mediaRoot == "" || *mediaArtifacts == "" || *tlsCert == "" || *tlsKey == "" || *clientCA == "" { + return fmt.Errorf("media-service needs -state-dir, -artifacts, -tls-cert, -tls-key and -client-ca") + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + fmt.Println("media-service: central media service running") + return multiplane.MediaService(ctx, config, *listen, *proxyListen, *tlsCert, *tlsKey, *clientCA, *mediaRoot, *mediaArtifacts, clients, trusted) + case "report-relay": + // Lab only: forwards the guests' report connections, naming each + // guest's address, to the media service's PROXY listener. + if *upstream == "" { + return fmt.Errorf("report-relay needs -listen and -upstream") + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + return multiplane.ReportRelay(ctx, *listen, *upstream) + case "site-worker", "site-observer": + default: + return fmt.Errorf("unknown command") + } + if *cell == "" || (os.Args[1] == "site-worker" && *handoff == "") { + return fmt.Errorf("cell and (for site-worker) handoff required") + } + cfg, err := rest.InClusterConfig() + if *kubeconfig != "" { + cfg, err = clientcmd.BuildConfigFromFlags("", *kubeconfig) + } + if err != nil { + return err + } + cfg.Timeout = 30 * time.Second + api, err := dynamic.NewForConfig(cfg) + if err != nil { + return err + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + var store *site.Store + cellView := &coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell} + if memberProfile == "commissioning" { + store, err = cellView.SelectMember(ctx, *handoff, ledger, os.Getenv("FLEET_SITE_STATE"), os.Getenv("FLEET_SITE_PROJECT"), os.Args[1] == "site-observer") + } else { + store, err = openStore() + } + if err != nil { + return err + } + if os.Args[1] == "site-observer" { + if memberProfile == "commissioning" { + cellView.ReadBoot, err = memberBootReader(cfg, cellView.Enrollment) + if err != nil { + return err + } + } + // The observer never runs work: it reports what the store holds and + // the enrollment's delivery declaration, read again on every pass. + cellView.Delivery = func() ([]custody.OfferedMethod, error) { + data, err := os.ReadFile(*deliveryFile) + if err != nil { + return nil, err + } + return custody.ParseOffered(data) + } + return cellView.Observe(ctx, *interval, store, site.NewResults(store), func(name string, err error) { + fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) + }) + } + err = runSiteWorker(ctx, cfg, cellView, *handoff, store) + fmt.Fprintf(os.Stderr, "site-worker: handoff %s: %s\n", *handoff, classify(err)) + switch { + case err == nil, errors.Is(err, site.ErrAlreadyRunning): + return nil + case errors.Is(err, site.ErrStaleFence), errors.Is(err, coordination.ErrNotDelivered): + os.Exit(exitRejected) + } + os.Exit(exitRetry) + return nil +} + +func runSiteWorker(ctx context.Context, config *rest.Config, cell *coordination.Cell, handoff string, store *site.Store) error { + return cell.WorkWithRunner(ctx, handoff, store, func() (*site.Runner, error) { + runner, err := siteRunner(ctx, config, cell.Name, store, cell.Enrollment) + if err != nil { + return nil, err + } + runner.Payloads = coordination.HandoffPayloads{API: cell.API, Namespace: cell.Namespace, Cell: cell.Name} + return runner, nil + }) +} + +// phase runs one management phase until it converges, retrying pending +// effects. +func phase(name, configPath string, once bool) error { + config, err := multiplane.ReadConfig(configPath) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + if name == "seed" { + return multiplane.Seed(ctx, config) + } + r, err := multiplane.New(ctx, config) + if err != nil { + return err + } + // The Redfish lab serves a firmware inventory; the local VM has none. + if redfishMode() { + r.PlanFirmware = multiplane.LabFirmware + } + action := map[string]func(context.Context) error{ + "commission": r.Commission, "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, + "release": r.Release, "release-b": r.ReleaseSecond, "reuse": r.Reuse, + "admit-install-b": r.AdmitInstallSecond, "recovery-mismatch": r.RecoveryMismatch, "probe-unallocatable": r.ProbeUnallocatable, "tenant-isolation": r.TenantIsolation, + "media-not-offered": r.MediaNotOffered, "media-offered": r.MediaOffered, "media-unpinned": r.MediaUnpinned, "media-install-held": r.MediaInstallHeld, "media-install-download": r.MediaInstallDownload, "media-install-lost": r.MediaInstallLost, "media-install": r.MediaInstall, + }[name] + last := "" + for { + err = action(ctx) + // Report each new reason a phase is waiting, so a phase that times + // out shows what it waited for. + if err != nil && err.Error() != last { + last = err.Error() + fmt.Printf("%s: waiting: %v\n", name, err) + } + if strings.HasPrefix(name, "admit-install") && errors.Is(err, multiplane.ErrAdmittedUnknown) { + fmt.Println("Installation admitted and delivered; its result remains Unknown") + return nil + } + if err == nil && (name == "commission" || name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation" || strings.HasPrefix(name, "media-")) { + return nil + } + if err == nil { + fmt.Println(name + ": verified local acceptance phase (synthetic authority)") + return nil + } + if once || multiplane.Terminal(err) || errors.Is(err, multiplane.ErrLocationNotServed) { + return err + } + if ctx.Err() != nil { + return fmt.Errorf("%s did not converge; last error: %w", name, err) + } + time.Sleep(3 * time.Second) + } +} + +const coordinationNamespace = "fleet-coordination" + +// redfishMode selects the Redfish workers for site roles. The site's Flux +// layers set it; there is no automatic choice between them. +func redfishMode() bool { return os.Getenv("FLEET_SITE_PROVIDER") == "redfish" } + +// probe performs read-only Redfish discovery of one enrolled System and +// prints only an outcome class. Exit codes: 0 discovered, 10 credential +// rejected, 11 capability unsupported, 12 identity mismatch, 13 TLS key +// other than the pin. +func probe(endpoint, credentials, system, uuid, pin, clientID string) error { + user, err1 := os.ReadFile(credentials + "/username") + password, err2 := os.ReadFile(credentials + "/password") + if credentials == "" || err1 != nil || err2 != nil { + return fmt.Errorf("redfish-probe: credentials unavailable") + } + c, err := redfish.NewPinnedClient(endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), pin, 20*time.Second) + if err != nil { + return err + } + if clientID != "" { + if err := c.SetUserAgent("fleet-redfish-probe/" + clientID); err != nil { + return err + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + s, err := c.Discover(ctx, redfish.Target{SystemID: system, SystemUUID: uuid}) + switch { + case err == nil: + fmt.Printf("redfish-probe: discovered %s at %s; ResetType %s; boot targets %s\n", s.ID, s.Path, strings.Join(s.ResetTypes, ","), strings.Join(s.BootTargets, ",")) + return nil + case errors.Is(err, redfish.ErrUnauthorized): + fmt.Println("redfish-probe: credential rejected; no effect issued") + os.Exit(10) + case errors.Is(err, redfish.ErrUnsupported): + fmt.Println("redfish-probe: required capability not advertised; no effect issued") + os.Exit(11) + case errors.Is(err, redfish.ErrPinMismatch): + fmt.Println("redfish-probe: the BMC's TLS key does not match the pin; no request sent") + os.Exit(13) + case errors.Is(err, redfish.ErrIdentity): + fmt.Println("redfish-probe: enrolled identity not matched exactly; no effect issued") + os.Exit(12) + } + return err +} + +// Worker exit codes are the Job podFailurePolicy contract: a handoff that is +// not this cell's, or an assignment below the Device's stored fence, fails +// the Job without retry; anything else is retried by the Job controller +// against the same assignment. Exit 0 follows a stored result, which only +// the coordinator turns into custody. +const ( + exitRejected = 65 + exitRetry = 75 +) + +// classify names an outcome without printing handoff or journal contents. +func classify(err error) string { + switch { + case err == nil: + return "result stored in the site store" + case errors.Is(err, site.ErrAlreadyRunning): + return "another worker runs this assignment" + case errors.Is(err, site.ErrStaleFence): + return "fenced: a newer operation was admitted for the Device" + case errors.Is(err, coordination.ErrNotDelivered): + return "invalid: not an assignment for this cell" + default: + return "pending: " + err.Error() + } +} diff --git a/cmd/fleet-multiplane/member_selection_test.go b/cmd/fleet-multiplane/member_selection_test.go new file mode 100644 index 00000000..9b2760ad --- /dev/null +++ b/cmd/fleet-multiplane/member_selection_test.go @@ -0,0 +1,204 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +func TestRuntimeOwnerEnrollmentTwoMemberDevices(t *testing.T) { + previous := memberProfile + memberProfile = "commissioning" + t.Cleanup(func() { memberProfile = previous }) + t.Setenv("FLEET_SITE_PROVIDER", "redfish") + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + reject := func(err error) { + t.Helper() + if err == nil { + t.Fatal("expected refusal") + } + } + ledger, root := t.TempDir(), t.TempDir() + must(os.Chmod(root, 0700)) + must(os.Chmod(ledger, 0700)) + must(os.WriteFile(filepath.Join(ledger, "confirmed.json"), []byte("[]"), 0600)) + ctx := t.Context() + api := fake.NewSimpleDynamicClient(runtime.NewScheme()) + hub := coordination.Hub{API: api, Namespace: coordinationNamespace, Cell: "site-a"} + for i := 1; i <= 2; i++ { + name := fmt.Sprintf("server-%d", i) + device := "assets/" + name + binding := site.MemberBinding{Device: device, UID: "uid-" + name, Project: "project-a", Cell: hub.Cell} + dir := filepath.Join(root, "devices", fmt.Sprintf("%x", sha256.Sum256([]byte(device)))[:32]) + must(os.MkdirAll(dir, 0700)) + journal := filepath.Join(dir, "state.json") + seed, err := json.Marshal(map[string]any{"device": device, "memberBinding": binding, "fence": 4, "stopped": 4}) + must(err) + must(os.WriteFile(journal, seed, 0600)) + entry := site.MemberEnrollment{Binding: binding, Target: redfish.Target{Device: device, Endpoint: fmt.Sprintf("https://192.0.2.%d:443", i), SystemID: "System.1", SystemUUID: fmt.Sprintf("00000000-0000-4000-8000-%012d", i)}, Pin: strings.Repeat(fmt.Sprintf("%02x", i), 32), CredentialNamespace: "credentials", CredentialUID: "secret-" + name, JournalSHA256: fmt.Sprintf("%x", sha256.Sum256(seed))} + spec := ops.DeviceRecoverySpec{OperationEnvelope: ops.OperationEnvelope{DeviceRef: ops.DeviceReference{Name: name}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "inspect"}}}, Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderNone}, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "synthetic"}} + spec.Creator.UID = "staff-id" + spec.Creator.Username = "staff" + inputs, err := json.Marshal(spec) + must(err) + digest, err := custody.SpecDigest(spec) + must(err) + now := time.Now().UTC() + assignment := site.Assignment{Device: device, Operation: ops.OperationReference{Kind: "DeviceRecovery", Name: "recover-" + name}, Fence: 5, AdmittedAt: now, Deadline: now.Add(time.Hour), Inputs: inputs, InputDigest: digest, Snapshot: ops.DeviceSnapshot{Extra: map[string]string{custody.PhysicalOperationUIDKey: "op-" + name, custody.PhysicalCustodyUIDKey: "custody-" + name, custody.PhysicalDeviceUIDKey: binding.UID, custody.PhysicalRouteKey: "route"}}} + must(hub.Deliver(ctx, assignment, nil)) + handoff := coordination.AssignmentName(assignment) + cell := coordination.Cell{API: api, Name: hub.Cell, Namespace: coordinationNamespace} + selectWork := func(project string) (*site.Store, error) { + return cell.SelectMember(ctx, handoff, ledger, root, project, false) + } + _, err = selectWork(binding.Project) + reject(err) + wrong := entry + wrong.JournalSHA256 = strings.Repeat("f", 64) + reject(site.ConfirmMember(ledger, root, wrong)) + decisionJSON, err := json.Marshal(entry) + must(err) + decision, err := site.ParseMemberDecision(strings.NewReader(string(decisionJSON))) + must(err) + outcomes := make(chan error, 2) + for range 2 { + go func() { outcomes <- site.ConfirmMember(ledger, root, decision) }() + } + must(<-outcomes) + must(<-outcomes) + wrong = entry + wrong.CredentialUID += "-replacement" + reject(site.ConfirmMember(ledger, root, wrong)) + _, err = selectWork("other-project") + reject(err) + store, err := selectWork(binding.Project) + must(err) + if cell.Enrollment.Target != entry.Target || !store.BoundTo(entry.RetainedBinding()) { + t.Fatal("incorrect selection") + } + ledgerFile := filepath.Join(ledger, "confirmed.json") + confirmed, err := os.ReadFile(ledgerFile) + must(err) + _, _, err = hub.Fence(ctx, device) + must(err) + report, err := api.Resource(coordination.Resource).Namespace(coordinationNamespace).Get(ctx, coordination.ReportName(device), metav1.GetOptions{}) + must(err) + publish := func() error { return cell.Publish(ctx, report.DeepCopy(), store, site.NewResults(store)) } + changed, err := json.Marshal([]site.MemberEnrollment{wrong}) + must(err) + for _, invalid := range [][]byte{[]byte("[]"), changed, []byte("{")} { + must(os.WriteFile(ledgerFile, invalid, 0600)) + cell.ReadBoot = func(context.Context) (*coordination.CommissioningBoot, error) { + t.Fatal("revoked observer contacted hardware") + return nil, nil + } + reject(publish()) + reject(runSiteWorker(ctx, nil, &cell, handoff, store)) + seen, stopped, err := store.Peek(device) + must(err) + if seen != 4 || stopped != 4 { + t.Fatal("revoked recovery changed fence") + } + } + must(os.WriteFile(ledgerFile, confirmed, 0600)) + must(runSiteWorker(ctx, nil, &cell, handoff, store)) + seen, stopped, err := store.Peek(device) + must(err) + if seen != 5 || stopped != 5 { + t.Fatal("recovery was not retained") + } + settled, err := os.ReadFile(journal) + must(err) + for _, change := range []string{"seen", "stopped", "digest", "decision"} { + cell.ReadBoot = func(context.Context) (*coordination.CommissioningBoot, error) { + if change == "decision" { + must(os.WriteFile(ledgerFile, changed, 0600)) + } else { + var state map[string]json.RawMessage + must(json.Unmarshal(settled, &state)) + switch change { + case "seen": + state["fence"] = json.RawMessage(`6`) + case "stopped": + state["stopped"] = json.RawMessage(`4`) + case "digest": + delete(state, "recoveryDigest") + } + data, err := json.Marshal(state) + must(err) + must(os.WriteFile(journal, data, 0600)) + } + return &coordination.CommissioningBoot{Target: "Pxe", Enabled: "Once"}, nil + } + before := len(api.Actions()) + reject(publish()) + if len(api.Actions()) != before { + t.Fatalf("published changed %s", change) + } + must(os.WriteFile(journal, settled, 0600)) + must(os.WriteFile(ledgerFile, confirmed, 0600)) + } + cell.ReadBoot = nil + must(site.ConfirmMember(ledger, root, entry)) + assignment.Operation = ops.OperationReference{Kind: "DeviceCommissioning", Name: "commission-" + name} + assignment.Fence++ + assignment.Snapshot.BMCEndpoint = entry.Target.Endpoint + assignment.Snapshot.SystemUUID = entry.Target.SystemUUID + assignment.Snapshot.BMCPublicKeySHA256 = entry.Pin + must(hub.Deliver(ctx, assignment, nil)) + handoff = coordination.AssignmentName(assignment) + _, err = selectWork(binding.Project) + must(err) + reject(cell.WorkWithRunner(ctx, handoff, store, func() (*site.Runner, error) { + must(os.WriteFile(ledgerFile, changed, 0600)) + return &site.Runner{Store: store}, nil + })) + after, err := os.ReadFile(journal) + must(err) + if !bytes.Equal(after, settled) { + t.Fatal("commissioning retained after owner decision changed") + } + must(os.WriteFile(ledgerFile, confirmed, 0600)) + for j, mutate := range []func(*site.Assignment){func(a *site.Assignment) { a.Snapshot.Extra[custody.PhysicalDeviceUIDKey] = "other" }, func(a *site.Assignment) { a.Snapshot.BMCEndpoint = "https://192.0.2.254:443" }, func(a *site.Assignment) { a.Snapshot.SystemUUID = "other" }, func(a *site.Assignment) { a.Snapshot.BMCPublicKeySHA256 = "other" }, func(a *site.Assignment) { a.Snapshot.Extra[custody.SnapshotSystemID] = "other" }} { + altered := assignment + altered.Snapshot.Extra = map[string]string{} + for key, value := range assignment.Snapshot.Extra { + altered.Snapshot.Extra[key] = value + } + altered.Operation.Name += fmt.Sprint(j) + mutate(&altered) + must(hub.Deliver(ctx, altered, nil)) + handoff = coordination.AssignmentName(altered) + _, err = selectWork(binding.Project) + reject(err) + } + defer func() { + must(os.Remove(journal)) + _, _, err = site.SelectMember(ledger, root, binding.Project, hub.Cell, device) + reject(err) + reject(site.ConfirmMember(ledger, root, entry)) + }() + } +} diff --git a/cmd/fleet-multiplane/recovery_test.go b/cmd/fleet-multiplane/recovery_test.go new file mode 100644 index 00000000..2e9968e9 --- /dev/null +++ b/cmd/fleet-multiplane/recovery_test.go @@ -0,0 +1,117 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "golang.org/x/sys/unix" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +func TestMemberWorkerResolveWithoutHardwareConfig(t *testing.T) { + oldProfile := memberProfile + memberProfile = "commissioning" + t.Cleanup(func() { memberProfile = oldProfile }) + t.Setenv("FLEET_SITE_PROVIDER", "redfish") + for _, key := range []string{"FLEET_REDFISH_ENROLLMENT", "FLEET_SITE_CREDENTIALS_NAMESPACE", "FLEET_RECEIPT_ORIGIN", "FLEET_RECEIPT_PKI", "FLEET_BOOT_EVIDENCE"} { + t.Setenv(key, "") + } + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + binding := site.MemberBinding{Device: "provider/asset", UID: "asset-id", Cell: "cell-example", Project: "provider"} + root := t.TempDir() + must(os.Chmod(root, 0700)) + sum := sha256.Sum256([]byte(binding.Device)) + dir := filepath.Join(root, "devices", fmt.Sprintf("%x", sum[:16])) + must(os.MkdirAll(dir, 0700)) + seed, err := json.Marshal(map[string]any{"device": binding.Device, "memberBinding": binding, "fence": 2, "stopped": 1}) + must(err) + must(os.WriteFile(filepath.Join(dir, "state.json"), seed, 0600)) + spec := ops.DeviceRecoverySpec{OperationEnvelope: ops.OperationEnvelope{DeviceRef: ops.DeviceReference{Name: "asset"}, Creator: ops.Creator{Username: "operator", UID: "operator-id"}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "verify imported asset"}}}, Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderNone}, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "synthetic inspection"}} + inputs, err := json.Marshal(spec) + must(err) + digest, err := custody.SpecDigest(spec) + must(err) + now := time.Now().UTC() + assignment := site.Assignment{Device: binding.Device, Operation: ops.OperationReference{Kind: "DeviceRecovery", Name: "resolve-example"}, AdmittedAt: now, Deadline: now.Add(time.Hour), Fence: 3, Inputs: inputs, InputDigest: digest, Snapshot: ops.DeviceSnapshot{Extra: map[string]string{custody.PhysicalDeviceUIDKey: binding.UID, custody.PhysicalOperationUIDKey: "operation-id", custody.PhysicalCustodyUIDKey: "custody-id", custody.PhysicalRouteKey: "route-example"}}} + ctx := t.Context() + runWorker := func(ctx context.Context, assignment site.Assignment) error { + t.Helper() + store, err := site.OpenRetainedStore(root, binding) + must(err) + api := fake.NewSimpleDynamicClient(runtime.NewScheme()) + hub := coordination.Hub{API: api, Namespace: coordinationNamespace, Cell: binding.Cell} + must(hub.Deliver(ctx, assignment, nil)) + name := coordination.AssignmentName(assignment) + cell := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: binding.Cell, Member: &binding, MemberHandoff: name} + api.ClearActions() + err = runSiteWorker(ctx, nil, &cell, name, store) + if actions := api.Actions(); len(actions) != 1 || !actions[0].Matches("get", coordination.Resource.Resource) { + t.Fatalf("unexpected worker API actions: %v", actions) + } + return err + } + checkProof := func(seen, stopped int64, digest string) { + t.Helper() + store, err := site.OpenRetainedStore(root, binding) + must(err) + report, err := store.PeekFence(binding.Device) + must(err) + if report.Seen != seen || report.Stopped != stopped || report.RecoveryDigest != digest { + t.Fatalf("incorrect retained fence: %+v", report) + } + journal, err := store.Journal(binding.Device) + must(err) + _, found, err := site.NewResults(store).Get(binding.Device, assignment.Operation, assignment.Fence) + must(err) + if len(journal) != 0 || found { + t.Fatal("recovery produced provider steps or an operation result") + } + } + wrong := assignment + wrong.InputDigest = "wrong-digest" + if err := runWorker(ctx, wrong); !errors.Is(err, coordination.ErrNotDelivered) { + t.Fatalf("altered Resolve inputs: %v", err) + } + checkProof(2, 1, "") + older, err := os.OpenFile(filepath.Join(dir, "run.lock"), os.O_CREATE|os.O_RDWR, 0600) + must(err) + defer older.Close() + must(unix.Flock(int(older.Fd()), unix.LOCK_EX)) + wait, cancel := context.WithTimeout(ctx, 250*time.Millisecond) + err = runWorker(wait, assignment) + cancel() + if err == nil { + t.Fatal("reported a stop while an older worker held the lock") + } + checkProof(3, 1, "") + must(unix.Flock(int(older.Fd()), unix.LOCK_UN)) + must(runWorker(ctx, assignment)) + must(runWorker(ctx, assignment)) + proof, err := assignment.Digest() + must(err) + checkProof(3, 3, proof) + assignment.Snapshot.Extra[custody.PhysicalOperationUIDKey] = "replacement-id" + if err := runWorker(ctx, assignment); err == nil { + t.Fatal("reused stopped proof for a different operation UID") + } + checkProof(3, 3, proof) +} diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go new file mode 100644 index 00000000..0d7c8944 --- /dev/null +++ b/cmd/fleet-multiplane/site.go @@ -0,0 +1,457 @@ +package main + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/netip" + "os" + "path/filepath" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/powerwork" + "go.datum.net/fleet/internal/site/redfishwork" + "go.datum.net/fleet/internal/site/vmwork" +) + +func memberBootReader(config *rest.Config, entry *site.MemberEnrollment) (func(context.Context) (*coordination.CommissioningBoot, error), error) { + target, binding := entry.Target, entry.Binding + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + return nil, err + } + reader, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return nil, err + } + credentials := site.SecretCredentials{Approved: entry, Reader: reader, Namespace: entry.CredentialNamespace, Project: binding.Project} + if credentials.Namespace == "" { + return nil, errors.New("credential namespace required") + } + return func(ctx context.Context) (*coordination.CommissioningBoot, error) { + cred, found, err := credentials.Lookup(ctx, binding.Device) + if err != nil || !found { + return nil, errors.New("device credential unavailable") + } + pin, err := redfish.ParsePin(cred.Pin) + if err != nil { + return nil, err + } + bmc, err := redfish.NewPinnedClientVia(target.Endpoint, cred.Username, cred.Password, pin, 5*time.Second, entry.TCPGateway) + if err != nil { + return nil, err + } + at := time.Now().UTC() + system, err := bmc.Identify(ctx, target) + if err != nil { + return nil, err + } + if !system.ExplicitPXEOnce() { + return nil, errors.New("no explicit Pxe/Once capability") + } + return &coordination.CommissioningBoot{Target: "Pxe", Enabled: "Once", SystemUUID: system.UUID, Pin: pin, ObservedAt: at}, nil + }, nil +} + +// The site's retained volume: the site store, the local VM disks, and the +// installer artifacts baked into the site image. +const ( + defaultStore = "/var/lib/fleet-local/site" + vmDisks = "/var/lib/fleet-local/vm" + artifacts = "/opt/fleet-local/artifacts" + // libvirtSocketDir is where a local VM site mounts the hypervisor. A + // Redfish site must not have it. + libvirtSocketDir = "/run/fleet-libvirt" +) + +// openStore opens the site store, creating its owner-only root once. A +// read-only role, such as the boot server, finds it existing. +func openStore() (*site.Store, error) { + root := os.Getenv("FLEET_SITE_STATE") + if root == "" { + root = defaultStore + } + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return nil, errors.New("FLEET_SITE_STATE must be a clean absolute path") + } + if _, err := os.Stat(root); os.IsNotExist(err) { + if err := os.MkdirAll(root, 0o700); err != nil { + return nil, err + } + } + return site.OpenStore(root, nil) +} + +func siteImage() (string, error) { return redfish.VerifyArtifacts(artifacts) } + +func bootRoot() (string, error) { + root := os.Getenv("FLEET_BOOT_EVIDENCE") + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return "", errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + return root, nil +} + +// vmBootConfig is what the local VM boot server needs: the artifacts it +// serves, the image they are, and where it records deliveries. +func vmBootConfig() (vmwork.Config, error) { + if os.Getenv("FLEET_LOCAL_VM") != "disposable-container" { + return vmwork.Config{}, errors.New("the local VM site requires its disposable container") + } + image, err := siteImage() + if err != nil { + return vmwork.Config{}, err + } + origin, err := redfish.ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return vmwork.Config{}, err + } + boot, err := bootRoot() + if err != nil { + return vmwork.Config{}, err + } + return vmwork.Config{Artifacts: artifacts, Image: image, Disks: vmDisks, BootRoot: boot, BootOrigin: origin, PXE: true}, nil +} + +// vmConfig is the local VM worker's configuration from its environment: +// the boot configuration, the hypervisor, and the site's enrollment. +func vmConfig() (vmwork.Config, fixture.Enrollment, error) { + config, err := vmBootConfig() + if err != nil { + return vmwork.Config{}, nil, err + } + accelerator := os.Getenv("FLEET_LOCAL_VM_ACCEL") + switch accelerator { + case "": + accelerator = "kvm" + case "kvm", "tcg": + default: + return vmwork.Config{}, nil, errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") + } + 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() + if err := decoder.Decode(&enrollment); err != nil || len(enrollment) == 0 { + return vmwork.Config{}, nil, errors.New("FLEET_SITE_ENROLLMENT must enroll the site's Devices") + } + config.Accelerator, config.URI = accelerator, uri + 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. +func redfishBootServer(store *site.Store) (redfishwork.BootServer, error) { + boot, err := bootRoot() + if err != nil { + return redfishwork.BootServer{}, err + } + origin, err := redfish.ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return redfishwork.BootServer{}, err + } + image, err := siteImage() + if err != nil { + return redfishwork.BootServer{}, err + } + return redfishwork.BootServer{Store: store, Origin: origin, Artifacts: artifacts, Image: image, BootRoot: boot}, nil +} + +// redfishConfig is the Redfish worker's configuration from its environment. +// A Redfish site has no hypervisor fallback. +func redfishConfig(entry *site.MemberEnrollment) (redfishwork.Config, redfish.Enrollment, error) { + if os.Getenv("FLEET_LIBVIRT_URI") != "" { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("a Redfish site refuses a libvirt URI") + } + if _, err := os.Stat(libvirtSocketDir); err == nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("a Redfish site refuses a mounted libvirt socket") + } + enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if memberProfile == "commissioning" { + if entry == nil || len(enrollment.Targets) != 0 { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("commissioning needs owner enrollment and target-free site DHCP configuration") + } + enrollment.Targets = []redfish.Target{entry.Target} + } + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, err + } + console := os.Getenv("FLEET_REDFISH_CONSOLE") + if memberProfile != "commissioning" && !filepath.IsAbs(console) { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") + } + boot, err := bootRoot() + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, err + } + work := redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced, DHCPInstances: enrollment.DHCPInstances, Artifacts: artifacts} + // The site's trust for the central media service: its certificate in + // PEM, base64 encoded. A site without it cannot use virtual media. + if value := os.Getenv("FLEET_MEDIA_CA"); value != "" { + ca, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_CA must be a base64 PEM certificate") + } + work.MediaCA = ca + } + // Where the media service sees this site's installed servers report + // from: IPv4 or IPv6 prefixes, comma separated. + for _, value := range strings.Split(os.Getenv("FLEET_MEDIA_REPORT_FROM"), ",") { + if value = strings.TrimSpace(value); value == "" { + continue + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_REPORT_FROM must list address prefixes") + } + work.ReportFrom = append(work.ReportFrom, prefix.Masked()) + } + // How this site's installed servers reach the media service, when not + // at its recorded endpoint. + if value := os.Getenv("FLEET_MEDIA_REPORT_ORIGIN"); value != "" { + origin, err := redfish.ParseEndpoint(value) + if err != nil || !strings.HasPrefix(origin, "https://") { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_REPORT_ORIGIN must be https://IP:port") + } + work.ReportOrigin = origin + } + return work, enrollment, nil +} + +// siteRunner is the site runner for this cell's mode. A Redfish worker reads +// each Device's own BMC credential Secret, never a shared credential. +func siteRunner(_ context.Context, config *rest.Config, cell string, store *site.Store, entry *site.MemberEnrollment) (*site.Runner, error) { + runner := &site.Runner{Site: cell, Store: store, Results: site.NewResults(store)} + if !redfishMode() { + vm, enrollment, err := vmConfig() + if err != nil { + return nil, err + } + runner.Access = fixture.Access{Enrollment: enrollment} + runner.Kinds = map[string]site.Kind{"DeviceInstallation": vmwork.Installation{Config: vm}, "DeviceWipe": vmwork.Wipe{Config: vm}, "DeviceCommissioning": vmwork.Commissioning{Config: vm}} + return runner, nil + } + work, enrollment, err := redfishConfig(entry) + if err != nil { + return nil, err + } + if memberProfile == "commissioning" { + target, found := enrollment.Target(entry.Binding.Device) + if !found || len(enrollment.Targets) != 1 || !strings.HasPrefix(target.Endpoint, "https://") { + return nil, errors.New("physical commissioning requires one enrolled HTTPS target") + } + work.BurnInReceipt, err = redfishwork.OpenReceiptReader(os.Getenv("FLEET_RECEIPT_ORIGIN"), os.Getenv("FLEET_RECEIPT_PKI")) + if err != nil { + return nil, err + } + } + namespace, project := os.Getenv("FLEET_SITE_CREDENTIALS_NAMESPACE"), os.Getenv("FLEET_SITE_PROJECT") + if entry != nil { + namespace, project = entry.CredentialNamespace, entry.Binding.Project + } + if namespace == "" || project == "" { + return nil, errors.New("FLEET_SITE_CREDENTIALS_NAMESPACE and FLEET_SITE_PROJECT name the per-Device credential Secrets") + } + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + return nil, err + } + reader, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return nil, err + } + targets := site.StaticTargets{} + for _, target := range enrollment.Targets { + targets[target.Device] = target + } + access := site.RedfishAccess{Credentials: site.SecretCredentials{Approved: entry, Reader: reader, Namespace: namespace, Project: project}, Targets: targets} + if memberProfile == "commissioning" { + access.CommissioningDevice = entry.Binding.Device + access.Dial = func(endpoint, username, password, pin string) (*redfish.Client, error) { + return redfish.NewPinnedClientVia(endpoint, username, password, pin, 30*time.Second, entry.TCPGateway) + } + } + // The site worker's media service identity is its own Secret, read under + // a grant of its own, never part of a Device's BMC credential. + if identity := os.Getenv("FLEET_SITE_WORKER_IDENTITY_NAMESPACE"); identity != "" { + access.MediaIdentity = site.SecretWorkerIdentity{Reader: reader, Namespace: identity} + } + runner.Access = access + // The site serves one boot image, which also burns in. + image, err := siteImage() + if err != nil { + return nil, err + } + _, burnIn, _ := strings.Cut(image, "@") + runner.Kinds = redfishKinds(work, burnIn) + if memberProfile == "commissioning" { + runner.Kinds = map[string]site.Kind{"DeviceCommissioning": runner.Kinds["DeviceCommissioning"]} + } + return runner, nil +} + +// redfishKinds are the workers a Redfish site runs. Power runs only over +// Redfish: the local VM site has no BMC, so it refuses a power operation as +// an unsupported kind with nothing sent. +func redfishKinds(work redfishwork.Config, burnIn string) map[string]site.Kind { + return map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work}, + "DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn}, + "DevicePowerOperation": powerwork.Power{}} +} + +// boot serves network boots, the DHCP reservation feed, or probes that +// every closed admission is denied. +func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey, deliveryFile string) error { + store, err := openStore() + if err != nil { + return err + } + if command == "boot-denials" { + // The probe needs only the store's admissions and the listener it + // probes, given explicitly; it reads no boot server configuration. + origin, err := redfish.ParseBootOrigin(origin) + if err != nil { + return err + } + var summary string + if redfishMode() { + var extra []string + if extraMAC != "" { + extra = append(extra, extraMAC) + } + summary, err = redfishwork.BootServer{Store: store}.CheckClosedBoot(origin, extra) + } else { + summary, err = vmwork.Config{}.CheckClosedBoot(store, origin) + } + if err != nil { + return err + } + fmt.Println(summary) + return nil + } + if redfishMode() && command == "dhcp-feed" { + // Reservations come from the admitted operations in the store, and + // reports go beside the boot evidence. The feed serves no boot + // artifacts, so it needs no boot origin or installer image. It reads + // the workers' enrollment for one thing: the expected DHCP instances, + // the only ones it serves and takes reports from. + root, err := bootRoot() + if err != nil { + return err + } + declaration, err := os.ReadFile(deliveryFile) + if err != nil { + return fmt.Errorf("the site enrollment's delivery declaration: %w", err) + } + enrollment, err := feedEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT")), declaration) + if err != nil { + return err + } + token, err := os.ReadFile(syncToken) + if err != nil { + return fmt.Errorf("DHCP synchronizer token: %w", err) + } + return redfishwork.BootServer{Store: store, BootRoot: root, DHCPInstances: enrollment.DHCPInstances}.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) + } + if redfishMode() { + server, err := redfishBootServer(store) + if err != nil { + return err + } + return serveBoot(server.Handler(), vmwork.DefaultBootWindow*2) + } + if command == "dhcp-feed" { + return errors.New("the DHCP reservation feed serves only a Redfish site") + } + vm, err := vmBootConfig() + if err != nil { + return err + } + // Emulated firmware takes minutes to fetch the installer. + return serveBoot(vm.BootHandler(store), vmwork.DefaultBootWindow) +} + +// feedEnrollment is the enrollment the DHCP reservation feed serves. Only a +// site whose enrollment has synced DHCP and declares network boot has a +// feed. The defaults, static DHCP and no declaration, leave DHCP to the site +// and start no feed, and a site that declares only virtual media never +// network-boots, so it starts none either. +func feedEnrollment(raw, declaration []byte) (redfish.Enrollment, error) { + enrollment, err := redfish.ParseEnrollment(raw) + if err != nil { + return redfish.Enrollment{}, err + } + if enrollment.DHCP != redfish.DHCPSynced { + return redfish.Enrollment{}, errors.New("the DHCP reservation feed serves only a site whose enrollment has synced DHCP") + } + offered, err := custody.ParseOffered(declaration) + if err != nil { + return redfish.Enrollment{}, fmt.Errorf("the site enrollment's delivery declaration: %w", err) + } + if !custody.NetworkBootOffered(offered) { + return redfish.Enrollment{}, errors.New("the DHCP reservation feed serves only a site whose enrollment declares network boot") + } + return enrollment, nil +} + +// mediaStale probes the site store for a delayed worker: below the Device's +// stored fence it can neither open a media window nor journal a media step. +// Both attempts are refused, so the probe writes nothing. +func mediaStale(device string) error { + store, err := openStore() + if err != nil { + return err + } + fence, _, err := store.Peek(device) + if err != nil { + return err + } + if fence < 2 { + return fmt.Errorf("media-stale: the Device has no fence above the first") + } + stale := fence - 1 + if err := store.PutRecord(device, stale, "media", "stale-probe", map[string]any{"operation": "stale-probe", "fence": stale}); !errors.Is(err, site.ErrStaleFence) { + return fmt.Errorf("media-stale: a media window at fence %d was not refused: %v", stale, err) + } + if _, _, err := store.IntendWithPayload(device, stale, "stale-probe", "media-insert-boot", nil); !errors.Is(err, site.ErrStaleFence) { + return fmt.Errorf("media-stale: a media step at fence %d was not refused: %v", stale, err) + } + fmt.Printf("PASS at stored fence %d, a worker at fence %d was refused a media window and the media-insert-boot step\n", fence, stale) + return nil +} diff --git a/cmd/fleet-multiplane/site_test.go b/cmd/fleet-multiplane/site_test.go new file mode 100644 index 00000000..4b0b0ff9 --- /dev/null +++ b/cmd/fleet-multiplane/site_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "go.datum.net/fleet/internal/site/powerwork" + "go.datum.net/fleet/internal/site/redfishwork" +) + +// 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) + } +} + +// TestARedfishSiteRunsPowerOperations requires the Redfish site's worker kinds, +// which siteRunner installs, to include power beside the install, wipe and +// commissioning workers. siteRunner itself reads the site image's artifacts, +// so the multi-plane Redfish run covers that it uses them. +func TestARedfishSiteRunsPowerOperations(t *testing.T) { + kinds := redfishKinds(redfishwork.Config{}, "sha256:"+strings.Repeat("0", 64)) + if _, ok := kinds["DevicePowerOperation"].(powerwork.Power); !ok { + t.Fatalf("kinds = %v", kinds) + } + for _, kind := range []string{"DeviceInstallation", "DeviceWipe", "DeviceCommissioning"} { + if kinds[kind] == nil { + t.Fatalf("%s is not registered", kind) + } + } +} + +// syntheticEnrollment is a one-target site enrollment with the given DHCP +// fields. +func syntheticEnrollment(dhcp string) []byte { + return []byte(`{` + dhcp + `"targets":[{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1",` + + `"systemUUID":"00000000-0000-4000-8000-000000000001","diskBytes":2147483648,"console":"server-example-001.log"}]}`) +} + +// TestTheDHCPFeedStartsOnlyForSyncedDHCP refuses to start the reservation +// feed for an enrollment that leaves DHCP to the site, or names no DHCP +// mode. +func TestTheDHCPFeedStartsOnlyForSyncedDHCP(t *testing.T) { + networkBoot := []byte(`[{"method":"NetworkBoot"}]`) + if _, err := feedEnrollment(syntheticEnrollment(`"dhcp":"static",`), networkBoot); err == nil || !strings.Contains(err.Error(), "synced DHCP") { + t.Errorf("static DHCP: the feed started: %v", err) + } + if _, err := feedEnrollment(syntheticEnrollment(``), networkBoot); err == nil { + t.Error("no DHCP mode: the feed started") + } + enrollment, err := feedEnrollment(syntheticEnrollment(synced), networkBoot) + if err != nil || len(enrollment.DHCPInstances) != 1 { + t.Fatalf("synced DHCP: %+v, %v", enrollment, err) + } +} + +// synced is the DHCP fields of a synced enrollment with one instance. +const synced = `"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0"],` + +// TestTheDHCPFeedStartsOnlyWhereTheEnrollmentDeclaresNetworkBoot refuses +// to start the feed, even with synced DHCP, for a site whose enrollment +// declares only virtual media, declares nothing, or names no valid +// declaration. +func TestTheDHCPFeedStartsOnlyWhereTheEnrollmentDeclaresNetworkBoot(t *testing.T) { + for name, declaration := range map[string]string{ + "only virtual media": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443"}]`, + "nothing": `[]`, + "no declaration": ``, + "not a declaration": `{"method":"NetworkBoot"}`, + } { + if _, err := feedEnrollment(syntheticEnrollment(synced), []byte(declaration)); err == nil { + t.Errorf("%s: the feed started", name) + } + } + for name, declaration := range map[string]string{ + "network boot": `[{"method":"NetworkBoot"}]`, + "virtual media then network boot": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443"},{"method":"NetworkBoot"}]`, + } { + if _, err := feedEnrollment(syntheticEnrollment(synced), []byte(declaration)); err != nil { + t.Errorf("%s: the feed did not start: %v", name, err) + } + } +} diff --git a/cmd/fleet-multiplane/withhold.go b/cmd/fleet-multiplane/withhold.go new file mode 100644 index 00000000..0d4a7428 --- /dev/null +++ b/cmd/fleet-multiplane/withhold.go @@ -0,0 +1,83 @@ +package main + +import ( + "errors" + "fmt" + "net/http" + "os" + "strings" + "time" +) + +// labWithholdEnv names the lab-only fault hook's arm file. Only the local +// multi-plane site's Flux source (config/site) sets it, on the boot service; +// no production root may reference that source. The hook lives in this +// acceptance binary, so no production binary contains it. +const labWithholdEnv = "FLEET_LAB_BOOT_WITHHOLD" + +// withhold denies every boot request while the arm file exists, so an +// admitted installation's firmware never receives its installer and the +// worker waits for a receipt until its deadline. The listener stays up, so +// the boot service stays Ready and kro still creates workers. It records no +// delivery evidence for a withheld request, but counts each denial in a file +// beside the arm file, so the lab can prove the hook withheld a boot. +// Without the variable it returns the handler unchanged. +func withhold(next http.Handler) http.Handler { + path := os.Getenv(labWithholdEnv) + if path == "" { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + if _, err := os.Stat(path); err == nil { + // The count is evidence only; a failed write still denies. + if f, err := os.OpenFile(path+deniedSuffix, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600); err == nil { + _, _ = f.WriteString("denied\n") + _ = f.Close() + } + w.Header().Set("Cache-Control", "no-store") + http.Error(w, "boot denied", http.StatusForbidden) + return + } + next.ServeHTTP(w, request) + }) +} + +// deniedSuffix names the file beside the arm file that counts denials. +const deniedSuffix = ".denied" + +// armWithhold creates or removes the arm file, and reports how many boots +// the hook denied since it was last armed. It runs in the boot service's +// container, through the cell API. +func armWithhold(action string) error { + path := os.Getenv(labWithholdEnv) + if path == "" { + return errors.New("the lab boot withhold hook is not configured") + } + switch action { + case "arm": + if err := os.Remove(path + deniedSuffix); err != nil && !os.IsNotExist(err) { + return err + } + return os.WriteFile(path, nil, 0o600) + case "denied": + data, err := os.ReadFile(path + deniedSuffix) + if err != nil && !os.IsNotExist(err) { + return err + } + fmt.Println(strings.Count(string(data), "\n")) + return nil + case "clear": + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + return errors.New("boot-withhold takes arm, clear or denied") +} + +// serveBoot listens on :8080 with the same bounds as the site's boot +// servers. The write bound covers emulated firmware fetching the initrd. +func serveBoot(handler http.Handler, window time.Duration) error { + server := &http.Server{Addr: ":8080", Handler: withhold(handler), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} + return server.ListenAndServe() +} diff --git a/cmd/fleet-multiplane/withhold_test.go b/cmd/fleet-multiplane/withhold_test.go new file mode 100644 index 00000000..cf6e9c83 --- /dev/null +++ b/cmd/fleet-multiplane/withhold_test.go @@ -0,0 +1,196 @@ +package main + +import ( + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func served(t *testing.T, handler http.Handler, path string) int { + t.Helper() + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + return recorder.Code +} + +var ok = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + +func TestWithholdIsOffWithoutTheLabVariable(t *testing.T) { + t.Setenv(labWithholdEnv, "") + if err := armWithhold("arm"); err == nil { + t.Fatal("the hook armed without its lab variable") + } + if code := served(t, withhold(ok), "/pxe/52-54-00-77-01-0a/boot.ipxe"); code != http.StatusOK { + t.Fatalf("an unconfigured hook changed the response: %d", code) + } +} + +func TestAnArmedWithholdDeniesEveryBootRequest(t *testing.T) { + path := filepath.Join(t.TempDir(), "withhold") + t.Setenv(labWithholdEnv, path) + handler := withhold(ok) + paths := []string{"/pxe/boot.ipxe", "/pxe/52-54-00-77-01-0a/boot.ipxe", "/0123456789abcdef/token/kernel", "/0123456789abcdef/token/installer.gz"} + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusOK { + t.Fatalf("an unarmed hook denied %s: %d", p, code) + } + } + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusForbidden { + t.Fatalf("an armed hook served %s: %d", p, code) + } + } + if data, err := os.ReadFile(path + deniedSuffix); err != nil || strings.Count(string(data), "\n") != len(paths) { + t.Fatalf("denials counted = %q, %v, want %d", data, err, len(paths)) + } + // Arming again starts a new count. + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path + deniedSuffix); !os.IsNotExist(err) { + t.Fatalf("arming kept the earlier count: %v", err) + } + if err := armWithhold("clear"); err != nil { + t.Fatal(err) + } + if err := armWithhold("clear"); err != nil { + t.Fatalf("clearing a cleared hook: %v", err) + } + if code := served(t, handler, paths[1]); code != http.StatusOK { + t.Fatalf("a cleared hook still denies: %d", code) + } +} + +// TestOnlyTheLabSiteSourceSetsTheWithholdHook keeps the hook out of +// production. The primary control is the binary: only this acceptance +// binary reads the variable, and no production image runs it. The test adds +// that only the boot service of the local multi-plane site's Flux source +// sets the variable, that no other configuration includes or points a Flux +// path at that source, and that no other package names the variable. +func TestOnlyTheLabSiteSourceSetsTheWithholdHook(t *testing.T) { + root := filepath.Join("..", "..") + var setters []string + err := filepath.WalkDir(filepath.Join(root, "config"), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + text := string(data) + if strings.Contains(text, labWithholdEnv) { + setters = append(setters, rel) + } + lab := strings.HasPrefix(rel, filepath.Join("config", "site")+string(filepath.Separator)) || strings.HasPrefix(rel, filepath.Join("config", "multiplane")+string(filepath.Separator)) + if !lab && filepath.Ext(path) != ".md" && strings.Contains(text, "config/site") { + t.Errorf("%s points at the lab site source", rel) + } + if !lab && filepath.Base(path) == "kustomization.yaml" { + for _, line := range strings.Split(text, "\n") { + entry := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "- ")) + if strings.HasPrefix(entry, "#") { + continue + } + if strings.Contains(entry, "/site") && !strings.Contains(entry, "/site-") || strings.Contains(entry, "multiplane") { + t.Errorf("%s references the lab site source: %s", rel, entry) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + want := filepath.Join("config", "site", "services", "services.yaml") + if len(setters) != 1 || setters[0] != want { + t.Fatalf("the hook is set in %v, want only %s", setters, want) + } + services, err := os.ReadFile(filepath.Join(root, want)) + if err != nil { + t.Fatal(err) + } + boot := strings.Index(string(services), "kind: Deployment\nmetadata:\n name: fleet-site-boot\n") + next := strings.Index(string(services)[boot+1:], "\n---") + if boot < 0 || next < 0 || !strings.Contains(string(services)[boot:boot+1+next], labWithholdEnv) { + t.Fatal("the hook is set outside the boot service's Deployment") + } + for _, dir := range []string{"internal", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, dir), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || filepath.Dir(path) == "." { + return err + } + if abs, _ := filepath.Abs(filepath.Dir(path)); abs == mustAbs(t, ".") { + return nil + } + data, err := os.ReadFile(path) + if err == nil && strings.Contains(string(data), labWithholdEnv) { + t.Errorf("%s names the lab hook", path) + } + return err + }) + if err != nil { + t.Fatal(err) + } + } +} + +func mustAbs(t *testing.T, path string) string { + t.Helper() + abs, err := filepath.Abs(path) + if err != nil { + t.Fatal(err) + } + return abs +} + +// TestNothingElseInTheRepositorySetsTheWithholdHook scans every tracked +// kind of file outside the docs: only this package, the lab boot service's +// one env entry, and the lab steps that arm and clear it may name the hook. +func TestNothingElseInTheRepositorySetsTheWithholdHook(t *testing.T) { + root := mustAbs(t, filepath.Join("..", "..")) + allowed := map[string]int{ + filepath.Join("config", "site", "services", "services.yaml"): 1, + filepath.Join("hack", "multiplane", "steps.sh"): -1, + } + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + if entry.IsDir() { + switch rel { + case ".git", "docs", filepath.Join("cmd", "fleet-multiplane"): + return filepath.SkipDir + } + return nil + } + if strings.HasSuffix(rel, ".md") { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + count := strings.Count(string(data), labWithholdEnv) + want, ok := allowed[rel] + switch { + case !ok && (count > 0 || strings.Contains(string(data), "boot-withhold")): + t.Errorf("%s names the lab boot hook", rel) + case ok && want >= 0 && count != want: + t.Errorf("%s sets the lab boot hook %d times, want %d", rel, count, want) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go new file mode 100644 index 00000000..96dc479b --- /dev/null +++ b/cmd/fleet-registration/main.go @@ -0,0 +1,144 @@ +package main + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "flag" + "fmt" + "net/http" + "os" + "slices" + "sort" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/projectdiscovery" + "go.datum.net/fleet/internal/registration" + resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody/creatorwebhook" + "go.datum.net/fleet/internal/powerwebhook" +) + +func main() { + var configFile, providers, powerWriter, cert, key, clientCA, clients, projectors string + flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") + flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider scope searched for duplicate hardware identity") + flag.StringVar(&powerWriter, "machine-power-writer", "", "username of the manager's Milo identity, the only writer of Machine status.power; empty refuses every power change") + flag.StringVar(&cert, "tls-cert", "/etc/fleet/registration/tls.crt", "serving certificate") + flag.StringVar(&key, "tls-key", "/etc/fleet/registration/tls.key", "serving key") + flag.StringVar(&clientCA, "client-ca", "/etc/fleet/registration/client-ca.crt", "CA dedicated to trusted API-server webhook clients") + flag.StringVar(&clients, "client-identities", "", "required comma-separated subjects of the API-server webhook client certificates; any other certificate is refused") + flag.StringVar(&projectors, "capacity-projectors", "", "comma-separated usernames of the capacity projector, the only writer of registered capacity status") + flag.Parse() + if err := run(ctrl.SetupSignalHandler(), configFile, providers, powerWriter, cert, key, clientCA, list(clients), list(projectors)); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(ctx context.Context, configFile, providers, powerWriter, cert, key, clientCA string, clients, projectors []string) error { + config, err := projectdiscovery.LoadConfig(configFile) + if err != nil { + return err + } + projects, err := providerScope(providers) + if err != nil { + return err + } + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { + if err := add(scheme); err != nil { + return err + } + } + rootConfig, err := clientcmd.BuildConfigFromFlags("", config.Discovery.DiscoveryKubeconfigPath) + if err != nil { + return err + } + root, err := client.New(rootConfig, client.Options{Scheme: scheme}) + if err != nil { + return err + } + template := rootConfig + if config.Discovery.ProjectKubeconfigPath != "" { + template, err = clientcmd.BuildConfigFromFlags("", config.Discovery.ProjectKubeconfigPath) + if err != nil { + return err + } + } + handler := registration.NewHandler(config.AuthorityID, projects, root, template, scheme) + handler.Projectors = projectors + tlsConfig, err := webhookTLS(clientCA, clients) + if err != nil { + return err + } + server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(&creatorwebhook.Handler{Projects: projects, Resources: creatorwebhook.Resources}, &powerwebhook.Handler{Writer: powerWriter}), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} + go func() { + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) + }() + err = server.ListenAndServeTLS(cert, key) + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err +} + +func providerScope(providers string) ([]string, error) { + projects := strings.Split(providers, ",") + sort.Strings(projects) + for index, name := range projects { + if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { + return nil, errors.New("a nonempty, unique provider scope is required") + } + } + return projects, nil +} + +func list(value string) []string { + var out []string + for _, item := range strings.Split(value, ",") { + if item = strings.TrimSpace(item); item != "" { + out = append(out, item) + } + } + return out +} + +// webhookTLS accepts only clients whose certificate chains to the dedicated +// client CA and whose subject common name is one of the configured API +// server identities. Any other certificate is refused during the handshake, +// before a request is read. +func webhookTLS(clientCA string, identities []string) (*tls.Config, error) { + if len(identities) == 0 { + return nil, errors.New("--client-identities must name the API-server webhook clients") + } + caBytes, err := os.ReadFile(clientCA) + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caBytes) { + return nil, errors.New("API-server client CA is invalid") + } + return &tls.Config{MinVersion: tls.VersionTLS13, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool, + VerifyConnection: func(state tls.ConnectionState) error { + if len(state.PeerCertificates) == 0 || !slices.Contains(identities, state.PeerCertificates[0].Subject.CommonName) { + return errors.New("the client certificate is not a configured API-server webhook client") + } + return nil + }}, nil +} diff --git a/cmd/fleet-registration/main_test.go b/cmd/fleet-registration/main_test.go new file mode 100644 index 00000000..668aae19 --- /dev/null +++ b/cmd/fleet-registration/main_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "io" + "log" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" +) + +func TestWebhookRequiresTrustedAPIServerClient(t *testing.T) { + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + issuer := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "synthetic-api-server-ca"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + ca, err := x509.CreateCertificate(rand.Reader, issuer, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "synthetic-api-server"}, NotBefore: issuer.NotBefore, NotAfter: issuer.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + certificate, err := x509.CreateCertificate(rand.Reader, leaf, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "client-ca.crt") + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca}), 0600); err != nil { + t.Fatal(err) + } + config, err := webhookTLS(path, []string{"synthetic-api-server"}) + if err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) })) + server.TLS = config + server.Config.ErrorLog = log.New(io.Discard, "", 0) + server.StartTLS() + defer server.Close() + if response, err := server.Client().Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("unauthenticated AdmissionReview transport was accepted") + } + transport := server.Client().Transport.(*http.Transport).Clone() + transport.TLSClientConfig.Certificates = []tls.Certificate{{Certificate: [][]byte{certificate}, PrivateKey: privateKey}} + trusted := &http.Client{Transport: transport} + response, err := trusted.Get(server.URL) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != http.StatusNoContent { + t.Fatal("trusted API-server client failed") + } + untrustedTransport := server.Client().Transport.(*http.Transport).Clone() + untrustedTransport.TLSClientConfig.Certificates = server.TLS.Certificates + untrusted := &http.Client{Transport: untrustedTransport} + if response, err := untrusted.Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("untrusted client certificate was accepted") + } + if _, err := webhookTLS(filepath.Join(t.TempDir(), "absent"), []string{"synthetic-api-server"}); err == nil { + t.Fatal("missing CA accepted") + } + if _, err := webhookTLS(path, nil); err == nil { + t.Fatal("a webhook with no configured client identity started") + } + // A certificate from the same CA with another subject is refused during + // the handshake. + other := &x509.Certificate{SerialNumber: big.NewInt(3), Subject: pkix.Name{CommonName: "synthetic-other-client"}, NotBefore: issuer.NotBefore, NotAfter: issuer.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + otherCertificate, err := x509.CreateCertificate(rand.Reader, other, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + otherTransport := server.Client().Transport.(*http.Transport).Clone() + otherTransport.TLSClientConfig.Certificates = []tls.Certificate{{Certificate: [][]byte{otherCertificate}, PrivateKey: privateKey}} + if response, err := (&http.Client{Transport: otherTransport}).Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("a client certificate with an unlisted subject was accepted") + } +} diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index e4b38324..7fd0a1f7 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -1,10 +1,12 @@ package main import ( + "bytes" "context" - "crypto/subtle" + "encoding/json" "errors" "flag" + "fmt" "io" "log/slog" "net/http" @@ -15,84 +17,151 @@ import ( "time" "unicode" - "go.datum.net/fleet/internal/simulator" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/simwork" + "go.datum.net/fleet/internal/site/siteapi" ) const shutdownTimeout = 10 * time.Second const maxTokenFileBytes = 4096 +// fleet-simulator is the simulator site: synthetic Devices with no BMC whose +// install and wipe effects go through the site framework's fenced journal. +// The coordinator reaches it over the site API. func main() { - var runtimeAddress, adminAddress, statePath, runtimeTokenPath, adminTokenPath string - flag.StringVar(&runtimeAddress, "listen-address", "127.0.0.1:8080", "runtime HTTP listen address") - flag.StringVar(&adminAddress, "admin-listen-address", "", "optional admin HTTP listen address; disabled by default") - flag.StringVar(&statePath, "state-file", "/var/lib/fleet-simulator/state.json", "durable state path") - flag.StringVar(&runtimeTokenPath, "runtime-token-file", "", "required file containing the runtime bearer token") - flag.StringVar(&adminTokenPath, "admin-token-file", "", "file containing the admin bearer token; required when the admin listener is enabled") + var address, stateDir, tokenPath, siteName, enrollmentPath string + var discover bool + var discoveryInterval time.Duration + flag.StringVar(&address, "listen-address", "127.0.0.1:8080", "site API listen address") + flag.StringVar(&stateDir, "state-dir", "/var/lib/fleet/site", "the site store's owner-only directory") + flag.StringVar(&tokenPath, "runtime-token-file", "", "required file containing the site API bearer token") + flag.StringVar(&siteName, "site", "simulator", "this site's name") + flag.StringVar(&enrollmentPath, "enrollment-file", "", "required JSON enrollment of the Devices this site serves") + flag.BoolVar(&discover, "discover", false, "write fixture discovery for the enrolled Devices, using the in-cluster credential") + flag.DurationVar(&discoveryInterval, "discovery-interval", time.Minute, "how often fixture discovery runs") flag.Parse() logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - runtimeToken, err := readToken(runtimeTokenPath) - if err != nil { - logger.Error("load runtime token", "error", err) + fail := func(what string, err error) { + logger.Error(what, "error", err) os.Exit(1) } - store, err := simulator.Open(statePath) + if _, err := readToken(tokenPath); err != nil { + fail("load site token", err) + } + enrollment, err := readEnrollment(enrollmentPath) if err != nil { - logger.Error("open simulator state", "error", err) - os.Exit(1) + fail("load enrollment", err) } - - runtimeTokenSource := func() (string, error) { return readToken(runtimeTokenPath) } - servers := []*http.Server{newServer(runtimeAddress, simulator.RuntimeHandlerWithTokenSource(store, runtimeTokenSource, logger), logger)} - if adminAddress != "" { - adminToken, err := readToken(adminTokenPath) + if err := os.MkdirAll(stateDir, 0o700); err != nil { + fail("create the site store", err) + } + if err := os.Chmod(stateDir, 0o700); err != nil { + fail("restrict the site store", err) + } + store, err := site.OpenStore(stateDir, nil) + if err != nil { + fail("open the site store", err) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + results := site.NewResults(store) + runner := &site.Runner{Site: siteName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Payloads: site.StorePayloads{Store: store}} + runner.Kinds["DevicePowerOperation"] = simwork.Power{} + dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} + // The simulator's installs and wipes are simulated, so its declaration + // keeps the lifecycle it always had: it starts no DHCP, claims no boot + // address and attaches no boot NIC, and offers no virtual media. + server := newServer(address, siteapi.Handler(dispatcher, store, results, custody.NetworkBootOnly, func() (string, error) { return readToken(tokenPath) }), logger) + if discover { + api, err := discoveryClient() if err != nil { - logger.Error("load admin token", "error", err) - os.Exit(1) + fail("build the discovery client", err) } - if err := validateDistinctTokens(runtimeToken, adminToken); err != nil { - logger.Error("validate simulator credentials", "error", err) - os.Exit(1) - } - adminTokenSource := func() (string, error) { return readToken(adminTokenPath) } - servers = append(servers, newServer(adminAddress, simulator.AdminHandlerWithTokenSource(store, adminTokenSource, logger), logger)) - } - - errCh := make(chan error, len(servers)) - for _, server := range servers { - server := server go func() { - logger.Info("fleet simulator listening", "address", server.Addr) - errCh <- server.ListenAndServe() + for { + if err := fixture.DiscoverPower(ctx, api, enrollment, time.Now(), simwork.Observe(store)); err != nil && ctx.Err() == nil { + logger.Info("fixture discovery incomplete", "error", err.Error()) + } + select { + case <-ctx.Done(): + return + case <-time.After(discoveryInterval): + } + } }() } - - signals := make(chan os.Signal, 1) - signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) + errCh := make(chan error, 1) + go func() { + logger.Info("simulator site listening", "address", address, "site", siteName, "devices", len(enrollment)) + errCh <- server.ListenAndServe() + }() failed := false select { - case sig := <-signals: - logger.Info("shutting down fleet simulator", "signal", sig.String()) + case <-ctx.Done(): + logger.Info("shutting down the simulator site") case err := <-errCh: if !errors.Is(err, http.ErrServerClosed) { - logger.Error("fleet simulator server failed", "error", err) + logger.Error("simulator site server failed", "error", err) failed = true } } - - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + shutdown, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() - for _, server := range servers { - if err := server.Shutdown(ctx); err != nil { - logger.Error("shut down fleet simulator server", "address", server.Addr, "error", err) - failed = true - } + if err := server.Shutdown(shutdown); err != nil { + logger.Error("shut down the simulator site", "error", err) + failed = true } + // Workers stopped by shutdown store no result; the next process + // resumes them from the journal. + dispatcher.Wait() if failed { os.Exit(1) } } +func readEnrollment(path string) (fixture.Enrollment, error) { + if path == "" { + return nil, errors.New("an enrollment file is required") + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + var enrollment fixture.Enrollment + if err := decoder.Decode(&enrollment); err != nil { + return nil, err + } + for device, target := range enrollment { + if !strings.Contains(device, "/") || target.SystemUUID == "" || target.BMCEndpoint == "" || target.BMCPublicKeySHA256 == "" || len(target.Disks) == 0 { + return nil, fmt.Errorf("enrollment of %s is incomplete", device) + } + } + return enrollment, nil +} + +func discoveryClient() (client.Client, error) { + config, err := rest.InClusterConfig() + if err != nil { + return nil, err + } + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + return nil, err + } + return client.New(config, client.Options{Scheme: scheme}) +} + func readToken(path string) (string, error) { if path == "" { return "", errors.New("token file is required") @@ -126,13 +195,6 @@ func readToken(path string) (string, error) { return token, nil } -func validateDistinctTokens(runtimeToken, adminToken string) error { - if len(runtimeToken) == len(adminToken) && subtle.ConstantTimeCompare([]byte(runtimeToken), []byte(adminToken)) == 1 { - return errors.New("runtime and admin tokens must be distinct") - } - return nil -} - func newServer(address string, handler http.Handler, logger *slog.Logger) *http.Server { return &http.Server{ Addr: address, diff --git a/cmd/fleet-simulator/main_test.go b/cmd/fleet-simulator/main_test.go index 12260921..017240cf 100644 --- a/cmd/fleet-simulator/main_test.go +++ b/cmd/fleet-simulator/main_test.go @@ -41,12 +41,28 @@ func TestReadToken(t *testing.T) { } } -func TestRuntimeAndAdminTokensMustDiffer(t *testing.T) { - if err := validateDistinctTokens("runtime", "admin"); err != nil { - t.Fatalf("distinct tokens rejected: %v", err) +func TestReadEnrollmentRequiresCompleteTargets(t *testing.T) { + dir := t.TempDir() + complete := filepath.Join(dir, "complete.json") + if err := os.WriteFile(complete, []byte(`{"fleet-provider/server-example-001":{"bmcEndpoint":"https://[2001:db8::1]","systemUUID":"00000000-0000-4000-8000-000000000001","bootMACAddress":"02:00:00:00:00:01","bmcPublicKeySHA256":"`+strings.Repeat("a", 64)+`","disks":["disk-0"]}}`), 0o600); err != nil { + t.Fatal(err) + } + if enrollment, err := readEnrollment(complete); err != nil || len(enrollment) != 1 { + t.Fatalf("complete enrollment = %v, %v", enrollment, err) } - if err := validateDistinctTokens("same", "same"); err == nil { - t.Fatal("equal runtime and admin tokens were accepted") + for name, body := range map[string]string{ + "no-namespace": `{"server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k","disks":["disk-0"]}}`, + "no-key": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","disks":["disk-0"]}}`, + "no-disks": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k"}}`, + "unknown": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k","disks":["disk-0"],"extra":true}}`, + } { + path := filepath.Join(dir, name+".json") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if _, err := readEnrollment(path); err == nil { + t.Errorf("%s: enrollment accepted", name) + } } } diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 06124f34..9c13d1aa 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -1,66 +1,215 @@ +// fleet-standalone-smoke runs the standalone smoke test's phases, and the +// coordinator process the phases rely on, in one kind cluster. package main import ( "context" + "errors" "flag" "fmt" + "log/slog" "net/http" "os" + "os/signal" "strings" + "syscall" "time" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site/siteapi" "go.datum.net/fleet/internal/standalone" ) +const ( + providerPrincipal = "system:serviceaccount:fleet-system:fleet-standalone-smoke" + releasePrincipal = "system:serviceaccount:fleet-system:fleet-release-controller" +) + func main() { options := standalone.DefaultOptions() - var phase, simulatorURL, tokenFile string - flag.StringVar(&phase, "phase", "", "required smoke phase: allocate, install, or release") - flag.StringVar(&simulatorURL, "simulator-url", "http://fleet-simulator:8080", "synthetic simulator runtime URL") - flag.StringVar(&tokenFile, "runtime-token-file", "", "file containing the synthetic simulator runtime token") - flag.StringVar(&options.PrivateNamespace, "private-namespace", options.PrivateNamespace, "private record namespace") + var phase, coordinatorToken, releaseToken, siteURL, siteToken, siteName, devices, projectorToken, authorToken, approverToken, operatorToken string + flag.StringVar(&phase, "phase", "", "required: commission, allocate, install, reinstall, release, or coordinate") + flag.StringVar(&projectorToken, "projector-token-file", "", "the capacity projector's ServiceAccount token (coordinate)") + flag.StringVar(&authorToken, "plan-author-token-file", "", "the plan author's ServiceAccount token (commission)") + flag.StringVar(&approverToken, "plan-approver-token-file", "", "the plan approver's ServiceAccount token (commission)") + flag.StringVar(&operatorToken, "operator-token-file", "", "the commissioning operator's ServiceAccount token (commission)") + flag.StringVar(&coordinatorToken, "coordinator-token-file", "", "the custody coordinator's ServiceAccount token (phases)") + flag.StringVar(&releaseToken, "release-token-file", "", "the release controller's ServiceAccount token (phases)") + flag.StringVar(&siteURL, "site-url", "http://fleet-simulator:8080", "the simulator site's API (coordinate)") + flag.StringVar(&siteToken, "site-token-file", "", "the simulator site's bearer token (coordinate)") + flag.StringVar(&siteName, "site", "simulator", "the simulator site's name (coordinate)") + flag.StringVar(&devices, "devices", "synthetic-device-central-01", "comma-separated Devices the site serves (coordinate)") flag.StringVar(&options.ProviderNamespace, "provider-namespace", options.ProviderNamespace, "synthetic provider namespace") flag.StringVar(&options.FirstNamespace, "first-namespace", options.FirstNamespace, "first consumer namespace stand-in") flag.StringVar(&options.SecondNamespace, "second-namespace", options.SecondNamespace, "second consumer namespace stand-in") - flag.StringVar(&options.ImageName, "image", options.ImageName, "digest-pinned synthetic image name") flag.Parse() - if phase == "" || tokenFile == "" { - fail(fmt.Errorf("phase and runtime-token-file are required")) + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + config := ctrl.GetConfigOrDie() + registry, err := custody.DefaultRegistry() + must(err) + if phase == "coordinate" { + must(coordinate(ctx, config, registry, options.ProviderNamespace, siteName, siteURL, siteToken, projectorToken, strings.Split(devices, ","))) + return } - tokenBytes, err := os.ReadFile(tokenFile) - if err != nil { - fail(err) + if coordinatorToken == "" || releaseToken == "" { + must(errors.New("phases need the coordinator and release controller token files")) } - token := strings.TrimSpace(string(tokenBytes)) - if token == "" || strings.ContainsAny(token, "\r\n") { - fail(fmt.Errorf("runtime token must be one nonempty line")) + provider, err := newClient(config) + must(err) + coordinatorConfig, releaseConfig := withToken(config, coordinatorToken), withToken(config, releaseToken) + coordinatorClient, err := newClient(coordinatorConfig) + must(err) + releaseClient, err := newClient(releaseConfig) + must(err) + providerCreator, err := allocation.Creator(ctx, config) + must(err) + releaseCreator, err := allocation.Creator(ctx, releaseConfig) + must(err) + offers := &capacity.Projector{Reader: provider, Namespace: options.ProviderNamespace, Cleaning: capacity.Policies(provider, options.ProviderNamespace)} + allocator := &allocation.Allocator{ + Provider: provider, ProviderCreator: providerCreator, + Releaser: releaseClient, ReleaseCreator: releaseCreator, + Custody: &custody.Coordinator{Client: coordinatorClient, Registry: registry, Config: custody.Config{Namespace: options.ProviderNamespace, Principals: principals()}}, + Namespace: options.ProviderNamespace, + Capacity: offers, + // The fixture Device's boot NIC and the simulator's one enrolled disk. + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Sites: simulatorOffer{site: siteName}, } - scheme := runtime.NewScheme() - if err := clientgoscheme.AddToScheme(scheme); err != nil { - fail(err) + runner := standalone.Runner{Client: provider, Allocator: allocator, Options: options} + if phase == standalone.PhaseCommission { + runner.Staff, err = staff(ctx, config, authorToken, approverToken, operatorToken) + must(err) } - if err := fleetv1.AddToScheme(scheme); err != nil { - fail(err) + must(runner.Run(ctx, phase)) + fmt.Printf("standalone synthetic smoke phase %s completed\n", phase) +} + +// simulatorOffer is the phases' view of the simulator site, which declares +// only network boot. The phases hold no site credential, so they do not +// read the declaration; the coordinator reads it from the site's API and +// refuses an installation recording any other method. +type simulatorOffer struct{ site string } + +func (s simulatorOffer) Serving(*inventory.Device) []string { return []string{s.site} } + +func (s simulatorOffer) Fence(context.Context, string, *inventory.Device) (custody.SiteFence, bool, error) { + return custody.SiteFence{}, false, nil +} + +func (s simulatorOffer) DeliveryMethods(context.Context, string, *inventory.Device) ([]custody.OfferedMethod, bool, error) { + return custody.NetworkBootOnly, true, nil +} + +// coordinate is the coordinator process: the custody loop with the simulator +// as the only site. +func coordinate(ctx context.Context, config *rest.Config, registry *custody.Registry, namespace, siteName, siteURL, tokenFile, projectorToken string, devices []string) error { + if tokenFile == "" || projectorToken == "" { + return errors.New("coordinate needs the site and capacity projector token files") } - kube, err := client.New(ctrl.GetConfigOrDie(), client.Options{Scheme: scheme}) + projectorClient, err := newClient(withToken(config, projectorToken)) if err != nil { - fail(err) + return err } - provider, err := executor.NewHTTPClient(simulatorURL, token, &http.Client{Timeout: 30 * time.Second}) + api, err := newClient(config) if err != nil { - fail(err) + return err } - if err := (standalone.Runner{Client: kube, Executor: provider, Options: options}).Run(context.Background(), phase); err != nil { - fail(err) + remote, err := siteapi.NewClient(siteURL, func() (string, error) { return readToken(tokenFile) }, &http.Client{Timeout: 30 * time.Second}) + if err != nil { + return err } - fmt.Printf("standalone synthetic smoke phase %s completed\n", phase) + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + for _, device := range devices { + if device = strings.TrimSpace(device); device != "" { + sites.Devices[device] = []string{siteName} + } + } + coordinator := &custody.Coordinator{Client: api, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals()}} + logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: capacity.Policies(projectorClient, namespace)} + loop := &delivery.Loop{Client: api, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, + OnError: func(err error) { logger.Info("coordinator pass incomplete", "error", err.Error()) }} + logger.Info("custody coordinator running", "namespace", namespace, "site", siteName) + return loop.Run(ctx) +} + +// staff returns the commissioning phase's three people, each with their own +// token. +func staff(ctx context.Context, config *rest.Config, author, approver, operator string) (*standalone.Staff, error) { + if author == "" || approver == "" || operator == "" { + return nil, errors.New("commission needs the plan author, approver and operator token files") + } + out := &standalone.Staff{} + for _, person := range []struct { + token string + client *client.Client + creator *ops.Creator + }{{author, &out.Author, &out.AuthorCreator}, {approver, &out.Approver, &out.ApproverCreator}, {operator, &out.Operator, &out.OperatorCreator}} { + personConfig := withToken(config, person.token) + api, err := newClient(personConfig) + if err != nil { + return nil, err + } + creator, err := allocation.Creator(ctx, personConfig) + if err != nil { + return nil, err + } + *person.client, *person.creator = api, creator + } + return out, nil +} + +func principals() custody.Principals { + return custody.Principals{custody.CreatorMetalProvider: {{Username: providerPrincipal}}, custody.CreatorReleaseController: {{Username: releasePrincipal}}} +} + +func newClient(config *rest.Config) (client.Client, error) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, fleetv1.AddToScheme, inventory.AddToScheme, ops.AddToScheme} { + if err := add(scheme); err != nil { + return nil, err + } + } + return client.New(config, client.Options{Scheme: scheme}) +} + +// withToken is the in-cluster config authenticated as another +// ServiceAccount. +func withToken(config *rest.Config, tokenFile string) *rest.Config { + copied := rest.AnonymousClientConfig(config) + copied.BearerTokenFile = tokenFile + return copied } -func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) } +func readToken(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(data)) + if token == "" || strings.ContainsAny(token, "\r\n") { + return "", errors.New("the token must be one nonempty line") + } + return token, nil +} + +func must(err error) { + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/fleet-uuid-preflight/main.go b/cmd/fleet-uuid-preflight/main.go new file mode 100644 index 00000000..14889dc0 --- /dev/null +++ b/cmd/fleet-uuid-preflight/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/registration" +) + +func main() { + var device inventory.Device + if err := json.NewDecoder(os.Stdin).Decode(&device); err != nil || device.Kind != "Device" || device.APIVersion != inventory.GroupVersion.String() { + fmt.Fprintln(os.Stderr, "expected an inventory Device as JSON on standard input") + os.Exit(1) + } + candidate, err := registration.ObservedCompletionUUID(&device, time.Now()) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Println(candidate) +} diff --git a/config/README.md b/config/README.md index df6693e2..ee0c9b84 100644 --- a/config/README.md +++ b/config/README.md @@ -9,79 +9,343 @@ entitlements, ServiceAvailability resources, and publication rules must referenc `metal`. See the [API architecture](../docs/architecture/README.md) for group separation and breaking alpha rename constraints. -The repository publishes two production manifest roots. They target different -API servers and must be reconciled independently. +The repository publishes Milo and management-cluster manifest roots. They +target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs, IAM protected resources and roles, service registration, and machine quota registration | -| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, the Device custody and operation kinds with their roles and creator webhook, and the mandatory capacity-registration webhook. Devices can be deleted. | +| `config/milo-synthetic` | A separate non-production Milo control plane | The same kinds, ProtectedResources and roles, with the Device custody kinds but without the creator webhook and the capacity-registration webhook | +| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, and admission fences. It holds no private records: the Secret-backed records and their namespace are removed. | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | +`config/components/device-deletion-protection` is a reusable component: a +ValidatingAdmissionPolicy and binding that deny a Device `DELETE` unless the +Device is `Retired` or its namespace is being deleted, with no exemptions. +Production-specific configuration lives in the deploying repository, which +opts in by adding the component to the root it applies to Milo. No root in this +repository includes it, and `hack/validate-overlay-isolation.sh` fails if one +does or if the component's policy is weakened. See +[Device deletion protection](../docs/development/inventory-capacity-registration.md#device-deletion-protection). + +The synthetic staging overlay excludes the inert-registration service. Pair it +with `config/milo-synthetic` in a **separate non-production Milo control +plane**, not production `config/milo`. That root preserves the +pre-registration synthetic API contract. There is no request field, actor +exemption, or runtime switch that bypasses production registration admission. + The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). +The separate `fleet-registration` Deployment serves inert inventory-backed +capacity admission, the operation creator webhook, and the Machine power +webhook. `config/components/machine-power-admission` admits a change to a +Machine's `status.power` only from the identity named by `fleet-registration`'s +`--machine-power-writer` flag, the manager's Milo identity; unset, every power +change is refused. `config/milo` includes it, and `config/standalone` enforces +the same rule with a ValidatingAdmissionPolicy. See +[Machine power](../docs/development/device-custody.md#machine-power). +The service keeps no state: each capacity create is checked against live +Devices and capacities in the provider projects. Its TLS trust, read/SAR +credentials and webhook serving CA are environment-owned; it has no host RBAC +and mounts no service account token. Read the +[registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) +before applying either root: an unavailable service blocks capacity writes, +operation creates and Machine power changes globally, and nothing else. Pod +TCP readiness is transport-only; it must not +enable UI registration. This does not enable production allocation or +provisioning. + `config/components/service-catalog-staging` is a Kustomize component with staging's Bare Metal prices: committed servers and server setup, which contracts charge, as billing ServicePricings for `metal.datumapis.com`. Staging's infra enables it on `config/milo`; production doesn't, so production has no Bare Metal prices. A price change is a new `-v2` pricing, since a ServicePricing can't be changed. +`config/components/inventory` registers the operator-written `DeviceClaim` and +`Device` kinds of `fleet.datumapis.com` in Milo: their CRDs, ProtectedResources, +and inventory viewer, editor, manager, importer and discoverer roles. The production `config/milo` and isolated +non-production `config/milo-synthetic` roots include it; records +live in the provider project. `config/inventory` renders the CRDs alone for a +legacy management-cluster install and will be removed. See +[Planning and registering physical devices](../docs/operations/physical-inventory.md). + +`config/components/device-operations` registers `DeviceCustody`, the Device +operation kinds, `CleaningPolicy`, their ProtectedResources, the coordinator, +requester, viewer, recovery operator, power operator and cleaning policy admin roles, and the +creator and cleaning policy webhooks. `config/milo` includes all of it, and the +`fleet-registration` server serves the webhooks at +`/validate-operation-creator` and `/validate-cleaning-policy`. `config/milo-synthetic` includes the kinds, +ProtectedResources and roles without the webhook, because it installs no +registration webhook. `config/standalone` includes only the CRDs and enforces the +creator rule with a ValidatingAdmissionPolicy. Including the kinds installs no +coordinator: the production manager has no provider, so nothing creates +custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). + +`config/base/bmc-discovery` runs read-only BMC discovery for one Milo project +in a cluster that can reach the BMC network: one replica, no leader election, +unprivileged. It is in no root here; the deploying repository applies it with +its namespace, image digest, Milo kubeconfig Secret and configuration. +`examples/` holds a synthetic credential Secret and a sidecar container +snippet. See [BMC discovery](../docs/operations/bmc-discovery.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. +`config/multiplane` and `config/site` are the Flux source for the local +multi-plane acceptance only: Flux definitions per local cluster, Milo test +workloads, Karmada and kro releases, the coordination API and the kro site +graph. The harness stages them into an OCI artifact; see +[Flux-reconciled local environment](../docs/operations/gitops.md). They are not +production roots, and neither production root may reference them. + `config/overlays/synthetic-staging` is the temporary Milo-routed acceptance -environment. It uses the real private custody, exclusivity, cleanup, and reuse +environment. It uses the real Device custody, exclusivity, release, and reuse implementation, but substitutes synthetic admission and provider evidence. It -accepts only powered-off, networkless claims in `us-central-1`; its status -conditions identify that boundary. The manager still engages every consuming -project, but the synthetic handler and publisher act only for the one -configured consumer project (`consumerProjectName`); every other engaged -project gets blocked lifecycle handlers and requested-hardware resolution. With -the publication keys documented below it uses one distinct provider project, -publishes a locked class reference and exact profile copy into the consumer, -and retains both project lifetimes in allocation custody. Provider Machine events wake +accepts only networkless claims in `us-central-1` whose power is unset or `Off`; +its status conditions identify that boundary. The manager still engages every +consuming project, but the synthetic handler and publisher act only for the one +configured consumer project (`consumerProjectName`); every other engaged project +gets blocked lifecycle handlers and requested-hardware resolution. With the +publication keys documented below it uses one distinct provider project, +publishes a locked class reference and exact profile copy into the consumer, and +records both project lifetimes on each allocation. Provider Machine events wake consumer claims directly; no polling resync is enabled. -The simulator runs in a separate `fleet-synthetic-provider` Deployment behind a -ClusterIP Service. The manager uses Service DNS and mounts the same dedicated -runtime credential as the provider. The environment must supply the -`fleet-system/fleet-synthetic-provider-auth` Secret with a `token` key; the -staging infra overlay generates it through External Secrets with `CreatedOnce`. -Neither process uses a Kubernetes API token to authenticate provider requests. -The provider has its own service account with token automount disabled and no -RBAC grants. Its NetworkPolicy permits runtime ingress only from manager pods -in the same namespace and denies egress. The runtime uses cluster-local HTTP; -this is a synthetic staging boundary, not a production transport-security design. -The admin listener is disabled. - -The provider keeps its operation log on a retained 1 Gi ReadWriteOnce PVC using -the cluster's default StorageClass. It runs one replica with a `Recreate` strategy: -its file store is not safe for multiple writers. Do not scale it above one or -force-delete a running provider pod. Manager rollouts do not restart the provider -or discard its state. Provider rollouts briefly interrupt runtime calls; private -Fleet authority and the persisted simulator log retain exact inputs and outcomes. -Both mounts read the credential from the projected Secret directory, allowing -rotation without a restart; projection skew may temporarily reject requests. -This overlay must never be promoted to production. - -### Moving from the colocated simulator - -Deploy the environment's generated credential before publishing this overlay. -Stop the old manager and verify all synthetic allocations and private custody -have completed release before replacing the sidecar. Do not treat missing public -Machines as proof of cleanup. The new PVC starts empty: this change does not copy -the sidecar's ephemeral state and must not be used to abandon active operations. -After rollout, verify both Deployments, Service routing, PVC binding, and a fresh -allocation and verified release. Check provider restart recovery with an active -synthetic claim before treating persistent-state recovery as verified in staging. -Do not delete the PVC as a recovery shortcut. - - -Render both production roots before publishing the Kustomize bundle: +The simulator is a site. It runs in a separate `fleet-synthetic-provider` +Deployment behind a ClusterIP Service. The manager runs the custody coordinator +loop, and reaches the site through Service DNS with the site API bearer token. +The environment must supply the `fleet-system/fleet-synthetic-provider-auth` +Secret with a `token` key; the environment generates it, for example through +External Secrets with `CreatedOnce`. The provider has its own service account with token +automount disabled and no RBAC grants. Its NetworkPolicy permits runtime ingress +only from manager pods in the same namespace and denies egress. The runtime uses +cluster-local HTTP; this is a synthetic staging boundary, not a production +transport-security design. The admin listener is disabled. + +The site keeps its store on a retained 1 Gi ReadWriteOnce PVC using the cluster's +default StorageClass. The store holds each Device's fence and its simulated +server. It runs one replica with a `Recreate` strategy: the store is not safe for +multiple writers. Do not scale it above one or force-delete a running provider +pod. Manager rollouts do not restart the provider or discard its state. Provider +rollouts briefly interrupt site calls; custody and the site store retain exact +inputs and outcomes. The site reads its token from the projected Secret +directory, allowing rotation without a restart; projection skew may temporarily +reject requests. This overlay must never be promoted to production. + +### Moving from the Secret-backed staging + +The cutover to Device custody deletes the private records, their namespace and +RBAC, and the manager's `--private-namespace` flag. It adds no migration and +reads no old record. An environment that ran the old overlay must do the +following before the new manager runs: + +1. Release every old synthetic allocation, or discard the synthetic state. Do not + treat missing public Machines as proof of cleanup. +2. Make sure the provider project has its records: Devices with their BMC + endpoints and identities, and the capacities, as in [Planning and + registering physical devices](../docs/operations/physical-inventory.md). + Records GitOps already manages stay with it; import by hand only the ones it + does not. +3. Create three Milo identities that sign in with client certificates, bind + one to `fleet.datumapis.com-device-coordinator`, one to + `fleet.datumapis.com-device-wipe-requester` and one to + `fleet.datumapis.com-capacity-projector` in the provider project, and + issue each a client certificate with a cert-manager Certificate whose + Secret is the one below. Bind each role on the provider project, not on + one namespace: evaluating capacity lists Devices in every namespace to + find a duplicate identity. +4. Give the manager's own identity, the Metal provider, these roles in the + provider project: `metal.datumapis.com-controller`, which now deletes an + allocation that lost its Device before it held it; + `fleet.datumapis.com-device-installation-requester`; and + `fleet.datumapis.com-inventory-discoverer`, because in synthetic staging the manager writes the + fixture discovery of the site's Devices. One manager process holds all + three component credentials. Each write carries its own component's + identity, but the process can act as any of them: this is the synthetic + seam, not production separation. +5. Replace the site enrollment placeholder with the Devices the site serves. +6. Delete the old `fleet-system-private` namespace and its Secrets by hand. + Its manifest was never pruned, so Flux leaves it in place. +7. Delete the publisher's copy of the MachineClass in the consumer project. Its + source names the old `project` field and is immutable, so the publisher + recreates it with `publisherRef`. +8. After rollout, verify both Deployments, Service routing and PVC binding. + Do not delete the PVC as a recovery shortcut. Do not test an allocation + yet: no capacity is allocatable until its Device is commissioned. + +#### Commissioning the synthetic Devices + +The new manager no longer marks synthetic capacity `Prepared`, `Healthy` and +`Available` by itself. The capacity projector derives them from evidence, so +after rollout every existing capacity reads `Prepared=False` with reason +`NotCommissioned`, and an allocation fails with insufficient capacity. That is +correct: nothing has proven the servers yet. Commission each synthetic Device +before testing an allocation. The examples use the synthetic names this +repository ships; substitute your own Devices, namespace and people. + +1. **Choose three identities.** A plan author, a plan approver and a + commissioning operator. The author and the approver must be two different + people: custody refuses an approval whose creator has the author's + username. Never bind the author and approver roles to the same principal, + or to groups that share a member. The operator may be either person or a + third. Bind each role on the provider project: + + ```yaml + apiVersion: iam.miloapis.com/v1alpha1 + kind: PolicyBinding + metadata: + name: fleet-plan-author-example + namespace: example-provider-project + spec: + roleRef: + name: fleet.datumapis.com-device-commissioning-plan-author + namespace: milo-system # where the environment installs the Fleet roles + subjects: + - kind: User + name: plan-author@example.com + uid: 00000000-0000-4000-8000-0000000000a1 + resourceSelector: + resourceRef: + apiGroup: resourcemanager.miloapis.com + kind: Project + name: example-provider-project + uid: 00000000-0000-4000-8000-0000000000f1 + ``` + + Create the same binding for `plan-approver@example.com` with + `fleet.datumapis.com-device-commissioning-plan-approver`, and for + `operator@example.com` with + `fleet.datumapis.com-device-commissioning-operator`. + +2. **Author the plan.** An inventory editor labels the Devices the plan + covers, and the plan author creates the plan. `creator` must be the author's own username, and + `uid` only if their credential carries one. The content describes the + hardware every covered Device must have. + + ```sh + kubectl label device server-example-001 -n default fleet.datumapis.com/hardware-model=synthetic + ``` + + ```yaml + apiVersion: fleet.datumapis.com/v1alpha1 + kind: DeviceCommissioningPlan + metadata: + name: synthetic-plan-v1 + namespace: default + spec: + creator: + username: plan-author@example.com + deviceSelector: + matchLabels: + fleet.datumapis.com/hardware-model: synthetic + content: + inspection: + cpu: {architecture: amd64, cores: 2} + memory: {capacity: 2Gi} + disks: {count: 1, minCapacity: 2Gi} + interfaces: {count: 1} + firmware: + - {component: BMC, version: 1.0.0} + burnIn: + image: + name: synthetic-burn-in + digest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + duration: 1m + evidenceLifetime: 720h + ``` + +3. **A different person approves it.** The approval's name, and the + generation and digest it names, must match the plan exactly as the API + server stores it, so compute them from the stored plan rather than by + hand. The approver runs, from a checkout: + + ```sh + kubectl get devicecommissioningplan synthetic-plan-v1 -n default -o json > plan.json + go run ./hack/commissioning-request approval --plan plan.json \ + --username plan-approver@example.com | kubectl create -f - + ``` + + The printed approval looks like this; the name's suffix and the digest + are derived from the plan: + + ```yaml + apiVersion: fleet.datumapis.com/v1alpha1 + kind: DeviceCommissioningPlanApproval + metadata: + name: synthetic-plan-v1-<16 hex characters> + namespace: default + spec: + creator: + username: plan-approver@example.com + planRef: + name: synthetic-plan-v1 + generation: 1 + digest: sha256: + ``` + +4. **Add hardware and firmware to the site enrollment.** The synthetic site + inspects what its enrollment says each Device has. Give every Device in + the `fleet-synthetic-site-enrollment` ConfigMap a `hardware` field and a + `firmware` list that meet the plan; a Device without `hardware` cannot be + commissioned. The manager and the synthetic provider read the ConfigMap + only when they start, so this is best done with step 5 above, before the + new manager runs. A change made later takes effect after a rollout of + both; the provider's `Recreate` strategy keeps its store safe: + + ```sh + kubectl rollout restart deployment/fleet-synthetic-provider deployment/fleet-manager -n fleet-system + ``` + + ```json + {"default/server-example-001": { + "bmcEndpoint": "https://[2001:db8::31]", + "systemUUID": "00000000-0000-4000-8000-000000000031", + "bootMACAddress": "02:00:00:00:00:31", + "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", + "disks": ["disk-0"], + "hardware": { + "cpu": {"architecture": "amd64", "cores": 2}, + "memory": "2Gi", + "disks": [{"name": "disk-0", "capacity": "2Gi"}], + "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:31"}] + }, + "firmware": [{"component": "BMC", "version": "1.0.0"}] + }} + ``` + +5. **Create one commissioning per Device.** The operator creates each one + under the plan, with an exact copy of its content and the Device's + incarnation label, again computed from the stored objects. Create, do not + apply: the name is generated. + + ```sh + kubectl get device server-example-001 -n default -o json > device.json + go run ./hack/commissioning-request commission --plan plan.json --device device.json \ + --username operator@example.com --reason "synthetic intake" | kubectl create -f - + ``` + +6. **Wait for `Prepared` and `Available`.** Each commissioning should end + `Succeeded` with result `Passed`, and the capacity projector then sets + `Prepared`, `Healthy` and `Available` to `True`: + + ```sh + kubectl get devicecommissionings -n default + kubectl wait machinecapacity --all -n default --for=condition=Available --timeout=10m + ``` + + A `Failed` result names what did not match the plan in its evidence. Fix + the enrollment or the plan (a changed plan is a new plan, approved again) + and commission again. + +7. **Then verify a fresh allocation** and its verified release. + + +Render the Milo and management-cluster roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null +kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null ``` @@ -161,6 +425,22 @@ data: publishedProfileName: ``` +The overlay also takes these inputs for the custody coordinator, which the +manager runs under its leader lease together with fixture discovery: + +| Input | Flag | Content | +| --- | --- | --- | +| Secret `fleet-system/fleet-custody-coordinator-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-coordinator-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-coordinator` role in the provider project, as a cert-manager Certificate writes it. Supplied by the environment. | +| Secret `fleet-system/fleet-release-controller-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-release-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-wipe-requester` role in the provider project. Supplied by the environment. | +| Secret `fleet-system/fleet-capacity-projector-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-projector-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-capacity-projector` role in the provider project. Supplied by the environment. | +| ConfigMap `fleet-system/fleet-synthetic-site-enrollment`, key `enrollment.json` | `--synthetic-site-enrollment-file` | The Devices the synthetic site serves, keyed `/`, each with its BMC endpoint, system UUID, boot MAC address, key digest and disks. The overlay ships a synthetic placeholder for `server-example-001`, and an environment replaces it with the Devices it imports. | +| `--synthetic-device-namespace` | Default `default` | The namespace of the Devices, capacities and allocations in the provider project. Every enrolled Device must be in it. | + +The manager's own identity is the Metal provider. Fixture discovery is written by +the manager because the synthetic site has no API credential. The cutover +requires a person to re-import the records and create the two credentials; see +[Moving from the Secret-backed staging](#moving-from-the-secret-backed-staging). + The publisher refuses name collisions, reference chains, mutable profile-copy drift, a profile not allowed by the source class, or replacement source/project lifetimes. It writes only into the engaged consumer project, and only a @@ -212,11 +492,11 @@ the discovery role and the project identity needs the controller role plus Fleet, NSO, quota, entitlement, Namespace, and Event access goes through the routed Milo project credential. The management-cluster service account has no -cluster-wide role. It receives only leader-election access in `fleet-system` -and Secret access in `fleet-system-private`; the separate host cache is confined -to that private namespace. Cache scoping is not an authorization boundary. The -private namespace and `fleet-system` have Flux pruning disabled so uninstalling -one release cannot implicitly delete retained lifecycle authority. +cluster-wide role. It receives only leader-election access in `fleet-system`: +its lease, and the Events leader election records there. +It holds no Secret access: allocations, custody and operations live in the +provider project, not in the management cluster. `fleet-system` has Flux pruning +disabled. ## Project discovery @@ -227,10 +507,9 @@ gets its own runtime: the identity read from Milo, a client and cache bound to that project's control plane, a verifier run before every reconcile, its own mappers, and its own lifecycle owners. Every request carries its project's cluster name and is reconciled only through that runtime, and only when the -runtime's identity matches the request. Private records stay in the one host -namespace `fleet-system-private`; their names and indexes already key on the -consumer project's authority and UID, and a private-record event reaches only -the runtime engaged for exactly that project lifetime. +runtime's identity matches the request. A MachineAllocation lives in the +provider project and is named from the consumer project's UID and the Machine +UID, so equal Machine UIDs in two projects never share one. The synthetic provider project may itself be an Active `metal` consumer. It then engages like any other consumer, with blocked lifecycle handlers and the @@ -252,9 +531,9 @@ standby is warm. When a project leaves the consumer set (its ServiceConsumer is Denied or deleted), the manager only stops reconciling it. It does not release custody, call a provider, delete Fleet records, or rewrite Machine status, including -for a project with active custody. Private records for the departed project -stay in place, and its queued events and deadlines are dropped. If the project -is engaged again, reconciliation resumes from the retained records. Discovery +for a project with active custody. Its allocations stay in place, and its queued +events and deadlines are dropped. If the project is engaged again, +reconciliation resumes from the retained allocations. Discovery is observational: the manager adds no ServiceConsumer finalizer, so it never gates a project's deletion, and it does not confirm platform suspension (it drops the consumer library's `Paused` status patch, because Fleet implements no @@ -265,8 +544,8 @@ suspension). `/readyz` on port `health` (8081) reports discovery and cache health, not provider readiness. It passes when the provider project's ServiceConsumer cache has synced, every project with an Active `metal` ServiceConsumer is engaged on -that replica, every engaged project cache has synced, and the private-record -cache has synced. It never depends on a provider integration. It also keeps +that replica, and every engaged project cache has synced. It never depends on a +provider integration. It also keeps failing, with an explicit `project discovery is misconfigured` error, while no Service is registered for `metal.datumapis.com`, or while `consumerScopedProjection.providerProject` differs from that Service's @@ -309,7 +588,7 @@ removing the manifest does not authorize deletion or settle old obligations. Before explicitly deleting an existing legacy registration, verify there are no legacy grants, claims, allowance buckets, or creation policies, and all legacy allocations have verified release. Never retarget its immutable `spec.resourceType` -or delete retained private allocation records. Environments that have not completed +or delete a retained MachineAllocation. Environments that have not completed this audit must retain their existing registration. Coordinate environment changes before publishing the corrected bundle: publication @@ -318,55 +597,4 @@ must use `metal.datumapis.com/v1alpha1`, location availability must reference `metal`, and staff bindings must reference the Metal IAM roles. Gate the manager on inventory and service availability as well as the Milo configuration. Confirm old allocations are released immediately before rollout; absence of public -Machines alone does not prove private cleanup is complete. - -### Hand off bootstrap field ownership before removing the sidecar - -A staging Deployment initially applied by `fleet-staging-bootstrap` may retain -that server-side apply owner's fields alongside `kustomize-controller`. Removing -the sidecar from the Flux manifest can then fail with -`spec.template.spec.containers[1].image: Required value`: Flux removes the image -it owns, while bootstrap ownership retains the rest of the obsolete container. -The new provider Deployment does not cause this validation error. - -After stopping the manager, waiting for its Pods to terminate, and verifying -all private custody/asset records are Released, inspect the Deployment with -`kubectl get deployment fleet-manager -n fleet-system --show-managed-fields -o json`. -Use the explicit staging context for every command. Confirm that the obsolete -sidecar is co-owned by `fleet-staging-bootstrap` and `kustomize-controller`. -Do not remove managedFields directly or delete/recreate the Deployment. - -The old bootstrap apply owner can relinquish its fields by applying only the -Deployment's identity under its original field-manager name: - -```sh -kubectl --context "$staging_context" -n fleet-system apply \ - --server-side --field-manager=fleet-staging-bootstrap \ - --dry-run=server --show-managed-fields -o json -f - <<'YAML' -apiVersion: apps/v1 -kind: Deployment -metadata: - name: fleet-manager - namespace: fleet-system -YAML -``` - -Compare the returned `spec` with a fresh live read. They must be identical, -including `replicas: 0`, and the sidecar's remaining apply owner must be -`kustomize-controller`. If these checks fail, stop and investigate exclusive -bootstrap-owned fields rather than forcing the change. This relinquishes the -bootstrap **Apply** ownership; any historical **Update** entries are distinct -and must not be erased indiscriminately. - -Once reviewed, repeat the same command without `--dry-run=server`. Re-read the -Deployment to confirm the same invariants, then request reconciliation of -`fleet-system/fleet-host`. Flux can now remove the entire obsolete container and -install the separate provider. This handoff changes ownership only; it must not -restart the old manager, modify private records, rotate credentials, or remove -provider state. Continue with the allocation, restart recovery, and release -checks described above. - -On November 12, 2026, the staging server accepted this ownership-only dry run: -the complete Deployment spec remained identical at zero replicas, and only -`kustomize-controller` retained sidecar ownership. Execution and successful -post-handoff reconciliation must be verified separately. +Machines alone does not prove cleanup is complete. diff --git a/config/base/bmc-discovery/config.yaml b/config/base/bmc-discovery/config.yaml new file mode 100644 index 00000000..106e77ee --- /dev/null +++ b/config/base/bmc-discovery/config.yaml @@ -0,0 +1,11 @@ +# Synthetic values; the deploying repository replaces them. +project: example-provider-project +miloKubeconfig: /var/run/fleet/milo/kubeconfig +deviceNamespaces: [default] +# credentialNamespace defaults to the pod's namespace ($POD_NAMESPACE). +interval: 1h +retryBase: 30s +minContactInterval: 1m +requestTimeout: 20s +concurrency: 4 +healthProbeAddress: ":8081" diff --git a/config/base/bmc-discovery/deployment.yaml b/config/base/bmc-discovery/deployment.yaml new file mode 100644 index 00000000..a7fabe40 --- /dev/null +++ b/config/base/bmc-discovery/deployment.yaml @@ -0,0 +1,71 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-bmc-discovery +spec: + # Exactly one replica and no leader election: two replicas would each + # contact every BMC and race on status. Recreate keeps a rollout from + # briefly running two. + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: fleet-bmc-discovery + template: + metadata: + labels: + app.kubernetes.io/name: fleet-bmc-discovery + spec: + serviceAccountName: fleet-bmc-discovery + # The token is needed to read credential Secrets in this namespace. Set + # localKubeconfig in the config and turn this off to use a mounted + # kubeconfig instead. + automountServiceAccountToken: true + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: bmc-discovery + image: ghcr.io/datum-cloud/fleet:latest + command: [/fleet-bmc-discovery] + args: + - --config=/etc/fleet/bmc-discovery/config.yaml + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + ports: + - name: probes + containerPort: 8081 + livenessProbe: + httpGet: {path: /healthz, port: probes} + readinessProbe: + httpGet: {path: /readyz, port: probes} + resources: + requests: {cpu: 20m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - {name: config, mountPath: /etc/fleet/bmc-discovery, readOnly: true} + - {name: milo, mountPath: /var/run/fleet/milo, readOnly: true} + volumes: + - name: config + configMap: + name: fleet-bmc-discovery-config + # A kubeconfig for the one Milo project, bound to the + # fleet.datumapis.com-inventory-discoverer role. Environment-owned. + - name: milo + secret: + secretName: fleet-bmc-discovery-milo-kubeconfig + defaultMode: 0440 + items: [{key: kubeconfig, path: kubeconfig}] diff --git a/config/base/bmc-discovery/examples/credential-secret.yaml b/config/base/bmc-discovery/examples/credential-secret.yaml new file mode 100644 index 00000000..c832d9dd --- /dev/null +++ b/config/base/bmc-discovery/examples/credential-secret.yaml @@ -0,0 +1,20 @@ +# Synthetic example of one BMC credential Secret. Not part of the base: create +# one per Device, in the namespace where discovery runs, outside Git. +apiVersion: v1 +kind: Secret +metadata: + name: bmc-example-device-01 + labels: + fleet.datumapis.com/bmc-credential: "true" + annotations: + fleet.datumapis.com/device-project: example-provider-project + fleet.datumapis.com/device-namespace: default + fleet.datumapis.com/device-name: example-device-01 +type: Opaque +stringData: + username: example-operator + password: example-password + # Leave unset for first contact. Discovery then records the observed key in + # the Device's status.discovery.tls.publicKeySHA256 and sends nothing. Set + # it only after verifying that value out of band. + # tlsPublicKeySHA256: 0000000000000000000000000000000000000000000000000000000000000000 diff --git a/config/base/bmc-discovery/examples/sidecar-container.yaml b/config/base/bmc-discovery/examples/sidecar-container.yaml new file mode 100644 index 00000000..6c058910 --- /dev/null +++ b/config/base/bmc-discovery/examples/sidecar-container.yaml @@ -0,0 +1,40 @@ +# Synthetic snippet: discovery as one extra container in a pod that already +# reaches the BMC network (for example a VPN gateway pod). Merge it into that +# pod's spec.template.spec. It shares only the network namespace; it needs no +# privilege, capability or other container. The pod's service account needs +# the Role in ../rbac.yaml bound to it, or set localKubeconfig in the config +# and mount a kubeconfig instead. +containers: + - name: bmc-discovery + image: ghcr.io/datum-cloud/fleet@sha256: + command: [/fleet-bmc-discovery] + args: [--config=/etc/fleet/bmc-discovery/config.yaml] + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + resources: + requests: {cpu: 20m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + runAsNonRoot: true + runAsUser: 65532 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + seccompProfile: + type: RuntimeDefault + volumeMounts: + - {name: bmc-discovery-config, mountPath: /etc/fleet/bmc-discovery, readOnly: true} + - {name: bmc-discovery-milo, mountPath: /var/run/fleet/milo, readOnly: true} +volumes: + - name: bmc-discovery-config + configMap: + name: fleet-bmc-discovery-config + - name: bmc-discovery-milo + secret: + secretName: fleet-bmc-discovery-milo-kubeconfig + defaultMode: 0440 + items: [{key: kubeconfig, path: kubeconfig}] diff --git a/config/base/bmc-discovery/kustomization.yaml b/config/base/bmc-discovery/kustomization.yaml new file mode 100644 index 00000000..c7c667d9 --- /dev/null +++ b/config/base/bmc-discovery/kustomization.yaml @@ -0,0 +1,14 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +# Read-only BMC discovery for one Milo project. Apply it to a cluster from +# which the BMC network is reachable, in the namespace that holds the +# credential Secrets; the deploying repository sets that namespace, the +# image digest, the Milo kubeconfig Secret and the config values. +# See docs/operations/bmc-discovery.md. +resources: + - rbac.yaml + - deployment.yaml +configMapGenerator: + - name: fleet-bmc-discovery-config + files: + - config.yaml diff --git a/config/base/bmc-discovery/rbac.yaml b/config/base/bmc-discovery/rbac.yaml new file mode 100644 index 00000000..5c831bc3 --- /dev/null +++ b/config/base/bmc-discovery/rbac.yaml @@ -0,0 +1,29 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-bmc-discovery +--- +# Lists and watches credential Secrets in its own namespace; discovery never +# gets one by name. Kubernetes RBAC cannot narrow this to the labelled +# Secrets, so keep discovery in a namespace that holds credential Secrets +# only. hack/validate-bmc-credential-namespace.sh checks every render here. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-bmc-discovery-credentials +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-bmc-discovery-credentials +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-bmc-discovery-credentials +subjects: + - kind: ServiceAccount + name: fleet-bmc-discovery diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 1e48fc93..b37d7d77 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -34,9 +34,18 @@ spec: properties: source: type: object - required: [project, name] + required: [publisherRef, name] properties: - project: {type: string, minLength: 1} + publisherRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a publisher is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} name: {type: string, minLength: 1} profilePolicy: {type: object, x-kubernetes-preserve-unknown-fields: true} access: {type: object, x-kubernetes-preserve-unknown-fields: true} @@ -146,6 +155,8 @@ spec: - rule: >- self.deviceRef == oldSelf.deviceRef message: physical-device identity is immutable + - rule: self.cleaningPolicyRef.name != '' || self.allocationPolicy == 'Disabled' + message: unconfigured cleaning policy is permitted only for Disabled records properties: deviceRef: type: object @@ -155,7 +166,7 @@ spec: cleaningPolicyRef: type: object required: [name] - properties: {name: {type: string, minLength: 1}} + properties: {name: {type: string}} reclaimPolicy: {type: string, enum: [Retain]} status: type: object @@ -212,7 +223,18 @@ spec: (has(self.networkInterfaces) && has(oldSelf.networkInterfaces) && self.networkInterfaces == oldSelf.networkInterfaces)) message: allocation inputs are immutable + - rule: >- + (!has(self.creator) && !has(oldSelf.creator)) || + (has(self.creator) && has(oldSelf.creator) && self.creator == oldSelf.creator) + message: creator is immutable properties: + creator: + type: object + description: The authenticated caller that created the Machine. Admission sets it; clients cannot choose it. + required: [username, uid] + properties: + username: {type: string, minLength: 1} + uid: {type: string, minLength: 1} machineClassRef: {type: object, required: [name], properties: {name: {type: string}}} machineProfileRef: {type: object, required: [name], properties: {name: {type: string}}} locationRef: {type: object, required: [name], properties: {name: {type: string}}} @@ -248,7 +270,7 @@ spec: required: [name] properties: {name: {type: string, minLength: 1}} reclaimPolicy: {type: string, enum: [Delete, Retain], default: Delete} - powerState: {type: string, enum: ["On", "Off"], default: "Off"} + powerState: {type: string, enum: ["On", "Off"]} status: type: object x-kubernetes-validations: @@ -353,15 +375,26 @@ spec: metadata: {type: object} spec: type: object - required: [machineRef, machineCapacityRef] + required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicy, drives, bootInterface, targetDisks] x-kubernetes-validations: - {rule: 'self == oldSelf', message: MachineAllocation identity and endpoints are immutable} properties: + # No spec holds an object UID. The allocation's name hashes the + # consumer and Machine UIDs, and its labels record them. + consumerRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a consumer is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} machineRef: type: object - required: [project, namespace, name] + required: [namespace, name] properties: - project: {type: string, minLength: 1} namespace: {type: string, minLength: 1} name: {type: string, minLength: 1} machineCapacityRef: @@ -370,6 +403,138 @@ spec: properties: namespace: {type: string, minLength: 1} name: {type: string, minLength: 1} + deviceRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + accepted: + type: object + required: [machineClassRef, machineProfileRef, cpu, memory] + properties: + machineClassRef: + type: object + required: [name, generation, digest] + properties: + name: {type: string, minLength: 1} + generation: {type: integer, format: int64, minimum: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + machineProfileRef: + type: object + required: [name, generation, digest] + properties: + name: {type: string, minLength: 1} + generation: {type: integer, format: int64, minimum: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + cpu: + type: object + required: [architecture, cores] + properties: + architecture: {type: string, minLength: 1, maxLength: 63} + cores: {type: integer, format: int64, minimum: 1} + memory: + type: object + required: [capacity] + properties: + capacity: {type: string, minLength: 1} + hardware: {type: object, x-kubernetes-preserve-unknown-fields: true} + authority: + type: object + required: [principal, decision] + properties: + principal: {type: string, minLength: 1, maxLength: 253} + decision: {type: string, minLength: 1, maxLength: 253} + quotaClaimRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + cleaningPolicy: + type: object + required: [name, generation, digest, spec] + properties: + name: {type: string, minLength: 1, maxLength: 253} + generation: {type: integer, format: int64, minimum: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + spec: + type: object + required: [assurance, rules] + properties: + assurance: {type: string, enum: [Clear, Purge]} + rules: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, match, methods, verify, timePerTiB] + properties: + name: {type: string, minLength: 1, maxLength: 63} + match: + type: object + required: [protocol, mediaType] + properties: + protocol: {type: string, enum: [NVMe, SATA, SAS]} + mediaType: {type: string, enum: [SSD, HDD]} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + qualified: + type: array + maxItems: 32 + items: + type: object + required: [model, firmware, methods] + properties: + model: {type: string, minLength: 1, maxLength: 128} + firmware: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: set + items: {type: string, minLength: 1, maxLength: 64} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + alwaysEncrypts: {type: boolean} + drives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, serialNumber, model, firmware, protocol, mediaType, capacityBytes, rule] + properties: + name: {type: string, pattern: '^disk-[0-9]+$', maxLength: 12} + serialNumber: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + firmware: {type: string, maxLength: 63} + protocol: {type: string, maxLength: 31} + mediaType: {type: string, maxLength: 31} + capacityBytes: {type: integer, minimum: 0} + rule: {type: string, maxLength: 63} + bootInterface: {type: string, minLength: 1, maxLength: 63} + targetDisks: + type: array + minItems: 1 + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} status: type: object x-kubernetes-validations: @@ -377,6 +542,59 @@ spec: message: a released MachineAllocation is terminal properties: phase: {type: string, enum: [Pending, Active, Releasing, Released, Unknown]} + wipe: + type: object + required: [name, step] + properties: + name: {type: string, minLength: 1} + step: {type: integer, format: int32, minimum: 1} + bootClaims: + type: array + maxItems: 64 + items: + type: object + required: [operationKind, operation, claim] + properties: + operationKind: {type: string, enum: [DeviceInstallation, DeviceWipe]} + operation: {type: string, minLength: 1, maxLength: 253} + claim: + type: object + required: [apiGroup, kind, name] + properties: + apiGroup: {type: string, minLength: 1, maxLength: 253} + kind: {type: string, minLength: 1, maxLength: 63} + name: {type: string, minLength: 1, maxLength: 253} + network: + type: object + properties: + interfaces: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, network, attachment, claim] + properties: + name: {type: string, minLength: 1, maxLength: 63} + network: + type: object + required: [namespace, name] + properties: {namespace: {type: string, minLength: 1}, name: {type: string, minLength: 1}} + attachment: + type: object + required: [macAddress, switch, port] + properties: + macAddress: {type: string, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + switch: {type: string, minLength: 1, maxLength: 253} + port: {type: string, minLength: 1, maxLength: 63} + claim: + type: object + required: [namespace, name] + properties: + namespace: {type: string, minLength: 1} + name: {type: string, minLength: 1, maxLength: 253} + uid: {type: string} conditions: type: array items: {type: object, x-kubernetes-preserve-unknown-fields: true} @@ -428,7 +646,143 @@ spec: type: object properties: phase: {type: string} + resolvedImage: + type: object + required: [name, digest] + properties: + name: {type: string, minLength: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} completedAt: {type: string, format: date-time} conditions: type: array items: {type: object, x-kubernetes-preserve-unknown-fields: true} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineimages.metal.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: metal.datumapis.com + names: {kind: MachineImage, listKind: MachineImageList, plural: machineimages, singular: machineimage, shortNames: [mimg]} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + additionalPrinterColumns: + - {name: Availability, type: string, jsonPath: .spec.availability} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - rule: >- + (has(self.definition) && !has(self.source) && has(self.availability)) || + (!has(self.definition) && has(self.source) && !has(self.availability)) + message: an image is either a provider definition with an availability or a published source reference + - rule: >- + has(self.definition) == has(oldSelf.definition) && + (!has(self.definition) || self.definition == oldSelf.definition) && + (!has(self.source) || self.source == oldSelf.source) + message: an image's definition and source are immutable + properties: + definition: + type: object + required: [family, version, architecture, firmwareModes, digest] + properties: + family: {type: string, minLength: 1, maxLength: 63} + version: {type: string, minLength: 1, maxLength: 63} + architecture: {type: string, minLength: 1, maxLength: 63} + firmwareModes: + type: array + minItems: 1 + maxItems: 2 + x-kubernetes-list-type: set + items: {type: string, enum: [UEFI, BIOS]} + bootstrapFormats: + type: array + maxItems: 1 + x-kubernetes-list-type: set + items: {type: string, enum: [NoCloud]} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + source: + type: object + required: [publisherRef, name] + properties: + publisherRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a publisher is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} + name: {type: string, minLength: 1} + availability: {type: string, enum: [Available, Withdrawn]} + status: + type: object + properties: + resolved: {type: object, x-kubernetes-preserve-unknown-fields: true} + conditions: + type: array + items: {type: object, x-kubernetes-preserve-unknown-fields: true} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineimagepublications.metal.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: metal.datumapis.com + names: {kind: MachineImagePublication, listKind: MachineImagePublicationList, plural: machineimagepublications, singular: machineimagepublication} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - {rule: 'self == oldSelf', message: a publication record is immutable} + required: [consumerRef, image, source, digest] + properties: + consumerRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a consumer is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} + image: + type: object + required: [namespace, name] + properties: + namespace: {type: string, minLength: 1} + name: {type: string, minLength: 1} + source: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} diff --git a/config/base/manager/deployment.yaml b/config/base/manager/deployment.yaml index e0546962..8697749e 100644 --- a/config/base/manager/deployment.yaml +++ b/config/base/manager/deployment.yaml @@ -37,7 +37,6 @@ spec: # blocked and only requested hardware is resolved. args: - --config=/etc/fleet/manager/config.yaml - - --private-namespace=fleet-system-private - --leader-election-namespace=fleet-system ports: - name: health diff --git a/config/base/manager/kustomization.yaml b/config/base/manager/kustomization.yaml index b61f6474..8820a53a 100644 --- a/config/base/manager/kustomization.yaml +++ b/config/base/manager/kustomization.yaml @@ -5,6 +5,4 @@ resources: - service-account.yaml - leader-election-role.yaml - leader-election-role-binding.yaml - - private-record-role.yaml - - private-record-role-binding.yaml - deployment.yaml diff --git a/config/base/manager/leader-election-role.yaml b/config/base/manager/leader-election-role.yaml index 50e3c35d..05577a9c 100644 --- a/config/base/manager/leader-election-role.yaml +++ b/config/base/manager/leader-election-role.yaml @@ -7,3 +7,8 @@ rules: - apiGroups: [coordination.k8s.io] resources: [leases] verbs: [get, list, watch, create, update, patch, delete] + # Leader election records each lease change as a core Event in the lease's + # namespace, and patches it when the change repeats. + - apiGroups: [""] + resources: [events] + verbs: [create, patch] diff --git a/config/base/manager/namespace.yaml b/config/base/manager/namespace.yaml index 8b8553ab..cf4711d0 100644 --- a/config/base/manager/namespace.yaml +++ b/config/base/manager/namespace.yaml @@ -5,11 +5,3 @@ metadata: annotations: kustomize.toolkit.fluxcd.io/prune: disabled fleet.datumapis.com/shared-with-standalone: "true" ---- -apiVersion: v1 -kind: Namespace -metadata: - name: fleet-system-private - annotations: - kustomize.toolkit.fluxcd.io/prune: disabled - fleet.datumapis.com/shared-with-standalone: "true" diff --git a/config/base/manager/private-record-role-binding.yaml b/config/base/manager/private-record-role-binding.yaml deleted file mode 100644 index 679abd8b..00000000 --- a/config/base/manager/private-record-role-binding.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-manager-private-records - namespace: fleet-system-private -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: fleet-manager-private-records -subjects: - - kind: ServiceAccount - name: fleet-manager - namespace: fleet-system diff --git a/config/base/manager/private-record-role.yaml b/config/base/manager/private-record-role.yaml deleted file mode 100644 index 4c9159fc..00000000 --- a/config/base/manager/private-record-role.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-manager-private-records - namespace: fleet-system-private -rules: - - apiGroups: [''] - resources: [secrets] - verbs: [get, list, watch, create, update, patch, delete] diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml new file mode 100644 index 00000000..553a94b4 --- /dev/null +++ b/config/base/registration/deployment.yaml @@ -0,0 +1,94 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-registration + namespace: fleet-system +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-registration + namespace: fleet-system +spec: + selector: + app.kubernetes.io/name: fleet-registration + ports: + - name: https + port: 9443 + targetPort: https +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-registration + namespace: fleet-system +spec: + replicas: 2 + selector: + matchLabels: + app.kubernetes.io/name: fleet-registration + template: + metadata: + labels: + app.kubernetes.io/name: fleet-registration + spec: + serviceAccountName: fleet-registration + # The service reads Milo through mounted credentials only; it needs no + # host Kubernetes API access. + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: registration + image: ghcr.io/datum-cloud/fleet:latest + command: [/fleet-registration] + args: + - --config=/etc/fleet/manager/config.yaml + - --provider-projects=datum-cloud + # Environment-owned: the subjects of the API-server webhook + # client certificates, and the capacity projector's username. + # The placeholders accept no real caller. + - --client-identities=replace-with-api-server-webhook-client + - --capacity-projectors=replace-with-capacity-projector + ports: + - name: https + containerPort: 9443 + readinessProbe: + tcpSocket: + port: https + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 512Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - {name: config, mountPath: /etc/fleet/manager, readOnly: true} + - {name: root, mountPath: /var/run/fleet/milo, readOnly: true} + - {name: projects, mountPath: /var/run/fleet/projects, readOnly: true} + - {name: tls, mountPath: /etc/fleet/registration, readOnly: true} + volumes: + - name: config + configMap: + name: fleet-manager-config + - name: root + secret: + secretName: fleet-registration-milo-kubeconfig + defaultMode: 0440 + items: [{key: value, path: kubeconfig}] + - name: projects + secret: + secretName: fleet-registration-project-kubeconfig + defaultMode: 0440 + items: [{key: value, path: kubeconfig}] + - name: tls + secret: + secretName: fleet-registration-tls + defaultMode: 0440 diff --git a/config/base/registration/kustomization.yaml b/config/base/registration/kustomization.yaml new file mode 100644 index 00000000..9c2d28b0 --- /dev/null +++ b/config/base/registration/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - deployment.yaml diff --git a/config/base/simulator/statefulset.yaml b/config/base/simulator/statefulset.yaml index 9fe530fc..6f968d59 100644 --- a/config/base/simulator/statefulset.yaml +++ b/config/base/simulator/statefulset.yaml @@ -13,6 +13,8 @@ spec: labels: {app.kubernetes.io/name: fleet-simulator} spec: serviceAccountName: fleet-simulator + # Fixture discovery writes the status of the Devices this site serves. + automountServiceAccountToken: true securityContext: runAsNonRoot: true runAsUser: 65532 @@ -27,10 +29,12 @@ spec: args: - --listen-address=0.0.0.0:8080 - --runtime-token-file=/var/run/fleet/token - - --state-file=/var/lib/fleet/state.json + - --state-dir=/var/lib/fleet/site + - --enrollment-file=/etc/fleet/enrollment/enrollment.json + - --discover ports: [{name: runtime, containerPort: 8080}] readinessProbe: {httpGet: {path: /readyz, port: runtime}, periodSeconds: 2} - livenessProbe: {httpGet: {path: /healthz, port: runtime}, periodSeconds: 10} + livenessProbe: {httpGet: {path: /readyz, port: runtime}, periodSeconds: 10} securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} resources: requests: {cpu: 20m, memory: 32Mi} @@ -38,9 +42,12 @@ spec: volumeMounts: - {name: state, mountPath: /var/lib/fleet} - {name: runtime-token, mountPath: /var/run/fleet, readOnly: true} + - {name: enrollment, mountPath: /etc/fleet/enrollment, readOnly: true} volumes: - name: runtime-token secret: {secretName: fleet-simulator-runtime, defaultMode: 0440} + - name: enrollment + configMap: {name: fleet-simulator-enrollment, defaultMode: 0440} volumeClaimTemplates: - metadata: {name: state} spec: diff --git a/config/components/admission/policies.yaml b/config/components/admission/policies.yaml index 234d30cc..fef959f6 100644 --- a/config/components/admission/policies.yaml +++ b/config/components/admission/policies.yaml @@ -26,35 +26,3 @@ metadata: spec: policyName: fleet-machine-finalizer-protection validationActions: [Deny] ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-private-record-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [CREATE, UPDATE, DELETE] - resources: [secrets] - matchConditions: - - name: private-record - expression: >- - (request.operation != 'DELETE' && has(object.metadata.labels) && - 'fleet.datumapis.com/private-record' in object.metadata.labels) || - (request.operation != 'CREATE' && has(oldObject.metadata.labels) && - 'fleet.datumapis.com/private-record' in oldObject.metadata.labels) - validations: - - expression: >- - request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-manager' - message: Fleet private coordination records are service-controlled. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-private-record-protection -spec: - policyName: fleet-private-record-protection - validationActions: [Deny] diff --git a/config/components/boot-addresses/boot-address-checker.yaml b/config/components/boot-addresses/boot-address-checker.yaml new file mode 100644 index 00000000..3b61a02b --- /dev/null +++ b/config/components/boot-addresses/boot-address-checker.yaml @@ -0,0 +1,11 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-boot-address-checker + annotations: + kubernetes.io/display-name: Fleet Boot Address Checker + kubernetes.io/description: The custody coordinator at a site whose DHCP Fleet synchronizes. Reads an operation's boot address claim at admission. +spec: + launchStage: Alpha + includedPermissions: + - ipam.miloapis.com/ipclaims.get diff --git a/config/components/boot-addresses/boot-address-requester.yaml b/config/components/boot-addresses/boot-address-requester.yaml new file mode 100644 index 00000000..944a86dd --- /dev/null +++ b/config/components/boot-addresses/boot-address-requester.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-boot-address-requester + annotations: + kubernetes.io/display-name: Fleet Boot Address Requester + kubernetes.io/description: The Fleet provider for Metal and the release controller at a site whose DHCP Fleet synchronizes. Claims and releases the boot address of each installation and wipe, and reads IPAM's allocations to confirm a release. +spec: + launchStage: Alpha + includedPermissions: + - ipam.miloapis.com/ipclaims.create + - ipam.miloapis.com/ipclaims.get + - ipam.miloapis.com/ipclaims.list + - ipam.miloapis.com/ipclaims.delete + - ipam.miloapis.com/ipallocations.get + - ipam.miloapis.com/ipallocations.list diff --git a/config/components/boot-addresses/kustomization.yaml b/config/components/boot-addresses/kustomization.yaml new file mode 100644 index 00000000..8d05313c --- /dev/null +++ b/config/components/boot-addresses/kustomization.yaml @@ -0,0 +1,11 @@ +# Roles for boot address claims, which only a site whose DHCP Fleet +# synchronizes uses (docs/operations/boot-network.md). No overlay includes +# this component, so no environment grants Fleet any IPAM permission until +# it enables boot addresses: it then includes this component and binds the +# requester role to the installation and wipe requesters and the checker +# role to the custody coordinator. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - boot-address-requester.yaml + - boot-address-checker.yaml diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml new file mode 100644 index 00000000..a0d79d9e --- /dev/null +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -0,0 +1,8 @@ +# Reusable and opt-in: no root in this repository includes it. A deploying +# repository that must keep in-service Devices adds it to the root it applies +# to the Milo control plane, where Devices are admitted. See +# docs/development/inventory-capacity-registration.md#device-deletion-protection. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - policy.yaml diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml new file mode 100644 index 00000000..7f96fa87 --- /dev/null +++ b/config/components/device-deletion-protection/policy.yaml @@ -0,0 +1,75 @@ +# A Device is deleted only after it is Retired, so a Device in service stays +# visible to duplicate-hardware checks. Retire a Device by moving +# spec.lifecycle to Decommissioning and then Retired; the CRD rejects every +# other path to Retired, and Retired is terminal. +# +# Three exceptions admit a DELETE: +# +# 1. The Device's namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace +# is the privileged escape hatch: it lets the namespace controller finish +# and takes its Devices with it. +# 2. The Device is Retired. +# 3. The request's username is listed, exactly, in the cleanupUsernames key of +# the binding's parameter ConfigMap. This lets a project cleanup controller +# drain Devices in place, which namespace deletion cannot do for `default`. +# Entries are separated by commas or newlines and trimmed; empty entries +# and an empty username never match. Groups, prefixes and wildcards are not +# consulted. +# +# Exception 3 is a stopgap. Milo's project cleanup deletes namespaced +# resources before it marks any namespace for deletion, and it never deletes +# `default`, so exception 1 cannot cover project teardown today. Milo should +# mark every namespace it purges, `default` included, before deleting its +# contents. This policy can then rely on that namespace signal and drop the +# subject exemption. +# +# The binding below has no paramRef, so params is null and exception 3 is off. +# A deploying repository turns it on by adding the ConfigMap and patching the +# binding with a paramRef that sets parameterNotFoundAction: Deny; a missing +# ConfigMap then denies every Device DELETE. The API server runs admission once +# per object for deletecollection, garbage collection and namespace cleanup, so +# each of those paths is held to the same rule. A missing namespace object or +# an evaluation error denies the request (failurePolicy: Fail). +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-deletion-protection +spec: + failurePolicy: Fail + paramKind: + apiVersion: v1 + kind: ConfigMap + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [DELETE] + resources: [devices] + validations: + - expression: >- + (namespaceObject != null && has(namespaceObject.metadata) && + has(namespaceObject.metadata.deletionTimestamp)) || + (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && + oldObject.spec.lifecycle == 'Retired') || + (params != null && has(params.data) && 'cleanupUsernames' in params.data && + request.userInfo.username != '' && + params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, + entry.trim() != '' && entry.trim() == request.userInfo.username)) + reason: Forbidden + message: >- + A Device can be deleted only when it is Retired, when its namespace is + being deleted, or by a configured cleanup identity. Move the Device to + Decommissioning, then Retired, first; its identity must stay visible to + duplicate-hardware checks while it is in service. +--- +# No paramRef: params is null and only the namespace and Retired exceptions +# apply. See docs/development/inventory-capacity-registration.md#cleanup-identity. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-deletion-protection +spec: + policyName: fleet-device-deletion-protection + validationActions: [Deny] diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml new file mode 100644 index 00000000..e184cd8e --- /dev/null +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -0,0 +1,2273 @@ +# DeviceCustody and the Device operation kinds proposed in #174 at d4d17f9. +# The coordinator is the only writer of custody and of operation status. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecustodies.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCustody + listKind: DeviceCustodyList + plural: devicecustodies + singular: devicecustody + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: State + type: string + jsonPath: .spec.state + - name: Holder + type: string + jsonPath: .spec.holder.type + - name: Fence + type: integer + jsonPath: .spec.fence + - name: Active + type: string + jsonPath: .spec.activeOperation.name + - name: Hold + type: string + jsonPath: .spec.recoveryHold.name + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + state: + type: string + enum: + - Verified + - Unverified + holder: + type: object + properties: + type: + type: string + enum: + - None + - Allocation + - Release + - Service + - Retired + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + openGates: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + disposedDrives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + serialNumber: + type: string + maxLength: 253 + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + recovery: + type: string + minLength: 1 + maxLength: 253 + required: + - name + - serialNumber + - method + - reference + - recovery + required: + - type + x-kubernetes-validations: + - rule: (self.type == 'Allocation' || self.type == 'Release') == has(self.allocationRef) + message: allocationRef is set exactly for Allocation and Release + - rule: self.type == 'Release' || !has(self.openGates) || size(self.openGates) == 0 + message: only Release has open gates + - rule: self.type == 'Release' || !has(self.disposedDrives) || size(self.disposedDrives) == 0 + message: only Release records disposed drives + fence: + type: integer + format: int64 + minimum: 0 + activeOperation: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 1 + phase: + type: string + enum: + - Admitted + - Dispatched + - Verifying + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + inputDigest: + type: string + minLength: 1 + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + settles: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + required: + - kind + - name + - fence + required: + - kind + - name + - fence + - phase + - admittedAt + - deadline + - inputDigest + - snapshot + - creator + lastResult: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + finishedAt: + type: string + format: date-time + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + required: + - kind + - name + - fence + - phase + - finishedAt + recoveryHold: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + since: + type: string + format: date-time + reason: + type: string + minLength: 1 + maxLength: 128 + deadline: + type: string + format: date-time + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + retryAuthorizedBy: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + required: + - kind + - name + - fence + retries: + type: integer + format: int32 + minimum: 0 + retryName: + type: string + maxLength: 253 + drives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + serialNumber: + type: string + maxLength: 253 + state: + type: string + enum: + - Missing + - Uncovered + required: + - name + - serialNumber + - state + waiting: + type: object + properties: + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 512 + required: + - reason + - message + required: + - kind + - name + - fence + - since + - reason + conflicts: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + rejectedResults: + type: object + properties: + count: + type: integer + format: int64 + minimum: 0 + last: + type: object + properties: + kind: + type: string + maxLength: 63 + name: + type: string + maxLength: 253 + fence: + type: integer + format: int64 + site: + type: string + maxLength: 253 + rejectedAt: + type: string + format: date-time + required: + - count + - last + required: + - deviceRef + - state + - holder + - fence + x-kubernetes-validations: + - rule: self.deviceRef.name == oldSelf.deviceRef.name + message: custody names one Device + - rule: self.fence >= oldSelf.fence + message: the fence never decreases + - rule: oldSelf.holder.type != 'Retired' || self.holder.type == 'Retired' + message: Retired is terminal + - rule: '!has(self.activeOperation) || self.activeOperation.fence == self.fence' + message: the active operation carries the current fence + required: + - spec + x-kubernetes-validations: + - rule: self.metadata.name == self.spec.deviceRef.name + message: custody has the same name as its Device +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceinstallations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceInstallation + listKind: DeviceInstallationList + plural: deviceinstallations + singular: deviceinstallation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + firmwareModes: + type: array + maxItems: 2 + items: + type: string + enum: + - UEFI + - BIOS + downloads: + type: array + maxItems: 8 + items: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 63 + reference: + type: string + minLength: 1 + maxLength: 512 + required: + - name + - reference + required: + - name + - digest + bootstrap: + type: object + properties: + ref: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - ref + - digest + bootInterface: + type: string + minLength: 1 + maxLength: 63 + targetDisks: + type: array + minItems: 1 + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + bootNetwork: + type: object + properties: + addressClaim: + type: object + properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + required: + - apiGroup + - kind + - name + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address + # Optional in the schema so installations stored before it + # existed stay valid; admission refuses an installation that + # records no known method. + delivery: + type: object + properties: + method: + type: string + enum: + - NetworkBoot + - VirtualMedia + addresses: + type: string + enum: + - DataNetwork + mediaService: + type: string + maxLength: 64 + fetchWindow: + type: string + maxLength: 32 + reportWindow: + type: string + maxLength: 32 + reportAddress: + type: object + properties: + addressClaim: + type: object + properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + required: + - apiGroup + - kind + - name + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address + required: + - method + x-kubernetes-validations: + - rule: self.method != 'NetworkBoot' || (!has(self.addresses) && !has(self.mediaService) && !has(self.fetchWindow) && !has(self.reportWindow) && !has(self.reportAddress)) + message: network boot records no virtual media inputs + - rule: self.method != 'VirtualMedia' || (has(self.addresses) && has(self.mediaService) && has(self.fetchWindow) && has(self.reportWindow) && has(self.reportAddress)) + message: virtual media records the site's address mode, media service, phase windows and the Machine's report address + required: + - creator + - deviceRef + - authority + - image + - bootInterface + - targetDisks + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicewipes.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceWipe + listKind: DeviceWipeList + plural: devicewipes + singular: devicewipe + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + step: + type: integer + format: int32 + minimum: 1 + policy: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - name + - generation + - digest + assurance: + type: string + enum: [Clear, Purge] + drives: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, serialNumber, model, firmware, protocol, mediaType, capacityBytes] + properties: + name: {type: string, pattern: '^disk-[0-9]+$', maxLength: 12} + serialNumber: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + firmware: {type: string, maxLength: 63} + protocol: {type: string, maxLength: 31} + mediaType: {type: string, maxLength: 31} + capacityBytes: {type: integer, minimum: 0} + rule: {type: string, maxLength: 63} + methods: + type: array + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + state: {type: string, enum: [Missing, Uncovered]} + # Optional in the schema so wipes stored before it existed stay + # valid; admission refuses a wipe whose boot interface the + # Device does not record with a MAC address. + bootInterface: + type: string + minLength: 1 + maxLength: 63 + bootNetwork: + type: object + properties: + addressClaim: + type: object + properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + required: + - apiGroup + - kind + - name + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address + required: + - creator + - deviceRef + - authority + - step + - policy + - assurance + - drives + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicepoweroperations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DevicePowerOperation + listKind: DevicePowerOperationList + plural: devicepoweroperations + singular: devicepoweroperation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Action + type: string + jsonPath: .spec.action + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + action: + type: string + enum: + - "On" + - ForceOff + - ForceRestart + - PowerCycle + expectedSystemUUID: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + machineGeneration: + type: integer + format: int64 + minimum: 1 + required: + - creator + - deviceRef + - authority + - action + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + - rule: has(self.authority.serviceRequest) == has(self.expectedSystemUUID) + message: a staff operation sets expectedSystemUUID, and a provider operation omits it + - rule: has(self.authority.allocationRef) == has(self.machineGeneration) + message: a provider operation sets machineGeneration, and a staff operation omits it + - rule: '!has(self.authority.allocationRef) || size(self.authority.allocationRef.name) <= 200' + message: a provider operation's allocation name is at most 200 characters, so its name and retry names fit + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + properties: + requestSentAt: + type: string + format: date-time + power: + type: object + properties: + before: + type: object + properties: + state: + type: string + enum: + - "On" + - "Off" + - PoweringOn + - PoweringOff + - Paused + observedAt: + type: string + format: date-time + required: + - state + - observedAt + after: + type: object + properties: + state: + type: string + enum: + - "On" + - "Off" + - PoweringOn + - PoweringOff + - Paused + observedAt: + type: string + format: date-time + required: + - state + - observedAt + resetEvidence: + type: string + enum: + - LastResetTime + - ObservedOff + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicerecoveries.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceRecovery + listKind: DeviceRecoveryList + plural: devicerecoveries + singular: devicerecovery + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + decision: + type: string + enum: + - Settle + - Retry + - Retire + - Resolve + - DisposeDrive + hold: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + required: + - kind + - name + - fence + evidence: + type: object + properties: + observedAt: + type: string + format: date-time + summary: + type: string + minLength: 1 + maxLength: 1024 + data: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + required: + - observedAt + - summary + diskDisposal: + type: object + properties: + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + required: + - method + - reference + drive: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + required: + - name + - method + - reference + resolve: + type: object + properties: + holder: + type: string + enum: + - None + - Allocation + - Release + - Retired + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + required: + - holder + required: + - creator + - deviceRef + - authority + - decision + - evidence + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + - rule: (self.decision == 'Resolve') == has(self.resolve) + message: resolve is set exactly for Resolve + - rule: self.decision == 'Resolve' || has(self.hold) + message: Settle, Retry, Retire and DisposeDrive name the hold + - rule: '!has(self.diskDisposal) || self.decision == ''Retire''' + message: only Retire records disk disposal + - rule: (self.decision == 'DisposeDrive') == has(self.drive) + message: drive is set exactly for DisposeDrive + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissionings.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioning + listKind: DeviceCommissioningList + plural: devicecommissionings + singular: devicecommissioning + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + plan: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 236 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + approval: + type: string + minLength: 18 + maxLength: 253 + content: + type: object + properties: + inspection: + type: object + properties: + cpu: + type: object + properties: + architecture: + type: string + enum: [amd64, arm64] + cores: + type: integer + format: int64 + minimum: 1 + maximum: 4096 + required: [architecture, cores] + memory: + type: object + properties: + capacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [capacity] + disks: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + minCapacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [count, minCapacity] + interfaces: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + required: [count] + required: [cpu, memory, disks, interfaces] + firmware: + type: array + maxItems: 32 + items: + type: object + properties: + component: + type: string + minLength: 1 + maxLength: 128 + version: + type: string + minLength: 1 + maxLength: 128 + required: [component, version] + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [component] + burnIn: + type: object + properties: + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, digest] + duration: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1m') && duration(self) <= duration('24h') + message: burn-in runs from 1 minute to 24 hours + required: [image, duration] + required: [inspection, burnIn] + required: [name, generation, digest, approval, content] + required: + - creator + - deviceRef + - authority + - plan + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissioningplans.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioningPlan + listKind: DeviceCommissioningPlanList + plural: devicecommissioningplans + singular: devicecommissioningplan + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Creator + type: string + jsonPath: .spec.creator.username + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceSelector: + type: object + properties: + matchLabels: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 63 + matchExpressions: + type: array + maxItems: 16 + items: + type: object + properties: + key: + type: string + minLength: 1 + maxLength: 317 + operator: + type: string + enum: [In, NotIn, Exists, DoesNotExist] + values: + type: array + maxItems: 16 + items: + type: string + maxLength: 63 + required: [key, operator] + x-kubernetes-validations: + - rule: (has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) && size(self.matchExpressions) > 0) + message: a plan must select Devices + supersedes: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 253 + x-kubernetes-list-type: set + content: + type: object + properties: + inspection: + type: object + properties: + cpu: + type: object + properties: + architecture: + type: string + enum: [amd64, arm64] + cores: + type: integer + format: int64 + minimum: 1 + maximum: 4096 + required: [architecture, cores] + memory: + type: object + properties: + capacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [capacity] + disks: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + minCapacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [count, minCapacity] + interfaces: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + required: [count] + required: [cpu, memory, disks, interfaces] + firmware: + type: array + maxItems: 32 + items: + type: object + properties: + component: + type: string + minLength: 1 + maxLength: 128 + version: + type: string + minLength: 1 + maxLength: 128 + required: [component, version] + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [component] + burnIn: + type: object + properties: + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, digest] + duration: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1m') && duration(self) <= duration('24h') + message: burn-in runs from 1 minute to 24 hours + required: [image, duration] + required: [inspection, burnIn] + evidenceLifetime: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1h') && duration(self) <= duration('8760h') + message: evidence stays current from 1 hour to 365 days + required: + - creator + - deviceSelector + - content + - evidenceLifetime + x-kubernetes-validations: + - rule: self == oldSelf + message: the spec is immutable after create + required: + - spec + x-kubernetes-validations: + - rule: size(self.metadata.name) <= 236 + message: a plan's name leaves room for its approval's suffix +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissioningplanapprovals.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioningPlanApproval + listKind: DeviceCommissioningPlanApprovalList + plural: devicecommissioningplanapprovals + singular: devicecommissioningplanapproval + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Approver + type: string + jsonPath: .spec.creator.username + - name: Digest + type: string + jsonPath: .spec.planRef.digest + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + planRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 236 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, generation, digest] + required: + - creator + - planRef + x-kubernetes-validations: + - rule: self == oldSelf + message: the spec is immutable after create + required: + - spec + x-kubernetes-validations: + - rule: self.metadata.name.startsWith(self.spec.planRef.name + '-') && size(self.metadata.name) == size(self.spec.planRef.name) + 17 + message: an approval's name is its plan's name and a suffix derived from the plan's UID +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cleaningpolicies.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: CleaningPolicy + listKind: CleaningPolicyList + plural: cleaningpolicies + singular: cleaningpolicy + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Assurance + type: string + jsonPath: .spec.assurance + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: [assurance, rules] + properties: + assurance: {type: string, enum: [Clear, Purge]} + rules: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, match, methods, verify, timePerTiB] + properties: + name: {type: string, minLength: 1, maxLength: 63} + match: + type: object + required: [protocol, mediaType] + properties: + protocol: {type: string, enum: [NVMe, SATA, SAS]} + mediaType: {type: string, enum: [SSD, HDD]} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + qualified: + type: array + maxItems: 32 + items: + type: object + required: [model, firmware, methods] + properties: + model: {type: string, minLength: 1, maxLength: 128} + firmware: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: set + items: {type: string, minLength: 1, maxLength: 64} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + alwaysEncrypts: {type: boolean} + x-kubernetes-validations: + - rule: self == oldSelf + message: a CleaningPolicy spec is immutable; create a new policy instead + required: + - spec diff --git a/config/components/device-operations/crds/kustomization.yaml b/config/components/device-operations/crds/kustomization.yaml new file mode 100644 index 00000000..24d03271 --- /dev/null +++ b/config/components/device-operations/crds/kustomization.yaml @@ -0,0 +1,3 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [fleet.datumapis.com.yaml, sealedpayloads.yaml] diff --git a/config/components/device-operations/crds/sealedpayloads.yaml b/config/components/device-operations/crds/sealedpayloads.yaml new file mode 100644 index 00000000..b5cff7d3 --- /dev/null +++ b/config/components/device-operations/crds/sealedpayloads.yaml @@ -0,0 +1,41 @@ +# The sealed store for customer bootstrap data (#184). A dedicated kind, not a +# Secret, because Milo grants permissions per kind or per object, never per +# namespace: only roles that name this kind can read it. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: sealedpayloads.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: SealedPayload + listKind: SealedPayloadList + plural: sealedpayloads + singular: sealedpayload + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - {rule: 'self == oldSelf', message: a sealed payload never changes} + required: [operationName, allocationName, digest, salt, data] + properties: + operationName: {type: string, minLength: 1, maxLength: 253} + allocationName: {type: string, minLength: 1, maxLength: 253} + digest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + # 32 random bytes, base64. + salt: {type: string, format: byte, minLength: 44, maxLength: 44} + # At most 96 KiB of encoded bootstrap data, base64. + data: {type: string, format: byte, minLength: 1, maxLength: 131072} diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml new file mode 100644 index 00000000..0b86e400 --- /dev/null +++ b/config/components/device-operations/kustomization.yaml @@ -0,0 +1,11 @@ +# Device custody and operations (#174 at d4d17f9): the kinds, their +# ProtectedResources and roles, and the creator webhook, which the +# fleet-registration server serves. config/milo includes all of it; +# config/milo-synthetic includes everything but the webhook. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crds + - protected-resources + - roles + - webhook.yaml diff --git a/config/components/device-operations/protected-resources/cleaningpolicy.yaml b/config/components/device-operations/protected-resources/cleaningpolicy.yaml new file mode 100644 index 00000000..6ccd1417 --- /dev/null +++ b/config/components/device-operations/protected-resources/cleaningpolicy.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-cleaningpolicy +spec: + serviceRef: + name: fleet.datumapis.com + kind: CleaningPolicy + plural: cleaningpolicies + singular: cleaningpolicy + # The spec is immutable, so no role needs update or patch. A changed + # policy is a new policy. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecommissioning.yaml b/config/components/device-operations/protected-resources/devicecommissioning.yaml new file mode 100644 index 00000000..89bfbb7f --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioning.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioning +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioning + plural: devicecommissionings + singular: devicecommissioning + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicecommissionings/status.update and + # devicecommissionings/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecommissioningplan.yaml b/config/components/device-operations/protected-resources/devicecommissioningplan.yaml new file mode 100644 index 00000000..c319de68 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioningplan.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioningplan +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioningPlan + plural: devicecommissioningplans + singular: devicecommissioningplan + # The spec is immutable after create, so no role grants update or patch. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml b/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml new file mode 100644 index 00000000..0c253986 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioningplanapproval +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioningPlanApproval + plural: devicecommissioningplanapprovals + singular: devicecommissioningplanapproval + # The spec is immutable after create, so no role grants update or patch. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecustody.yaml b/config/components/device-operations/protected-resources/devicecustody.yaml new file mode 100644 index 00000000..1412df9c --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecustody.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecustody +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCustody + plural: devicecustodies + singular: devicecustody + # Custody keeps its fields in spec, like a Lease, and has no status. Only + # the coordinator role holds a write verb. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/deviceinstallation.yaml b/config/components/device-operations/protected-resources/deviceinstallation.yaml new file mode 100644 index 00000000..c3dfe734 --- /dev/null +++ b/config/components/device-operations/protected-resources/deviceinstallation.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-deviceinstallation +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceInstallation + plural: deviceinstallations + singular: deviceinstallation + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use deviceinstallations/status.update and + # deviceinstallations/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicepoweroperation.yaml b/config/components/device-operations/protected-resources/devicepoweroperation.yaml new file mode 100644 index 00000000..e701646c --- /dev/null +++ b/config/components/device-operations/protected-resources/devicepoweroperation.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicepoweroperation +spec: + serviceRef: + name: fleet.datumapis.com + kind: DevicePowerOperation + plural: devicepoweroperations + singular: devicepoweroperation + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicepoweroperations/status.update and + # devicepoweroperations/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicerecovery.yaml b/config/components/device-operations/protected-resources/devicerecovery.yaml new file mode 100644 index 00000000..5debf720 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicerecovery.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicerecovery +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceRecovery + plural: devicerecoveries + singular: devicerecovery + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicerecoveries/status.update and + # devicerecoveries/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicewipe.yaml b/config/components/device-operations/protected-resources/devicewipe.yaml new file mode 100644 index 00000000..c7fc7ddd --- /dev/null +++ b/config/components/device-operations/protected-resources/devicewipe.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicewipe +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceWipe + plural: devicewipes + singular: devicewipe + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicewipes/status.update and + # devicewipes/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml new file mode 100644 index 00000000..34698aae --- /dev/null +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -0,0 +1,13 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - devicecustody.yaml + - deviceinstallation.yaml + - devicewipe.yaml + - devicepoweroperation.yaml + - devicerecovery.yaml + - sealedpayload.yaml + - cleaningpolicy.yaml + - devicecommissioning.yaml + - devicecommissioningplan.yaml + - devicecommissioningplanapproval.yaml diff --git a/config/components/device-operations/protected-resources/sealedpayload.yaml b/config/components/device-operations/protected-resources/sealedpayload.yaml new file mode 100644 index 00000000..e3ec9a3b --- /dev/null +++ b/config/components/device-operations/protected-resources/sealedpayload.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-sealedpayload +spec: + serviceRef: + name: fleet.datumapis.com + kind: SealedPayload + plural: sealedpayloads + singular: sealedpayload + # The spec never changes, so there is no update or patch. + permissions: [list, get, watch, create, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/roles/capacity-projector.yaml b/config/components/device-operations/roles/capacity-projector.yaml new file mode 100644 index 00000000..964cc023 --- /dev/null +++ b/config/components/device-operations/roles/capacity-projector.yaml @@ -0,0 +1,30 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-capacity-projector + annotations: + kubernetes.io/display-name: Fleet Capacity Projector + kubernetes.io/description: The only writer of MachineCapacity status. Derives Prepared, Healthy, Available and the hardware from commissioning, discovery and custody evidence. Bound on the provider project, it reads Devices in every namespace, a deliberate widening so a duplicate identity in another namespace withdraws the offer. +spec: + launchStage: Alpha + includedPermissions: + - metal.datumapis.com/machinecapacities.get + - metal.datumapis.com/machinecapacities.list + - metal.datumapis.com/machinecapacities.watch + - metal.datumapis.com/machinecapacities.updateStatus + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch + - fleet.datumapis.com/cleaningpolicies.get diff --git a/config/components/device-operations/roles/cleaning-policy-admin.yaml b/config/components/device-operations/roles/cleaning-policy-admin.yaml new file mode 100644 index 00000000..ec48a121 --- /dev/null +++ b/config/components/device-operations/roles/cleaning-policy-admin.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-cleaning-policy-admin + annotations: + kubernetes.io/display-name: Fleet Cleaning Policy Admin + kubernetes.io/description: Provider operators. Create and delete CleaningPolicies, which say how Fleet cleans a server between customers. A policy cannot be changed after creation. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/cleaningpolicies.create + - fleet.datumapis.com/cleaningpolicies.get + - fleet.datumapis.com/cleaningpolicies.list + - fleet.datumapis.com/cleaningpolicies.watch + - fleet.datumapis.com/cleaningpolicies.delete diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml new file mode 100644 index 00000000..92e5ec37 --- /dev/null +++ b/config/components/device-operations/roles/coordinator.yaml @@ -0,0 +1,72 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-coordinator + annotations: + kubernetes.io/display-name: Fleet Device Coordinator + kubernetes.io/description: The only writer of Device custody and of operation status. Reads inventory and allocations to rebuild custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/sites.list + - fleet.datumapis.com/deviceclaims.get + - fleet.datumapis.com/racks.get + - fleet.datumapis.com/facilities.get + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/devicecustodies.create + - fleet.datumapis.com/devicecustodies.update + - fleet.datumapis.com/devicecustodies.delete + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/deviceinstallations.delete + - fleet.datumapis.com/deviceinstallations.updateStatus + - fleet.datumapis.com/deviceinstallations/status.update + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicewipes.delete + - fleet.datumapis.com/devicewipes.updateStatus + - fleet.datumapis.com/devicewipes/status.update + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicepoweroperations.delete + - fleet.datumapis.com/devicepoweroperations.updateStatus + - fleet.datumapis.com/devicepoweroperations/status.update + - fleet.datumapis.com/devicerecoveries.get + - fleet.datumapis.com/devicerecoveries.list + - fleet.datumapis.com/devicerecoveries.watch + - fleet.datumapis.com/devicerecoveries.delete + - fleet.datumapis.com/devicerecoveries.updateStatus + - fleet.datumapis.com/devicerecoveries/status.update + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissionings.delete + - fleet.datumapis.com/devicecommissionings.updateStatus + - fleet.datumapis.com/devicecommissionings/status.update + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - metal.datumapis.com/machineallocations.get + - metal.datumapis.com/machineallocations.list + - metal.datumapis.com/machineallocations.watch + - metal.datumapis.com/machinecapacities.get + - metal.datumapis.com/machinecapacities.list + - metal.datumapis.com/machinecapacities.watch + # The coordinator checks each payload at admission, the federation + # courier in it delivers payloads to sites, and it deletes them. No + # other role can read the sealed store. + - fleet.datumapis.com/sealedpayloads.get + - fleet.datumapis.com/sealedpayloads.list + - fleet.datumapis.com/sealedpayloads.watch + - fleet.datumapis.com/sealedpayloads.delete diff --git a/config/components/device-operations/roles/device-commissioning-operator.yaml b/config/components/device-operations/roles/device-commissioning-operator.yaml new file mode 100644 index 00000000..43db6147 --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-operator.yaml @@ -0,0 +1,13 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-operator + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Operator + kubernetes.io/description: Commission a Device that no customer holds, under its current qualified plan. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissionings.create diff --git a/config/components/device-operations/roles/device-commissioning-plan-approver.yaml b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml new file mode 100644 index 00000000..7c25b4d6 --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-plan-approver + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Plan Approver + kubernetes.io/description: Approve another person's commissioning plan, or revoke an approval. Never bind this role and the plan author role to the same principal, or to groups that share a member. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissioningplanapprovals.create + - fleet.datumapis.com/devicecommissioningplanapprovals.delete diff --git a/config/components/device-operations/roles/device-commissioning-plan-author.yaml b/config/components/device-operations/roles/device-commissioning-plan-author.yaml new file mode 100644 index 00000000..2bb58563 --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-plan-author.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-plan-author + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Plan Author + kubernetes.io/description: Write and delete commissioning plans. An author cannot approve a plan they wrote. Never bind this role and the plan approver role to the same principal, or to groups that share a member. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissioningplans.create + - fleet.datumapis.com/devicecommissioningplans.delete diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml new file mode 100644 index 00000000..ed620e56 --- /dev/null +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -0,0 +1,32 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-installation-requester + annotations: + kubernetes.io/display-name: Fleet Device Installation Requester + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, and pins cleaning policies, and reads custody and the commissioning evidence it evaluates capacity from. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/deviceinstallations.create + # It copies bootstrap data into the sealed store and never reads it back. + - fleet.datumapis.com/sealedpayloads.create + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/cleaningpolicies.get + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml new file mode 100644 index 00000000..3f974f77 --- /dev/null +++ b/config/components/device-operations/roles/kustomization.yaml @@ -0,0 +1,15 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - coordinator.yaml + - viewer.yaml + - recovery-operator.yaml + - installation-requester.yaml + - wipe-requester.yaml + - cleaning-policy-admin.yaml + - device-commissioning-operator.yaml + - device-commissioning-plan-author.yaml + - device-commissioning-plan-approver.yaml + - capacity-projector.yaml + - power-operator.yaml + - power-requester.yaml diff --git a/config/components/device-operations/roles/power-operator.yaml b/config/components/device-operations/roles/power-operator.yaml new file mode 100644 index 00000000..85992605 --- /dev/null +++ b/config/components/device-operations/roles/power-operator.yaml @@ -0,0 +1,13 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-operator + annotations: + kubernetes.io/display-name: Fleet Device Power Operator + kubernetes.io/description: Power a Device on or off, or reset it, while no customer holds it. Creates only DevicePowerOperations, and does not read MachineAllocations. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.create diff --git a/config/components/device-operations/roles/power-requester.yaml b/config/components/device-operations/roles/power-requester.yaml new file mode 100644 index 00000000..f0fd80db --- /dev/null +++ b/config/components/device-operations/roles/power-requester.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-requester + annotations: + kubernetes.io/display-name: Fleet Device Power Requester + kubernetes.io/description: The Fleet provider for Metal. Creates DevicePowerOperations from Machine power intent and reads custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.create + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch diff --git a/config/components/device-operations/roles/recovery-operator.yaml b/config/components/device-operations/roles/recovery-operator.yaml new file mode 100644 index 00000000..2ed16ee5 --- /dev/null +++ b/config/components/device-operations/roles/recovery-operator.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-recovery-operator + annotations: + kubernetes.io/display-name: Fleet Device Recovery Operator + kubernetes.io/description: Settle, retry, retire or resolve a Device whose operation outcome is unknown or whose custody is Unverified. Reads MachineAllocations to identify the customer. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicerecoveries.create + - metal.datumapis.com/machineallocations.get + - metal.datumapis.com/machineallocations.list + - metal.datumapis.com/machineallocations.watch diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml new file mode 100644 index 00000000..ba168a7b --- /dev/null +++ b/config/components/device-operations/roles/viewer.yaml @@ -0,0 +1,37 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-operations-viewer + annotations: + kubernetes.io/display-name: Fleet Device Operations Viewer + kubernetes.io/description: Read Device custody and operations. Does not read MachineAllocations, so it does not see which customer holds a Device. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicerecoveries.get + - fleet.datumapis.com/devicerecoveries.list + - fleet.datumapis.com/devicerecoveries.watch + - fleet.datumapis.com/cleaningpolicies.get + - fleet.datumapis.com/cleaningpolicies.list + - fleet.datumapis.com/cleaningpolicies.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch diff --git a/config/components/device-operations/roles/wipe-requester.yaml b/config/components/device-operations/roles/wipe-requester.yaml new file mode 100644 index 00000000..ff7dce80 --- /dev/null +++ b/config/components/device-operations/roles/wipe-requester.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-wipe-requester + annotations: + kubernetes.io/display-name: Fleet Device Wipe Requester + kubernetes.io/description: The release controller. Creates DeviceWipes during release and reads custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicewipes.create + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml new file mode 100644 index 00000000..b32721d7 --- /dev/null +++ b/config/components/device-operations/webhook.yaml @@ -0,0 +1,42 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-operation-creator +webhooks: + # Milo's root API server calls this webhook, because Milo does not evaluate + # admission policies stored in a project. It rejects a create whose + # spec.creator is not the authenticated caller, and any change to it. It is + # fail-closed. Status writes are not routed; only the coordinator role can + # make them. + - name: creator.operations.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-operation-creator + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + # The same list as creatorwebhook.Resources and the standalone creator + # policy; TestPackagedResourcesMatch keeps them in step. + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + scope: Namespaced + # Rejects a CleaningPolicy whose methods cannot reach its assurance, or + # that does not fit its drives. The CRD keeps the spec immutable. + - name: cleaningpolicies.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-cleaning-policy + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE] + resources: [cleaningpolicies] + scope: Namespaced diff --git a/config/components/device-uuid-completion/kustomization.yaml b/config/components/device-uuid-completion/kustomization.yaml new file mode 100644 index 00000000..4fd00748 --- /dev/null +++ b/config/components/device-uuid-completion/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/device-uuid-completion/transition.json b/config/components/device-uuid-completion/transition.json new file mode 100644 index 00000000..f5e2b09e --- /dev/null +++ b/config/components/device-uuid-completion/transition.json @@ -0,0 +1,5 @@ +[ + {"op":"test","path":"/spec/versions/0/name","value":"v1alpha1"}, + {"op":"test","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/x-kubernetes-validations/1/rule","value":"self.identity == oldSelf.identity"}, + {"op":"replace","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/x-kubernetes-validations/1","value":{"rule":"self.identity == oldSelf.identity || (!has(oldSelf.identity.systemUUID) && has(self.identity.systemUUID) && has(oldSelf.identity.serial) && self.identity.model == oldSelf.identity.model && (has(self.identity.serial) == has(oldSelf.identity.serial) && (!has(self.identity.serial) || self.identity.serial == oldSelf.identity.serial)) && (has(self.identity.manufacturer) == has(oldSelf.identity.manufacturer) && (!has(self.identity.manufacturer) || self.identity.manufacturer == oldSelf.identity.manufacturer)) && (has(self.identity.unidentified) == has(oldSelf.identity.unidentified) && (!has(self.identity.unidentified) || self.identity.unidentified == oldSelf.identity.unidentified)) && (has(self.identity.unidentifiedReason) == has(oldSelf.identity.unidentifiedReason) && (!has(self.identity.unidentifiedReason) || self.identity.unidentifiedReason == oldSelf.identity.unidentifiedReason)))","message":"identity is immutable except for guarded serial-only UUID completion"}} +] diff --git a/config/components/device-uuid-completion/webhook.yaml b/config/components/device-uuid-completion/webhook.yaml new file mode 100644 index 00000000..6589274f --- /dev/null +++ b/config/components/device-uuid-completion/webhook.yaml @@ -0,0 +1,24 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-device-uuid +webhooks: + - name: uuid.devices.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 15 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-device-uuid + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [CREATE, UPDATE] + resources: [devices] + scope: Namespaced + matchConditions: + - name: uuid-create-or-identity-change + expression: >- + request.operation == 'CREATE' ? has(object.spec.identity.systemUUID) : + object.spec.identity != oldObject.spec.identity diff --git a/config/components/device-uuid-permission/kustomization.yaml b/config/components/device-uuid-permission/kustomization.yaml new file mode 100644 index 00000000..2aeaced4 --- /dev/null +++ b/config/components/device-uuid-permission/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +patches: + - target: + group: iam.miloapis.com + version: v1alpha1 + kind: ProtectedResource + name: fleet.datumapis.com-device + patch: |- + - op: add + path: /spec/permissions/- + value: completeuuid diff --git a/config/components/iam/protected-resources/kustomization.yaml b/config/components/iam/protected-resources/kustomization.yaml index 1fe1bed8..48436f24 100644 --- a/config/components/iam/protected-resources/kustomization.yaml +++ b/config/components/iam/protected-resources/kustomization.yaml @@ -7,3 +7,5 @@ resources: - machinecapacity.yaml - machineallocation.yaml - installation.yaml + - machineimage.yaml + - machineimagepublication.yaml diff --git a/config/components/iam/protected-resources/machineimage.yaml b/config/components/iam/protected-resources/machineimage.yaml new file mode 100644 index 00000000..96105793 --- /dev/null +++ b/config/components/iam/protected-resources/machineimage.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: metal.datumapis.com-machineimage +spec: + serviceRef: + name: metal.datumapis.com + kind: MachineImage + plural: machineimages + singular: machineimage + permissions: [list, get, watch, create, update, patch, delete, updateStatus, use] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/iam/protected-resources/machineimagepublication.yaml b/config/components/iam/protected-resources/machineimagepublication.yaml new file mode 100644 index 00000000..44a4f67e --- /dev/null +++ b/config/components/iam/protected-resources/machineimagepublication.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: metal.datumapis.com-machineimagepublication +spec: + serviceRef: + name: metal.datumapis.com + kind: MachineImagePublication + plural: machineimagepublications + singular: machineimagepublication + permissions: [list, get, watch, create, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/iam/roles/claimant.yaml b/config/components/iam/roles/claimant.yaml index 4bfa49d4..ee55173f 100644 --- a/config/components/iam/roles/claimant.yaml +++ b/config/components/iam/roles/claimant.yaml @@ -12,6 +12,7 @@ spec: includedPermissions: - metal.datumapis.com/machineclasses.use - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machines.create - metal.datumapis.com/machines.update - metal.datumapis.com/machines.patch diff --git a/config/components/iam/roles/consumer.yaml b/config/components/iam/roles/consumer.yaml index 79d4a471..eadb061f 100644 --- a/config/components/iam/roles/consumer.yaml +++ b/config/components/iam/roles/consumer.yaml @@ -15,6 +15,7 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machines.create - metal.datumapis.com/machines.update - metal.datumapis.com/machines.patch diff --git a/config/components/iam/roles/controller.yaml b/config/components/iam/roles/controller.yaml index 1ba48bd0..4bc87f12 100644 --- a/config/components/iam/roles/controller.yaml +++ b/config/components/iam/roles/controller.yaml @@ -13,13 +13,19 @@ spec: includedPermissions: - metal.datumapis.com/machineclasses.updateStatus - metal.datumapis.com/machineprofiles.updateStatus - - metal.datumapis.com/machinecapacities.updateStatus - metal.datumapis.com/machines.updateStatus - metal.datumapis.com/machineallocations.list - metal.datumapis.com/machineallocations.get - metal.datumapis.com/machineallocations.watch - metal.datumapis.com/machineallocations.create + # An allocation that lost its Device before it ever held it is deleted, + # and the allocator selects again. + - metal.datumapis.com/machineallocations.delete - metal.datumapis.com/machineallocations.update - metal.datumapis.com/machineallocations.patch - metal.datumapis.com/machineallocations.updateStatus - metal.datumapis.com/installations.updateStatus + # Admission resolves an image through its publication record. + - metal.datumapis.com/machineimagepublications.list + - metal.datumapis.com/machineimagepublications.get + - metal.datumapis.com/machineimagepublications.watch diff --git a/config/components/iam/roles/provider.yaml b/config/components/iam/roles/provider.yaml index d0517411..7566d8b0 100644 --- a/config/components/iam/roles/provider.yaml +++ b/config/components/iam/roles/provider.yaml @@ -24,6 +24,14 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.list + - metal.datumapis.com/machineimages.get + - metal.datumapis.com/machineimages.watch + - metal.datumapis.com/machineimages.create + - metal.datumapis.com/machineimages.update + - metal.datumapis.com/machineimages.patch + - metal.datumapis.com/machineimages.delete + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machinecapacities.list - metal.datumapis.com/machinecapacities.get - metal.datumapis.com/machinecapacities.watch diff --git a/config/components/iam/roles/publisher.yaml b/config/components/iam/roles/publisher.yaml index 97793bbe..f3c31d52 100644 --- a/config/components/iam/roles/publisher.yaml +++ b/config/components/iam/roles/publisher.yaml @@ -20,3 +20,15 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.updateStatus + # Publishing an image writes the consumer copy and the provider's + # publication record. Unpublishing deletes both, which is also how a + # publication is repaired after its copy or source is recreated. + # Customers hold no write on either kind. + - metal.datumapis.com/machineimages.create + - metal.datumapis.com/machineimages.update + - metal.datumapis.com/machineimages.patch + - metal.datumapis.com/machineimages.delete + - metal.datumapis.com/machineimages.updateStatus + - metal.datumapis.com/machineimagepublications.get + - metal.datumapis.com/machineimagepublications.create + - metal.datumapis.com/machineimagepublications.delete diff --git a/config/components/iam/roles/viewer.yaml b/config/components/iam/roles/viewer.yaml index 2899e220..a76afba6 100644 --- a/config/components/iam/roles/viewer.yaml +++ b/config/components/iam/roles/viewer.yaml @@ -20,3 +20,6 @@ spec: - metal.datumapis.com/installations.list - metal.datumapis.com/installations.get - metal.datumapis.com/installations.watch + - metal.datumapis.com/machineimages.list + - metal.datumapis.com/machineimages.get + - metal.datumapis.com/machineimages.watch diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml new file mode 100644 index 00000000..ed64acf7 --- /dev/null +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -0,0 +1,1458 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceclaims.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceClaim + listKind: DeviceClaimList + plural: deviceclaims + singular: deviceclaim + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Scope + type: string + jsonPath: .spec.placement.scope + - name: Facility + type: string + jsonPath: .spec.placement.facilityRef.name + - name: Rack + type: string + jsonPath: .spec.placement.rackRef.name + - name: Position + type: integer + jsonPath: .spec.placement.position + - name: Model + type: string + jsonPath: .spec.expectedIdentity.model + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - lifecycle + - expectedIdentity + - placement + x-kubernetes-validations: + - rule: self.placement == oldSelf.placement + message: installation placement is immutable; migration requires an explicit handover + properties: + expectedIdentity: + type: object + required: + - model + properties: + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 + placement: + type: object + required: + - scope + properties: + position: + type: integer + format: int32 + minimum: 1 + maximum: 100 + height: + type: integer + format: int32 + minimum: 1 + maximum: 100 + face: + type: string + enum: + - front + - rear + scope: + type: string + enum: + - Facility + - RackMembership + - RackUnits + - NonRackUnitMount + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + mount: + type: string + minLength: 1 + maxLength: 253 + x-kubernetes-validations: + - rule: 'self.scope == ''Facility'' ? (has(self.facilityRef) && !has(self.rackRef)) : (has(self.rackRef) + && !has(self.facilityRef))' + message: typed placement requires exactly the reference appropriate to its scope + - rule: 'self.scope == ''RackUnits'' ? (has(self.position) && has(self.height) && has(self.face) && !has(self.mount)) + : (!has(self.position) && !has(self.height) && !has(self.face) && (self.scope == ''NonRackUnitMount'' + ? has(self.mount) : !has(self.mount)))' + message: partial placement cannot assert rack units; non-unit mounts require a mount identifier + lifecycle: + type: string + enum: + - Installation + cableRefs: + type: array + maxItems: 256 + items: *id001 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + displayName: + type: string + minLength: 1 + maxLength: 253 + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devices.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Device + listKind: DeviceList + plural: devices + singular: device + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Claim + type: string + jsonPath: .spec.claimRef.name + - name: Model + type: string + jsonPath: .spec.identity.model + - name: Serial + type: string + jsonPath: .spec.identity.serial + - name: Lifecycle + type: string + jsonPath: .spec.lifecycle + - name: System UUID + type: string + priority: 1 + jsonPath: .spec.identity.systemUUID + - name: Unidentified + type: boolean + priority: 1 + jsonPath: .spec.identity.unidentified + - name: Discovered + type: string + priority: 1 + jsonPath: .status.conditions[?(@.type=="Discovered")].status + - name: Identity + type: string + priority: 1 + jsonPath: .status.conditions[?(@.type=="IdentityMatched")].reason + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - claimRef + - identity + x-kubernetes-validations: + - rule: self.claimRef == oldSelf.claimRef + message: claimRef is immutable; bind replacement hardware as a new Device + - rule: self.identity == oldSelf.identity + message: identity is immutable; a hardware swap is a new Device + - rule: '!has(self.identity.unidentified) || !has(self.bmc)' + message: a device without hardware identity cannot record a BMC endpoint; it cannot be enrolled as machine capacity + - rule: '!has(oldSelf.deviceTypeRef) || (has(self.deviceTypeRef) && self.deviceTypeRef == oldSelf.deviceTypeRef)' + message: an assigned catalog reference cannot be removed or rebound + - rule: '!has(oldSelf.reportedPlacement) || has(self.reportedPlacement)' + message: retain a report; omit unknown location fields rather than removing the report + - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' + optionalOldSelf: true + message: first report revision must be 1; every changed report must increment revision exactly once + - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, + has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) + || !(a.macAddress in self.unmappedMACAddresses))))' + message: a MAC address may be recorded only once + - rule: '!has(self.components) || has(self.topologyAuthority)' + message: typed components require Cable topology + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, (m.from.componentID + != m.to.componentID || m.from.position != m.to.position) && self.components.exists(c, c.id == m.from.componentID + && m.from.position <= (has(c.positions) ? c.positions : 1)) && self.components.exists(c, c.id == + m.to.componentID && m.to.position <= (has(c.positions) ? c.positions : 1))))' + message: internal mappings must reference present component positions + - rule: '!has(self.internalMappings) || self.internalMappings.all(m, self.internalMappings.filter(n, + n.from == m.from).size() == 1)' + message: each internal source position maps once + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') ? self.components.exists(c, c.id == m.to.componentID + && c.type == ''RearPort'') : (self.components.exists(c, c.id == m.from.componentID && c.type == + ''PowerOutlet'') && self.components.exists(c, c.id == m.to.componentID && c.type == ''PowerInlet''))))' + message: internal paths must map front to rear or power outlet to inlet + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, !self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') || self.internalMappings.filter(n, n.to.componentID + == m.to.componentID && n.to.position == m.to.position).size() == 1))' + message: a pass-through rear position can be mapped only once + - rule: '!has(self.serviceAssociations) || (has(self.components) && self.serviceAssociations.all(a, + self.components.exists(c, c.id == a.componentID)))' + message: service associations must reference present components + - rule: '!has(oldSelf.lifecycle) || oldSelf.lifecycle != ''Retired'' || (has(self.lifecycle) && self.lifecycle + == ''Retired'')' + message: Retired is terminal; a Retired Device cannot change lifecycle + - rule: '!has(self.lifecycle) || self.lifecycle != ''Retired'' || (has(oldSelf.lifecycle) && oldSelf.lifecycle + in [''Decommissioning'', ''Retired''])' + message: move an Active Device to Decommissioning before Retired + properties: + lifecycle: + type: string + enum: [Active, Decommissioning, Retired] + default: Active + deviceTypeRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' + reportedPlacement: + type: object + required: [revision, observedAt, reason, reference] + x-kubernetes-validations: + - rule: '(!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth) && !has(self.mount)) || has(self.rackRef)' + message: rack geometry requires a reported rack + - rule: '!has(self.mount) || (!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth))' + message: non-unit mounts cannot also report unit geometry + - rule: '!has(self.position) || !has(self.height) || self.position + self.height <= 101.0' + message: reported geometry exceeds supported rack bounds + properties: + revision: + type: integer + minimum: 1 + maximum: 2147483647 + reason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + reference: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + observedAt: + type: string + format: date-time + facilityRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + rackRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + position: + type: number + minimum: 1 + maximum: 100 + height: + type: number + minimum: 0 + exclusiveMinimum: true + maximum: 100 + face: + type: string + enum: [front, rear] + fullDepth: + type: boolean + mount: + type: string + minLength: 1 + maxLength: 253 + claimRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + identity: + type: object + required: + - model + x-kubernetes-validations: + - rule: has(self.serial) || has(self.systemUUID) || has(self.unidentified) + message: a device needs a serial or system UUID, or unidentified set to true with a reason + - rule: '!has(self.unidentified) || self.unidentified' + message: unidentified may only be true; omit it when the device has a serial or system UUID + - rule: has(self.unidentified) == has(self.unidentifiedReason) + message: unidentified and unidentifiedReason must be set together + - rule: '!has(self.unidentified) || (!has(self.serial) && !has(self.systemUUID))' + message: an unidentified device cannot carry a serial or system UUID; record identified hardware as a new Device + properties: + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 + systemUUID: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + unidentified: + type: boolean + unidentifiedReason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + bmc: + type: object + required: + - endpoint + properties: + endpoint: + type: string + maxLength: 2048 + x-kubernetes-validations: + - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() + != '' + message: bmc.endpoint must be an https URL without credentials + interfaces: + type: array + maxItems: 32 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 63 + macAddress: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + unmappedMACAddresses: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + assetTag: + type: string + minLength: 1 + maxLength: 253 + providerHostRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + components: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + internalMappings: + type: array + maxItems: 256 + items: + type: object + properties: + from: &id002 + type: object + properties: + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + to: *id002 + required: + - from + - to + serviceAssociations: + type: array + maxItems: 128 + items: + type: object + properties: + serviceRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + componentID: + type: string + minLength: 1 + maxLength: 63 + required: + - serviceRef + - componentID + topologyAuthority: + type: string + enum: + - Cable + displayName: + type: string + minLength: 1 + maxLength: 253 + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + width: + type: string + enum: + - Full + - Half + status: + type: object + description: Written only by read-only BMC discovery through the status subresource. Observations are evidence; spec stays authoritative. + properties: + observedGeneration: + type: integer + format: int64 + minimum: 0 + discovery: + type: object + properties: + lastAttemptAt: {type: string, format: date-time} + lastAttemptEndpoint: {type: string, maxLength: 2048} + tls: + type: object + required: [observedAt, endpoint, publicKeySHA256] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + publicKeySHA256: {type: string, pattern: '^[0-9a-f]{64}$'} + notAfter: {type: string, format: date-time} + selfSigned: {type: boolean} + serviceRoot: + type: object + required: [observedAt, endpoint] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + redfishVersion: {type: string, maxLength: 63} + uuid: {type: string, maxLength: 36} + vendor: {type: string, maxLength: 253} + product: {type: string, maxLength: 253} + inventory: + type: object + required: [observedAt, endpoint] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + managers: + type: array + maxItems: 16 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + model: {type: string, maxLength: 253} + firmwareVersion: {type: string, maxLength: 253} + networkInterfaces: + type: array + maxItems: 32 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + linkStatus: {type: string, maxLength: 63} + speedMbps: {type: integer, minimum: 0, maximum: 100000000} + systems: + type: array + maxItems: 16 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + uuid: {type: string, pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'} + manufacturer: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + serialNumber: {type: string, maxLength: 253} + sku: {type: string, maxLength: 253} + powerState: {type: string, maxLength: 63} + resetTypes: + type: array + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} + resetTypesObserved: {type: boolean} + networkInterfaces: + type: array + maxItems: 32 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + linkStatus: {type: string, maxLength: 63} + speedMbps: {type: integer, minimum: 0, maximum: 100000000} + storage: + type: object + properties: + drives: + type: array + maxItems: 32 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + serialNumber: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + firmware: {type: string, maxLength: 63} + protocol: {type: string, maxLength: 31} + mediaType: {type: string, maxLength: 31} + capacityBytes: {type: integer, minimum: 0} + encryptionStatus: {type: string, maxLength: 63} + inVolume: {type: boolean} + conditions: + type: array + maxItems: 8 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [type] + items: + type: object + required: [type, status, lastTransitionTime, reason, message] + properties: + type: {type: string, minLength: 1, maxLength: 316, pattern: '^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$'} + status: {type: string, enum: ['True', 'False', 'Unknown']} + observedGeneration: {type: integer, format: int64, minimum: 0} + lastTransitionTime: {type: string, format: date-time} + reason: {type: string, minLength: 1, maxLength: 1024, pattern: '^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$'} + message: {type: string, maxLength: 32768} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: facilities.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Facility + listKind: FacilityList + plural: facilities + singular: facility + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + identifiers: + type: array + maxItems: 64 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [provider, type, value] + items: + type: object + required: [provider, type, value] + properties: + provider: + type: string + minLength: 1 + maxLength: 253 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: + type: string + enum: [PremisesCode, PremisesAlias, PremisesID] + value: + type: string + minLength: 1 + maxLength: 253 + locationRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + required: + - displayName + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: sites.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Site + listKind: SiteList + plural: sites + singular: site + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + code: + type: string + minLength: 1 + maxLength: 64 + facilityRefs: + type: array + maxItems: 64 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name] + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + required: + - displayName + - code + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: racks.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Rack + listKind: RackList + plural: racks + singular: rack + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + facilityRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + heightUnits: + type: integer + minimum: 1 + maximum: 100 + required: + - displayName + - facilityRef + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cables.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Cable + listKind: CableList + plural: cables + singular: cable + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + medium: + type: string + enum: + - Copper + - Fiber + - Power + - Console + - Unknown + lanes: + type: array + maxItems: 64 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + a: &id002 + type: object + properties: + deviceRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + powerFeedRef: *id001 + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + x-kubernetes-validations: + - rule: has(self.deviceRef) != has(self.powerFeedRef) + message: exactly one local endpoint owner is required + b: *id002 + required: + - id + - a + - b + x-kubernetes-validations: + - rule: '!(self.a.componentID == self.b.componentID && self.a.position == self.b.position && ((has(self.a.deviceRef) + && has(self.b.deviceRef) && self.a.deviceRef.name == self.b.deviceRef.name) || (has(self.a.powerFeedRef) + && has(self.b.powerFeedRef) && self.a.powerFeedRef.name == self.b.powerFeedRef.name)))' + message: a cable lane must have different endpoints + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + required: + - displayName + - medium + - lanes + x-kubernetes-validations: + - rule: self.lanes.all(l, self.lanes.filter(m, (m.a.componentID == l.a.componentID && m.a.position == + l.a.position && ((has(m.a.deviceRef) && has(l.a.deviceRef) && m.a.deviceRef.name == l.a.deviceRef.name) + || (has(m.a.powerFeedRef) && has(l.a.powerFeedRef) && m.a.powerFeedRef.name == l.a.powerFeedRef.name))) + || (m.b.componentID == l.a.componentID && m.b.position == l.a.position && ((has(m.b.deviceRef) && + has(l.a.deviceRef) && m.b.deviceRef.name == l.a.deviceRef.name) || (has(m.b.powerFeedRef) && has(l.a.powerFeedRef) + && m.b.powerFeedRef.name == l.a.powerFeedRef.name)))).size() == 1 && self.lanes.filter(m, (m.a.componentID + == l.b.componentID && m.a.position == l.b.position && ((has(m.a.deviceRef) && has(l.b.deviceRef) + && m.a.deviceRef.name == l.b.deviceRef.name) || (has(m.a.powerFeedRef) && has(l.b.powerFeedRef) + && m.a.powerFeedRef.name == l.b.powerFeedRef.name))) || (m.b.componentID == l.b.componentID && m.b.position + == l.b.position && ((has(m.b.deviceRef) && has(l.b.deviceRef) && m.b.deviceRef.name == l.b.deviceRef.name) + || (has(m.b.powerFeedRef) && has(l.b.powerFeedRef) && m.b.powerFeedRef.name == l.b.powerFeedRef.name)))).size() + == 1) + message: each termination position can occur only once in a cable + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: powerfeeds.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: PowerFeed + listKind: PowerFeedList + plural: powerfeeds + singular: powerfeed + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + supply: + type: object + properties: + type: + type: string + enum: + - AC + - DC + - Unknown + voltageV: + type: integer + minimum: 1 + maximum: 100000 + currentA: + type: integer + minimum: 1 + maximum: 100000 + phase: + type: string + enum: + - single-phase + - three-phase + - Unknown + required: + - type + terminations: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + upstreamSources: + type: array + maxItems: 64 + items: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + required: + - displayName + - facilityRef + - terminations + x-kubernetes-validations: + - rule: self.terminations.all(t, t.type == 'PowerOutlet') + message: feed terminations must be power outlets + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: manufacturers.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Manufacturer + listKind: ManufacturerList + plural: manufacturers + singular: manufacturer + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - canonicalName + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + canonicalName: &id001 + type: string + minLength: 1 + maxLength: 253 + pattern: '^[A-Za-z0-9]([ -~]*[!-~])?$' + aliases: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: *id001 + x-kubernetes-validations: + - rule: '!has(self.aliases) || self.aliases.all(a, a.lowerAscii() != self.canonicalName.lowerAscii() + && self.aliases.filter(b, a.lowerAscii() == b.lowerAscii()).size() + == 1)' + message: aliases must be distinct ignoring ASCII case and cannot repeat + the canonical name + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicetypes.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceType + listKind: DeviceTypeList + plural: devicetypes + singular: devicetype + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - manufacturerRef + - model + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + manufacturerRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' + model: + type: string + minLength: 1 + maxLength: 253 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + width: + type: string + enum: + - Full + - Half + faceplate: + type: object + required: + - banks + properties: + banks: + type: array + minItems: 1 + maxItems: 32 + items: + type: object + required: + - id + - face + - rows + - columns + properties: + id: + type: string + minLength: 1 + maxLength: 63 + face: + type: string + enum: + - Front + - Rear + rows: + type: integer + minimum: 1 + maximum: 8 + columns: + type: integer + minimum: 1 + maximum: 64 + offset: + type: number + minimum: 0 + maximum: 1 + cellMM: + type: object + required: + - width + - height + properties: + width: + type: number + minimum: 1 + maximum: 450 + height: + type: number + minimum: 1 + maximum: 400 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + x-kubernetes-validations: + - rule: "['Front', 'Rear'].all(f, self.banks.all(b, b.face != f || has(b.offset)) + || self.banks.all(b, b.face != f || !has(b.offset)))" + message: bank offsets must be set on every bank of a face or on none + componentTemplates: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + face: + type: string + enum: + - Front + - Rear + layout: + type: object + required: + - bank + - row + - column + properties: + bank: + type: string + minLength: 1 + maxLength: 63 + row: + type: integer + minimum: 1 + maximum: 8 + column: + type: integer + minimum: 1 + maximum: 64 + span: + type: integer + minimum: 1 + maximum: 64 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + x-kubernetes-validations: + # The overlap rule below compares every pair of templates. This + # cap keeps its worst runtime cost near 60% of the per-call CEL + # limit; 256 laid-out templates can exceed it. Evaluated first so + # an over-cap object reports the cap, not a cost error. + - rule: self.filter(t, has(t.layout)).size() <= 128 + message: at most 128 templates may carry a layout; leave the rest without + one + - rule: 'self.all(t, !has(t.layout) || self.exists_one(u, has(u.layout) + && u.layout.row == t.layout.row && u.layout.column < t.layout.column + + (has(t.layout.span) ? t.layout.span : 1) && t.layout.column < u.layout.column + + (has(u.layout.span) ? u.layout.span : 1) && u.layout.bank == t.layout.bank))' + message: two templates overlap in one bank row; each cell, including a + span, holds one template + x-kubernetes-validations: + - rule: '!has(self.componentTemplates) || self.componentTemplates.all(t, !has(t.layout) + || has(t.face) && has(self.faceplate) && self.faceplate.banks.exists(b, + b.id == t.layout.bank && b.face == t.face))' + message: a template layout must name a faceplate bank on the template's own + face + - rule: '!has(self.componentTemplates) || !has(self.faceplate) || self.componentTemplates.all(t, + !has(t.layout) || self.faceplate.banks.all(b, b.id != t.layout.bank || + t.layout.row <= b.rows && t.layout.column + (has(t.layout.span) ? t.layout.span + : 1) - 1 <= b.columns))' + message: a template layout, including its span, must fall inside its bank's + rows and columns + - rule: self.manufacturerRef == oldSelf.manufacturerRef && self.model + == oldSelf.model + message: manufacturer and normalized model identity are immutable; displayName + is mutable + status: + type: object diff --git a/config/components/inventory/crds/kustomization.yaml b/config/components/inventory/crds/kustomization.yaml new file mode 100644 index 00000000..1f890b4c --- /dev/null +++ b/config/components/inventory/crds/kustomization.yaml @@ -0,0 +1,3 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [fleet.datumapis.com.yaml] diff --git a/config/components/inventory/kustomization.yaml b/config/components/inventory/kustomization.yaml new file mode 100644 index 00000000..cc727f1c --- /dev/null +++ b/config/components/inventory/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crds + - protected-resources + - roles diff --git a/config/components/inventory/protected-resources/cable.yaml b/config/components/inventory/protected-resources/cable.yaml new file mode 100644 index 00000000..f92364db --- /dev/null +++ b/config/components/inventory/protected-resources/cable.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-cable +spec: + serviceRef: + name: fleet.datumapis.com + kind: Cable + plural: cables + singular: cable + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/device.yaml b/config/components/inventory/protected-resources/device.yaml new file mode 100644 index 00000000..8ca7e516 --- /dev/null +++ b/config/components/inventory/protected-resources/device.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-device +spec: + serviceRef: + name: fleet.datumapis.com + kind: Device + plural: devices + singular: device + # updateStatus is held only by the discoverer role. With subresource + # authorization enabled, status writes use devices/status.update and + # devices/status.patch instead. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/deviceclaim.yaml b/config/components/inventory/protected-resources/deviceclaim.yaml new file mode 100644 index 00000000..2d4cad48 --- /dev/null +++ b/config/components/inventory/protected-resources/deviceclaim.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-deviceclaim +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceClaim + plural: deviceclaims + singular: deviceclaim + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/devicetype.yaml b/config/components/inventory/protected-resources/devicetype.yaml new file mode 100644 index 00000000..8a268545 --- /dev/null +++ b/config/components/inventory/protected-resources/devicetype.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicetype +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceType + plural: devicetypes + singular: devicetype + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/facility.yaml b/config/components/inventory/protected-resources/facility.yaml new file mode 100644 index 00000000..5a84110a --- /dev/null +++ b/config/components/inventory/protected-resources/facility.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-facility +spec: + serviceRef: + name: fleet.datumapis.com + kind: Facility + plural: facilities + singular: facility + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/kustomization.yaml b/config/components/inventory/protected-resources/kustomization.yaml new file mode 100644 index 00000000..b107ad0e --- /dev/null +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - manufacturer.yaml + - devicetype.yaml + - deviceclaim.yaml + - device.yaml + - facility.yaml + - site.yaml + - rack.yaml + - cable.yaml + - powerfeed.yaml diff --git a/config/components/inventory/protected-resources/manufacturer.yaml b/config/components/inventory/protected-resources/manufacturer.yaml new file mode 100644 index 00000000..e5e1f632 --- /dev/null +++ b/config/components/inventory/protected-resources/manufacturer.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-manufacturer +spec: + serviceRef: + name: fleet.datumapis.com + kind: Manufacturer + plural: manufacturers + singular: manufacturer + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/powerfeed.yaml b/config/components/inventory/protected-resources/powerfeed.yaml new file mode 100644 index 00000000..f731d7df --- /dev/null +++ b/config/components/inventory/protected-resources/powerfeed.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-powerfeed +spec: + serviceRef: + name: fleet.datumapis.com + kind: PowerFeed + plural: powerfeeds + singular: powerfeed + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/rack.yaml b/config/components/inventory/protected-resources/rack.yaml new file mode 100644 index 00000000..b1f974aa --- /dev/null +++ b/config/components/inventory/protected-resources/rack.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-rack +spec: + serviceRef: + name: fleet.datumapis.com + kind: Rack + plural: racks + singular: rack + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/site.yaml b/config/components/inventory/protected-resources/site.yaml new file mode 100644 index 00000000..618a9d5f --- /dev/null +++ b/config/components/inventory/protected-resources/site.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-site +spec: + serviceRef: + name: fleet.datumapis.com + kind: Site + plural: sites + singular: site + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/roles/discoverer.yaml b/config/components/inventory/roles/discoverer.yaml new file mode 100644 index 00000000..0eec5bf9 --- /dev/null +++ b/config/components/inventory/roles/discoverer.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-discoverer + annotations: + kubernetes.io/display-name: Fleet Inventory Discoverer + kubernetes.io/description: Read Devices and write only what their BMCs report into Device status +spec: + launchStage: Alpha + # Deliberately not the viewer role: discovery reads Devices only. + includedPermissions: + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devices.updateStatus + - fleet.datumapis.com/devices/status.update + - fleet.datumapis.com/devices/status.patch diff --git a/config/components/inventory/roles/editor.yaml b/config/components/inventory/roles/editor.yaml new file mode 100644 index 00000000..a951878d --- /dev/null +++ b/config/components/inventory/roles/editor.yaml @@ -0,0 +1,48 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-editor + annotations: + kubernetes.io/display-name: Fleet Inventory Editor + kubernetes.io/description: Plan slots and register devices in provider inventory +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/manufacturers.delete + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/devicetypes.delete + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.update + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/sites.delete + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.update + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/deviceclaims.delete + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/devices.delete + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/facilities.delete + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/racks.delete + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/cables.delete + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch + - fleet.datumapis.com/powerfeeds.delete diff --git a/config/components/inventory/roles/importer.yaml b/config/components/inventory/roles/importer.yaml new file mode 100644 index 00000000..54f5e258 --- /dev/null +++ b/config/components/inventory/roles/importer.yaml @@ -0,0 +1,30 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-importer + annotations: + kubernetes.io/display-name: Fleet Inventory Importer + kubernetes.io/description: Create and server-side apply physical inventory records from an external source without deleting them or writing status +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.patch diff --git a/config/components/inventory/roles/kustomization.yaml b/config/components/inventory/roles/kustomization.yaml new file mode 100644 index 00000000..66a0d1f3 --- /dev/null +++ b/config/components/inventory/roles/kustomization.yaml @@ -0,0 +1,8 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - viewer.yaml + - editor.yaml + - manager.yaml + - importer.yaml + - discoverer.yaml diff --git a/config/components/inventory/roles/manager.yaml b/config/components/inventory/roles/manager.yaml new file mode 100644 index 00000000..f9f79f74 --- /dev/null +++ b/config/components/inventory/roles/manager.yaml @@ -0,0 +1,39 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-manager + annotations: + kubernetes.io/display-name: Fleet Inventory Manager + kubernetes.io/description: Create and maintain physical inventory records without deletion or operational control +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.update + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.update + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch diff --git a/config/components/inventory/roles/viewer.yaml b/config/components/inventory/roles/viewer.yaml new file mode 100644 index 00000000..72e63237 --- /dev/null +++ b/config/components/inventory/roles/viewer.yaml @@ -0,0 +1,37 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-viewer + annotations: + kubernetes.io/display-name: Fleet Inventory Viewer + kubernetes.io/description: View the provider's planned slots and registered devices +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/manufacturers.get + - fleet.datumapis.com/manufacturers.list + - fleet.datumapis.com/manufacturers.watch + - fleet.datumapis.com/devicetypes.get + - fleet.datumapis.com/devicetypes.list + - fleet.datumapis.com/devicetypes.watch + - fleet.datumapis.com/sites.get + - fleet.datumapis.com/sites.list + - fleet.datumapis.com/sites.watch + - fleet.datumapis.com/deviceclaims.list + - fleet.datumapis.com/deviceclaims.get + - fleet.datumapis.com/deviceclaims.watch + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/facilities.get + - fleet.datumapis.com/facilities.list + - fleet.datumapis.com/facilities.watch + - fleet.datumapis.com/racks.get + - fleet.datumapis.com/racks.list + - fleet.datumapis.com/racks.watch + - fleet.datumapis.com/cables.get + - fleet.datumapis.com/cables.list + - fleet.datumapis.com/cables.watch + - fleet.datumapis.com/powerfeeds.get + - fleet.datumapis.com/powerfeeds.list + - fleet.datumapis.com/powerfeeds.watch diff --git a/config/components/machine-admission/kustomization.yaml b/config/components/machine-admission/kustomization.yaml new file mode 100644 index 00000000..e1e551fe --- /dev/null +++ b/config/components/machine-admission/kustomization.yaml @@ -0,0 +1,9 @@ +# Machine creator admission: the webhooks that record who created each +# Machine and add its protection finalizer in the same write. The +# fleet-registration server serves them. No root includes this component +# yet: the finalizer needs a manager that releases Machines, and the +# production manager's lifecycle handlers are still blocked. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/machine-admission/webhook.yaml b/config/components/machine-admission/webhook.yaml new file mode 100644 index 00000000..0ae140fa --- /dev/null +++ b/config/components/machine-admission/webhook.yaml @@ -0,0 +1,47 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: fleet-machine-creator +webhooks: + # Milo's root API server calls this webhook, because Milo does not evaluate + # admission policies stored in a project. On create it writes the + # authenticated caller into spec.creator, replacing any client value, and + # adds the Machine protection finalizer. It is fail-closed. + - name: creator.machines.metal.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + reinvocationPolicy: Never + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/mutate-machine-creator + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE] + resources: [machines] + scope: Namespaced +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-machine-creator +webhooks: + # Runs after every mutating webhook. It refuses a create whose creator is + # not the caller or that lacks the protection finalizer, and any change to + # the creator. Status writes are not routed. + - name: creator.machines.metal.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-machine-creator + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [machines] + scope: Namespaced diff --git a/config/components/machine-power-admission/kustomization.yaml b/config/components/machine-power-admission/kustomization.yaml new file mode 100644 index 00000000..4fd00748 --- /dev/null +++ b/config/components/machine-power-admission/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/machine-power-admission/webhook.yaml b/config/components/machine-power-admission/webhook.yaml new file mode 100644 index 00000000..686e158b --- /dev/null +++ b/config/components/machine-power-admission/webhook.yaml @@ -0,0 +1,33 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-machine-power +webhooks: + # The manager's power projector is the only writer of a Machine's + # status.power. RBAC cannot hold that field to one writer: Milo authorizes a + # status write with the Machine's update and patch permissions, which the + # consumer roles hold. Milo's root API server calls this webhook, because + # Milo does not evaluate admission policies stored in a project. Only status + # writes that change status.power are routed, so an unavailable service + # blocks power changes and nothing else. It is fail-closed. The + # fleet-registration server serves it; its --machine-power-writer flag names + # the projector's identity, and without it every power change is refused. + - name: power.machines.metal.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-machine-power + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [UPDATE] + resources: [machines/status] + scope: Namespaced + matchConditions: + - name: power-changes + expression: >- + (has(object.status) && has(object.status.power)) != (has(oldObject.status) && has(oldObject.status.power)) + || (has(object.status) && has(object.status.power) && object.status.power != oldObject.status.power) diff --git a/config/components/registration-admission/kustomization.yaml b/config/components/registration-admission/kustomization.yaml new file mode 100644 index 00000000..4fd00748 --- /dev/null +++ b/config/components/registration-admission/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml new file mode 100644 index 00000000..96505547 --- /dev/null +++ b/config/components/registration-admission/webhook.yaml @@ -0,0 +1,38 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-capacity-registration +webhooks: + # Only inventory-backed capacity is routed here, and it is fail-closed. + # Creates are checked against live Devices. Updates may change only the + # allocation policy, cleaning policy and pool label, under the stage-2 + # rules; deletes only remove Disabled capacity whose Device is gone or + # Retired; status writes come only from the capacity projector. Capacity is + # inventory-backed when it carries a registration annotation + # (fleet.datumapis.com/registration-*) on the new or old object, or when a + # create uses the derived device- name. Capacity without the marker, such + # as synthetic or hand-made capacity, is not routed and is governed by RBAC + # alone. + - name: registration.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 20 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-registration + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [machinecapacities, machinecapacities/status] + scope: Namespaced + matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) diff --git a/config/inventory/kustomization.yaml b/config/inventory/kustomization.yaml new file mode 100644 index 00000000..a44f7dd6 --- /dev/null +++ b/config/inventory/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../components/inventory/crds diff --git a/config/milo-synthetic/kustomization.yaml b/config/milo-synthetic/kustomization.yaml new file mode 100644 index 00000000..17a59dbd --- /dev/null +++ b/config/milo-synthetic/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../base/crd + - ../components/iam + - ../components/service-catalog + - ../components/inventory + # Device custody and operations without the creator webhook: this root + # installs no webhook, as it installs no registration webhook. + - ../components/device-operations/crds + - ../components/device-operations/protected-resources + - ../components/device-operations/roles diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index baa07462..8752e82f 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -4,3 +4,7 @@ resources: - ../base/crd - ../components/iam - ../components/service-catalog + - ../components/inventory + - ../components/registration-admission + - ../components/device-operations + - ../components/machine-power-admission diff --git a/config/multiplane/cell-federation/federation.yaml b/config/multiplane/cell-federation/federation.yaml new file mode 100644 index 00000000..6b54d1cc --- /dev/null +++ b/config/multiplane/cell-federation/federation.yaml @@ -0,0 +1,47 @@ +# Karmada push-mode member identity on the selected cell. It can deliver +# intent and read local status, but holds no status write or Secret read. +# Its token is minted by bootstrap enrollment, never stored in the source. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-federation, namespace: fleet-coordination} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-federation, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs, machineallocationpayloads] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [""] + resources: [events] + verbs: [create, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-federation, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-federation, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-federation} +--- +# The member informer lists handoffs across namespaces and reads discovery. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-federation-discovery} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs, machineallocationpayloads] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [nodes, pods, namespaces] + verbs: [get, list, watch] + - nonResourceURLs: [/healthz, /readyz, /version, /api, /api/*, /apis, /apis/*] + verbs: [get] +--- +# Discovery is bound to the same federation identity, not a second one. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-federation-reader} +subjects: + - {kind: ServiceAccount, name: fleet-federation, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-federation-discovery} diff --git a/config/multiplane/cell-federation/kustomization.yaml b/config/multiplane/cell-federation/kustomization.yaml new file mode 100644 index 00000000..66f25f05 --- /dev/null +++ b/config/multiplane/cell-federation/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - federation.yaml diff --git a/config/multiplane/clusters/cell-site/kustomization.yaml b/config/multiplane/clusters/cell-site/kustomization.yaml new file mode 100644 index 00000000..1da011a3 --- /dev/null +++ b/config/multiplane/clusters/cell-site/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - site.yaml diff --git a/config/multiplane/clusters/cell-site/site.yaml b/config/multiplane/clusters/cell-site/site.yaml new file mode 100644 index 00000000..eb209ab2 --- /dev/null +++ b/config/multiplane/clusters/cell-site/site.yaml @@ -0,0 +1,53 @@ +# Site layers present in the environment only once the scoped asset is known. +# +# Shared site services: runtime, boot Deployment and Service, observer and the +# worker admission parameter. Flux owns them directly, applied as a scoped +# identity that can write only Deployments, Services and ConfigMaps in +# fleet-site. wait covers every Deployment becoming Available. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-services, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/services + dependsOn: + - {name: fleet-site-base, namespace: flux-system} + serviceAccountName: fleet-site-services-reconciler + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} +--- +# The one HandoffDispatcher instance, applied as a scoped identity that can +# manage only HandoffDispatchers in fleet-site: never Jobs, Deployments, +# volumes or handoffs. It is applied only after the graph is Active and the +# shared services are healthy, and is itself healthy only when kro reports +# the graph ACTIVE against those Flux-owned references. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-dispatch, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/instance + dependsOn: + - {name: fleet-site-graph, namespace: flux-system} + - {name: fleet-site-services, namespace: flux-system} + - {name: fleet-federation, namespace: flux-system} + serviceAccountName: fleet-site-dispatch-reconciler + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} + healthCheckExprs: + - apiVersion: site.fleet.datumapis.com/v1alpha1 + kind: HandoffDispatcher + current: status.state == 'ACTIVE' + inProgress: status.state != 'ACTIVE' diff --git a/config/multiplane/clusters/cell/cell.yaml b/config/multiplane/clusters/cell/cell.yaml new file mode 100644 index 00000000..2a5df0c4 --- /dev/null +++ b/config/multiplane/clusters/cell/cell.yaml @@ -0,0 +1,88 @@ +# Selected cell. Handoff CRD and namespace; prune false (see the hub copy). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-coordination, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: false + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/coordination +--- +# Karmada push-mode member identity; its token is enrolled by bootstrap. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-federation, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/cell-federation + dependsOn: + - {name: fleet-coordination, namespace: flux-system} +--- +# kro controller. wait covers the HelmRelease and its OCI chart source, so +# a bad chart revision makes this not Ready and blocks the site layers. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: kro, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 3m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/kro +--- +# Site namespace, retained volume, service identities, observer RBAC, kro's +# narrowed grants and the admission policy for kro's writes. Shared site +# infrastructure does not depend on kro: a broken kro release blocks only the +# graph and the dispatcher. The claim binds on first consumer +# (WaitForFirstConsumer). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-base, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/base + dependsOn: + - {name: fleet-coordination, namespace: flux-system} + healthCheckExprs: + - apiVersion: v1 + kind: PersistentVolumeClaim + current: status.phase == 'Pending' || status.phase == 'Bound' + failed: status.phase == 'Lost' +--- +# The HandoffDispatcher ResourceGraphDefinition, applied as a scoped identity +# that can manage only ResourceGraphDefinitions. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-graph, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/graph + dependsOn: + - {name: kro, namespace: flux-system} + - {name: fleet-site-base, namespace: flux-system} + serviceAccountName: fleet-site-graph-reconciler + healthCheckExprs: + - apiVersion: kro.run/v1alpha1 + kind: ResourceGraphDefinition + current: status.state == 'Active' + inProgress: status.state != 'Active' diff --git a/config/multiplane/clusters/cell/kustomization.yaml b/config/multiplane/clusters/cell/kustomization.yaml new file mode 100644 index 00000000..94c2a59e --- /dev/null +++ b/config/multiplane/clusters/cell/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - cell.yaml diff --git a/config/multiplane/clusters/hub/hub.yaml b/config/multiplane/clusters/hub/hub.yaml new file mode 100644 index 00000000..67b9f73f --- /dev/null +++ b/config/multiplane/clusters/hub/hub.yaml @@ -0,0 +1,87 @@ +# The namespace exists before the release so the environment ConfigMap that +# Karmada-API Kustomizations substitute from can live beside their kubeconfig. +apiVersion: v1 +kind: Namespace +metadata: + name: karmada-system + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# Karmada chart on the host. wait covers the HelmRelease and its source. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: karmada, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 20m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada +--- +# Handoff CRD and namespace on the Karmada API. prune false: never +# garbage-collect a CRD with retained intent (as datum-cloud/infra karmada-crds). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-coordination, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: false + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/coordination + dependsOn: + - {name: karmada, namespace: flux-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} +--- +# Management intent role, the status interpreter and the member Secret namespace. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-api, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada-api + dependsOn: + - {name: fleet-karmada-coordination, namespace: karmada-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} +--- +# Member registration and placement. The member credential Secret is +# enrolled by bootstrap; this waits until Karmada reports the member Ready. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-members, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada-members + dependsOn: + - {name: fleet-karmada-api, namespace: karmada-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} + healthCheckExprs: + - apiVersion: cluster.karmada.io/v1alpha1 + kind: Cluster + current: status.conditions.exists(e, e.type == 'Ready' && e.status == 'True') diff --git a/config/multiplane/clusters/hub/kustomization.yaml b/config/multiplane/clusters/hub/kustomization.yaml new file mode 100644 index 00000000..7eedca2e --- /dev/null +++ b/config/multiplane/clusters/hub/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - hub.yaml diff --git a/config/multiplane/clusters/platform-ipam/ipam.yaml b/config/multiplane/clusters/platform-ipam/ipam.yaml new file mode 100644 index 00000000..31f5adec --- /dev/null +++ b/config/multiplane/clusters/platform-ipam/ipam.yaml @@ -0,0 +1,98 @@ +# Platform cluster, synchronized lab DHCP mode only (run.sh --synced-dhcp): +# the IPAM service (milo-os/ipam v0.6.0) beside the provider project's Milo +# API, which aggregates it as ipam.miloapis.com. IPAM's own published +# manifests, pinned by digest, as the platform's Flux consumes them; the lab +# patches below are the only changes. Bootstrap enrolls the credentials and +# registers the APIService in the provider Milo API. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: {name: ipam-kustomize, namespace: flux-system} +spec: + interval: 1h + url: oci://ghcr.io/milo-os/ipam-kustomize + # v0.6.0 (revision v0.6.0@sha1:1f6f22938dd165e568bb0fb1e4c50167ab09d6ae). + ref: + digest: sha256:62305dde600b8efa10a68a786e60b2e826837897cd93378c9e94d7adbff3f647 +--- +# Namespace, IPAM's PostgreSQL and the NetworkPolicy toward Milo. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: ipam-system, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/ipam +--- +# IPAM's published base: the apiserver Deployment, Service, PDB, +# NetworkPolicy and the host-cluster RBAC it ships with. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: ipam-apiserver, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: ipam-kustomize, namespace: flux-system} + path: ./base + targetNamespace: ipam-system + dependsOn: + - {name: ipam-system, namespace: flux-system} + - {name: milo-provider, namespace: flux-system} + images: + # ghcr.io/milo-os/ipam:v0.6.0 (multi-arch index). + - name: ghcr.io/milo-os/ipam + digest: sha256:18d472179ddff8db77a812fd0f0874248dd08e5a2425197152cc4cc2e9a7ce0d + patches: + # No cert-manager CSI driver in the lab: the serving key is a Secret + # enrolled by bootstrap, whose certificate is the APIService caBundle. + - target: {kind: Deployment, name: ipam-apiserver} + patch: |- + - op: test + path: /spec/template/spec/volumes/0/name + value: tls-certs + - op: replace + path: /spec/template/spec/volumes/0 + value: {name: tls-certs, secret: {secretName: ipam-apiserver-tls, defaultMode: 288}} + # Delegate TokenReview and SubjectAccessReview to the provider Milo API, + # as the platform does, through a kubeconfig bootstrap enrolls. The + # control-plane-ca ConfigMap the base mounts holds Milo's front-proxy CA. + # The lab Milo serves no quota API, so quota is off. One replica and + # smaller requests fit the single platform node. Mode 288 is 0440: IPAM + # runs as 65532 with that fsGroup. + - target: {kind: Deployment, name: ipam-apiserver} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: ipam-apiserver} + spec: + replicas: 1 + template: + spec: + containers: + - name: apiserver + env: + - {name: KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: AUTHENTICATION_KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: AUTHORIZATION_KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: ENABLE_QUOTA, value: "false"} + resources: + requests: {cpu: 50m, memory: 96Mi} + # IPAM publishes a 4Gi limit for production; the lab + # bounds it at 1Gi, well above its startup with five + # informers, so an OOM is not the first failure. + limits: {cpu: "1", memory: 1Gi} + volumeMounts: + - {name: milo-credentials, mountPath: /etc/kubernetes/milo, readOnly: true} + initContainers: + - name: migrate + resources: + requests: {cpu: 10m, memory: 32Mi} + volumes: + - name: milo-credentials + secret: {secretName: ipam-milo-credentials, defaultMode: 288} diff --git a/config/multiplane/clusters/platform-ipam/kustomization.yaml b/config/multiplane/clusters/platform-ipam/kustomization.yaml new file mode 100644 index 00000000..85b2a0b3 --- /dev/null +++ b/config/multiplane/clusters/platform-ipam/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ipam.yaml diff --git a/config/multiplane/clusters/platform/kustomization.yaml b/config/multiplane/clusters/platform/kustomization.yaml new file mode 100644 index 00000000..c771d7e5 --- /dev/null +++ b/config/multiplane/clusters/platform/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - milo.yaml diff --git a/config/multiplane/clusters/platform/milo.yaml b/config/multiplane/clusters/platform/milo.yaml new file mode 100644 index 00000000..fc32dff0 --- /dev/null +++ b/config/multiplane/clusters/platform/milo.yaml @@ -0,0 +1,37 @@ +# Platform cluster: three independent Milo project APIs, each with its own +# Kustomization, process, etcd and volume, so each can fail independently. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-provider, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/provider +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-consumer-a, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/consumer-a +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-consumer-b, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/consumer-b diff --git a/config/multiplane/coordination/crd.yaml b/config/multiplane/coordination/crd.yaml new file mode 100644 index 00000000..5c1947af --- /dev/null +++ b/config/multiplane/coordination/crd.yaml @@ -0,0 +1,87 @@ +# Federation handoff API: install on the Karmada API and participating cells. +# Never install in consumer project APIs. A handoff carries one admitted +# operation's site assignment, or asks for a Device's fence report. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineallocationhandoffs.coordination.fleet.datumapis.com + annotations: + # Deleting the CRD deletes every retained handoff. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + group: coordination.fleet.datumapis.com + scope: Namespaced + names: + plural: machineallocationhandoffs + singular: machineallocationhandoff + kind: MachineAllocationHandoff + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + spec: + type: object + required: [cell, device] + x-kubernetes-validations: + - rule: self == oldSelf + message: A handoff is immutable + properties: + cell: {type: string, minLength: 1, maxLength: 63} + # The Device as namespace/name in the provider project. + device: {type: string, minLength: 3, maxLength: 317} + # The exact assignment JSON; absent on a fence report request. + assignmentJSON: + type: string + minLength: 1 + maxLength: 65536 + # The assignment's MachineAllocationPayload, derived from the + # handoff; the assignment's worker may get only it. + payload: {type: string, pattern: '^op-[a-f0-9]{40}-payload$'} + status: + type: object + x-kubernetes-preserve-unknown-fields: true +--- +# An assignment's bootstrap payload, beside its handoff and never inside it. +# A dedicated kind, not a Secret: RBAC on it reaches only payloads, so the +# federation member, kro and each worker need no Secret permission, and no +# BMC credential is exposed to grant one. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineallocationpayloads.coordination.fleet.datumapis.com + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + group: coordination.fleet.datumapis.com + scope: Namespaced + names: + plural: machineallocationpayloads + singular: machineallocationpayload + kind: MachineAllocationPayload + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + spec: + type: object + required: [cell, payload] + x-kubernetes-validations: + - rule: self == oldSelf + message: A payload is immutable + properties: + cell: {type: string, minLength: 1, maxLength: 63} + # The site payload JSON: reference, salted digest, salt and + # data, base64. At most 96 KiB of encoded data. + payload: {type: string, format: byte, minLength: 1, maxLength: 262144} diff --git a/config/multiplane/coordination/kustomization.yaml b/config/multiplane/coordination/kustomization.yaml new file mode 100644 index 00000000..4e95a55e --- /dev/null +++ b/config/multiplane/coordination/kustomization.yaml @@ -0,0 +1,7 @@ +# Handoff API and namespace for the Karmada API and every participating cell. +# Reconciled by Flux with prune disabled; see docs/operations/gitops.md. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespace.yaml + - crd.yaml diff --git a/config/multiplane/coordination/namespace.yaml b/config/multiplane/coordination/namespace.yaml new file mode 100644 index 00000000..7695e765 --- /dev/null +++ b/config/multiplane/coordination/namespace.yaml @@ -0,0 +1,8 @@ +# Retained handoff intent lives here on the Karmada API and on each cell. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-coordination + annotations: + # Never garbage-collect: deleting the namespace deletes every handoff. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/flux/components.yaml b/config/multiplane/flux/components.yaml new file mode 100644 index 00000000..933285d6 --- /dev/null +++ b/config/multiplane/flux/components.yaml @@ -0,0 +1,55 @@ +# Flux v2.9.6 controller selection and pins, the same for every local cluster. +# The harness stages this file, unchanged, as environment/flux-components/ +# kustomization.yaml beside the release install.yaml (gotk-components.yaml), +# which it downloads and verifies against the SHA-256 pinned in +# hack/multiplane/flux.py; the upstream manifest is not committed, so this file +# is deliberately not named kustomization.yaml. The bootstrap applies this exact +# build once; afterwards each cluster's Flux reconciles (and owns) its own +# controllers from the source. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - gotk-components.yaml +images: + - name: ghcr.io/fluxcd/source-controller + digest: sha256:6a6693172589f8ff26123a231d5fa6ceb194a6efb4dc647cdf057c959f76a2e3 + - name: ghcr.io/fluxcd/kustomize-controller + digest: sha256:2ebeaa341da77d52b6abbbba5efcee0450d47f8b42f0e6f33b08f9020262d606 + - name: ghcr.io/fluxcd/helm-controller + digest: sha256:0d52fff5c4d476277b8fcb6beb9041e269adb5db943fe69f5a806ea0c92b1511 + - name: ghcr.io/fluxcd/notification-controller + digest: sha256:840f318265ee26f0d2c48a158bf7896b22aa4e998e320a18646309f0e40b15da +# Image automation and source-watcher are not used. +patches: + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: image-automation-controller, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: image-reflector-controller, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: source-watcher, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: v1 + kind: Service + metadata: {name: source-watcher, namespace: flux-system} + # Local tuning: re-check unready dependencies every 10s instead of 30s, so a + # revision ripples through the four-level site chain in under a minute. + - target: {kind: Deployment, name: kustomize-controller} + patch: |- + - op: add + path: /spec/template/spec/containers/0/args/- + value: --requeue-dependency=10s + - target: {kind: Deployment, name: helm-controller} + patch: |- + - op: add + path: /spec/template/spec/containers/0/args/- + value: --requeue-dependency=10s diff --git a/config/multiplane/ipam/kustomization.yaml b/config/multiplane/ipam/kustomization.yaml new file mode 100644 index 00000000..fd9a3688 --- /dev/null +++ b/config/multiplane/ipam/kustomization.yaml @@ -0,0 +1,11 @@ +# IPAM's namespace and its own PostgreSQL, beside the provider project's Milo +# API (synchronized lab DHCP mode only). The IPAM apiserver itself comes from +# IPAM's published manifests (config/multiplane/clusters/platform-ipam). +# Bootstrap enrolls the database password, IPAM's serving key and its Milo +# credentials as Secrets; none is in the source. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespace.yaml + - postgres.yaml + - networkpolicy.yaml diff --git a/config/multiplane/ipam/namespace.yaml b/config/multiplane/ipam/namespace.yaml new file mode 100644 index 00000000..fbcd8543 --- /dev/null +++ b/config/multiplane/ipam/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: ipam-system + annotations: + # Holds IPAM's database volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/ipam/networkpolicy.yaml b/config/multiplane/ipam/networkpolicy.yaml new file mode 100644 index 00000000..9344fba7 --- /dev/null +++ b/config/multiplane/ipam/networkpolicy.yaml @@ -0,0 +1,27 @@ +# Additive to the NetworkPolicy in IPAM's published base, which admits only +# kube-system and telemetry-system. Here the front proxy is the provider +# project's Milo API, and IPAM delegates authentication and authorization back +# to it, so both directions name that namespace. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: {name: ipam-apiserver-milo, namespace: ipam-system} +spec: + podSelector: + matchLabels: {app: ipam-apiserver} + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: milo-provider} + podSelector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + ports: + - {protocol: TCP, port: 8443} + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: milo-provider} + podSelector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + ports: + - {protocol: TCP, port: 6443} diff --git a/config/multiplane/ipam/postgres.yaml b/config/multiplane/ipam/postgres.yaml new file mode 100644 index 00000000..e56abace --- /dev/null +++ b/config/multiplane/ipam/postgres.yaml @@ -0,0 +1,66 @@ +# IPAM's own PostgreSQL. IPAM owns this storage; Fleet never connects to it. +# IPAM's postgres component floats its chart (16.x) and image, so the lab runs +# the official image pinned by digest instead. The postgres-credentials +# Secret (password, and the DSN IPAM reads) is written by bootstrap. +apiVersion: v1 +kind: Service +metadata: {name: ipam-postgres, namespace: ipam-system} +spec: + clusterIP: None + selector: {app.kubernetes.io/name: ipam-postgres} + ports: + - {name: postgres, port: 5432, targetPort: 5432} +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: {name: ipam-postgres, namespace: ipam-system} +spec: + serviceName: ipam-postgres + replicas: 1 + # The database outlives the Pod and the StatefulSet. + persistentVolumeClaimRetentionPolicy: {whenDeleted: Retain, whenScaled: Retain} + selector: + matchLabels: {app.kubernetes.io/name: ipam-postgres} + template: + metadata: + labels: {app.kubernetes.io/name: ipam-postgres} + spec: + automountServiceAccountToken: false + enableServiceLinks: false + securityContext: + runAsNonRoot: true + runAsUser: 70 + runAsGroup: 70 + fsGroup: 70 + seccompProfile: {type: RuntimeDefault} + containers: + - name: postgres + # PostgreSQL 17.10, official Alpine image (multi-arch index). + image: postgres:17.10-alpine@sha256:742f40ea20b9ff2ff31db5458d127452988a2164df9e17441e191f3b72252193 + args: [-c, shared_buffers=32MB, -c, max_connections=50] + env: + - {name: POSTGRES_USER, value: ipam} + - {name: POSTGRES_DB, value: ipam} + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: {name: postgres-credentials, key: password} + - {name: PGDATA, value: /var/lib/postgresql/data/pgdata} + ports: + - {name: postgres, containerPort: 5432} + readinessProbe: + exec: + command: [pg_isready, -U, ipam, -d, ipam, -h, 127.0.0.1] + periodSeconds: 5 + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: data, mountPath: /var/lib/postgresql/data} + volumeClaimTemplates: + - metadata: {name: data} + spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 1Gi}} diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml new file mode 100644 index 00000000..10f9732d --- /dev/null +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -0,0 +1,25 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-management, namespace: fleet-coordination} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-management, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + # patch marks a handoff's result answered; the spec stays immutable. + verbs: [get, list, watch, create, patch] + # The courier writes each assignment's payload, checks an existing one, + # and deletes it once the result is answered or the operation ends. + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + verbs: [get, list, create, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-management, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-management, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-management} diff --git a/config/multiplane/karmada-api/interpreter.yaml b/config/multiplane/karmada-api/interpreter.yaml new file mode 100644 index 00000000..736d2141 --- /dev/null +++ b/config/multiplane/karmada-api/interpreter.yaml @@ -0,0 +1,31 @@ +apiVersion: config.karmada.io/v1alpha1 +kind: ResourceInterpreterCustomization +metadata: + name: fleet-machine-allocation-handoff +spec: + target: + apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + customizations: + statusReflection: + luaScript: | + function ReflectStatus(observedObj) + if observedObj.status == nil then return {} end + return observedObj.status + end + statusAggregation: + luaScript: | + function AggregateStatus(desiredObj, statusItems) + local reflected = {} + for _, item in ipairs(statusItems or {}) do + if item.status ~= nil and item.status.observation ~= nil then + table.insert(reflected, { + clusterName = item.clusterName, + observation = item.status.observation + }) + end + end + -- Clear missing results; do not retain old success on zero replicas. + desiredObj.status = {reflected = reflected} + return desiredObj + end diff --git a/config/multiplane/karmada-api/kustomization.yaml b/config/multiplane/karmada-api/kustomization.yaml new file mode 100644 index 00000000..34d85767 --- /dev/null +++ b/config/multiplane/karmada-api/kustomization.yaml @@ -0,0 +1,8 @@ +# Karmada API configuration: management's intent-only role and the status +# interpreter. Applied by Flux on the host through the chart's karmada-kubeconfig. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - hub-rbac.yaml + - interpreter.yaml + - member-namespace.yaml diff --git a/config/multiplane/karmada-api/member-namespace.yaml b/config/multiplane/karmada-api/member-namespace.yaml new file mode 100644 index 00000000..f7136f2d --- /dev/null +++ b/config/multiplane/karmada-api/member-namespace.yaml @@ -0,0 +1,8 @@ +# Holds each member's push-mode credential Secret. The Secret itself is +# credential enrollment, written by bootstrap and never stored in the source. +apiVersion: v1 +kind: Namespace +metadata: + name: karmada-cluster + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/karmada-members/kustomization.yaml b/config/multiplane/karmada-members/kustomization.yaml new file mode 100644 index 00000000..3066f53f --- /dev/null +++ b/config/multiplane/karmada-members/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - members.yaml diff --git a/config/multiplane/karmada-members/members.yaml b/config/multiplane/karmada-members/members.yaml new file mode 100644 index 00000000..663e5f12 --- /dev/null +++ b/config/multiplane/karmada-members/members.yaml @@ -0,0 +1,41 @@ +# Push-mode member registration and placement for the selected cell. Values +# come from the per-environment fleet-environment ConfigMap (postBuild). +# The member's token Secret is enrolled by bootstrap, never stored in Git. +apiVersion: cluster.karmada.io/v1alpha1 +kind: Cluster +metadata: + name: "${FLEET_CELL}" + annotations: + # Unjoining a member deletes what Karmada propagated to it, including + # retained handoffs. Removing a member is an ordered manual procedure. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + syncMode: Push + apiEndpoint: "${FLEET_CELL_ENDPOINT}" + secretRef: + name: "${FLEET_CELL}" + namespace: karmada-cluster +--- +apiVersion: policy.karmada.io/v1alpha1 +kind: PropagationPolicy +metadata: + name: fleet-selected-cell + namespace: fleet-coordination +spec: + resourceSelectors: + - apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + labelSelector: + matchLabels: + coordination.fleet.datumapis.com/cell: "${FLEET_CELL}" + # An assignment's bootstrap payload travels beside its handoff. Deleting + # it on the hub deletes the cell's copy. + - apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationPayload + labelSelector: + matchLabels: + coordination.fleet.datumapis.com/cell: "${FLEET_CELL}" + placement: + clusterAffinity: + clusterNames: + - "${FLEET_CELL}" diff --git a/config/multiplane/karmada/karmada.yaml b/config/multiplane/karmada/karmada.yaml new file mode 100644 index 00000000..95dbc1de --- /dev/null +++ b/config/multiplane/karmada/karmada.yaml @@ -0,0 +1,81 @@ +# Karmada v1.16.0 on the management host, the chart pinned by the connected +# datum-cloud/test-infra federation checkout. HelmRepository + HelmRelease +# follows datum-cloud/infra infrastructure/karmada. Keep fsync enabled; single +# local replicas are not an HA qualification. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: HelmRepository +metadata: + name: karmada-charts + namespace: flux-system +spec: + interval: 1h + url: https://raw.githubusercontent.com/karmada-io/karmada/master/charts +--- +apiVersion: helm.toolkit.fluxcd.io/v2 +kind: HelmRelease +metadata: + name: karmada + namespace: flux-system + annotations: + # Uninstalling Karmada deletes retained coordination intent; removing it + # from the source must never garbage-collect the release. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + interval: 30m + timeout: 15m + releaseName: karmada + targetNamespace: karmada-system + storageNamespace: karmada-system + chart: + spec: + chart: karmada + version: v1.16.0 + sourceRef: {kind: HelmRepository, name: karmada-charts} + interval: 1h + install: + remediation: {retries: 3} + upgrade: + # Chart hooks regenerate certificates on upgrade; a failed upgrade is + # rolled back rather than retried into a different state. + remediation: {retries: 1, strategy: rollback} + crds: Skip + # As in datum-cloud/infra: report drift, do not overwrite. Pre-upgrade cert + # hooks make blind correction of this release unsafe. + driftDetection: {mode: warn} + values: + # Floating chart defaults pinned by index digest. + cfssl: + image: {digest: "sha256:a32a9048078819d3035f5dc46637346a0e7da9df297ab234994c9a80cde10b98"} + kubectl: + image: {digest: "sha256:8919c149c2e3d6860e0143c117900e64d71395172aaef0e01e604bb98c8e7ce0"} + apiServer: + serviceType: NodePort + nodePort: 32443 + resources: + requests: {cpu: 100m, memory: 256Mi} + limits: {memory: 768Mi} + controllerManager: + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 384Mi} + scheduler: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 192Mi} + webhook: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 192Mi} + aggregatedApiServer: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + kubeControllerManager: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + etcd: + internal: + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 384Mi} diff --git a/config/multiplane/karmada/kustomization.yaml b/config/multiplane/karmada/kustomization.yaml new file mode 100644 index 00000000..4f8395db --- /dev/null +++ b/config/multiplane/karmada/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - karmada.yaml diff --git a/config/multiplane/kro/kro.yaml b/config/multiplane/kro/kro.yaml new file mode 100644 index 00000000..082b3b9d --- /dev/null +++ b/config/multiplane/kro/kro.yaml @@ -0,0 +1,72 @@ +# kro v0.9.4 on the selected cell from its official OCI chart, pinned by +# manifest digest (chart layer SHA-256 ceeb6307...; image by digest below). +apiVersion: v1 +kind: Namespace +metadata: {name: kro-system} +--- +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: + name: kro-chart + namespace: flux-system +spec: + interval: 1h + url: oci://registry.k8s.io/kro/charts/kro + ref: + digest: sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c + layerSelector: + mediaType: application/vnd.cncf.helm.chart.content.v1.tar+gzip + operation: copy +--- +apiVersion: helm.toolkit.fluxcd.io/v2 +kind: HelmRelease +metadata: + name: kro + namespace: flux-system +spec: + interval: 30m + timeout: 5m + releaseName: kro + targetNamespace: kro-system + storageNamespace: kro-system + chartRef: {kind: OCIRepository, name: kro-chart} + install: + crds: Create + remediation: {retries: 3} + upgrade: + # Never replace kro CRDs implicitly; a CRD change is a reviewed upgrade. + crds: Skip + remediation: {retries: 3, strategy: rollback} + # kro holds no durable state: helm-controller corrects drift in its objects. + driftDetection: {mode: enabled} + # The chart's static controller role grants cluster-wide ConfigMap + # read/write, which kro v0.9.4 never uses (leader election uses Leases). + # Remove it. The test op makes a changed chart fail the release instead of + # silently removing another rule. + postRenderers: + - kustomize: + patches: + - target: {kind: ClusterRole, name: "kro:controller:static"} + patch: |- + - op: test + path: /rules/7 + value: {apiGroups: [""], resources: [configmaps], verbs: [get, list, watch, create, update, patch, delete]} + - op: remove + path: /rules/7 + values: + image: + tag: v0.9.4@sha256:eaf9fbaddd9d7f6cf400a8d47ab066b14cbef22b92a79be7bbdc7b3673376fb9 + rbac: + # Minimal controller role plus the aggregated fleet-site-kro ClusterRole. + mode: aggregation + deployment: + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + config: + enableLeaderElection: true + logLevel: info + rgd: + # Default per-dimension limit is 10; the acceptance delivers up to + # about 8 handoffs, including injected delivery faults. + maxCollectionDimensionSize: 64 diff --git a/config/multiplane/kro/kustomization.yaml b/config/multiplane/kro/kustomization.yaml new file mode 100644 index 00000000..be57d832 --- /dev/null +++ b/config/multiplane/kro/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - kro.yaml diff --git a/config/multiplane/milo/base/kustomization.yaml b/config/multiplane/milo/base/kustomization.yaml new file mode 100644 index 00000000..c771d7e5 --- /dev/null +++ b/config/multiplane/milo/base/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - milo.yaml diff --git a/config/multiplane/milo/base/milo.yaml b/config/multiplane/milo/base/milo.yaml new file mode 100644 index 00000000..c38c3ee9 --- /dev/null +++ b/config/multiplane/milo/base/milo.yaml @@ -0,0 +1,114 @@ +# One independent Milo project API process and its own etcd. Each overlay +# places this in its own namespace, with its own PVC and NodePort. The +# milo-apiserver-private Secret (static tokens and a self-signed serving key) +# is a local credential seam written by bootstrap; it is never in the source. +apiVersion: v1 +kind: Service +metadata: {name: milo-etcd} +spec: + clusterIP: None + selector: {app.kubernetes.io/name: milo-etcd} + ports: + - {name: client, port: 2379, targetPort: 2379} +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: {name: milo-etcd} +spec: + serviceName: milo-etcd + replicas: 1 + # Project storage outlives the Pod and the StatefulSet. + persistentVolumeClaimRetentionPolicy: {whenDeleted: Retain, whenScaled: Retain} + selector: + matchLabels: {app.kubernetes.io/name: milo-etcd} + template: + metadata: + labels: {app.kubernetes.io/name: milo-etcd} + spec: + automountServiceAccountToken: false + containers: + - name: etcd + image: registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11cc5c04b114ccdef39a9265eeef818e3d02f5359be035ae784097fdec5 + command: [/usr/local/bin/etcd] + args: + - --name=milo-etcd-0 + - --data-dir=/var/lib/etcd/data + - --listen-client-urls=http://0.0.0.0:2379 + - --advertise-client-urls=http://milo-etcd-0.milo-etcd:2379 + ports: + - {name: client, containerPort: 2379} + resources: + requests: {cpu: 25m, memory: 48Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: data, mountPath: /var/lib/etcd} + volumeClaimTemplates: + - metadata: {name: data} + spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 1Gi}} +--- +apiVersion: v1 +kind: Service +metadata: {name: milo-apiserver} +spec: + type: NodePort + selector: {app.kubernetes.io/name: milo-apiserver} + ports: + - {name: https, port: 6443, targetPort: 6443, nodePort: 30440} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: {name: milo-apiserver} +spec: + # Fault injection suspends this namespace's Kustomization before scaling; + # otherwise Flux restores this value. + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + template: + metadata: + labels: {app.kubernetes.io/name: milo-apiserver} + spec: + automountServiceAccountToken: false + enableServiceLinks: false + containers: + - name: apiserver + # 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 + - --etcd-prefix=/registry + - --authorization-mode=RBAC + - --token-auth-file=/private/tokens.csv + - --tls-cert-file=/private/tls.crt + - --tls-private-key-file=/private/tls.key + - --service-account-key-file=/private/tls.crt + - --service-account-signing-key-file=/private/tls.key + - --service-account-issuer=https://fleet-local.invalid + - --client-ca-file=/private/tls.crt + - --secure-port=6443 + - --bind-address=0.0.0.0 + - --anonymous-auth=false + - --v=0 + ports: + - {name: https, containerPort: 6443} + readinessProbe: + tcpSocket: {port: 6443} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 100m, memory: 192Mi} + limits: {memory: 384Mi} + volumeMounts: + - {name: private, mountPath: /private, readOnly: true} + volumes: + - name: private + secret: {secretName: milo-apiserver-private, defaultMode: 0400} diff --git a/config/multiplane/milo/consumer-a/kustomization.yaml b/config/multiplane/milo/consumer-a/kustomization.yaml new file mode 100644 index 00000000..3a381d3e --- /dev/null +++ b/config/multiplane/milo/consumer-a/kustomization.yaml @@ -0,0 +1,13 @@ +# Milo project API "consumer-a": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-consumer-a +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30442 diff --git a/config/multiplane/milo/consumer-a/namespace.yaml b/config/multiplane/milo/consumer-a/namespace.yaml new file mode 100644 index 00000000..60b21ec3 --- /dev/null +++ b/config/multiplane/milo/consumer-a/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-consumer-a + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/milo/consumer-b/kustomization.yaml b/config/multiplane/milo/consumer-b/kustomization.yaml new file mode 100644 index 00000000..5c1e727f --- /dev/null +++ b/config/multiplane/milo/consumer-b/kustomization.yaml @@ -0,0 +1,13 @@ +# Milo project API "consumer-b": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-consumer-b +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30443 diff --git a/config/multiplane/milo/consumer-b/namespace.yaml b/config/multiplane/milo/consumer-b/namespace.yaml new file mode 100644 index 00000000..2baff5c4 --- /dev/null +++ b/config/multiplane/milo/consumer-b/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-consumer-b + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/milo/provider/kustomization.yaml b/config/multiplane/milo/provider/kustomization.yaml new file mode 100644 index 00000000..9d4a2d69 --- /dev/null +++ b/config/multiplane/milo/provider/kustomization.yaml @@ -0,0 +1,31 @@ +# Milo project API "provider": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-provider +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30441 + # The aggregation layer, as the platform's Milo runs it: Milo proxies + # aggregated APIs (IPAM, in synchronized lab DHCP mode) with a front-proxy + # client certificate, and the APIs trust its CA for the X-Remote-* identity + # headers, project extras included. Bootstrap enrolls the CA and client key + # in milo-apiserver-private; they are never in the source. + - target: {kind: Deployment, name: milo-apiserver} + patch: |- + - op: test + path: /spec/template/spec/containers/0/name + value: apiserver + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --proxy-client-cert-file=/private/front-proxy-client.crt} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --proxy-client-key-file=/private/front-proxy-client.key} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-client-ca-file=/private/front-proxy-ca.crt} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-allowed-names=fleet-front-proxy-client} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-username-headers=X-Remote-User} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-uid-headers=X-Remote-Uid} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-group-headers=X-Remote-Group} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-extra-headers-prefix=X-Remote-Extra-} diff --git a/config/multiplane/milo/provider/namespace.yaml b/config/multiplane/milo/provider/namespace.yaml new file mode 100644 index 00000000..56638df3 --- /dev/null +++ b/config/multiplane/milo/provider/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-provider + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/overlays/management-plane/kustomization.yaml b/config/overlays/management-plane/kustomization.yaml index 38194887..dbeae129 100644 --- a/config/overlays/management-plane/kustomization.yaml +++ b/config/overlays/management-plane/kustomization.yaml @@ -3,6 +3,7 @@ kind: Kustomization resources: - ../../base/crd - ../../base/manager + - ../../base/registration - ../../components/admission components: - ../../components/consumer-ui-plugin diff --git a/config/overlays/synthetic-staging/kustomization.yaml b/config/overlays/synthetic-staging/kustomization.yaml index 62241eef..f1363d79 100644 --- a/config/overlays/synthetic-staging/kustomization.yaml +++ b/config/overlays/synthetic-staging/kustomization.yaml @@ -4,6 +4,7 @@ resources: - ../management-plane - provider.yaml patches: + - path: registration-exclusion.yaml - target: group: apps version: v1 @@ -32,6 +33,18 @@ patches: - op: add path: /spec/template/spec/containers/0/args/- value: --synthetic-published-profile-name=$(FLEET_PUBLISHED_PROFILE_NAME) + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-coordinator-client-cert-dir=/var/run/fleet/coordinator + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-release-client-cert-dir=/var/run/fleet/release + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-projector-client-cert-dir=/var/run/fleet/projector + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-site-enrollment-file=/etc/fleet/enrollment/enrollment.json - op: add path: /spec/template/spec/containers/0/env value: @@ -70,6 +83,79 @@ patches: name: synthetic-provider-token mountPath: /var/run/fleet/provider readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: custody-coordinator-client-cert + mountPath: /var/run/fleet/coordinator + readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: release-controller-client-cert + mountPath: /var/run/fleet/release + readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: capacity-projector-client-cert + mountPath: /var/run/fleet/projector + readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: synthetic-site-enrollment + mountPath: /etc/fleet/enrollment + readOnly: true + - op: add + path: /spec/template/spec/volumes/- + value: + name: custody-coordinator-client-cert + # A cert-manager Certificate's Secret for the coordinator's Milo + # identity. The whole Secret is mounted so a renewal is picked up. + secret: + secretName: fleet-custody-coordinator-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: release-controller-client-cert + # A cert-manager Certificate's Secret for the release controller's + # Milo identity. + secret: + secretName: fleet-release-controller-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: capacity-projector-client-cert + # A cert-manager Certificate's Secret for the capacity projector's + # Milo identity. + secret: + secretName: fleet-capacity-projector-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: synthetic-site-enrollment + configMap: + name: fleet-synthetic-site-enrollment + defaultMode: 0440 - op: add path: /spec/template/spec/volumes/- value: diff --git a/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml b/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml new file mode 100644 index 00000000..74ca5404 --- /dev/null +++ b/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml @@ -0,0 +1,18 @@ +# Operators apply this to the synthetic provider project, in the Device +# namespace (--synthetic-device-namespace). It is not part of the overlay, +# which renders into the management cluster. Synthetic staging allocates no +# capacity until the policy its capacity names exists. The synthetic site +# overwrites its one disk and reads it back, so the policy claims only Clear. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: CleaningPolicy +metadata: + name: synthetic-tenant-reuse-v1 + namespace: default +spec: + assurance: Clear + rules: + - name: nvme-ssd + match: {protocol: NVMe, mediaType: SSD} + methods: [Overwrite] + verify: {mode: Full} + timePerTiB: 1h diff --git a/config/overlays/synthetic-staging/provider.yaml b/config/overlays/synthetic-staging/provider.yaml index 37ecbe78..30497a71 100644 --- a/config/overlays/synthetic-staging/provider.yaml +++ b/config/overlays/synthetic-staging/provider.yaml @@ -1,3 +1,16 @@ +# The synthetic provider site's enrollment: the Devices it serves, with the +# identity their Device records carry and the key digest fixture discovery +# reports. This placeholder is synthetic; an environment replaces it with the +# Devices it imports. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-synthetic-site-enrollment + namespace: fleet-system +data: + enrollment.json: | + {"default/server-example-001": {"bmcEndpoint": "https://[2001:db8::31]", "systemUUID": "00000000-0000-4000-8000-000000000031", "bootMACAddress": "02:00:00:00:00:31", "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", "disks": ["disk-0"]}} +--- apiVersion: v1 kind: ServiceAccount metadata: @@ -25,7 +38,7 @@ metadata: namespace: fleet-system spec: replicas: 1 - # The simulator state file has one writer; never overlap provider pods. + # The site store has one writer; never overlap provider pods. strategy: type: Recreate selector: @@ -56,7 +69,8 @@ spec: args: - --listen-address=0.0.0.0:8090 - --runtime-token-file=/var/run/fleet/provider/token - - --state-file=/var/lib/fleet/state.json + - --state-dir=/var/lib/fleet/site + - --enrollment-file=/etc/fleet/enrollment/enrollment.json ports: - name: runtime containerPort: 8090 @@ -64,7 +78,7 @@ spec: httpGet: {path: /readyz, port: runtime} periodSeconds: 2 livenessProbe: - httpGet: {path: /healthz, port: runtime} + httpGet: {path: /readyz, port: runtime} periodSeconds: 10 resources: requests: {cpu: 10m, memory: 24Mi} @@ -79,7 +93,14 @@ spec: - name: runtime-token mountPath: /var/run/fleet/provider readOnly: true + - name: enrollment + mountPath: /etc/fleet/enrollment + readOnly: true volumes: + - name: enrollment + configMap: + name: fleet-synthetic-site-enrollment + defaultMode: 0440 - name: state persistentVolumeClaim: claimName: fleet-synthetic-provider-state diff --git a/config/overlays/synthetic-staging/registration-exclusion.yaml b/config/overlays/synthetic-staging/registration-exclusion.yaml new file mode 100644 index 00000000..e4801d66 --- /dev/null +++ b/config/overlays/synthetic-staging/registration-exclusion.yaml @@ -0,0 +1,22 @@ +# The synthetic Milo root (config/milo-synthetic) installs no registration +# webhook, so the registration workload has nothing to serve here. +$patch: delete +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-registration + namespace: fleet-system +--- +$patch: delete +apiVersion: v1 +kind: Service +metadata: + name: fleet-registration + namespace: fleet-system +--- +$patch: delete +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-registration + namespace: fleet-system diff --git a/config/site/base/enrollment.json b/config/site/base/enrollment.json new file mode 100644 index 00000000..7f958453 --- /dev/null +++ b/config/site/base/enrollment.json @@ -0,0 +1 @@ +{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"], "hardware": {"bootMode": "BIOS", "cpu": {"architecture": "amd64", "cores": 2}, "memory": "2Gi", "disks": [{"name": "disk-0", "capacity": "2Gi"}], "interfaces": [{"name": "primary", "macAddress": "52:54:00:77:00:02"}]}}} diff --git a/config/site/base/kro.yaml b/config/site/base/kro.yaml new file mode 100644 index 00000000..c75e6984 --- /dev/null +++ b/config/site/base/kro.yaml @@ -0,0 +1,227 @@ +# kro's grant for the handoff dispatcher graph. kro creates only per-operation +# worker objects; the shared site services, their Service and the journal +# volume are Flux-owned and kro may only read them. +# +# Reads are cluster-wide because kro v0.9.4 watches every kind it manages or +# references with cluster-wide metadata informers. Writes are namespaced: +# Jobs and ServiceAccounts in fleet-site, Roles and RoleBindings in +# fleet-coordination. kro holds no Deployment, Service, volume, ConfigMap or +# Secret write and no handoff spec or status write. To create a per-operation +# Role granting get on one handoff and on its one payload, kro itself must +# hold get on both kinds, and it holds nothing more on payloads: no list, +# watch or write, and no escalate or bind. The worker identity policy admits +# only the per-operation Role and binding shapes, and the cluster RBAC policy +# refuses every cluster-wide Role or binding kro writes. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-site-kro + # Aggregated into the kro controller ClusterRole (chart rbac.mode=aggregation). + labels: {rbac.kro.run/aggregate-to-controller: "true"} +rules: + - apiGroups: [site.fleet.datumapis.com] + resources: [handoffdispatchers, handoffdispatchers/status, handoffdispatchers/finalizers] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [persistentvolumeclaims, services, serviceaccounts] + verbs: [get, list, watch] + - apiGroups: [apps] + resources: [deployments] + verbs: [get, list, watch] + - apiGroups: [batch] + resources: [jobs] + verbs: [get, list, watch] + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-workers, namespace: fleet-site} +rules: + - apiGroups: [batch] + resources: [jobs] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [serviceaccounts] + verbs: [create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-workers, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-workers} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-rbac, namespace: fleet-coordination} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-rbac, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-rbac} +--- +# RBAC alone would still let a graph revision create any Job in fleet-site, +# including one that runs as the observer (the status writer) or as a +# privileged container. These policies bind kro's writes to the per-operation +# shape: w- names, the matching ServiceAccount, the site image the +# shared services run (parameter written by the services layer), no privilege, +# no host namespaces and no volume other than the journal claim and emptyDir. +# They apply only to kro's own requests; nothing else in the cluster is gated. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-worker-jobs} +spec: + failurePolicy: Fail + paramKind: {apiVersion: v1, kind: ConfigMap} + matchConstraints: + namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: fleet-site} + resourceRules: + - {apiGroups: [batch], apiVersions: ["*"], resources: [jobs], operations: [CREATE, UPDATE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + variables: + - name: pod + expression: object.spec.template.spec + - name: handoff + expression: "has(object.metadata.labels) && 'fleet.datumapis.com/handoff' in object.metadata.labels ? object.metadata.labels['fleet.datumapis.com/handoff'] : ''" + validations: + - expression: "variables.handoff.startsWith('op-') && object.metadata.name == 'w-' + variables.handoff" + message: a worker Job must be named w- and labelled with that handoff + - expression: "has(variables.pod.serviceAccountName) && variables.pod.serviceAccountName == object.metadata.name" + message: a worker Job must run as its own per-operation ServiceAccount + - expression: >- + size(variables.pod.containers) == 1 && + (!has(variables.pod.initContainers) || size(variables.pod.initContainers) == 0) && + variables.pod.containers.all(c, c.image == params.data.image) + message: a worker Job must run one container from the site image the shared services run + - expression: >- + variables.pod.containers.all(c, has(c.securityContext) && + (!has(c.securityContext.privileged) || !c.securityContext.privileged) && + has(c.securityContext.allowPrivilegeEscalation) && !c.securityContext.allowPrivilegeEscalation && + has(c.securityContext.capabilities) && has(c.securityContext.capabilities.drop) && + 'ALL' in c.securityContext.capabilities.drop && + (!has(c.securityContext.capabilities.add) || size(c.securityContext.capabilities.add) == 0)) + message: a worker Job must be unprivileged with all capabilities dropped + - expression: >- + !(has(variables.pod.hostNetwork) && variables.pod.hostNetwork) && + !(has(variables.pod.hostPID) && variables.pod.hostPID) && + !(has(variables.pod.hostIPC) && variables.pod.hostIPC) + message: a worker Job must not use host namespaces + - expression: >- + !has(variables.pod.volumes) || variables.pod.volumes.all(v, + (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir)) + message: a worker Job may mount only the site journal claim and emptyDir + # The kubelet resolves Secret references for a Pod whatever its + # ServiceAccount may read, so a worker takes environment only from + # literal values and the site enrollment. + - expression: >- + variables.pod.containers.all(c, !has(c.envFrom) && (!has(c.env) || c.env.all(e, !has(e.valueFrom) || + (has(e.valueFrom.configMapKeyRef) && e.valueFrom.configMapKeyRef.name == 'fleet-site-enrollment' && + !has(e.valueFrom.secretKeyRef) && !has(e.valueFrom.fieldRef) && !has(e.valueFrom.resourceFieldRef))))) + message: a worker Job may take environment only from literal values and the site enrollment + - expression: >- + variables.pod.containers.all(c, !has(c.args) && has(c.command) && size(c.command) == 6 && + c.command[0] == 'fleet-multiplane' && c.command[1] == 'site-worker' && + c.command[2] == '--handoff' && c.command[3] == variables.handoff && c.command[4] == '--cell') + message: a worker Job must run only the site worker for its own handoff +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-worker-jobs} +spec: + policyName: fleet-site-kro-worker-jobs + validationActions: [Deny] + paramRef: + name: fleet-site-worker-policy + namespace: fleet-site + parameterNotFoundAction: Deny +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-worker-identity} +spec: + failurePolicy: Fail + matchConstraints: + namespaceSelector: + matchExpressions: + - {key: kubernetes.io/metadata.name, operator: In, values: [fleet-site, fleet-coordination]} + resourceRules: + - {apiGroups: [""], apiVersions: ["*"], resources: [serviceaccounts], operations: [CREATE, UPDATE]} + - {apiGroups: [rbac.authorization.k8s.io], apiVersions: ["*"], resources: [roles, rolebindings], operations: [CREATE, UPDATE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + variables: + - name: kind + expression: request.resource.resource + - name: handoff + expression: "object.metadata.name.startsWith('w-op-') ? object.metadata.name.substring(2) : ''" + validations: + - expression: "variables.handoff != ''" + message: kro may create only per-operation identities named w- + - expression: "variables.kind != 'serviceaccounts' || request.namespace == 'fleet-site'" + message: worker ServiceAccounts live in fleet-site + - expression: >- + variables.kind != 'roles' || (has(object.rules) && size(object.rules) == 2 && + object.rules[0].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[0].resources == ['machineallocationhandoffs'] && object.rules[0].verbs == ['get'] && + has(object.rules[0].resourceNames) && object.rules[0].resourceNames == [variables.handoff] && + !has(object.rules[0].nonResourceURLs) && + object.rules[1].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[1].resources == ['machineallocationpayloads'] && object.rules[1].verbs == ['get'] && + has(object.rules[1].resourceNames) && object.rules[1].resourceNames == [variables.handoff + '-payload'] && + !has(object.rules[1].nonResourceURLs)) + message: a worker Role may grant only get on its own handoff and on its own payload + - expression: >- + variables.kind != 'rolebindings' || (object.roleRef.kind == 'Role' && + object.roleRef.name == object.metadata.name && has(object.subjects) && size(object.subjects) == 1 && + object.subjects[0].kind == 'ServiceAccount' && object.subjects[0].name == object.metadata.name && + object.subjects[0].namespace == 'fleet-site') + message: a worker RoleBinding may bind only its own Role to its own ServiceAccount +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-worker-identity} +spec: + policyName: fleet-site-kro-worker-identity + validationActions: [Deny] +--- +# kro holds no cluster-wide RBAC write, and this refuses one anyway: a graph +# revision must never create or change a ClusterRole or ClusterRoleBinding. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-cluster-rbac} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - {apiGroups: [rbac.authorization.k8s.io], apiVersions: ["*"], resources: [clusterroles, clusterrolebindings], operations: [CREATE, UPDATE, DELETE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + validations: + - expression: "false" + message: kro may not write cluster-wide RBAC +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-cluster-rbac} +spec: + policyName: fleet-site-kro-cluster-rbac + validationActions: [Deny] diff --git a/config/site/base/kustomization.yaml b/config/site/base/kustomization.yaml new file mode 100644 index 00000000..9ad8af9f --- /dev/null +++ b/config/site/base/kustomization.yaml @@ -0,0 +1,15 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - site.yaml + - kro.yaml + - reconcilers.yaml +# The local VM site's enrollment of the one synthetic Device it serves: the +# identity its fixture Device records and the key digest fixture discovery +# reports. Synthetic data only. The Redfish site enrolls its targets in its +# graph instead. +configMapGenerator: + - name: fleet-site-enrollment + namespace: fleet-site + files: [enrollment.json] + options: {disableNameSuffixHash: true} diff --git a/config/site/base/reconcilers.yaml b/config/site/base/reconcilers.yaml new file mode 100644 index 00000000..c95b5a19 --- /dev/null +++ b/config/site/base/reconcilers.yaml @@ -0,0 +1,81 @@ +# Scoped Flux identities for the site layers, created with the site namespace. +# kustomize-controller impersonates these ServiceAccounts, so each layer can +# write only its own kinds: +# fleet-site-services Deployments, the boot Service and the worker-policy +# ConfigMap in fleet-site +# fleet-site-graph ResourceGraphDefinitions +# fleet-site-dispatch HandoffDispatchers in fleet-site +# None of them can write Jobs, volumes, RBAC, admission policy or handoffs. +# Source authors remain trusted: the services layer chooses the privileged +# runtime image, the graph chooses the worker template within the admission +# policy, and the same source owns this admin-applied base. kro remains the +# sole writer of the per-operation objects the graph generates. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-services-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-services-reconciler, namespace: fleet-site} +rules: + - apiGroups: [apps] + resources: [deployments] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [""] + resources: [services, configmaps] + verbs: [get, list, watch, create, update, patch, delete] + # Read-only, for kstatus health checks of the Deployments. + - apiGroups: [apps] + resources: [replicasets] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [pods] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-services-reconciler, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: fleet-site-services-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-services-reconciler} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-graph-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-site-graph-reconciler} +rules: + - apiGroups: [kro.run] + resources: [resourcegraphdefinitions] + verbs: [get, list, watch, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-site-graph-reconciler} +subjects: + - {kind: ServiceAccount, name: fleet-site-graph-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-site-graph-reconciler} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-dispatch-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-dispatch-reconciler, namespace: fleet-site} +rules: + - apiGroups: [site.fleet.datumapis.com] + resources: [handoffdispatchers] + verbs: [get, list, watch, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-dispatch-reconciler, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: fleet-site-dispatch-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-dispatch-reconciler} diff --git a/config/site/base/site.yaml b/config/site/base/site.yaml new file mode 100644 index 00000000..38491165 --- /dev/null +++ b/config/site/base/site.yaml @@ -0,0 +1,78 @@ +# Experimental Kubernetes site for one selected local cell. Reconciled by the +# cell's Flux after the MachineAllocationHandoff CRD and fleet-coordination +# namespace exist. See docs/operations/site-execution.md and gitops.md. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site + annotations: + # Deleting the namespace would delete the journal volume claim. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# Retain: deleting the claim never deletes the provider journal, disks or boot +# evidence. A journal reset would let replayed handoffs be admitted as new. +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: fleet-site-retain + annotations: + # StorageClass parameters are immutable; create once, never prune. + kustomize.toolkit.fluxcd.io/prune: disabled + kustomize.toolkit.fluxcd.io/ssa: IfNotPresent +provisioner: rancher.io/local-path +reclaimPolicy: Retain +volumeBindingMode: WaitForFirstConsumer +--- +# The durable site volume belongs to this layer alone. The shared services +# mount it and the dispatcher graph only references it, so neither the services +# layer nor any graph or instance lifecycle can delete it. Flux creates it once +# and never updates or prunes it: removing it from the source, a controller +# restart or a reconcile cannot replace the journal. +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: fleet-site-state + namespace: fleet-site + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled + kustomize.toolkit.fluxcd.io/ssa: IfNotPresent +spec: + storageClassName: fleet-site-retain + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 8Gi}} +--- +# Identities of the shared site services (config/site/services). The runtime +# and boot service hold no API token. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-runtime, namespace: fleet-site} +automountServiceAccountToken: false +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-boot, namespace: fleet-site} +automountServiceAccountToken: false +--- +# The observer is the only writer of handoff status on this cell. It holds no +# create/delete or spec-write permission and no Secret access. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-observer, namespace: fleet-site} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-observer, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs/status] + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-observer, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-site-observer, namespace: fleet-site} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-observer} diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml new file mode 100644 index 00000000..1e08f3b7 --- /dev/null +++ b/config/site/dhcp/component/dhcp.yaml @@ -0,0 +1,131 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-dhcp, namespace: fleet-site} +automountServiceAccountToken: false +--- +# One site's Kea DHCPv4 instances, in a central cluster rather than at the +# site. Each Pod's name is its stable instance name in the applied reports, +# so a StatefulSet, never a Deployment: a replaced Pod keeps its name and its +# last report. The instances share one load-balancer address on UDP 67 +# (below), which the site's relays reach over the WAN link. Kea answers only relayed +# requests, on a UDP socket, so it needs no host networking; the base +# configuration's relay filter limits it to the site's relays. The site's +# enrollment lists these Pods' names as its expected DHCP instances. To +# retire one, make sure it no longer answers, scale down (the highest +# ordinal goes first), shrink the enrollment's dhcpInstances to match, and +# restart the site's workers and feed. +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + serviceName: fleet-site-dhcp + replicas: 2 + podManagementPolicy: Parallel + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-dhcp} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-dhcp} + spec: + serviceAccountName: fleet-site-dhcp + automountServiceAccountToken: false + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: {matchLabels: {app.kubernetes.io/name: fleet-site-dhcp}} + topologyKey: kubernetes.io/hostname + containers: + - name: kea + # ISC's image, pinned by digest. It is built for linux/amd64 only. + image: docker.cloudsmith.io/isc/docker/kea-dhcp4:2.6.3@sha256:c40abb1522b15edb9a6d1119ad22b3765bf818a51d6776f498e874ad13416065 + # Kea 2.6 refuses a control socket directory that is not 0750, + # and an emptyDir is created 0777. + command: [sh, -c, 'chmod 0750 /var/run/kea && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] + ports: + - {name: dhcp, containerPort: 67, protocol: UDP} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL], add: [NET_BIND_SERVICE]} + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: base, mountPath: /etc/kea-base, readOnly: true} + - {name: control, mountPath: /var/run/kea} + - name: sync + image: "${FLEET_DHCP_SYNC_IMAGE}" + imagePullPolicy: IfNotPresent + command: + - /fleet-dhcp-sync + # The site's feed, over TLS only, wherever the site's boot Pod + # runs. + - -feed=${FLEET_DHCP_FEED_URL} + - -token-file=/etc/fleet-dhcp/token + - -ca-file=/etc/fleet-dhcp-tls/ca.crt + - -kea-socket=/var/run/kea/kea4-ctrl-socket + - -base-config=/etc/kea-base/kea-dhcp4.conf + env: + - name: POD_NAME + valueFrom: {fieldRef: {fieldPath: metadata.name}} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + volumeMounts: + - {name: base, mountPath: /etc/kea-base, readOnly: true} + - {name: control, mountPath: /var/run/kea} + - {name: token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: feed-ca, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + volumes: + - name: base + configMap: {name: fleet-site-dhcp-base} + - name: control + emptyDir: {} + - name: token + secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400} + - name: feed-ca + secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400, items: [{key: ca.crt, path: ca.crt}]} +--- +# One instance may restart at a time. Retiring an instance is an operator +# step; see the comment on the StatefulSet. +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + maxUnavailable: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-dhcp} +--- +# One load-balancer address on UDP 67 for all of the site's instances, which +# the site's relays forward to. Any instance may answer a request. Each +# instance applies the same feed through its own synchronizer and reports it +# under its own stable name, so the withdrawal gate covers every expected one; +# an instance that has not applied a reservation yet stays silent, because +# Kea is not authoritative, and the firmware retries. Client-IP affinity +# sends all of one relay's traffic to one instance, so the replicas give +# availability, not load sharing per relay; a relay's retries keep reaching +# the same instance until its synchronizer applies the reservation, within +# one poll. Kea replies to the relay +# address in each request; the site's relays must accept replies from the +# cluster's egress address. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + type: LoadBalancer + externalTrafficPolicy: Local + sessionAffinity: ClientIP + selector: {app.kubernetes.io/name: fleet-site-dhcp} + ports: + - {name: dhcp, port: 67, targetPort: 67, protocol: UDP} diff --git a/config/site/dhcp/component/kustomization.yaml b/config/site/dhcp/component/kustomization.yaml new file mode 100644 index 00000000..3aa57dc6 --- /dev/null +++ b/config/site/dhcp/component/kustomization.yaml @@ -0,0 +1,14 @@ +# One synchronized site's DHCP service, deployed to a central cluster: Kea +# DHCPv4 instances, each with its synchronizer, behind one load-balancer +# address on UDP 67. The site's feed is the separate ../feed component, +# beside the site's boot service. Network operations owns the base +# configuration (ConfigMap fleet-site-dhcp-base) and the relays that point at +# the instances' addresses. The environment supplies the Secrets +# fleet-site-dhcp-sync (key token, at least 32 characters) and +# fleet-site-dhcp-feed-tls (ca.crt), never in Git, and the +# FLEET_DHCP_FEED_URL and FLEET_DHCP_SYNC_IMAGE substitutions. See +# docs/operations/boot-network.md. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - dhcp.yaml diff --git a/config/site/dhcp/example/base.yaml b/config/site/dhcp/example/base.yaml new file mode 100644 index 00000000..8a24fa47 --- /dev/null +++ b/config/site/dhcp/example/base.yaml @@ -0,0 +1,35 @@ +# A synthetic base configuration. Network operations owns the real one: the +# site's provisioning subnet and gateway, the relay addresses Kea accepts, and +# the boot options. Kea answers only relayed requests on a UDP socket, and the +# relay filter limits it to the site's relays. It has no pools, so Kea answers +# only reserved MACs, and Kea 2.6 requires the control socket under +# /var/run/kea. Firmware boots over UEFI HTTP boot, never TFTP: requests from +# the HTTP boot vendor class get the boot service's loader URL. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-dhcp-base + namespace: fleet-site +data: + kea-dhcp4.conf: | + {"Dhcp4": { + "interfaces-config": {"interfaces": ["*"], "dhcp-socket-type": "udp"}, + "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, + "lease-database": {"type": "memfile", "persist": false}, + "host-reservation-identifiers": ["hw-address"], + "authoritative": false, + "client-classes": [{ + "name": "HTTPClient", + "test": "substring(option[60].hex,0,10) == 'HTTPClient'", + "option-data": [{"name": "vendor-class-identifier", "data": "HTTPClient"}], + "boot-file-name": "http://192.0.2.80:8080/pxe/ipxe.efi" + }], + "valid-lifetime": 600, + "subnet4": [{ + "id": 1, + "subnet": "198.51.100.0/24", + "relay": {"ip-addresses": ["198.51.100.1"]}, + "option-data": [{"name": "routers", "data": "198.51.100.1"}], + "boot-file-name": "http://192.0.2.80:8080/pxe/boot.ipxe" + }] + }} diff --git a/config/site/dhcp/example/enrollment.yaml b/config/site/dhcp/example/enrollment.yaml new file mode 100644 index 00000000..a4574d87 --- /dev/null +++ b/config/site/dhcp/example/enrollment.yaml @@ -0,0 +1,10 @@ +# A synthetic synced enrollment for the render check. An environment supplies +# the same enrollment its site workers get, naming the StatefulSet's Pods as +# the expected DHCP instances. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-redfish-enrollment + namespace: fleet-site +data: + enrollment: '{"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0","fleet-site-dhcp-1"],"targets":[{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"00000000-0000-4000-8000-000000000001","diskBytes":2147483648,"console":"server-example-001.log"}]}' diff --git a/config/site/dhcp/example/kustomization.yaml b/config/site/dhcp/example/kustomization.yaml new file mode 100644 index 00000000..7514db36 --- /dev/null +++ b/config/site/dhcp/example/kustomization.yaml @@ -0,0 +1,13 @@ +# Render check only: the Redfish site services with the feed, and the site's +# central DHCP instances with a synthetic base configuration, in one render. +# An environment deploys the two to different clusters and supplies its own +# base configuration from network operations. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../redfish/services + - base.yaml + - enrollment.yaml +components: + - ../feed + - ../component diff --git a/config/site/dhcp/feed/kustomization.yaml b/config/site/dhcp/feed/kustomization.yaml new file mode 100644 index 00000000..c20b16f7 --- /dev/null +++ b/config/site/dhcp/feed/kustomization.yaml @@ -0,0 +1,62 @@ +# The reservation feed: a container beside the boot service, which reads the +# site store and writes the applied reports beside the boot evidence, and a +# Service. The site's central DHCP instances reach it over TLS only. The +# environment supplies the Secrets fleet-site-dhcp-sync (key token) and +# fleet-site-dhcp-feed-tls (tls.crt, tls.key, ca.crt), never in Git, and the +# ConfigMap fleet-site-redfish-enrollment (key enrollment): the same synced +# Redfish enrollment the site's workers get. The feed serves, and takes +# reports from, only the enrollment's dhcpInstances, and starts only while +# the site's delivery declaration, the fleet-site-delivery ConfigMap, offers +# network boot. The Kea component and the Redfish lab's synchronized DHCP +# both use it. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - service.yaml +patches: + # The feed reads the site store and writes the applied reports beside the + # boot evidence, so it runs in the boot Pod, which holds the state volume. + - target: {kind: Deployment, name: fleet-site-boot} + patch: |- + - op: add + path: /spec/template/spec/containers/- + value: + name: dhcp-feed + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key, -delivery-methods, /etc/fleet-site-delivery/methods] + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - name: FLEET_REDFISH_ENROLLMENT + valueFrom: {configMapKeyRef: {name: fleet-site-redfish-enrollment, key: enrollment}} + ports: + - {name: dhcp-feed, containerPort: 8081} + readinessProbe: + tcpSocket: {port: 8081} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} + - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: dhcp-feed-tls, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - {name: dhcp-feed-delivery, mountPath: /etc/fleet-site-delivery, readOnly: true} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-tls, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400}} + # The site enrollment's delivery declaration: the feed starts only + # while it declares network boot. + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-delivery, configMap: {name: fleet-site-delivery}} diff --git a/config/site/dhcp/feed/service.yaml b/config/site/dhcp/feed/service.yaml new file mode 100644 index 00000000..57cd234c --- /dev/null +++ b/config/site/dhcp/feed/service.yaml @@ -0,0 +1,12 @@ +# The feed, over TLS only. An environment exposes it to the cluster that +# runs the site's DHCP instances, which authenticate with the site's token. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-dhcp-feed + namespace: fleet-site +spec: + type: ClusterIP + selector: {app.kubernetes.io/name: fleet-site-boot} + ports: + - {name: dhcp-feed, port: 8081, targetPort: 8081, protocol: TCP} diff --git a/config/site/dhcp/isolated-example/kea-dhcp4.conf b/config/site/dhcp/isolated-example/kea-dhcp4.conf new file mode 100644 index 00000000..fca96e21 --- /dev/null +++ b/config/site/dhcp/isolated-example/kea-dhcp4.conf @@ -0,0 +1,28 @@ +{ + "Dhcp4": { + "interfaces-config": { + "interfaces": ["eth0"], + "dhcp-socket-type": "udp", + "service-sockets-require-all": true + }, + "control-sockets": [{ + "socket-type": "unix", + "socket-name": "/run/kea/control/kea4-ctrl-socket" + }], + "lease-database": {"type": "memfile", "persist": false}, + "host-reservation-identifiers": ["hw-address"], + "authoritative": false, + "valid-lifetime": 60, + "subnet4": [{ + "id": 1, + "subnet": "192.168.77.0/24", + "relay": {"ip-addresses": ["192.168.77.1"]}, + "option-data": [{"name": "routers", "data": "192.168.77.1"}] + }], + "loggers": [{ + "name": "kea-dhcp4", + "output-options": [{"output": "stdout"}], + "severity": "INFO" + }] + } +} diff --git a/config/site/dhcp/isolated-example/kustomization.yaml b/config/site/dhcp/isolated-example/kustomization.yaml new file mode 100644 index 00000000..2b5ff48e --- /dev/null +++ b/config/site/dhcp/isolated-example/kustomization.yaml @@ -0,0 +1,13 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: fleet-dhcp-proof +resources: + - ../isolated + - namespace.yaml +configMapGenerator: + - name: fleet-dhcp-proof-base + files: + - kea-dhcp4.conf + - name: fleet-dhcp-proof-settings + literals: + - feed-url=https://feed.example.invalid:8081 diff --git a/config/site/dhcp/isolated-example/namespace.yaml b/config/site/dhcp/isolated-example/namespace.yaml new file mode 100644 index 00000000..65ad4ddb --- /dev/null +++ b/config/site/dhcp/isolated-example/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-dhcp-proof diff --git a/config/site/dhcp/isolated/README.md b/config/site/dhcp/isolated/README.md new file mode 100644 index 00000000..b9b87ecb --- /dev/null +++ b/config/site/dhcp/isolated/README.md @@ -0,0 +1,23 @@ +# Isolated synchronized DHCP consumer + +This reusable Kea 3.0.3 profile prepares one disposable synchronized DHCP instance. It is not the existing two-instance public DHCP component, a site producer, or proof of an end-to-end lease. The headless Service creates no public address. The stable instance name is `fleet-dhcp-proof-0`; the real worker enrollment must declare that exact name in `dhcpInstances`. + +## Environment contract + +Consume this Kustomize base from a pinned Fleet revision. The environment owns the namespace, connectivity policies, and these inputs: + +- Override `ghcr.io/datum-cloud/fleet:replace-me` with the reviewed synchronizer image digest using Kustomize images. The placeholder deliberately cannot deploy as provided. +- Generate `fleet-dhcp-proof-settings` with `feed-url`: the real HTTPS origin, whose certificate matches its hostname. Kustomize rewrites the generated ConfigMap reference. +- Generate `fleet-dhcp-proof-base` with `kea-dhcp4.conf`: approved subnet IDs, relay addresses, interface and router options. Use UDP sockets, the UNIX socket path `/run/kea/control/kea4-ctrl-socket`, and non-authoritative operation. Do not supply device reservations or Kea pools that bypass IPAM. Network operations owns this topology, not the generic consumer. +- Provision Secrets `fleet-dhcp-proof-sync` (key `token`) and `fleet-dhcp-proof-feed-ca` (key `ca.crt`) outside Git. The token must match the real feed; the CA must verify it. +- Restrict ingress to the approved relay, and egress to that relay, DNS and the real feed. Provide the relay return route and matching producer ingress. The base intentionally does not invent environment-specific NetworkPolicy selectors. + +The pinned Kea image requires amd64. Both processes use UID 100/GID 101 with no capabilities and read-only roots. A shared UNIX socket connects the synchronizer and Kea. Leases and runtime state are ephemeral. A socket readiness check is not evidence that synchronization or DHCP has succeeded. + +## Validation and activation + +`../isolated-example` is a render fixture with a reserved invalid feed origin and synthetic topology, not a deployable site. Run `bash hack/dhcp/validate-isolated.sh` and `bash hack/dhcp/test-transport.sh` from Fleet. The transport test creates and removes only its own Docker resources, exposes no host ports, and verifies status/apply/readback, not a DHCP lease. + +The real feed must share the admitted worker journal and boot evidence and enforce synced enrollment and network-boot delivery. See [boot networking](../../../../docs/operations/boot-network.md). Publishing a consumer does not package or supply that producer. + +Before activation, prove real operation/IPAM allocation, authenticated feed application for the exact instance, a matching disposable client lease, and withdrawal. The existing `hack/multiplane/run.sh --redfish --synced-dhcp` lab exercises the real IPAM contract, but its native Kea is not this consumer. Validate the composed deployment separately. Never substitute the hand-addressed Kea lab for dynamic allocation proof. Do not activate a real site's relay or boot existing devices as part of this preparation. diff --git a/config/site/dhcp/isolated/dhcp.yaml b/config/site/dhcp/isolated/dhcp.yaml new file mode 100644 index 00000000..c45f9f0b --- /dev/null +++ b/config/site/dhcp/isolated/dhcp.yaml @@ -0,0 +1,140 @@ +apiVersion: v1 +kind: Service +metadata: + name: fleet-dhcp-proof +spec: + clusterIP: None + selector: + app.kubernetes.io/name: fleet-dhcp-proof + ports: + - name: dhcp + port: 67 + protocol: UDP +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: fleet-dhcp-proof +spec: + serviceName: fleet-dhcp-proof + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: fleet-dhcp-proof + template: + metadata: + labels: + app.kubernetes.io/name: fleet-dhcp-proof + spec: + automountServiceAccountToken: false + enableServiceLinks: false + nodeSelector: + kubernetes.io/arch: amd64 + securityContext: + runAsNonRoot: true + runAsUser: 100 + runAsGroup: 101 + fsGroup: 101 + seccompProfile: + type: RuntimeDefault + sysctls: + - name: net.ipv4.ip_unprivileged_port_start + value: "67" + initContainers: + - name: control-directory + image: docker.cloudsmith.io/isc/docker/kea-dhcp4:3.0.3@sha256:ab73f52bca146a8df749490d464ca3b3f21cd00e114e6ed01cbb85b1bfc5ca32 + command: [/bin/sh, -ec, 'mkdir -p /run/kea/control && chmod 0750 /run/kea/control'] + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - name: run + mountPath: /run/kea + containers: + - name: kea + image: docker.cloudsmith.io/isc/docker/kea-dhcp4:3.0.3@sha256:ab73f52bca146a8df749490d464ca3b3f21cd00e114e6ed01cbb85b1bfc5ca32 + command: [/lib/ld-musl-x86_64.so.1, /usr/sbin/kea-dhcp4] + args: [-c, /etc/kea/kea-dhcp4.conf] + env: + - name: KEA_CONTROL_SOCKET_DIR + value: /run/kea/control + ports: + - name: dhcp + containerPort: 67 + protocol: UDP + readinessProbe: + exec: + command: [/bin/sh, -ec, 'test -S /run/kea/control/kea4-ctrl-socket'] + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - name: base + mountPath: /etc/kea + readOnly: true + - name: run + mountPath: /run/kea + - name: leases + mountPath: /var/lib/kea + - name: sync + image: ghcr.io/datum-cloud/fleet:replace-me + command: [/fleet-dhcp-sync] + args: + - -feed=$(FLEET_DHCP_FEED_URL) + - -token-file=/etc/fleet-dhcp/token + - -ca-file=/etc/fleet-dhcp-ca/ca.crt + - -kea-socket=/run/kea/control/kea4-ctrl-socket + - -base-config=/etc/kea/kea-dhcp4.conf + env: + - name: FLEET_DHCP_FEED_URL + valueFrom: + configMapKeyRef: + name: fleet-dhcp-proof-settings + key: feed-url + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + volumeMounts: + - name: base + mountPath: /etc/kea + readOnly: true + - name: run + mountPath: /run/kea + - name: token + mountPath: /etc/fleet-dhcp + readOnly: true + - name: ca + mountPath: /etc/fleet-dhcp-ca + readOnly: true + volumes: + - name: base + configMap: + name: fleet-dhcp-proof-base + - name: run + emptyDir: {medium: Memory, sizeLimit: 1Mi} + - name: leases + emptyDir: {medium: Memory, sizeLimit: 16Mi} + - name: token + secret: + secretName: fleet-dhcp-proof-sync + defaultMode: 0440 + - name: ca + secret: + secretName: fleet-dhcp-proof-feed-ca + defaultMode: 0440 diff --git a/config/site/dhcp/isolated/kustomization.yaml b/config/site/dhcp/isolated/kustomization.yaml new file mode 100644 index 00000000..1edda1dc --- /dev/null +++ b/config/site/dhcp/isolated/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - dhcp.yaml diff --git a/config/site/dhcp/producer/README.md b/config/site/dhcp/producer/README.md new file mode 100644 index 00000000..70992563 --- /dev/null +++ b/config/site/dhcp/producer/README.md @@ -0,0 +1,24 @@ +# Real site producer for an isolated DHCP proof + +This opt-in base runs the existing Redfish boot service and authenticated DHCP feed against the actual worker's shared journal and boot evidence. It does not create admissions, worker assignments, IPAM claims, or installer-success evidence. No default overlay includes it. + +Use the Go-only `fleet-site-runtime` image built by `build/site-runtime.Dockerfile`, pinned by digest through `FLEET_SITE_IMAGE`. It includes the existing `fleet-multiplane` executable, but no shell, QEMU, libvirt, host sockets, or installer artifacts. This image supports the Redfish Go roles; it is not the privileged local-VM runtime image. Packaging alone does not establish that a worker is enrolled or running. + +## Required environment inputs + +- An isolated namespace and a disposable emulator identity, never an existing physical server. +- `fleet-site-state`: the **same PVC used by the real worker**, with `journal`, `boot-evidence`, and `artifacts` subdirectories. Provision the test-owned directories for UID/GID 65532 and run the test worker with that identity. Do not change ownership of another site's retained state. The journal mounts read-only in the producer; only the real worker writes admissions. Boot evidence is shared writable state. +- Pinned, verified kernel/initrd/checksum artifacts in `artifacts`, matching the real operation image. The boot service verifies these; no dummy artifact or fabricated completion substitutes for them. +- `fleet-site-runtime` ConfigMap, key `boot-origin`: the approved reachable boot origin. Discover the isolated Service's allocated IP when preparing the runtime; do not choose a site address in this base. +- `fleet-site-redfish-enrollment` ConfigMap, key `enrollment`: the exact real worker enrollment, `dhcp: synced`, and `dhcpInstances: [fleet-dhcp-proof-0]` when using the isolated consumer. Targets must reference only the disposable emulator. A mismatched instance set is not accepted. +- `fleet-site-delivery` ConfigMap, key `methods`: the same real network-boot offer used by the worker. This base deliberately supplies no offer. +- `fleet-site-dhcp-sync` Secret, key `token`; `fleet-site-dhcp-feed-tls` Secret, keys `tls.crt`, `tls.key`, and `ca.crt`. The isolated consumer's Secret names differ: provision matching token and CA contents through environment-managed secret references, never Git. The server certificate must match the feed origin used by the consumer. +- NetworkPolicy admitting only the test consumer to TLS port 8081 and the test client/relay runtime to boot port 8080, with the necessary return paths. No public Service, host networking, or host ports are included. + +The source, producer, and consumer remain inactive until these inputs and real worker delivery are reviewed. A listening feed with an empty journal is not an integration proof. An actual worker may power off and reset its target before opening the test window, so accepting a real Device here is unsafe. + +## Outcome boundaries + +The proof must correlate a real operation with its bound IPAM claim, open worker admission, authenticated feed revision, Kea application, and DHCP packet exchange. Test unknown-client denial, acquisition, renewal, and a fresh attempt after withdrawal. Removing a reservation does not revoke an existing lease. Deadline-induced withdrawal does not establish completed installation, settled custody, or permission to delete the claim: uncertain worker effects retain custody and address ownership until recovery is resolved. + +An isolated cluster pass does not validate any real site's relay, WAN route, or physical client path. Nothing in this preparation changes those systems. diff --git a/config/site/dhcp/producer/boot.yaml b/config/site/dhcp/producer/boot.yaml new file mode 100644 index 00000000..93c93f1a --- /dev/null +++ b/config/site/dhcp/producer/boot.yaml @@ -0,0 +1,81 @@ +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-boot +spec: + selector: + app.kubernetes.io/name: fleet-site-boot + ports: + - name: http + port: 8080 + targetPort: http +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-boot +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: fleet-site-boot + template: + metadata: + labels: + app.kubernetes.io/name: fleet-site-boot + spec: + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + containers: + - name: boot + image: "${FLEET_SITE_IMAGE}" + command: [fleet-multiplane, boot-service] + env: + - name: FLEET_SITE_PROVIDER + value: redfish + - name: FLEET_BOOT_EVIDENCE + value: /var/lib/fleet-boot + - name: FLEET_BOOT_ORIGIN + valueFrom: + configMapKeyRef: + name: fleet-site-runtime + key: boot-origin + ports: + - name: http + containerPort: 8080 + readinessProbe: + tcpSocket: + port: http + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - name: state + mountPath: /var/lib/fleet-local + subPath: journal + readOnly: true + - name: state + mountPath: /var/lib/fleet-boot + subPath: boot-evidence + - name: state + mountPath: /opt/fleet-local/artifacts + subPath: artifacts + readOnly: true + volumes: + - name: state + persistentVolumeClaim: + claimName: fleet-site-state diff --git a/config/site/dhcp/producer/kustomization.yaml b/config/site/dhcp/producer/kustomization.yaml new file mode 100644 index 00000000..c63c3e5d --- /dev/null +++ b/config/site/dhcp/producer/kustomization.yaml @@ -0,0 +1,31 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: fleet-site +resources: + - boot.yaml +components: + - ../feed +patches: + - target: + kind: Deployment + name: fleet-site-boot + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-boot + spec: + template: + spec: + containers: + - name: dhcp-feed + securityContext: + runAsUser: 65532 + runAsNonRoot: true + volumes: + - name: dhcp-sync-token + secret: + defaultMode: 0440 + - name: dhcp-feed-tls + secret: + defaultMode: 0440 diff --git a/config/site/graph/kustomization.yaml b/config/site/graph/kustomization.yaml new file mode 100644 index 00000000..24ef86fe --- /dev/null +++ b/config/site/graph/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - rgd.yaml diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml new file mode 100644 index 00000000..f02a2f8a --- /dev/null +++ b/config/site/graph/rgd.yaml @@ -0,0 +1,241 @@ +# kro ResourceGraphDefinition for one selected local cell. For each delivered +# assignment handoff it creates one bounded worker Job with its own +# ServiceAccount, Role and RoleBinding, and nothing else. The shared site +# services, their boot Service and the journal volume are owned by the cell's +# Flux (config/site/services, config/site/base); this graph only references +# them, so deleting the instance or the graph cannot delete them. +# +# Every resource here is derived execution state: none of it allocates, admits, +# completes or releases anything. The coordinator trusts only the +# Karmada-reflected status the observer derives from the site store. +apiVersion: kro.run/v1alpha1 +kind: ResourceGraphDefinition +metadata: + name: fleet-handoff-dispatcher + annotations: + # Deleting the graph orphans the dispatcher; retiring it is a manual procedure. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + schema: + apiVersion: v1alpha1 + kind: HandoffDispatcher + group: site.fleet.datumapis.com + spec: + cell: string | required=true + # Workers are created only after dispatch is enabled. The acceptance uses + # this to prove delivery and retention before any effect can start. + dispatch: boolean | default=false + # The shared runtime's accelerator. Workers refuse a runtime that + # published another, and each installation's journal binds it. + accelerator: string | required=true + # The central media service's certificate, for virtual media workers. + mediaCA: string | default="" + status: + bootOrigin: ${"http://" + bootService.spec.clusterIP + ":8080"} + workerImage: ${hypervisor.spec.template.spec.containers[0].image} + runtimeAvailable: ${hypervisor.status.?availableReplicas.orValue(0)} + bootAvailable: ${boot.status.?availableReplicas.orValue(0)} + observerAvailable: ${observer.status.?availableReplicas.orValue(0)} + deliveredHandoffs: ${size(handoffs)} + resources: + # Flux-owned site infrastructure, referenced and never managed by kro. A + # reference that is missing or not ready blocks new worker objects and + # disables pruning; existing Jobs are left alone. + - id: state + externalRef: + apiVersion: v1 + kind: PersistentVolumeClaim + metadata: + name: fleet-site-state + - id: bootService + readyWhen: + - ${bootService.spec.?clusterIP.orValue("") != ""} + externalRef: + apiVersion: v1 + kind: Service + metadata: + name: fleet-site-boot + - id: hypervisor + readyWhen: + - ${hypervisor.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-runtime + - id: boot + readyWhen: + - ${boot.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-boot + - id: observer + readyWhen: + - ${observer.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-observer + # Delivered assignments for this cell, watched by kro. Fence report + # handoffs start no worker. The workers re-validate the cell, name and + # exact assignment; selection here is not authority. + - id: handoffs + externalRef: + apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + metadata: + namespace: fleet-coordination + selector: + matchExpressions: + - key: coordination.fleet.datumapis.com/cell + operator: In + values: ["${schema.spec.cell}"] + - key: coordination.fleet.datumapis.com/role + operator: In + values: [assignment] + # Per-operation identity and policy: each worker may read exactly its own + # handoff and its own payload, which exists only for an operation with + # bootstrap data, and nothing else. It has no status, list or Secret + # permission. + # The fleet-site-kro-worker-identity admission policy enforces this shape. + - id: workerAccounts + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: v1 + kind: ServiceAccount + metadata: + name: ${"w-" + handoff.metadata.name} + labels: {app.kubernetes.io/name: fleet-site-worker} + - id: workerRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-coordination + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + resourceNames: ["${handoff.metadata.name}"] + verbs: [get] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + resourceNames: ["${handoff.metadata.name + '-payload'}"] + verbs: [get] + - id: workerBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-coordination + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/accounts: ${string(size(workerAccounts))} + fleet.datumapis.com/roles: ${string(size(workerRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + # One bounded Job per delivered assignment. The Job controller retries + # and replaces Pods; every Pod resumes the same assignment from the site + # store's journal. Job completion is not readiness: only the observer + # publishes, and only the coordinator accepts the reflected result. The Job runs the + # runtime's image (the fleet-site-kro-worker-jobs admission policy also + # requires it) and reaches the runtime only through its libvirt socket. + - id: workers + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: batch/v1 + kind: Job + metadata: + name: ${"w-" + handoff.metadata.name} + labels: + app.kubernetes.io/name: fleet-site-worker + fleet.datumapis.com/handoff: ${handoff.metadata.name} + annotations: + # Dependency edges: workers start only after the Flux-owned runtime, + # boot service and observer are ready and this operation's RBAC exists. + fleet.datumapis.com/runtime: ${hypervisor.metadata.name} + fleet.datumapis.com/boot: ${boot.metadata.name} + fleet.datumapis.com/observer: ${observer.metadata.name} + fleet.datumapis.com/bindings: ${string(size(workerBindings))} + spec: + backoffLimit: 6 + activeDeadlineSeconds: 3600 + # A replacement Pod starts only after the previous Pod is terminal, + # so two workers for one operation never overlap; the Device's run + # lock is the second guard. + podReplacementPolicy: Failed + podFailurePolicy: + rules: + # Exit 65: a handoff not for this cell, or an assignment below + # the Device's stored fence. Retrying cannot change it. + - action: FailJob + onExitCodes: {containerName: worker, operator: In, values: [65]} + - action: Ignore + onPodConditions: [{type: DisruptionTarget}] + template: + metadata: + labels: + app.kubernetes.io/name: fleet-site-worker + fleet.datumapis.com/handoff: ${handoff.metadata.name} + spec: + restartPolicy: Never + serviceAccountName: ${"w-" + handoff.metadata.name} + terminationGracePeriodSeconds: 10 + containers: + - name: worker + image: ${hypervisor.spec.template.spec.containers[0].image} + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, site-worker, --handoff, "${handoff.metadata.name}", --cell, "${schema.spec.cell}"] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: "${schema.spec.accelerator}"} + # The site's enrollment of the Devices it serves. + - name: FLEET_SITE_ENROLLMENT + valueFrom: + configMapKeyRef: {name: fleet-site-enrollment, key: enrollment.json} + - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + - {name: HOME, value: /tmp} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 50m, memory: 32Mi} + limits: {memory: 192Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: tmp, mountPath: /tmp} + volumes: + - name: state + persistentVolumeClaim: {claimName: "${state.metadata.name}"} + - name: tmp + emptyDir: {} diff --git a/config/site/instance/dispatcher.yaml b/config/site/instance/dispatcher.yaml new file mode 100644 index 00000000..04847aee --- /dev/null +++ b/config/site/instance/dispatcher.yaml @@ -0,0 +1,23 @@ +# The one HandoffDispatcher instance for the selected cell. Variables come from +# the environment's fleet-environment ConfigMap through Flux postBuild +# substitution; dispatch is enabled only by a new source revision. The +# instance controls only per-operation worker objects; the shared site +# services it depends on are Flux-owned (config/site/services). +apiVersion: site.fleet.datumapis.com/v1alpha1 +kind: HandoffDispatcher +metadata: + name: dispatcher + namespace: fleet-site + annotations: + # Deleting the instance prunes worker Jobs and their RBAC, which is not + # cancellation. Shared services and the journal are unaffected. + kustomize.toolkit.fluxcd.io/prune: disabled + fleet.datumapis.com/source-marker: "${FLEET_SOURCE_MARKER}" +spec: + cell: "${FLEET_CELL}" + dispatch: ${FLEET_SITE_DISPATCH} + accelerator: "${FLEET_LOCAL_VM_ACCEL}" + # The central media service's certificate in PEM, base64 encoded, or + # empty where no media service runs. It is public; workers verify the + # service with it. + mediaCA: "${FLEET_MEDIA_CA}" diff --git a/config/site/instance/kustomization.yaml b/config/site/instance/kustomization.yaml new file mode 100644 index 00000000..11f41084 --- /dev/null +++ b/config/site/instance/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - dispatcher.yaml diff --git a/config/site/redfish/base/bmc.yaml b/config/site/redfish/base/bmc.yaml new file mode 100644 index 00000000..02097f36 --- /dev/null +++ b/config/site/redfish/base/bmc.yaml @@ -0,0 +1,7 @@ +# Lab BMC identity (config/site/redfish/services). It holds no API token. Its +# synthetic credential Secret, fleet-site-bmc-credentials, is enrolled by the +# harness and is never part of a source revision. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-bmc, namespace: fleet-site} +automountServiceAccountToken: false diff --git a/config/site/redfish/base/credentials.yaml b/config/site/redfish/base/credentials.yaml new file mode 100644 index 00000000..e3790f76 --- /dev/null +++ b/config/site/redfish/base/credentials.yaml @@ -0,0 +1,36 @@ +# The site's per-Device BMC credential Secrets, by the BMC discovery contract. +# The harness enrolls them; they are never part of a source revision. Each +# Secret is named from its Device (bmc- and 20 hex digits of the Device's +# SHA-256), and each worker may get only its own Device's, then requires the +# contract's annotations and its approved pin. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site-credentials + labels: + # Holds only credential Secrets; hack/validate-bmc-credential-namespace.sh + # fails a render that adds any other Secret here. + fleet.datumapis.com/bmc-credential-namespace: "true" + annotations: + # Deleting the namespace deletes the enrolled credentials. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# To create a per-operation Role that gets a credential Secret here, kro +# itself must hold get on it. kro cannot list or watch them. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-credentials, namespace: fleet-site-credentials} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [secrets] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-credentials, namespace: fleet-site-credentials} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-credentials} diff --git a/config/site/redfish/base/identity.yaml b/config/site/redfish/base/identity.yaml new file mode 100644 index 00000000..5311a43b --- /dev/null +++ b/config/site/redfish/base/identity.yaml @@ -0,0 +1,31 @@ +# The site workers' own identity for the central media service: one client +# certificate Secret per site worker identity, fleet-site-worker-media. The +# harness enrolls it; it is never part of a source revision. It holds no BMC +# credential, and no BMC credential Secret holds it. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site-worker-identity + annotations: + # Deleting the namespace deletes the enrolled identity. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# To create a per-operation Role that gets the identity Secret, kro itself +# must hold get on it. kro cannot list or watch Secrets here. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-identity, namespace: fleet-site-worker-identity} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [secrets] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-identity, namespace: fleet-site-worker-identity} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-identity} diff --git a/config/site/redfish/base/kustomization.yaml b/config/site/redfish/base/kustomization.yaml new file mode 100644 index 00000000..9a26f23b --- /dev/null +++ b/config/site/redfish/base/kustomization.yaml @@ -0,0 +1,63 @@ +# Redfish-mode site base: the shared base plus the lab BMC identity, with the +# kro worker admission policy narrowed for Redfish workers. Selected by the +# environment's fleet-site-base path (hack/multiplane/flux.py --provider redfish). +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../base + - bmc.yaml + - credentials.yaml + - identity.yaml +patches: + - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-jobs} + patch: |- + # Redfish workers reach the lab hardware only through Redfish: no + # libvirt socket mount and no libvirt URI, and the Redfish provider. + - op: add + path: /spec/validations/- + value: + expression: >- + variables.pod.containers.all(c, !has(c.volumeMounts) || c.volumeMounts.all(m, + !(has(m.subPath) && m.subPath.startsWith('libvirt')) && !m.mountPath.startsWith('/run/fleet-libvirt') && !m.mountPath.startsWith('/var/lib/fleet-lab/disks'))) + message: a Redfish worker Job must not mount the libvirt socket or lab disks + - op: add + path: /spec/validations/- + value: + expression: >- + variables.pod.containers.all(c, has(c.env) && + c.env.exists(e, e.name == 'FLEET_SITE_PROVIDER' && has(e.value) && e.value == 'redfish') && + !c.env.exists(e, e.name == 'FLEET_LIBVIRT_URI')) + message: a Redfish worker Job must select the Redfish provider and carry no libvirt URI + # kro may create, in fleet-site-credentials, only a per-operation Role + # that gets one named credential Secret, and in fleet-site-worker-identity + # only one that gets the site worker identity Secret, each bound to that + # operation's own ServiceAccount. + - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-identity} + patch: |- + - op: test + path: /spec/validations/2/message + value: a worker Role may grant only get on its own handoff and on its own payload + - op: replace + path: /spec/matchConstraints/namespaceSelector/matchExpressions/0/values + value: [fleet-site, fleet-coordination, fleet-site-credentials, fleet-site-worker-identity] + - op: replace + path: /spec/validations/2 + value: + expression: >- + variables.kind != 'roles' || (request.namespace == 'fleet-site-credentials' ? + (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && + r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && size(r.resourceNames) == 1 && + r.resourceNames.all(n, n.matches('^bmc-[a-f0-9]{20}$')))) : + request.namespace == 'fleet-site-worker-identity' ? + (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && + r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && r.resourceNames == ['fleet-site-worker-media'])) : + (has(object.rules) && size(object.rules) == 2 && + object.rules[0].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[0].resources == ['machineallocationhandoffs'] && object.rules[0].verbs == ['get'] && + has(object.rules[0].resourceNames) && object.rules[0].resourceNames == [variables.handoff] && + !has(object.rules[0].nonResourceURLs) && + object.rules[1].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[1].resources == ['machineallocationpayloads'] && object.rules[1].verbs == ['get'] && + has(object.rules[1].resourceNames) && object.rules[1].resourceNames == [variables.handoff + '-payload'] && + !has(object.rules[1].nonResourceURLs))) + message: a worker Role may grant only get on its own handoff and on its own payload, or get on one named BMC credential or the site worker identity diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml new file mode 100644 index 00000000..d39e1cdd --- /dev/null +++ b/config/site/redfish/graph/kustomization.yaml @@ -0,0 +1,174 @@ +# Redfish-mode dispatcher graph: the shared graph with the worker template +# switched to the Redfish workers. Workers mount the site store, the boot +# evidence and the lab console capture (all read-only except the store); they +# have no libvirt socket. Each worker may get exactly its Device's BMC +# credential Secret in fleet-site-credentials, and list or watch none; there +# is no shared credential. The worker also waits for the Flux-owned lab BMC +# through an externalRef. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../graph +patches: + - target: {kind: ResourceGraphDefinition, name: fleet-handoff-dispatcher} + patch: |- + - op: test + path: /spec/resources/9/id + value: workers + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/env + value: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} + - {name: FLEET_SITE_CREDENTIALS_NAMESPACE, value: fleet-site-credentials} + - {name: FLEET_SITE_PROJECT, value: provider} + # Explicit site enrollment: each Device maps to exactly one BMC + # endpoint, Redfish System (Id and UUID) and console capture. The + # boot NIC comes from Device inventory. The lab's dnsmasq hands out + # static leases, so DHCP is "static" and an operation carries no + # boot address. Only target A is + # published as capacity; target B is enrolled to prove isolation. + - name: FLEET_REDFISH_ENROLLMENT + value: '{"dhcp":"static","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' + - {name: HOME, value: /tmp} + # The central media service's certificate, from the dispatcher + # instance: public, per environment. + - {name: FLEET_MEDIA_CA, value: "${schema.spec.mediaCA}"} + # The site worker's own media service identity: one named Secret, + # which the worker gets through a per-operation Role of its own. + - {name: FLEET_SITE_WORKER_IDENTITY_NAMESPACE, value: fleet-site-worker-identity} + # Where the media service sees this site's installed servers post + # their first-boot reports from: the lab network, named by the + # runtime's report relay. Each install reports from its own IPAM + # address inside it. + - {name: FLEET_MEDIA_REPORT_FROM, value: 192.168.77.0/24} + # How installed servers reach the media service: the relay on the + # lab bridge. + - {name: FLEET_MEDIA_REPORT_ORIGIN, value: "https://192.168.77.1:28443"} + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts + value: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console, readOnly: true} + - {name: tmp, mountPath: /tmp} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1bmc + value: ${bmc.metadata.name} + # Each worker may get exactly its Device's credential Secret. The graph + # derives the Secret's name from the Device the assignment itself names, + # as site.CredentialSecretName does, so no handoff field can name + # another Device's Secret. Only a handoff whose Device is its + # assignment's gets a Role; any other is refused by its worker with no + # grant at all. It may not list or watch Secrets. + - op: add + path: /spec/resources/- + value: + id: workerCredentialRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs.filter(h, h.spec.device == json.unmarshal(h.spec.assignmentJSON).device)} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-credentials + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: ["${'bmc-' + '%x'.format([hash.sha256(json.unmarshal(handoff.spec.assignmentJSON).device)]).substring(0, 20)}"] + verbs: [get] + - op: add + path: /spec/resources/- + value: + id: workerCredentialBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs.filter(h, h.spec.device == json.unmarshal(h.spec.assignmentJSON).device)} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-credentials + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/roles: ${string(size(workerCredentialRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1credentials + value: ${string(size(workerCredentialBindings))} + # Each worker may get exactly the site worker identity Secret, and no + # other Secret, in the identity namespace. + - op: add + path: /spec/resources/- + value: + id: workerIdentityRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-worker-identity + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: [fleet-site-worker-media] + verbs: [get] + - op: add + path: /spec/resources/- + value: + id: workerIdentityBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-worker-identity + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/roles: ${string(size(workerIdentityRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1identity + value: ${string(size(workerIdentityBindings))} + - op: add + path: /spec/resources/- + value: + id: bmc + readyWhen: + - ${bmc.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-bmc diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml new file mode 100644 index 00000000..459a2955 --- /dev/null +++ b/config/site/redfish/services/bmc.yaml @@ -0,0 +1,80 @@ +# Lab BMC: the unmodified DMTF Redfish Interface Emulator 1.2.2 with the +# lab-only adapter (hack/redfish-lab), from a digest-pinned image. It is the +# only Redfish endpoint and, besides the runtime, the only holder of the +# libvirt socket. It owns the lab targets' definitions and provisioning +# network. It serves Redfish over TLS with a key the harness generates per +# run; Fleet workers reach it only over a connection pinned to that key, with +# each Device's own synthetic credential. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-bmc + namespace: fleet-site +spec: + type: ClusterIP + clusterIP: "${FLEET_BMC_SERVICE_IP}" + selector: {app.kubernetes.io/name: fleet-site-bmc} + ports: + - {name: redfish, port: 8443, targetPort: 8443, protocol: TCP} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-bmc + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-bmc} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-bmc} + spec: + serviceAccountName: fleet-site-bmc + automountServiceAccountToken: false + containers: + - name: bmc + image: "${FLEET_BMC_IMAGE}" + imagePullPolicy: IfNotPresent + args: [serve] + 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} + readinessProbe: + httpGet: {path: /redfish/v1/, port: 8443, scheme: HTTPS} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: state, mountPath: /var/lib/fleet-bmc, subPath: bmc-state} + - {name: credentials, mountPath: /etc/fleet-bmc-credentials, readOnly: true} + - {name: tls, mountPath: /etc/fleet-bmc-tls, readOnly: true} + # Virtual media the BMC fetched, verifying the media service + # against its CA. + - {name: state, mountPath: /var/lib/fleet-lab-media, subPath: lab-media} + - {name: media-ca, mountPath: /etc/fleet-bmc-media-ca, readOnly: true} + - {name: tmp, mountPath: /tmp} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} + - name: credentials + secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} + - name: tls + secret: {secretName: fleet-site-bmc-tls, defaultMode: 0400} + - name: media-ca + secret: {secretName: fleet-site-media-ca, defaultMode: 0400} + - name: tmp + emptyDir: {} diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml new file mode 100644 index 00000000..72f25892 --- /dev/null +++ b/config/site/redfish/services/kustomization.yaml @@ -0,0 +1,71 @@ +# Redfish-mode shared site services: the shared services plus the lab BMC +# (DMTF Redfish Interface Emulator with the lab-only libvirt adapter). Only +# the runtime and the BMC hold the libvirt socket; workers hold neither. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../services + - bmc.yaml +patches: + - target: {kind: Deployment, name: fleet-site-runtime} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-runtime, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: libvirt + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-lab/disks, subPath: lab-disks} + - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console} + # The lab BMC's fetched virtual media, attached to guests + # as CD-ROMs at the path the BMC wrote them. + - {name: state, mountPath: /var/lib/fleet-lab-media, subPath: lab-media, readOnly: true} + # Lab guests post their first-boot reports to this relay on the + # lab bridge, the one address they reach besides the boot + # Service. The path to the workstation's central media service + # rewrites their addresses, so the relay names each guest's own + # address in a PROXY header on the service's relay listener. + - name: report-relay + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "${FLEET_MEDIA_HOST}:28444"] + securityContext: + runAsUser: 65534 + runAsNonRoot: true + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + - target: {kind: Deployment, name: fleet-site-boot} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-boot, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: boot + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - target: {kind: Deployment, name: fleet-site-observer} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-observer, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: observer + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} diff --git a/config/site/redfish/synced/graph/kustomization.yaml b/config/site/redfish/synced/graph/kustomization.yaml new file mode 100644 index 00000000..9b9b7ab1 --- /dev/null +++ b/config/site/redfish/synced/graph/kustomization.yaml @@ -0,0 +1,19 @@ +# Redfish lab with synchronized DHCP (run.sh --redfish --synced-dhcp): the +# Redfish graph with the site enrollment's DHCP mode set to synced, so a +# network boot needs a boot address and waits for the site's Kea to apply and +# later withdraw its reservation. The lab's one Kea instance, lab-kea, is the +# expected DHCP instance set; the feed reads the same enrollment from the +# ConfigMap in ../services. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../graph +patches: + - target: {kind: ResourceGraphDefinition, name: fleet-handoff-dispatcher} + patch: |- + - op: test + path: /spec/resources/9/template/spec/template/spec/containers/0/env/6/name + value: FLEET_REDFISH_ENROLLMENT + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/env/6/value + value: '{"dhcp":"synced","dhcpInstances":["lab-kea"],"targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' diff --git a/config/site/redfish/synced/services/enrollment.yaml b/config/site/redfish/synced/services/enrollment.yaml new file mode 100644 index 00000000..2302ab58 --- /dev/null +++ b/config/site/redfish/synced/services/enrollment.yaml @@ -0,0 +1,9 @@ +# The feed's copy of the synced lab enrollment. It must equal the workers' +# enrollment in ../graph exactly; hack/multiplane/test-redfish.py checks it. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-redfish-enrollment + namespace: fleet-site +data: + enrollment: '{"dhcp":"synced","dhcpInstances":["lab-kea"],"targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' diff --git a/config/site/redfish/synced/services/kea.yaml b/config/site/redfish/synced/services/kea.yaml new file mode 100644 index 00000000..41498f0b --- /dev/null +++ b/config/site/redfish/synced/services/kea.yaml @@ -0,0 +1,24 @@ +# The lab's base Kea configuration, in the network owner's role: the +# provisioning subnet on the lab bridge, its gateway and the boot program. It +# has no pools, so Kea answers only the MACs the reservation feed names. Kea +# keeps its leases on the site volume as evidence of each answer. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-dhcp-base + namespace: fleet-site +data: + kea-dhcp4.conf: | + {"Dhcp4": { + "interfaces-config": {"interfaces": ["fleetpxe0"], "dhcp-socket-type": "raw"}, + "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, + "lease-database": {"type": "memfile", "persist": true, "name": "/var/lib/kea/dhcp4.leases", "lfc-interval": 0}, + "host-reservation-identifiers": ["hw-address"], + "valid-lifetime": 600, + "subnet4": [{ + "id": 1, + "subnet": "192.168.77.0/24", + "option-data": [{"name": "routers", "data": "192.168.77.1"}], + "boot-file-name": "http://${FLEET_BOOT_SERVICE_IP}:8080/pxe/boot.ipxe" + }] + }} diff --git a/config/site/redfish/synced/services/kustomization.yaml b/config/site/redfish/synced/services/kustomization.yaml new file mode 100644 index 00000000..bc8b4a2c --- /dev/null +++ b/config/site/redfish/synced/services/kustomization.yaml @@ -0,0 +1,91 @@ +# Redfish lab with synchronized DHCP (run.sh --redfish --synced-dhcp). The lab +# provisioning network keeps its bridge but has no DHCP of its own; Kea, fed by +# Fleet's reservation feed, is the only DHCP server on it. Kea and its +# synchronizer run in the runtime Pod because the bridge lives in that Pod's +# network namespace. The feed runs beside the boot service, as at a site. +# The harness creates the Secrets fleet-site-dhcp-sync and +# fleet-site-dhcp-feed-tls before this layer reconciles; they are never in Git. +# enrollment.yaml gives the feed the synced graph's enrollment, whose one +# expected DHCP instance is lab-kea. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../services + - kea.yaml + - enrollment.yaml +components: + - ../../../dhcp/feed +patches: + - target: {kind: Deployment, name: fleet-site-bmc} + patch: |- + - op: add + path: /spec/template/spec/containers/0/env/- + value: {name: FLEET_LAB_DHCP, value: synced} + - target: {kind: Deployment, name: fleet-site-runtime} + patch: |- + - op: add + path: /spec/template/spec/containers/- + value: + name: kea + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + # Kea starts once the lab BMC adapter has created the bridge and + # libvirt has given it its address. Kea refuses a control socket + # directory that is not 0750. + command: [sh, -c, 'mkdir -p /var/run/kea && chmod 0750 /var/run/kea && until [ -e /sys/class/net/fleetpxe0 ] && grep -qw 192.168.77.1 /proc/net/fib_trie; do sleep 2; done && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] + env: + - {name: KEA_PIDFILE_DIR, value: /var/run/kea} + - {name: KEA_LOCKFILE_DIR, value: none} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL], add: [NET_BIND_SERVICE, NET_RAW]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: dhcp-base, mountPath: /etc/kea-base, readOnly: true} + - {name: kea-control, mountPath: /var/run/kea} + - {name: state, mountPath: /var/lib/kea, subPath: kea-leases} + - op: add + path: /spec/template/spec/containers/- + value: + name: dhcp-sync + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + # One instance with a fixed name: a restarted Pod reports as the + # same instance, so its earlier reports never strand a withdrawal. + command: + - /usr/local/bin/fleet-dhcp-sync + - -feed=https://fleet-site-dhcp-feed.fleet-site.svc:8081 + - -token-file=/etc/fleet-dhcp/token + - -ca-file=/etc/fleet-dhcp-tls/ca.crt + - -instance=lab-kea + - -kea-socket=/var/run/kea/kea4-ctrl-socket + - -base-config=/etc/kea-base/kea-dhcp4.conf + - -interval=2s + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + volumeMounts: + - {name: dhcp-base, mountPath: /etc/kea-base, readOnly: true} + - {name: kea-control, mountPath: /var/run/kea} + - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: dhcp-feed-ca, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-base, configMap: {name: fleet-site-dhcp-base}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: kea-control, emptyDir: {}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-ca, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400, items: [{key: ca.crt, path: ca.crt}]}} diff --git a/config/site/services/kustomization.yaml b/config/site/services/kustomization.yaml new file mode 100644 index 00000000..ee2822bf --- /dev/null +++ b/config/site/services/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - services.yaml diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml new file mode 100644 index 00000000..268ee5b0 --- /dev/null +++ b/config/site/services/services.yaml @@ -0,0 +1,183 @@ +# Shared site services for one selected local cell, owned directly by the +# cell's Flux (Kustomization fleet-site-services, scoped identity). Values come +# from the environment's fleet-environment ConfigMap through postBuild +# substitution. These services are long-lived site infrastructure, not +# operation state: no graph or instance lifecycle creates or deletes them. +# Every revision of this layer is a reviewed change: a runtime rollout stops any +# running guest, which leaves its operation Unknown and capacity occupied. +# +# The boot Service has a fixed ClusterIP from the cluster's static Service range, +# so Flux recreating it after deletion yields the same boot origin that the +# runtime, the boot service and every worker were configured with. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-boot + namespace: fleet-site +spec: + type: ClusterIP + clusterIP: "${FLEET_BOOT_SERVICE_IP}" + selector: {app.kubernetes.io/name: fleet-site-boot} + ports: + - {name: http, port: 8080, targetPort: 8080, protocol: TCP} +--- +# The site enrollment's boot delivery declaration: the methods this site +# offers, in its order of preference. The observer publishes it on every +# report handoff; the coordinator and the Metal provider read it there and +# keep no copy. The environment gives the JSON list base64-encoded, because +# Flux's substitution would drop the quotes around JSON text; the mounted +# file holds the JSON. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-delivery + namespace: fleet-site +binaryData: + methods: ${FLEET_SITE_DELIVERY_METHODS} +--- +# Admission parameter for kro-created worker Jobs: they must run the same +# digest-pinned image as these services. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-worker-policy + namespace: fleet-site +data: + image: "${FLEET_SITE_IMAGE}" +--- +# Hypervisor and provisioning bridge. Only this Pod is privileged; deleting +# it stops any guest, which leaves the operation Unknown, never released. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-runtime + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-runtime} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-runtime} + spec: + serviceAccountName: fleet-site-runtime + automountServiceAccountToken: false + terminationGracePeriodSeconds: 30 + containers: + - name: libvirt + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [/usr/local/bin/fleet-site-runtime] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} + - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} + securityContext: + privileged: true + runAsUser: 0 + resources: + requests: {cpu: 500m, memory: 2560Mi} + limits: {memory: 3Gi} + readinessProbe: + exec: + command: [virsh, --connect, "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock", list, --name] + periodSeconds: 5 + timeoutSeconds: 10 + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: state, mountPath: /var/log/libvirt, subPath: libvirt-log} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} +--- +# Boot service: site store read-only; writes only its own delivery evidence. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-boot + namespace: fleet-site +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-boot} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-boot} + spec: + serviceAccountName: fleet-site-boot + automountServiceAccountToken: false + containers: + - name: boot + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, boot-service] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} + - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + # Lab-only fault hook: while this file exists the boot service + # withholds every boot, and stays Ready. The deadline scenario + # arms it with `fleet-multiplane boot-withhold`. + - {name: FLEET_LAB_BOOT_WITHHOLD, value: /var/lib/fleet-boot/lab-withhold} + ports: + - {name: http, containerPort: 8080} + readinessProbe: + tcpSocket: {port: 8080} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} +--- +# Observer: the only handoff status writer. It reports the site store's fences +# and results, and deletes a result once the coordinator answered it. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-observer + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-observer} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-observer} + spec: + serviceAccountName: fleet-site-observer + containers: + - name: observer + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --interval, 10s, --delivery-methods, /etc/fleet-site-delivery/methods] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: delivery, mountPath: /etc/fleet-site-delivery, readOnly: true} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} + - name: delivery + configMap: {name: fleet-site-delivery} diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 40b9f723..0b81dcf3 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -18,6 +18,51 @@ spec: cpu: {architecture: amd64, cores: 24} memory: {capacity: 128Gi} --- +# The synthetic Device behind the capacity. The simulator site serves it, and +# its fixture discovery writes the Device's status. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: synthetic-device-central-01 + namespace: fleet-provider + labels: {fleet.datumapis.com/hardware-model: synthetic} +spec: + claimRef: {name: synthetic-claim-central-01} + identity: {model: synthetic, serial: synthetic-serial-central-01, systemUUID: 00000000-0000-4000-8000-000000000021} + bmc: {endpoint: "https://[2001:db8::21]"} + interfaces: [{name: primary, macAddress: "02:00:00:00:00:21"}] +--- +# The provider's one image release. The allocate phase publishes it into the +# first consumer namespace, which stands in for a consumer project. +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineImage +metadata: {name: debian-12, namespace: fleet-provider} +spec: + definition: + family: debian + version: "12" + architecture: amd64 + firmwareModes: [UEFI] + bootstrapFormats: [NoCloud] + digest: "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + availability: Available +--- +# The synthetic site overwrites its one disk and reads it back, so the +# fixture policy claims only Clear. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: CleaningPolicy +metadata: + name: synthetic-tenant-reuse-v1 + namespace: fleet-provider +spec: + assurance: Clear + rules: + - name: nvme-ssd + match: {protocol: NVMe, mediaType: SSD} + methods: [Overwrite] + verify: {mode: Full} + timePerTiB: 1h +--- apiVersion: metal.datumapis.com/v1alpha1 kind: MachineCapacity metadata: @@ -37,7 +82,6 @@ spec: machineClassRef: {name: standard-metal} machineProfileRef: {name: general-purpose-24c-128g} locationRef: {name: us-central-1} - powerState: "Off" --- apiVersion: metal.datumapis.com/v1alpha1 kind: Machine @@ -46,7 +90,6 @@ spec: machineClassRef: {name: standard-metal} machineProfileRef: {name: general-purpose-24c-128g} locationRef: {name: us-central-1} - powerState: "Off" --- apiVersion: metal.datumapis.com/v1alpha1 kind: Installation @@ -54,4 +97,25 @@ metadata: {name: debian-12, namespace: fleet-project-a} spec: machineRef: {name: allocation} expectedPredecessor: {type: None} - imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} + imageRef: {name: debian-12} + bootstrapConfigRef: {name: debian-12-bootstrap} +--- +# The consumer's bootstrap data, in its own namespace. Synthetic values only. +apiVersion: v1 +kind: Secret +metadata: {name: debian-12-bootstrap, namespace: fleet-project-a} +type: metal.datumapis.com/bootstrap +stringData: + userData: | + #cloud-config + hostname: synthetic-example + sshAuthorizedKeys: | + ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAISyntheticExampleOnly synthetic@example.com +--- +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: {name: debian-12-reinstall, namespace: fleet-project-a} +spec: + machineRef: {name: allocation} + expectedPredecessor: {type: Installation, name: debian-12} + imageRef: {name: debian-12} diff --git a/config/standalone/kustomization.yaml b/config/standalone/kustomization.yaml index c6fdb9c6..f6d886c2 100644 --- a/config/standalone/kustomization.yaml +++ b/config/standalone/kustomization.yaml @@ -4,11 +4,15 @@ commonAnnotations: fleet.datumapis.com/standalone-only: "true" resources: - ../base/crd + - ../components/inventory/crds + - ../components/device-operations/crds - ../base/simulator - namespaces.yaml - runtime-secret.yaml - rbac.yaml - fixtures.yaml + - site.yaml + - machine-power.yaml - smoke-cronjobs.yaml images: - name: ghcr.io/datum-cloud/fleet-simulator diff --git a/config/standalone/machine-power.yaml b/config/standalone/machine-power.yaml new file mode 100644 index 00000000..873d5ad3 --- /dev/null +++ b/config/standalone/machine-power.yaml @@ -0,0 +1,29 @@ +# The power rule. Milo projects ignore admission policies, so Milo uses the +# Machine power webhook; a plain cluster enforces the same rule with this +# policy: only the power projector's identity changes a Machine's +# status.power. Here that is the smoke runner, which runs the manager's +# projector for its fixture Machines. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-machine-power} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [metal.datumapis.com] + apiVersions: ["*"] + operations: [UPDATE] + resources: [machines/status] + validations: + - expression: >- + request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-standalone-smoke' + || ((has(object.status) && has(object.status.power)) == (has(oldObject.status) && has(oldObject.status.power)) + && (!(has(object.status) && has(object.status.power)) || object.status.power == oldObject.status.power)) + message: Only the power projector writes status.power. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-machine-power} +spec: + policyName: fleet-machine-power + validationActions: [Deny] diff --git a/config/standalone/namespaces.yaml b/config/standalone/namespaces.yaml index f185e578..310c0240 100644 --- a/config/standalone/namespaces.yaml +++ b/config/standalone/namespaces.yaml @@ -7,13 +7,6 @@ metadata: --- apiVersion: v1 kind: Namespace -metadata: - name: fleet-system-private - annotations: - fleet.datumapis.com/shared-with-standalone: "true" ---- -apiVersion: v1 -kind: Namespace metadata: name: fleet-provider --- diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index f684b667..df78f2c3 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -30,14 +30,41 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-synthetic-provider-writer, namespace: fleet-provider} rules: + # The Metal provider selects capacity, records allocations and creates + # installations. It evaluates each capacity from its commissioning, + # discovery and custody evidence, and never writes capacity status; + # custody decides. - apiGroups: [metal.datumapis.com] resources: [machinecapacities] - resourceNames: [central1-baremetal-01] - verbs: [get] + verbs: [get, list] - apiGroups: [metal.datumapis.com] - resources: [machinecapacities/status] - resourceNames: [central1-baremetal-01] + resources: [machineallocations] + verbs: [get, list, create, delete] + - apiGroups: [metal.datumapis.com] + resources: [machineallocations/status] verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [cleaningpolicies] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations] + verbs: [get, list, create] + # As the provider's publisher, it reads the image it publishes and records + # each publication; as the provider, it resolves images through them. + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + resourceNames: [debian-12] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machineimagepublications] + verbs: [get, create, delete] + # It copies bootstrap data into the sealed store and never reads it back. + - apiGroups: [fleet.datumapis.com] + resources: [sealedpayloads] + verbs: [create] + - apiGroups: [fleet.datumapis.com] + resources: [devices, devicecustodies, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -50,6 +77,24 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-synthetic-consumer-writer, namespace: fleet-project-a} rules: + # The Installation's bootstrap Secret. The fixture stands in for reading it + # under the Installation creator's authority. + - apiGroups: [""] + resources: [secrets] + resourceNames: [debian-12-bootstrap] + verbs: [get] + # The publisher's copy of the provider image. + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + verbs: [create] + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + resourceNames: [debian-12] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machineimages/status] + resourceNames: [debian-12] + verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [machines] resourceNames: [allocation] @@ -60,11 +105,11 @@ rules: verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [installations] - resourceNames: [debian-12] + resourceNames: [debian-12, debian-12-reinstall] verbs: [get] - apiGroups: [metal.datumapis.com] resources: [installations/status] - resourceNames: [debian-12] + resourceNames: [debian-12, debian-12-reinstall] verbs: [get, update] --- apiVersion: rbac.authorization.k8s.io/v1 @@ -94,17 +139,268 @@ roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-synthetic subjects: - {kind: ServiceAccount, name: fleet-standalone-smoke, namespace: fleet-system} --- +# The custody coordinator writes custody and operation status, and reads the +# Devices, allocations and operations custody depends on. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-custody-coordinator, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-custody-coordinator-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-custody-coordinator} +type: kubernetes.io/service-account-token +--- apiVersion: rbac.authorization.k8s.io/v1 kind: Role -metadata: {name: fleet-private-record-writer, namespace: fleet-system-private} +metadata: {name: fleet-custody-coordinator, namespace: fleet-provider} rules: - - apiGroups: [""] - resources: [secrets] - verbs: [get, list, watch, create, update] + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get, list, watch] + - apiGroups: [fleet.datumapis.com] + resources: [devicecustodies] + verbs: [get, list, watch, create, update, delete] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings] + verbs: [get, list, watch, delete] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations/status, devicewipes/status, devicepoweroperations/status, devicerecoveries/status, devicecommissionings/status] + verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list, watch] + - apiGroups: [metal.datumapis.com] + resources: [machineallocations] + verbs: [get, list, watch] + # The only reader of the sealed store: it checks, delivers and deletes. + - apiGroups: [fleet.datumapis.com] + resources: [sealedpayloads] + verbs: [get, list, watch, delete] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding -metadata: {name: fleet-private-record-writer, namespace: fleet-system-private} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-private-record-writer} +metadata: {name: fleet-custody-coordinator, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-custody-coordinator} +subjects: + - {kind: ServiceAccount, name: fleet-custody-coordinator, namespace: fleet-system} +--- +# A BMC key must be unique among every Device that is not retired, so the +# coordinator reads Devices in every namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-custody-coordinator-devices} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-custody-coordinator-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} +subjects: + - {kind: ServiceAccount, name: fleet-custody-coordinator, namespace: fleet-system} +--- +# The release controller creates the wipes of a release. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-release-controller, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-release-controller-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-release-controller} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-release-controller, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicewipes] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-release-controller, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-release-controller} +subjects: + - {kind: ServiceAccount, name: fleet-release-controller, namespace: fleet-system} +--- +# The simulator site's fixture discovery writes only the status of the +# Device it serves. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-simulator-discovery, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + resourceNames: [synthetic-device-central-01] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devices/status] + resourceNames: [synthetic-device-central-01] + verbs: [get, update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-simulator-discovery, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-simulator-discovery} +subjects: + - {kind: ServiceAccount, name: fleet-simulator, namespace: fleet-system} +--- +# The capacity projector is the only writer of capacity status. It derives +# Prepared, Healthy, Available and the hardware from evidence. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-capacity-projector, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-capacity-projector-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-capacity-projector} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-capacity-projector, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [cleaningpolicies] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machinecapacities] + verbs: [get, list] + - apiGroups: [metal.datumapis.com] + resources: [machinecapacities/status] + verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [devices, devicecustodies, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-capacity-projector, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-capacity-projector} +subjects: + - {kind: ServiceAccount, name: fleet-capacity-projector, namespace: fleet-system} +--- +# A duplicate identity anywhere in the project withdraws an offer, so the +# projector reads Devices in every namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-capacity-projector-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} +subjects: + - {kind: ServiceAccount, name: fleet-capacity-projector, namespace: fleet-system} +--- +# The smoke is the Metal provider, and the allocator offers a capacity only +# after evaluating it from live evidence, which includes the duplicate +# identity scan over Devices in every namespace. A namespaced binding would +# fail every offer, so this stays cluster-wide and read-only. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-standalone-smoke-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} subjects: - {kind: ServiceAccount, name: fleet-standalone-smoke, namespace: fleet-system} +--- +# Writes commissioning plans. It cannot approve them. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-plan-author, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-plan-author-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-plan-author} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-plan-author, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-plan-author, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-plan-author} +subjects: + - {kind: ServiceAccount, name: fleet-plan-author, namespace: fleet-system} +--- +# Approves another person's commissioning plan. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-plan-approver, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-plan-approver-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-plan-approver} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-plan-approver, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplanapprovals] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-plan-approver, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-plan-approver} +subjects: + - {kind: ServiceAccount, name: fleet-plan-approver, namespace: fleet-system} +--- +# Commissions a Device under its current plan. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-commissioning-operator, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-commissioning-operator-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-commissioning-operator} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-commissioning-operator, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissionings] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-commissioning-operator, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-commissioning-operator} +subjects: + - {kind: ServiceAccount, name: fleet-commissioning-operator, namespace: fleet-system} diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml new file mode 100644 index 00000000..0e50c6a7 --- /dev/null +++ b/config/standalone/site.yaml @@ -0,0 +1,72 @@ +# The simulator site's enrollment: the one synthetic Device it serves, with +# the identity its fixture Device records and the key digest its fixture +# discovery reports. Synthetic data only. +apiVersion: v1 +kind: ConfigMap +metadata: {name: fleet-simulator-enrollment, namespace: fleet-system} +data: + enrollment.json: | + {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"], "hardware": {"bootMode": "UEFI", "cpu": {"architecture": "amd64", "model": "synthetic", "sockets": 2, "cores": 24}, "memory": "128Gi", "disks": [{"name": "disk-0", "capacity": "960Gi"}], "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:21"}]}, "firmware": [{"component": "BMC", "version": "synthetic-1.0"}]}} +--- +# The custody coordinator: the only writer of custody and of operation +# status. It delivers admitted operations to the simulator site and reports +# their results. +apiVersion: apps/v1 +kind: Deployment +metadata: {name: fleet-custody-coordinator, namespace: fleet-system} +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-custody-coordinator} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-custody-coordinator} + spec: + serviceAccountName: fleet-custody-coordinator + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: coordinator + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=coordinate, --site-token-file=/var/run/fleet/token, --projector-token-file=/var/run/fleet/projector/token] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {cpu: 250m, memory: 128Mi} + volumeMounts: + - {name: runtime-token, mountPath: /var/run/fleet, readOnly: true} + - {name: projector-token, mountPath: /var/run/fleet/projector, readOnly: true} + volumes: + - {name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}} + - {name: projector-token, secret: {secretName: fleet-capacity-projector-token, defaultMode: 0440, items: [{key: token, path: token}]}} +--- +# The creator rule. Milo projects ignore admission policies, so Milo uses the +# creator webhook; a plain cluster enforces the same rule with this policy: +# an operation's creator is the caller who created it and never changes. A +# caller is its username, plus its UID when its credential carries one. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-operation-creator} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ["*"] + operations: [CREATE, UPDATE] + # The same list as the packaged webhook; TestPackagedResourcesMatch + # keeps them in step. + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + validations: + - expression: "request.operation != 'CREATE' || (object.spec.creator.username == request.userInfo.username && (has(object.spec.creator.uid) ? object.spec.creator.uid : '') == (has(request.userInfo.uid) ? request.userInfo.uid : ''))" + message: spec.creator must be the authenticated caller's username, and UID when it has one + - expression: "request.operation != 'UPDATE' || object.spec.creator == oldObject.spec.creator" + message: spec.creator cannot change +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-operation-creator} +spec: + policyName: fleet-operation-creator + validationActions: [Deny] diff --git a/config/standalone/smoke-cronjobs.yaml b/config/standalone/smoke-cronjobs.yaml index 6f5251db..187eda42 100644 --- a/config/standalone/smoke-cronjobs.yaml +++ b/config/standalone/smoke-cronjobs.yaml @@ -1,3 +1,38 @@ +# The commissioning phase acts as three people: one writes the plan, another +# approves it, and an operator commissions the Device. +apiVersion: batch/v1 +kind: CronJob +metadata: {name: fleet-smoke-commission, namespace: fleet-system} +spec: + schedule: "0 0 1 1 *" + suspend: true + jobTemplate: + spec: + backoffLimit: 0 + template: + spec: + serviceAccountName: fleet-standalone-smoke + restartPolicy: Never + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: smoke + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=commission, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token, --plan-author-token-file=/var/run/fleet/author/token, --plan-approver-token-file=/var/run/fleet/approver/token, --operator-token-file=/var/run/fleet/operator/token] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + - {name: author-token, mountPath: /var/run/fleet/author, readOnly: true} + - {name: approver-token, mountPath: /var/run/fleet/approver, readOnly: true} + - {name: operator-token, mountPath: /var/run/fleet/operator, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: author-token, secret: {secretName: fleet-plan-author-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: approver-token, secret: {secretName: fleet-plan-approver-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: operator-token, secret: {secretName: fleet-commissioning-operator-token, defaultMode: 0440, items: [{key: token, path: token}]}} +--- apiVersion: batch/v1 kind: CronJob metadata: {name: fleet-smoke-allocate, namespace: fleet-system} @@ -16,10 +51,14 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=allocate, --runtime-token-file=/var/run/fleet/token] + args: [--phase=allocate, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- apiVersion: batch/v1 kind: CronJob @@ -39,10 +78,41 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=install, --runtime-token-file=/var/run/fleet/token] + args: [--phase=install, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} +--- +apiVersion: batch/v1 +kind: CronJob +metadata: {name: fleet-smoke-reinstall, namespace: fleet-system} +spec: + schedule: "0 0 1 1 *" + suspend: true + jobTemplate: + spec: + backoffLimit: 0 + template: + spec: + serviceAccountName: fleet-standalone-smoke + restartPolicy: Never + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: smoke + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=reinstall, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- apiVersion: batch/v1 kind: CronJob @@ -62,7 +132,11 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=release, --runtime-token-file=/var/run/fleet/token] + args: [--phase=release, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 510c6d48..6a0a339f 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -58,7 +58,8 @@ processes or service-catalog entries. | Group | Resources and responsibility | Status | | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | -| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | +| `provider.metal.datumapis.com` | Proposed `MachineOffering` owns installation/management capability policy; `MachineOfferingAssignment` controls acquisition access. MachineClass becomes only a one-hop published consumer view; MachineProfile remains immutable requirements in Metal. | Proposed target design, not implemented by the six alpha CRDs above. | +| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs. Only a minimal, operator-written subset of `DeviceClaim` and `Device` is implemented. Its alpha CRDs, ProtectedResources and inventory roles are [registered in Milo](../operations/physical-inventory.md) by `config/milo`, and the records live in the provider project; no controller reads them. No real provider executor is implemented here. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract @@ -73,6 +74,18 @@ and Installation identifies an OS incarnation. Managed NodeClaim identity stays above allocation. These identities and lifetimes remain separate. Standalone and managed consumers use the same allocator and installation contract. +Metal is the common public contract, independent of provider implementation. +Fleet is optional for fulfillment. Allocations retain accepted offering identity, +contract/profile and installation/management capabilities. Catalog or assignment +withdrawal blocks new allocations, not retained runtime rights. Current action, +image, secret and endpoint permissions and explicit safety/suspension controls +still apply; cleanup uses retained obligations rather than acquisition grants. +The [PXE design](../enhancements/pxe-installation/README.md) defines the proposed +immutable managedImage/delegatedPXE union, exclusive execution drivers, and +completion assurance. Managed consumers require qualified assurance, not merely +an Installation Ready condition. These changes specify the target design without +compatibility or migration machinery for earlier drafts. + The broader proposals describe managed clusters, node services, image catalogs, and OS policy. Their implementation and final group placement remain separate design work. Vendor and OS adapters may retain typed groups; this document does @@ -87,18 +100,23 @@ not create additional service registrations for them. | Protected allocation custody | Service-owned private storage | The allocator retains exact identities, authority, and cleanup obligations before effects. | | Fleet physical inventory | Intended operator/provider infrastructure control planes | Inventory and provider controllers own their respective facts and execution contracts; exact scopes and deployment remain proposed. | | Coordination intent | Intended Karmada federation hub | Management writes admitted handoff intent. | -| Coordination replicas and execution | Intended selected location/cell | Federation delivers intent; the cell executes location work and reports status directly to the hub. | +| Coordination replicas and execution | Intended selected location/cell | Federation delivers intent; the cell executes location work and writes cell-local results only. | +| Reflected execution results | Intended Karmada federation hub | Karmada reflects results from the selected cell; management validates them before public projection. | The coordination design requires its CRD on the federation hub and participating cells, not in customer Milo project control planes. Management owns handoff -intent and the selected cell owns execution status. The management process's -deployment cluster is not implicitly the authoritative handoff store. +intent; the selected cell owns local execution results, and Karmada alone reflects +them to the hub. Cells receive no hub or consumer-project API credentials. The +management process's deployment cluster is not implicitly the authoritative handoff store. Management retains admission and reservation authority before creating a handoff. Federation targets the selected location, and the cell asks networking -to prepare the admitted interfaces. Current location evidence is projected into -the customer's Metal resource. Release requires verified location cleanup before -provider cleanup and quota settlement complete. Missing, stale, or uncertain +to prepare the admitted interfaces. The status path is cell-local result -> +Karmada reflection -> management validation -> public projection. Validation checks +selected cell, allocation, operation identity/revision, executor fence, and evidence +freshness. Wrong-cell, stale, conflicting, or partition-delayed results cannot +advance readiness; reflected status itself is not authority. Release requires +verified location cleanup before provider cleanup and quota settlement complete. Missing, stale, or uncertain execution evidence remains unknown. Networking/IPAM and Galactic retain authority over attachments, addresses, @@ -134,8 +152,7 @@ under new identities or delete old authority records to bypass cleanup. Environment-owned overlays must update service references and publication rules before enabling the renamed service. No live environment is changed by this PR. -Repository, Go module, binaries, private record labels and Secret types, and -release finalizers retain Fleet names. They are implementation identities. +Repository, Go module, binaries, and release finalizers retain Fleet names. They are implementation identities. The [design context](design.md) and [source proposals](../proposals/fleet-management/README.md) provide the lifecycle rationale; this document supersedes their provisional API naming where broader resource placement remains unresolved. diff --git a/docs/architecture/commissioning-member.md b/docs/architecture/commissioning-member.md new file mode 100644 index 00000000..8f5a56ee --- /dev/null +++ b/docs/architecture/commissioning-member.md @@ -0,0 +1,44 @@ +# Opt-in physical commissioning + +Set `commissioning: true` on a dedicated physical manager route. This replaces +the per-Device manager settings; the strict decoder rejects those old keys. +The same configuration serves Devices placed at its inventory Site. Each needs +a fresh member fence for its provider project, cell, namespaced name and UID; +the request must name and label that same Device. A replacement cannot inherit +an old fence or admission snapshot. Synthetic enrollment cannot share this route. +Passing the route check does not bypass plan approval or custody admission. Enrollment alone +does not authorize an operation. The profile permits commissioning and a staff +Resolve-to-None decision; it does not permit wipe, general power control, or +repeating a burn-in whose outcome is unknown. + +The member requires retained state bound to the same Device, UID, project and +cell. Missing or conflicting state is not an empty journal. Commissioning also +requires fresh evidence from the authenticated system that its firmware supports +both network boot and a one-time override. A fence heartbeat cannot renew that +evidence. Recovery requires the stopped fence and does not perform hardware work. + +The receipt reader binds each response to a fresh challenge, the Device, system +UUID, assignment digest and boot receipt. The external producer must authenticate +the caller and make a fresh, complete observation after receiving the challenge. +Only that observation can establish that a receipt is absent. A delayed feed, +ambiguous result or unavailable source cannot establish absence or readiness. +The profile includes a reader, not a receipt producer or a hardware qualification. + +**Member-side gap.** The commissioning member still opens one explicitly bound +retained journal and reads a single enrolled HTTPS Redfish target. There is no +runtime producer here that supplies a site worker with the authorized join of +provider project, cell, Device namespace/name and UID to enrolled endpoint, +Redfish System ID/UUID and pinned credential identity, and the matching retained +journal. The credential reader derives the Secret name from the Device rather +than accepting a caller's selector. A producer must preserve that restriction, +withdraw stale bindings, and distinguish new authority from a missing journal. +A discovery observation, assignment or heartbeat alone cannot establish this +join. Do not synthesize it from a handoff or provision per-Device manifests. +The two-Device manager test exercises route eligibility, not member dispatch, +receipt production, hardware execution or readiness. + +Legacy physical snapshots without a Device UID retain their route-token check outside the commissioning profile. An explicit UID must match; a missing UID never qualifies for commissioning. + +When migrating from per-Device settings to site commissioning, stop new physical submissions and keep the old manager and route running until all admitted work drains and uncertain outcomes are reconciled. This includes UID-pinned commissioning work: a Device UID does not preserve its route token across a restart or route replacement. If an outcome remains unknown, defer the cutover; do not resubmit the operation to obtain a new token. Only after the drain, replace the old settings with the site configuration and restart the manager. + +Run the synthetic checks with `go test -race ./cmd/fleet-manager ./cmd/fleet-multiplane ./internal/coordination ./internal/custody ./internal/delivery ./internal/redfish ./internal/site/...`. diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 125d7209..a046ee4d 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -11,6 +11,7 @@ replacement for the source proposals or a claim that their APIs exist. | --- | --- | --- | | [infra #5782: Fleet infrastructure management service](https://github.com/datum-cloud/infra/pull/5782) | `51781e2456367be82281e1443ca56d0686311133` | Service architecture, inventory, shared allocation, capacity publication, provisioning, OS configuration, and cluster lifecycle. Open draft at review time. | | [infra #7705: Node services and consumer pool gates](https://github.com/datum-cloud/infra/pull/7705) | `a712d2d3aaddcdc4d81c09d7f4cdd139bef06631` | Node services, consumer-owned pool sizing and gates, procurement guardrails, and regional independence. Open; targets the #5782 proposal branch. | +| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `d4d17f9b4a34307d190efb0cea59dde2f26662ee` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | Read the [core proposal at its reviewed revision][proposal] and the [extension at its reviewed revision][extension]. The latter includes the core @@ -18,6 +19,12 @@ proposal plus the extension. The [combined proposal](../proposals/fleet-manageme examples, and diagrams now live in this repository. The [migration record](../proposals/fleet-management/MIGRATION.md) preserves provenance and outstanding review points; the original discussions remain in `infra`. +The implemented [stage-1 registration decision](../development/inventory-capacity-registration.md) +allows explicitly unconfigured cleaning only for inert Disabled/Retain records. +It uses stateless project-plane admission against live Devices, plus optional +Device deletion protection, not allocation custody or provider enrollment. Enabling and preparation remain forbidden until +their policy resolution and authorization contracts are implemented. + ## Problem and intended outcome Operators currently repeat infrastructure facts across inventory, provisioning, @@ -57,6 +64,25 @@ logical attachments, address allocation, and switch configuration. Galactic owns fabric and routing intent. DNS, certificates, and service addresses stay with their owning services. Fleet consumes these contracts and their evidence. +The implemented [Site identity and Facility membership subset](../development/site-facility-relationship.md) +is observational only. Proposed Site placement policy remains unimplemented; +membership does not change the actual Location/ServiceAvailability authority. + +The [PXE enhancement](../enhancements/pxe-installation/README.md) defines the target +Metal installation contract, with Fleet as an optional provider implementation. +It supersedes older image-only examples for current design work without rewriting +the pinned source history. Installation has exactly one managedImage/delegatedPXE +source, consumes its predecessor atomically, and retains explicit completion mode, +assurance and one execution driver. Provisioning Redfish sessions attach to that +admitted operation, never independent boot authority. Installation, runtime power, +and release share serialization/fencing; session closure or callbacks do not prove +executor shutdown. Managed consumers require QualifiedImage assurance. + +For Fleet execution, management writes hub intent, the selected cell writes only +local results, Karmada reflects them, management validates exact identity, fence +and freshness, and the projector publishes public status. Cells have no hub +credentials. Partitions or uncertain results never imply readiness or settlement. + ## Lifecycle and authority contracts 1. **Preserve distinct identities.** DeviceClaim describes an approved physical diff --git a/docs/development/README.md b/docs/development/README.md index bd10d00b..b89afc37 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -6,27 +6,89 @@ This development guide records the implemented subset and its limitations. See [build, test, and run](#build-test-and-run) for local commands and the [implementation roadmap](roadmap.md) for proposed milestones and required evidence. -Status: public API foundation, standalone synthetic provider simulator, -same-cluster allocation/installation lifecycle library, unwired NSO network -lifecycle adapter, unwired Milo tenancy/quota authority contracts, and an -event-only manager wiring scaffold with an injected Machine lifecycle -handler implemented. The public allocation API now uses customer `Machine`, -provider `MachineCapacity`, protected immutable `MachineAllocation`, and -`Installation.machineRef`; authored references contain names while exact -incarnation evidence remains private. A packaged standalone synthetic smoke -scenario exercises local-scope contention, install recovery, cleanup, and -capacity reuse. An explicit Milo-routed synthetic staging overlay exercises -event-driven Machine allocation, contention, cleanup, and reuse through the -public project API. Production caller-preserving -admission, replayable Milo event adapters, and real providers are not implemented. +Status: public API foundation, the persistent simulator site, an +allocation and release library on Device custody, an unwired NSO network +lifecycle adapter, a Milo quota claim, and an event-only manager wiring scaffold +with an injected Machine lifecycle handler. The public allocation API uses +customer `Machine`, provider `MachineCapacity`, protected immutable +`MachineAllocation`, and `Installation.machineRef`. Authored references contain +names. A MachineAllocation names its consumer, a Milo Project or a standalone +Namespace, with a typed `consumerRef`, and its name and labels record the exact +incarnations. A packaged +standalone synthetic smoke scenario exercises local-scope contention, install +recovery, release with a wipe, and capacity reuse on Device custody. An explicit +Milo-routed synthetic staging overlay exercises event-driven Machine allocation, +contention, release, and reuse through the public project API. Production +caller-preserving allocation admission, replayable Milo event adapters, and +production provider integration are not implemented. +Inert [inventory-backed capacity registration](inventory-capacity-registration.md) +now has a stateless caller-preserving admission service that checks live +Devices, one capacity per Device through a Device-derived name, a Device +lifecycle (`Active`, `Decommissioning`, terminal `Retired`), an opt-in Device +deletion protection component that admits deletes only for Retired Devices or +a deleting namespace, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly +unconfigured, and governs only capacity that carries the registration marker; +synthetic, hand-made and legacy capacity and all capacity status writes are not +routed to it. Deployment trust inputs and live Milo acceptance remain required. + +[Device custody and operations](device-custody.md) is **implemented** through +Increment C, the cutover. Every mode allocates, installs and releases on +`DeviceCustody`, with the custody coordinator as its only writer. The +Secret-backed coordinator, its private records and the old executors are deleted, +and an allocation's private facts live on its MachineAllocation. The standalone +smoke and both multi-plane runs verify it. The end-to-end failure scenarios +(Increment D) are implemented, and both multi-plane runs verify them. +The [power kind's control plane](device-custody.md#device-power-operations) +is implemented on the same custody, and nothing creates power operations yet. + +[OS images and bootstrap data](machine-images.md) has its image catalog +**implemented**: a provider-published, digest-pinned `MachineImage` that +admission resolves through a publication record and checks against the +server's architecture and firmware mode. The simulator uses the sealed bootstrap store. Federation and guest seed +delivery are exercised only by isolated tests, not enabled in deployments. + +The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes +the [local VM site](../operations/local-vm.md) with native Milo project APIs, the +custody coordinator, and actual Karmada delivery. On the selected cell the site +runs as [Flux-owned Deployments and kro-created per-assignment worker Jobs](../operations/site-execution.md). +Each local cluster's [Flux](../operations/gitops.md) installs Milo, Karmada, kro and the shared site services from +an OCI artifact staged from the checkout. Run it +with `task multiplane:acceptance`. Its exit codes, bounded phases and sanitized +`evidence/` directory are documented there; `task multiplane:test-harness` runs its +offline tests, which CI also runs. The run passes every phase on custody. The +Redfish site workers (`internal/site/redfishwork`) read each +Device's own credential and connect only to its approved TLS key. +[Redfish-mode acceptance](../operations/redfish-lab.md) +(`task multiplane:redfish-acceptance`) exercises them against the unmodified DMTF +Redfish Interface Emulator and a lab-only libvirt adapter, and that run passes +every phase on custody too. They are not qualified against a physical BMC or server, and the +production manager does not use them. + +Machine creator admission is **implemented** and not packaged in any root. +Two webhooks that the registration server serves record the authenticated +caller in a Machine's `spec.creator`, replacing any value the client sent, and +add the Machine protection finalizer in the same create. They refuse a caller +without a Milo project context and any later change to the creator, and a CRD +rule keeps the creator unchanged if the webhooks are bypassed. Tests against a +real API server verify it. No handler reads the creator yet, and no Machine +without one is refused. See the [production admission +proposal](https://github.com/datum-cloud/fleet/pull/187). + Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. ## API group naming +The additive [shared hardware catalog](hardware-catalog.md) implements +Manufacturer/DeviceType records and denial-aware staff readers under the +provenance-free inventory contract. New registrations can select catalog models; +external import and existing-device migration are deferred. Templates never modify +installed assets. + The allocation APIs now use `metal.datumapis.com/v1alpha1`. Milo registers the Bare Metal service as `metal`; entitlement and location-availability readers use -that reference. Physical Device references use `fleet.datumapis.com`. The +that reference. Physical Device references use `fleet.datumapis.com`; that group +implements only a minimal, operator-written `DeviceClaim` and `Device` today. The [API architecture](../architecture/README.md) documents the proposed coordination group, control-plane placement, and rollout constraints. Group renaming does not migrate stored allocations or establish live acceptance. @@ -39,22 +101,18 @@ The implemented alpha surface follows the current machine-allocation proposal: `machineClassRef`, `machineProfileRef`, and `locationRef` names; - provider projects publish `MachineCapacity` objects whose immutable `deviceRef` names the separately owned physical inventory record; -- Fleet owns `MachineAllocation` records in the provider project. Their generated - names are allocation identities, their specs are immutable, and `Released` is - terminal; and +- Fleet owns `MachineAllocation` records in the provider project. Each is named + `alloc-` and 16 hex characters of the SHA-256 of the consumer UID and + the Machine UID, its spec is immutable, and `Released` is terminal; and - `Installation` names its Machine and, for reinstalls, the preceding - Installation. Fleet retains exact local object incarnations privately instead - of exposing Kubernetes UIDs in authored specs or status. + Installation. A MachineAllocation records the exact Machine, project and Device + incarnations, so authored specs and status expose no Kubernetes UIDs. CRDs, Go types, scheme registration, IAM ProtectedResources and roles, manager watches and routes, quota labels, standalone fixtures, and smoke assertions use -those names. The lifecycle library's existing service-owned Secret is still the -implemented storage encoding for the protected allocation record; introducing -the `MachineAllocation` kind does not make that record customer-writable. The -simulator continues to carry a private binding token and monotonic executor epoch -to fence its legacy single-file backend. Those values are absent from the public -and proposed resource contracts and must be replaced by immutable allocation -name plus executor fencing token before a production backend is connected. +those names. The MachineAllocation is the stored record, and no customer role can +write it. Fences are Device custody's, not an epoch or token in a record; see +[Device custody](device-custody.md#cutover-increment-c). ## Requested hardware @@ -64,22 +122,10 @@ removed as a breaking `v1alpha1` change with no conversion or migration. Stored profiles with the old shape must be recreated before upgrading. The allocator matches capacity only when the observed cores and memory equal the request. -Private records retained before that change still decode, but only so they can -be released. `controller.RetainedRequirements` is the `acceptedRequirements` -encoding in asset records, custody proposals, and Milo authority records. It -reads exact requirements unchanged. It also reads the complete former -`{min, max, exact}` shape for `cpu.cores` and `memory.capacity` and re-encodes -that shape verbatim. Allocation retries, selection, `Install`, network refresh, -and Milo recovery return `controller.ErrLegacyRecord` for such a record. That -error wraps `ErrRecordInvalid`. Synthetic staging reports it on a live Machine -as `Bound=False` and `Ready=False` with reason `LegacyCustodyRecord`, and does -not requeue. Deletion releases the record through the same verified cleanup -path as any other record, even when the profile UIDs it names were deleted -and recreated. Tests cover the legacy fixture decode, refusal without record -changes or provider effects, release with replaced profiles and with -unverified cleanup, staging status and finalizer removal, and Milo digest -preservation. See the -[upgrade notes](../enhancements/machine-lifecycle/README.md#machineprofile). +A MachineAllocation records the accepted class and profile references, with the +exact CPU and memory it allocated against. Fleet keeps no decoder or release +path for older record shapes, because the Secret-backed records are deleted. See +the [MachineProfile notes](../enhancements/machine-lifecycle/README.md#machineprofile). `requestedhardware.Project` is the one projection that writes `status.requestedHardware` and `RequestResolved`, and @@ -131,14 +177,10 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no `SameProject` against its identity, run its verifier, and delegate to the existing `ProjectReconciler` and `RouteReconciler`. A request for a project that is not engaged is dropped with no effect. -- **Private records.** All projects share the host namespace - `fleet-system-private`. Custody, operation, and authority record names hash - `(authorityID, projectUID, claimUID)`; asset records are keyed by provider - asset and are deliberately global, which is what makes allocation exclusive - across consumers. The private-record watch routes a record by its recorded - consumer project to the runtime engaged for exactly that lifetime. The - unscoped `Coordinator.Release(claimUID)` requires exactly one match, so equal - claim UIDs in two projects fail closed instead of colliding. +- **Allocations.** A MachineAllocation lives in the provider project and is named + from the consumer project UID and the Machine UID, so equal Machine UIDs in two + consumer projects never share one. Exclusivity belongs to Device custody, which + is global to the Device and so spans consumers. - **Handlers.** `manager.DefaultHandlers` gives each project blocked lifecycle handlers and the requested-hardware projector. `--synthetic-staging` uses `staging.ConsumerHandlers`, which installs the staging handler only for @@ -147,7 +189,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no into that project. Provider MachineCapacity events wake only that project. - **Provider as consumer.** The synthetic provider project may also be an Active metal consumer. It engages with `DefaultHandlers`; its runtime maps - only its own Machines and private records whose consumer is that project, so + only its own Machines, so provider MachineCapacity events cannot reach the synthetic consumer's claims through it, and its blocked handlers never write MachineCapacity status. The synthetic consumer itself must still differ from the provider. @@ -164,7 +206,58 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no consumer set. It does not release custody, call a provider, delete records, or rewrite status, including for a project with active custody. Its deadlines and queued events are dropped, and re-engagement resumes from the - retained private records. + retained allocations. Unbinding drains direct and dependency-route + reconciliations that already acquired the runtime before removing it from the + registry; a retained runtime pointer cannot start work after that barrier. + A blocked in-flight handler therefore delays completed departure rather than + falsely reporting it. This fixes an inherited race where informer removal and + registry removal could finish while a handler could still write. It does not + roll back effects already admitted before departure. Regression tests block a + handler explicitly and assert the barrier, in addition to the active-custody + no-write/no-release test. + Re-engagement also drains the previous runtime before publishing either + registry entry, so a new lifecycle owner's independent request locks cannot + overlap old work. The wait never holds the registry mutex. After waiting, + engagement rechecks both the cluster pointer and project-lifetime ownership; + a concurrent successor must itself drain, and a conflicting route is refused. + Cancellation aborts the waiting engagement without publishing its runtime or + engaging its controllers. An already initiated drain continues to completion; + it is not rolled back into an active runtime. Cancellation retires the prior + entry after its drain completes, without removing a concurrent successor. + A handler that never returns still prevents safe replacement; cancellation is + not evidence that its effects have stopped. Deterministic direct/routed replacement, + cancellation, stale-pointer, registry-revalidation and concurrent engagement + tests cover these process-local barriers, not distributed site fencing. + A per-cluster-route engagement gate also serializes publication through the + entire downstream controller setup call and failure cleanup. Draining alone + was insufficient: a paused predecessor's setup could otherwise resume after + its successor and replace the successor's controller watches. The gate is + acquired after effect-free runtime construction; waiting is context-cancellable + and never holds the registry mutex. Cancelling a waiter does not stop the + current runtime. Gates are reference-counted and removed after their last + holder or waiter leaves; unrelated routes remain independent. Project-lifetime + conflicts across routes are still checked under the registry mutex. + Each published runtime owns a child engagement context, cancelled when its + drain begins. This cancels partial downstream engagements on failure and invalidates + the old context even when replacement uses the same cluster implementation. + Cancellation starts draining immediately, but cleanup cannot remove lifetime + ownership or admit a successor until downstream setup returns and admitted + handlers finish. A downstream call that ignores cancellation therefore blocks + that route rather than allowing an unfenced successor. A setup that returns + nil after cancellation is reported as cancelled, not successful engagement. + Cleanup under an already-held gate uses a separate internal path, avoiding + recursive locking; stale cleanup can only cancel and remove its own runtime. + Downstream setup may read the registries and engage another route. Synchronous + recursion back into a held route with the supplied context is rejected with + `ErrProjectEngagementReentrant`, including cycles through another route. + Nested setup also refuses to wait on any other occupied route in this registry, + preventing two concurrent callbacks from deadlocking by requesting each + other's routes. Ordinary independent callers still wait cancellably. + Callbacks must propagate that context rather than create a detached context + and synchronously wait on their own engagement. Deterministic regressions + cover blocked setup, direct/dependency handlers, failed/cancelled setup, + cancelled waiters, cross-route lifetime transfer, stale cleanup, unrelated + progress, reentrant setup and same-implementation context replacement. - **Observational discovery.** The provider declares no managed resources, teardowns, or suspend hooks, so it adds no ServiceConsumer finalizer. Its discovery clients refuse every write. The library would otherwise patch @@ -177,8 +270,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no always-running group. Unlike Compute, this is done for every `ProviderRunnable`, so the consumer provider is not started twice. - **Readiness.** `/readyz` requires discovery to have synced, every consuming - project to be engaged, every engaged project cache to have synced, and the - private-record cache to have synced. It fails with `ErrDiscoveryMisconfigured` + project to be engaged, and every engaged project cache to have synced. It fails with `ErrDiscoveryMisconfigured` while the metal Service is missing or its producer project differs from `consumerScopedProjection.providerProject`. The former integration gate, which failed unless synthetic staging was on, is removed. Removing it enables no @@ -197,21 +289,21 @@ API servers (`internal/multiclustertest`) whose writes produce watch events. They cover: - no provider: two projects with identical Machine names and UIDs each pin from - their own profile, with no private record, finalizer, lifecycle condition, + their own profile, with no allocation, finalizer, lifecycle condition, or Installation change; -- custody isolation: a custody record wakes only its own project, and scoped - reads and an unscoped release cannot cross projects; +- project isolation: an event wakes only its own project, and scoped reads cannot + cross projects; - departure with active custody, re-engagement, restart with a replaced profile, and identity failures (unknown project, two clusters for one lifetime, project recreated while engaged); - synthetic staging end to end: allocation only in the publication consumer, with another engaged project untouched. -Coordinator tests already cover custody, allocation, and installation scoping -across project APIs with equal claim UIDs. An envtest test runs the real -consumer provider against separate API servers that serve every watched kind, -behind a Milo-shaped project router, with a real host lease and private cache. -It needs envtest binaries and is skipped without them. +Allocation tests cover custody and installation scoping with equal Machine UIDs +in separate project lifetimes. An envtest test runs the real consumer provider +against separate API servers that serve every watched kind, behind a Milo-shaped +project router, with a real host lease. It needs envtest binaries and is skipped +without them. ## Location authority @@ -246,29 +338,31 @@ ServiceAvailability can project a Location into entitled projects. ## Standalone synthetic smoke environment `cmd/fleet-standalone-smoke` is a test-only, phase-oriented harness around the -implemented lifecycle coordinator. The packaged fixture uses two Kubernetes +allocation library on Device custody. The packaged fixture uses two Kubernetes namespaces as project stand-ins and one synthetic `us-central-1` machine with 24 -cores and 128Gi of memory. The allocate phase retains custody before adding the -Fleet finalizer, binds one claim, and leaves the competing claim pending. The -install phase admits one exact digest-pinned operation through the persistent -simulator and is idempotent across worker and simulator restart. The release -phase verifies cleanup before finalizer removal and advances the retained asset -epoch before the waiting claim binds. - -The harness is the designated writer for one retained synthetic Machine evidence -record and public fixture status. The evidence pins the Machine UID, configured -location, hardware, and observation time; it is not refreshed across phases. -Both contenders pass capacity preflight against the same retained -`Available=True` evidence before private custody selects the sole winner. The -lifecycle coordinator remains the writer of custody, asset, -and operation records. It does not patch status from shell, delete private -records, strip finalizers, or use public status as authority. The simulator runs -under an explicit non-root UID/GID with a writable `fsGroup` PVC and group-readable -runtime-only bearer Secret; its admin listener is off. Docker bases are digest -pinned, and the smoke script derives a source-specific local image tag and -verifies the running workloads use it with pulls disabled. That identity commits -to HEAD, its tree, the tracked diff, and untracked file contents; a CI regression -test proves distinct clean commits produce distinct IDs. +cores and 128Gi of memory. A coordinator Deployment runs the custody loop, and +the simulator is the only site. The allocate phase waits for the Device's custody +to be `Verified`, allocates for one claim, and leaves the competing claim pending. +The install phase admits one exact digest-pinned `DeviceInstallation` through the +simulator and is idempotent across worker and simulator restart. A bounded +reinstall phase uses a distinct Installation naming the initial Installation as +its predecessor, retains the same allocation, and recovers the same successor +operation across retries and restart. An unknown result keeps readiness unknown +and the Device held. The release phase wipes the Device with a `DeviceWipe`, under +a fence above both installations, before the waiting claim is allocated. + +The phases run as the Metal provider, with the custody coordinator's and the +release controller's tokens in their own clients, so each write carries its +component's identity. The harness is the designated writer for the synthetic +capacity conditions and the public fixture status, because the capacity projector +is not wired. It does not patch custody or operation status, strip finalizers, or +use public status as authority. The simulator runs under an explicit non-root +UID/GID with a writable `fsGroup` PVC and group-readable runtime-only bearer +Secret; its admin listener is off. Docker bases are digest pinned, and the smoke +script derives a source-specific local image tag and verifies the running +workloads use it with pulls disabled. That identity commits to HEAD, its tree, +the tracked diff, and untracked file contents; a CI regression test proves +distinct clean commits produce distinct IDs. This is not the proposal acceptance environment. Namespace stand-ins do not model Milo project APIs, caller identity, IAM, entitlement, quota, purge, or @@ -304,23 +398,12 @@ freshness deadline scheduler. Queue keys include the Milo authority ID, root Project UID, namespace, name, and object UID. Equal names or UIDs in separate project lifetimes cannot share work. -The manager uses two controller-runtime caches with explicitly non-nil zero -`SyncPeriod` values. Its primary cache is scoped by Milo's project control-plane -URL and contains public Fleet, NSO, quota, entitlement, and Namespace resources. -A separate management-cluster cache is confined to `fleet-system-private` and -contains service-owned Secrets. Public and private reverse indexes are -registered on their owning caches, and Secret event sources explicitly use the -host cache. Leader election also uses the management-cluster configuration. -Dependency mappers use exact field indexes; private indexes consume only typed metadata exposed after the lifecycle -or Milo record owner validates the complete record and deterministic Secret -identity. Unknown or nested JSON lookalike fields have no routing meaning. The -manager's private-record predicate treats the Secret type and complete label set -as part of that trusted envelope, so a valid record that is relabelled or has -its type substituted is immediately reconciled into quarantine rather than -being hidden as a data-no-op update. The -mappers do not perform unqualified application Lists. Informer initial Add -events route retained private records after restart, including when the consumer -object is gone. Public status-only updates, including status written by an +The manager uses a controller-runtime cache with an explicitly non-nil zero +`SyncPeriod`. It is scoped by Milo's project control-plane URL and contains +public Fleet, NSO, quota, entitlement, and Namespace resources. Reverse indexes +are registered on that cache. Leader election uses the management-cluster +configuration. Dependency mappers use exact field indexes and do not perform +unqualified application Lists. Public status-only updates, including status written by an external actor, do not feed the lifecycle coordinator; external facts that must drive lifecycle work require an owned dependency resource and route. Claim and Installation spec generations, labels, annotations, finalizers, and @@ -333,30 +416,17 @@ a cache read or List failure is retried as the same source event instead of bein mistaken for an empty target set. Every direct and routed handler also verifies the configured Project lifetime through an injected trusted verifier. -`MachineHandler` implements the lifecycle ordering at the manager boundary. It -exact-reads the queued Machine and namespace lifetimes, resolves only injected -authoritative inputs, retains authority and custody before adding Fleet's -finalizer, waits for the finalizer update event before allocation, and removes -the finalizer only after verified cleanup and external settlement. Dependency -waits return without a timed requeue. Trusted evidence expiry can request one -exact coordinator-owned deadline; it is not a polling interval. Deletion and -same-name recreation use exact Machine incarnation evidence retained privately. - -`MiloMachineLifecycle` is the concrete bridge to the existing Milo adapter and -allocator. `PrepareOrRecoverClaim` validates current resolved inputs against the -immutable private authority record, so the finalizer event and manager restart -reuse the retained caller receipt rather than reauthorizing a different caller. -Release recovers from the exact consumer Project and Machine lifetimes and does -not require the public Machine, class, or profile to remain present. - -This handler is an orchestration seam, not a live integration. Watched objects -do not contain the create-time caller identity, protected publication -provenance, or trusted Machine observation time and location required by the -lifecycle contract. The manager binary therefore does not instantiate the -handler; lifecycle handlers stay blocked. An environment must provide those -inputs plus the Milo admission fence and quota custodian before enabling effects; -controller credentials, annotations, public status, and synthetic timestamps -are not accepted substitutes. +The manager has no production lifecycle handler. Allocation, installation and +release are the `internal/allocation` library on Device custody, which the +synthetic staging handler, the standalone smoke and the multi-plane runner call. +The Machine handler and Milo lifecycle bridge of the Secret-backed design are +deleted. A production handler needs the inputs the manager cannot get from +watched objects: the create-time caller identity, protected publication +provenance, and a trusted Machine observation time and location. The manager +binary therefore instantiates no handler, and lifecycle handlers stay blocked. An +environment must provide those inputs plus the Milo admission fence and quota +custodian before enabling effects; controller credentials, annotations, public +status, and synthetic timestamps are not accepted substitutes. Every dependency route now retains the source object's UID and exact routing snapshot. Non-delete work checks that UID against the current named object; if a @@ -381,10 +451,10 @@ drains timers, waits for any in-flight emission, and prevents post-stop work. Informer initial Add processing reconstructs still-relevant deadlines after a fresh process starts. -The setup watches the implemented Fleet resources, private records, NSO Network, +The setup watches the implemented Fleet resources, NSO Network, NetworkInterfaceClaim and NetworkInterface resources, Milo quota claims, and the reviewed ServiceEntitlement shape. External IAM, project-lifecycle, catalog, and -executor sources must provide durable cursor/replay or materialize watched state; +site sources must provide durable cursor/replay or materialize watched state; a lossy channel is not sufficient. Business pending states wait for their next dependency event and do not return a timed requeue. @@ -400,8 +470,8 @@ remain integration-owner responsibilities. `cmd/fleet-manager` discovers every consuming project, resolves each project's exact lifetime from Milo, derives each routed Milo REST host from an -environment-owned project kubeconfig template, keeps host-private records and -leader election on the management cluster, and starts the event graph. Its +environment-owned project kubeconfig template, keeps leader election on the +management cluster, and starts the event graph. Its readiness reports discovery and cache health only. Its production handlers deliberately perform no lifecycle or provider effects until trusted create-time caller/finalizer admission and live, replayable Milo adapters are supplied. A @@ -410,37 +480,39 @@ it after object creation, so this increment does not fabricate that authority with annotations or controller credentials. The opt-in `--synthetic-staging` mode is a temporary acceptance boundary. It -accepts only powered-off, networkless claims in `us-central-1`, synthesizes -clearly labelled admission and provider evidence, and invokes the same durable -coordinator used by the standalone and future production adapters. It is -event-driven: claim, class, profile, Machine, namespace, private-record, and -deletion events route exact work; it adds no periodic re-sync. One synthetic -Machine is exclusively bound, competing claims remain pending, cleanup must -complete before finalizer removal, and release wakes waiting claims for reuse. -Public conditions say `SyntheticStagingAdmission`, so this result cannot be -mistaken for Milo caller-preserving authorization. +accepts only networkless claims in `us-central-1` whose power is unset or `Off`, +synthesizes clearly labelled admission and provider evidence, and uses the same +allocation library on Device custody as the standalone smoke. The manager also +runs the custody coordinator loop and fixture discovery under its leader lease. +It is event-driven: claim, class, profile, Machine, namespace, and deletion +events route exact work; it adds no periodic re-sync. One synthetic Machine is +exclusively bound, competing claims remain pending, release must complete before +finalizer removal, and release wakes waiting claims for reuse. Public conditions +say `SyntheticStagingAdmission`, so this result cannot be mistaken for Milo +caller-preserving authorization. `config/overlays/synthetic-staging` is the only packaged activation path. It -packages the simulator as a separate single-replica Deployment and ClusterIP -Service using the same immutable Fleet release image. The manager reaches it -through Service DNS with an environment-owned shared runtime Secret; the provider +packages the simulator site as a separate single-replica Deployment and +ClusterIP Service using the same immutable Fleet release image. The manager +reaches it through Service DNS with an environment-owned site token; the provider has no Kubernetes API credential or RBAC grants. A NetworkPolicy restricts access to same-namespace manager pods, and the admin listener stays disabled. -The simulator's operation state resides on a retained PVC and survives manager -and provider pod replacement. A `Recreate` rollout avoids overlapping file-store -writers. The durable private coordinator continues to retain exact operation -inputs and recover idempotently. Store persistence and credential reload are -covered by local tests; independent Deployment restart recovery still requires -live staging verification after rollout. This remains synthetic API validation, -not production provider qualification. See the -[deployment and migration contract](../../config/README.md#moving-from-the-colocated-simulator). +The site store resides on a retained PVC and survives manager and provider pod +replacement. A `Recreate` rollout avoids overlapping store writers. Custody and +the site store retain exact operation inputs, and recovery is idempotent. Site +store persistence is covered by local tests. This remains synthetic API +validation, not production provider qualification. The overlay needs imported +records and two new credentials; see the [deployment and migration +contract](../../config/README.md#moving-from-the-secret-backed-staging). +Operators also apply the [fixture cleaning +policy](../../config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml) +to the provider project. No capacity is allocated until it exists. `config/overlays/management-plane` now packages the manager Deployment so its identity, RBAC, admission, image, and readiness boundary can be reviewed and -rolled out fail-closed. Its service account receives Secret permissions only -through a namespaced Role for `fleet-system-private`; cache scoping is not an -authorization boundary, and it has no host ClusterRole. The environment must +rolled out fail-closed. Its service account receives only leader-election access +in `fleet-system` and has no host ClusterRole. The environment must provide the authority ID and Project name in `fleet-manager-config`, mount the generated `milo-configuration-kubeconfig` Secret, and pin the image. The manager resolves the immutable Project UID from Milo at startup and fails @@ -460,68 +532,47 @@ source-specific publication example. Those remain environment/provider state. The two production roots target different API servers and must not be combined into one Flux reconciliation. -## Standalone lifecycle library - -`internal/controller` implements the recovery-critical core without installing a -manager or watches. Callers first create retained claim custody before adding a -claim finalizer, retaining the namespace lifetime plus a trusted caller-supplied -principal UID and admission decision ID; the library never manufactures an -authorization result. Allocation requires that exact finalizer and authority and -rejects deleting claims. -Allocation then selects only current, healthy, available machines -with fresh externally supplied evidence. It atomically reserves each physical -asset through deterministic private Secrets and retains `Preparing`, `Committed`, -`Releasing`, and `Released` authority. Released records are not deleted; a later -binding advances the provider epoch and receives new binding and fence tokens. -The claim-level `Selecting` record retains the complete proposed asset authority -before creation, allowing deletion to materialize and tombstone the proposal so -a delayed allocator cannot resurrect it. - -An independent custody record distinguishes a claim proven never bound from a -claim whose sole asset authority is unexpectedly missing. Release removes a -finalizer only after an unbound proof or retained cleanup completion. Corrupt, -duplicate, or cross-lifetime deterministic records fail closed. - -Installation admission retains exact inputs and a private predecessor before the -provider effect, including the initiating principal and installation decision plus -the image catalog authority, revision, and image decision. The operation also -retains the installation and claim namespace, name, and UID, so an informer -initial Add can route unfinished work after restart even when the public -Installation has been deleted. This is installation-record schema v2. A v1 -operation is upgraded atomically only when the exact public Installation and -claim request is still available to supply and verify the names omitted by v1; -otherwise it is quarantined from event routing and effects rather than guessed -or treated as ready. Image references must -resolve to canonical lowercase SHA-256 digests. Stable operation and result -identities include the authority/project claim scope, so equal claim UIDs from -independent project APIs cannot share an operation record. Installation custody -and asset lookup use that same scope; standalone requests derive an explicit -local scope from the Namespace UID. Response-loss recovery is therefore an exact -operation lookup rather than a second effect. Public claim status is not used as -predecessor authority. Before image resolution, operation creation, or a provider -effect, installation also requires Bound custody whose asset, claim identity, -scope, consumer/provider Projects, authority record, and external hold exactly -match the selected retained asset. - -`internal/executor` is the typed bearer-authenticated client for the simulator's -runtime surface. Transport failures, unavailable responses, malformed terminal -results, and lost responses are classified as unknown outcomes for lookup-based -recovery. Bearer HTTP remains a test-only transport, not a production identity -contract. - -The private namespace is a security boundary: the Fleet service account must be -its exclusive writer, and the `fleet-claim-`, `fleet-asset-`, and -`fleet-install-` name prefixes are reserved. Provider health, availability, and -observation timestamps supplied to the library must come from a trusted, -authenticated provider-status path; this increment does not establish that path. +## Allocation on Device custody + +`internal/allocation` is the recovery-critical core. It allocates, installs and +releases through Device custody and creates no Secret record. The allocator takes +an admitted request: the Machine's exact project and Machine incarnation, the +class and profile, and the admission decision. It writes in a fixed order: the +quota claim, then the MachineAllocation (create only), then the custody claim (a +conditional update). A retry finds the same allocation by its name. An allocation +whose Device another holder took, and which never held it, is deleted, and the +allocator selects again. An `Active` allocation that lost custody is not repaired +(`ErrCustodyLost`). + +Installation admission creates a `DeviceInstallation` named from the allocation +and the Installation UID. The Installation's predecessor must be the Machine's +current installation, and bootstrap data goes through the sealed store. Response-loss +recovery is an exact lookup by name, not a second effect. Release moves the +holder to `Release`, closes the gates, wipes the Device, deletes the quota claim, +and only then returns the Device to `None`. The allocation, installations and +wipes remain as the fence history. See [Cutover](device-custody.md#cutover-increment-c) +for the gates, wipe steps and recovery. + +The component identities are separate: the Metal provider creates allocations +and installations, the release controller creates wipes, and the custody +coordinator is the only writer of custody and operation status. Provider health, +availability and observation timestamps supplied to the library must come from a +trusted, authenticated provider-status path; this increment does not establish +that path. ## Network lifecycle adapter +Status: **implemented and inert**. The allocation library on Device custody does +not call this adapter, because no mode provisions Network or Address. Those +release gates close at once. The private asset and operation records this section +names were deleted in the cutover. The retention they describe is the contract a +future wiring must keep. Where it keeps it is **proposed**. + `internal/network` defines an NSO-independent lifecycle contract. Allocation preflights every requested interface before hardware selection, requiring exact namespace and location lifetime authority plus a caller-preserving network-use decision. The accepted Network UIDs, normalized request, decisions, and request -digest are retained in the private asset record before any NSO effect. +digest must be retained by the caller before any NSO effect. Fleet validates NSO's attachment shape before preflight and physical selection: families are unique `IPv4`/`IPv6` values with at most two entries, and address classes are unique with at most four entries. The Fleet CRD carries the same @@ -542,10 +593,10 @@ against guard closure; a separate pre-create check is insufficient. Immediately retained Network UID and generation are currently Ready and every retained address-class name still has the exact authorized lifetime UID. -The coordinator retains exact claim and interface UIDs plus current-generation -`Allocated`, `Prepared`, and `Programmed` observations. Installation admission -requires fresh `Allocated` and `Prepared` evidence and copies the exact network -revision and inputs into the private operation record. Public projection is a +The contract has the caller retain exact claim and interface UIDs plus +current-generation `Allocated`, `Prepared`, and `Programmed` observations. +Installation admission requires fresh `Allocated` and `Prepared` evidence and +copies the exact network revision and inputs into the operation's inputs. Public projection is a pure helper that publishes only Network names, MTU, addresses, and normalized conditions only while the observation is within the configured evidence age; stale evidence projects `NetworkReady=Unknown`. Internal UIDs, NSO claim names, @@ -555,8 +606,8 @@ Create intent for every interface is durably returned before any NSO create. Release first durably admits an exact per-interface delete vector without effects, then retries execute and verify individual deletes. Provider cleanup and finalizer release remain blocked while network deletion, retained-interface detachment, or outcome evidence is pending -or unknown. Object absence counts only after the private record proves deletion -was admitted for the exact retained UID. `Retain` additionally requires the +or unknown. Object absence counts only after the caller's retained record proves +deletion was admitted for the exact retained UID. `Retain` additionally requires the same retained interface UID to report `Available` with no claim reference. For `Retain`, an absent claim completes only when the closed guard proves the claim was never created, or when an exact interface name and UID retained before @@ -569,125 +620,104 @@ Production wiring must supply a location-scoped client, caller-preserving authorizer, and durable object guard; otherwise networked allocations fail closed before selection. -## Milo authority contracts - -`internal/milo` composes the lifecycle library with internal Milo project, -source-use, entitlement, quota, admission-fence, and release-custody contracts. -It is a library and test-fake integration only; it does not register a manager, -watches, webhooks, deployment, or acceptance environment. - -Project identity retains the configured Milo authority ID, route name, and root -Project UID. The authority ID and root UID identify the lifetime; the route name -only selects a control plane. Preparation verifies both consumer and provider -lifetimes, then retains consumer Namespace UID, claim UID, local and canonical -class/profile UIDs, canonical class revision and content digest, immutable -profile requirements, publisher revision, initiating principal UID, and the -caller-preserving source decision in a private service-controlled Secret. The -lifecycle custody record links that protected authority record before later -work. Custody names and claim lookups include the authority ID, consumer Project -UID, and claim UID; standalone use has an explicit local scope keyed by the -Namespace UID. Equal claim UIDs from independent project API servers therefore -cannot occupy the same private record. Provider asset identity includes the Milo -authority and provider Project UID, preventing reuse across project lifetimes. - -The adapter checks the exact retained claim, class, profile, location authority -(name, UID, and revision), revision, and content before capacity, quota, -fencing, or provider work. The source-use decision and admission commit bind -that complete class/profile/location combination. Current Machine inventory -does not carry separately authoritative placement evidence, so proving that a -selected Machine is physically in the retained location remains an upstream API -and provider-authority gap. The adapter accepts the -reviewed Milo v0.32.5 ServiceEntitlement evidence shape: Active phase plus a -current Ready condition on the exact entitlement UID. That API does not publish -the proposal's separate suspension evidence; ordering suspension against binding -remains an upstream admission-fence requirement rather than an invented local -condition. - -Deleting claims and claims missing Fleet's protection finalizer are rejected -before quota acquire, admission fencing, or any provider effect. - -Quota preparation durably records a deterministic intent before creating or -recovering one exact Milo ResourceClaim for -`metal.datumapis.com/machines`. Grant evidence requires the exact object UID, -request, consumer and resource references, and current status -`observedGeneration`. ResourceClaim deletion or `NotFound` is never -quota-settlement proof. Allocation requires an injected protected custodian -before requesting quota. Acquire, intent recovery/no-hold closure, and settlement -all pass through that custodian under the exact Project, authority record, and -intent lifetime. A no-hold receipt closes that intent against a later acquire; -the adapter never calls the ResourceClaim manager directly. A full -admission-commit digest binds the retained -source decision, exact entitlement lifetime, and exact quota hold UID, -generation, and evidence to the fence receipt. Sequential checks are not -presented as ordering concurrent invalidation against binding. - -Cleanup advances assets only to `CleanupVerified` while an external hold exists. -Fleet persists an exact custodian settlement receipt before releasing lifecycle -custody, and only then advances the asset to `Released` and permits finalizer -removal. Any retained hold is first installed into core custody even when a -crash occurred before that write. Quota recovery and settlement use the exact -retained consumer Project lifetime through the service-owned custodian rather -than resolving a possibly deleted or route-name-reused consumer API endpoint. -Retried allocation and release resume persisted fence, binding, intent, and -settlement states before considering new work. Persisted fence receipts are -revalidated against the complete retained commit on every decode. Unknown -create, release, or project outcomes retain custody and remain unknown. - -The tests verify source and lifetime substitution rejection before effects, -concurrent authority-record creation, both admission-fence orderings, stale or -corrupt persisted fence receipt rejection, lost quota-create recovery, a paused -acquire racing no-hold closure, hold-write crash recovery, pending-hold deletion, -binding recovery after a lost response, retry after a crash between core hold -clear and authority reset, cross-project claim-UID collisions, -cleanup-before-quota ordering, settlement-receipt replay, deleted or -route-name-reused consumer-project cleanup, malformed authority state rejection, -and delayed allocation or settlement racing completed release. These are -contract tests with fakes, not evidence of -a working Milo production integration. - -## Persistent provider simulator - -`cmd/fleet-simulator` is a test-only process for exercising provider-operation -recovery before a real hardware adapter exists. It supports synchronous -`install`, `power`, and `cleanup` operations plus operation lookup. It never -contacts, enrolls, or authorizes real hardware. - -The simulator writes one versioned JSON state file. Each mutation writes and -syncs a temporary file, atomically renames it over the retained state, and syncs -the parent directory. Operation IDs are idempotency keys: replaying the exact -request returns its retained result, while different retained input conflicts. -Every effect carries an asset ID, binding ID, monotonically increasing epoch, -and fencing token. Cleanup closes that epoch so delayed work from the released -binding cannot reactivate the asset; a later binding must advance the epoch. - -The `lost-response` fault persists the completed effect and consumes the fault in -the same state write before returning an unavailable response. A caller recovers -the retained result by operation ID instead of submitting new authority. A -failure after the state-file rename remains queryable in memory and is reported -as an unknown response outcome rather than rolling the process back behind the -visible file. - -The runtime and fault-injection surfaces use separate bearer credentials. The -admin listener is disabled by default, and the runtime listener defaults to -loopback. Runtime responses omit binding IDs, fencing tokens, and exact inputs. -Request bodies, identifiers, headers, and server timeouts are bounded. These -controls limit the local test surface; bearer authentication over plain HTTP is -not a production executor identity protocol. - -The persisted schema and HTTP endpoints are internal alpha interfaces. No -compatibility promise exists yet. The process fails closed if retained state is -corrupt or uses an unsupported schema version. +## Milo quota claim + +`internal/milo` holds Fleet's Milo service identity (`metal.datumapis.com`) and one +quota claim. The authority contracts of the Secret-backed design, which retained +project, source-use, entitlement and admission-fence evidence in private records, +are deleted. Production source-use, entitlement and admission-fence integration +is not implemented. + +The quota claim is **implemented and verified** by unit tests, and **implemented +and inert** end to end: no mode in this repository has Milo quota. The allocator +creates a Milo `ResourceClaim` named `fleet-machine-` and 16 hex characters of the +SHA-256 of the consumer project UID and the Machine UID, in the Machine's +namespace, before it creates the MachineAllocation. A retried create finds the +claim by name. Only a granted claim reserves quota, so a pending claim returns +`ErrQuotaPending` and the allocator retries. A claim that is not the claim Fleet +would create for that Machine is `ErrQuotaInvalid`. + +Fleet holds each claim with its quota custody finalizer from the moment it +creates it, so a claim deleted by anyone else, or by namespace purge, keeps its +quota until release. Milo still counts a deleting claim while a finalizer +holds it. Release deletes the claim, removes the finalizer with a conditional +update, and reports the quota free only once the claim is gone +(`TestReleaseIsObservedNotAssumed`). Removing the finalizer is the release +acknowledgment. A finalizer removed from a live claim is restored on the next +acquire. Milo itself supplies neither a custody anchor nor an acknowledgment, +and it lets anyone who can update the claim remove the finalizer. See the +[production admission +proposal](https://github.com/datum-cloud/fleet/pull/187). + +## Simulator site + +`cmd/fleet-simulator` is a test-only site for exercising the custody delivery and +recovery paths before a real hardware adapter exists. It serves a site HTTP API +(`internal/site/siteapi`) with a bearer token: it takes an assignment +(`PUT /v1/assignments`), reports a Device's fences (`GET /v1/fences/{namespace}/{name}`), +lists the results it holds (`GET /v1/results`) and forgets a result the +coordinator answered (`DELETE /v1/results`). It never contacts, enrolls or +authorizes real hardware. + +Its workers (`internal/site/simwork`) run on the [site +framework](device-custody.md#site-execution-increment-b). They keep a simulated +server in fenced records of the site store, so an older fence is refused, a +newer assignment stops an older worker, and a result is fenced and typed like a +real site's. With `--discover`, the process also writes fixture discovery for its +enrolled Devices, as BMC discovery would. Fixture access checks the enrollment +against the snapshot, with no BMC. The site store is an owner-only directory, and +every write replaces a file atomically and syncs it, so the simulator refuses +older fences after a restart. + +The runtime listener defaults to loopback, and the admin listener of the earlier +simulator is gone. Request bodies, identifiers, headers, and server timeouts are +bounded. The simulator refuses to start without a token and an enrollment. +Bearer authentication over plain HTTP is not a production site identity protocol. +The persisted store and the HTTP endpoints are internal alpha interfaces with no +compatibility promise. + +## Physical inventory subset + +`internal/api/inventory/v1alpha1` defines Facility, Rack, DeviceClaim, Device, +Cable and PowerFeed records. Each DeviceClaim is an observational installation +claim with typed, immutable placement, and Cable records are the only topology +authority; no move or replacement handover is automated. Records live +in the provider project in Milo. `config/components/inventory` holds their +CRDs, ProtectedResources, and the `fleet.datumapis.com-inventory-viewer` and +`-editor` roles. Only `config/milo` includes it. + +Records carry no attribution fields: resource audit logs record who changed a +record and `metadata.creationTimestamp` records when it was created. CEL requires +a Device serial or system UUID, or the explicit `identity.unidentified` marker +with a reason and neither, and keeps a Device's `claimRef` and identity immutable, +rejects duplicate or ambiguous MACs, and accepts only credential-free `https` +BMC endpoints. Status is a reserved subresource with no fields and no writer. +No metal role grants inventory access. + +The staff portal plugin's read-only Inventory tab pages through all six kinds, +shows physical relationships and components. Multiple historical bindings remain ambiguous rather than being +resolved by edit time. The primary workflow is [manual entry and review](../operations/physical-inventory.md#manually-record-a-small-installation) +through the existing Flux writer. Fleet reads no external inventory source; a +separate writer that copies records in uses the same API and validation. Unit +tests run API-server validation offline, including pruning of retired fields, +and check IAM. No deployment of this physical extension, physical verification, concurrent +reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run Run the implemented checks from the repository root: ```sh -go test ./... go test -race ./... go vet ./... ``` +CI runs every Go test once, with the race detector, split across parallel +jobs by package and, for the custody package, by test. A skipped test fails +its job, because each skip here means a missing tool or envtest assets. +Render, kustomize and script checks run in their own jobs. The documentation +link check needs ripgrep and fails without it. + The manager's multi-project envtest test needs envtest binaries. CI installs them; locally, run: @@ -698,28 +728,25 @@ go test -race ./... `task test:envtest` runs the same command. -For an isolated local run, create a synthetic credential file and keep the -default loopback listener: +For an isolated local simulator site, create a synthetic token file and a +synthetic enrollment, and keep the default loopback listener: ```sh +state_dir=$(mktemp -d) runtime_token_file=$(mktemp) chmod 600 "$runtime_token_file" openssl rand -hex 32 >"$runtime_token_file" +cat >"$state_dir/enrollment.json" <<'JSON' +{"default/server-example-001": {"bmcEndpoint": "https://[2001:db8::31]", "systemUUID": "00000000-0000-4000-8000-000000000031", "bootMACAddress": "02:00:00:00:00:31", "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", "disks": ["disk-0"]}} +JSON go run ./cmd/fleet-simulator \ --runtime-token-file="$runtime_token_file" \ - --state-file=/tmp/fleet-simulator-state.json -``` - -Fault injection and full retained-state inspection are disabled by default. To -enable them locally, create a second credential with a different value and add: - -```text ---admin-listen-address=127.0.0.1:8081 ---admin-token-file=/path/to/distinct-admin-token + --enrollment-file="$state_dir/enrollment.json" \ + --state-dir="$state_dir/site" ``` -The process refuses to start if the runtime and admin credential values match. -Remove the synthetic token and state files when the local run is complete. +Add `--discover` to write fixture discovery with the in-cluster credential. Remove +the synthetic token and state files when the local run is complete. ## Explicit gaps @@ -769,7 +796,7 @@ acceptance inventory. surfaces, but production lifecycle handlers and public status writes remain unwired. Trusted create-time caller capture and protected finalizer admission cannot be reconstructed from informer events. -- Live Milo project/IAM/catalog/quota event adapters and asynchronous executor +- Live Milo project/IAM/catalog/quota event adapters and asynchronous site completion sources are not implemented. They must support durable replay; polling is intentionally not a fallback. - Cross-project class sources and bootstrap secret retention are rejected rather @@ -778,25 +805,22 @@ acceptance inventory. and profile across two exact Milo project lifetimes. It uses synthetic admission, quota-hold, and source-use evidence, labels that boundary in public status, refuses publication collisions or profile drift, and is not production - authorization. The Milo adapter can - resolve a canonical source only when injected with trusted source authority, - fence, and custody implementations. The network adapter remains deliberately - unwired until production location, authorization, and object-guard owners are - available. + authorization. The network adapter remains deliberately unwired until + production location, authorization, and object-guard owners are available. - Milo v0.32.5 supplies ResourceClaim evidence but no service-owned quota custody - anchor or explicit release acknowledgment. It also does not supply Fleet's + anchor or explicit release acknowledgment; Fleet's own finalizer stands in + for both and is not protected. It also does not supply Fleet's caller-preserving source/provenance receipt, atomic invalidation-versus-bind fence, consumer-project deletion recovery, or provider-project purge guard. - Production cross-project allocation therefore fails closed; only test fakes - implement these interfaces in this increment. -- `LocalDigestImageResolver` is test-only. Production image authority, - namespace authorization, catalog lifetime identity, and digest resolution are - not implemented. + Production cross-project allocation therefore fails closed, and the quota claim + has no end-to-end run. +- Image resolution uses a fixture authorizer; the Milo image-use check is not + implemented. See [OS images and bootstrap data](machine-images.md). - No container image or Kubernetes deployment is delivered in this increment. - There is no mTLS workload identity, target-level authorization, or production - provider credential protocol. -- Operations complete synchronously. Delayed completion, partial effects, - cancellation boundaries, synchronization barriers, and worker takeover remain - unimplemented. -- The state file is intended for a single simulator process. Replication, + site credential protocol. +- The capacity projector is unwired (O1); see + [Device custody](device-custody.md#points-for-a-person). Bootstrap data + delivery is described in [OS images and bootstrap data](machine-images.md). +- The site store is intended for a single site process per Device. Replication, migration, backup, and upgrade/downgrade compatibility are not implemented. diff --git a/docs/development/datum-inventory-ui-alignment.md b/docs/development/datum-inventory-ui-alignment.md new file mode 100644 index 00000000..70686ba2 --- /dev/null +++ b/docs/development/datum-inventory-ui-alignment.md @@ -0,0 +1,171 @@ +# Inventory Datum UI alignment and stable navigation + +## Scope and sources + +This change originally started at PR104 commit +`4810fbf8b75fe50731a988326dd057f56e6b16cb` and now merges the exact stack base +`54ea22234decf841c01d17641b5686e558e4976d`, including settled asynchronous host +mount/test synchronization and the PR106 contract removal incorporated through +`5b60656759033b61674ee202a9ad94f4d49f4a64`. Provenance, Device sourceIdentity, +component sourceRef, placement method/snapshotDigest and NetBox importer tooling +remain removed. Visible blur/focus remains a complete no-op; actual hidden, +logout and stale-generation fences remain in force. PR107 integrates the landed +PR109 feature-branch merge `ff1902cf24ed43e2756eff20fc0073b6e809b2d7`. +Manufacturer and DeviceType categories share the stable navigation shell and +Datum table/form components. The catalog selector uses Datum Label with a native +select, retaining unavailable-selection and authorization protections. + +Design inputs are the [Fleet architecture](../architecture/design.md), the +[pinned inventory proposal](../proposals/fleet-management/inventory.md), and the +[existing inventory UI contract](staff-inventory-ui.md). These distinguish physical +records from allocation, installation, verification, and authority. + +Both frozen lockfiles resolve the declared `@datum-cloud/datum-ui: ^3.5.0` to +3.7.0. The implementation uses that installed package's README, exported type +declarations, emitted component source, and theme styles. No package manifest or +lockfile changes are needed. This is actual component adoption, not a root +package import plus custom lookalike controls. + +Host routing was inspected at staff-portal commit +`a0c4cd3e4bd9e0343ffe3310caaa25b160073b41`: + +- [`milo.layout.tsx`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/layouts/milo.layout.tsx) + calls `requireStaffUser` in its loader and supplies no query-only + `shouldRevalidate` exemption. +- [`plugin-page-outlet.tsx`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/modules/plugins/client/plugin-page-outlet.tsx) + keys page routes and error resets by path, not inventory query parameters. +- [`federation-host.ts`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/modules/plugins/client/federation-host.ts) + shares the Button and Card modules, with the host's versions winning. Its + package manifest currently declares Datum UI `^3.12.1` and React Router + `^8.3.1`; that is source evidence, not verification of any deployed host. + +No shallow-routing support is assumed. No host code, router loader, authentication +policy, or dependency version is changed here. + +## Implemented component alignment + +| Surface | Actual Datum UI use | +| --- | --- | +| Directory search, namespace, create/edit and reported-location inputs | `Input` and `Label`, preserving input types, bounds, required attributes, controlled values and accessible field names | +| Refresh, clear, component/lane add/remove, location actions, rack face controls | `Button`, explicitly using `htmlType` so auxiliary actions cannot submit a form | +| Inventory category navigation | `LinkButton as={Link}` with native router links and `aria-current`; no nested button/link or custom click/history implementation | +| Directory, physical components, cable lanes, equipment | `Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell`, and `TableCaption` | +| Access guidance | `Card`, `CardContent`, `Title`, and `Text`, retaining named region, heading, retry and error semantics | +| Section headings | `Title`; the programmatically focused detail heading uses `titleVariants` on its existing ref-bearing `h2` | + +The installed Button implementation renders a button even though its type surface +includes `asChild`; navigation therefore uses the implemented `LinkButton` API. +The pre-existing outer Fleet tabs and page-title components +already use Datum components and are not redesigned. + +Removed custom input, button, heading, table decoration and category-link skin +rules so they no longer override the adopted components. Remaining specialized +geometry and responsive layout use Datum semantic color/radius tokens instead of +hardcoded fallback palettes. The existing focusable table region retains scroll +ownership; the library's inner table container does not add a second scroller. + +## Stable tabs without bypassing host authority + +The directory's Fleet header and category navigation now live outside the private +session boundary. They contain only fixed category labels, never record names, +namespace values, counts or management controls. Counts remain in authorized +content. Hosted category links therefore remain present during initial loading, +permission denial and session checking, and select access guidance when denied. +The default hosted category stays Devices rather than silently choosing a different +readable category while the static tab still says Devices. + +For same-path navigation changing only `kind`, `record`, or `namespace`, without +a form submission or explicit revalidation: + +1. Normal React Router links run the real host loader. Back/forward and direct + namespaced links retain their URLs. No extra authority request is added. +2. Pending host checks still suspend read publication, invalidate operations, + and unmount private content/forms. Only static tabs and localized + “Checking inventory access…” text remain; the whole page is not replaced + with skeletons. +3. A successfully returned **same principal** may reuse its isolated QueryClient's + previously authorized inventory snapshot. The collection key no longer uses + per-mount `useId`; it remains scoped to plugin, provider project and that + private session client. It is retained for five minutes while inactive and is + fresh until explicit refresh/invalidation within that session. +4. Operation lifetimes restart after every completed host transition, including + batched transitions that never paint a pending frame. Reusing collection data + never revives an old operation, immutable edit baseline or draft. + +Explicit host revalidation, changed principal (including A–B–A), logout, hidden +visibility/pagehide and non-presentation navigation continue to discard the +session client or invalidate its generation. Read denials redact records; cached +data does not win over an observed error. Fresh form permission checks and guarded +submit-time exact reads/permission checks remain unchanged. Visible window +blur/focus still performs no request, remount, disabling or baseline reset. + +This intentionally trades seamless private-content continuity for a short localized +access-check message while the host is pending. It does not promise zero host +loader requests. Same-session presentation changes avoid redundant nine-collection +inventory reads; explicit refresh and real authority changes fetch again. Snapshot +reuse is not a live freshness or newly granted permission claim. + +## Deliberate remaining gaps + +- Native selects remain for filters, record references, component types, endpoints + and reported geometry. Datum 3.7.0 exports a Radix Select, not a drop-in native + select. Replacing these safely needs a separate keyboard, required/empty-value, + implicit-label, native fieldset-disabling and portal review. This change does + not invent an adapter or claim these are Datum Selects. +- Native details/summary, fieldsets/legends, semantic definition lists, responsive + form grids and bespoke rack geometry remain. Rack overlap and occupancy meaning + are unchanged. The source-defined muted palette is used, not a new palette. +- Catalog navigation tests cover stable tabs and reuse of all nine authorized + collection reads. This is local integration coverage, not authenticated catalog + UX acceptance. +- No authenticated staff-portal/Safari acceptance, deployed Module Federation + compatibility, production operation, or live API write is claimed. The parent + must review and run its deployment/host gates separately. + +## Validation + +- Provider after exact-base merge: `pnpm --dir ui/provider test`, typecheck and + production build pass. Coverage asserts actual library slots/variants, field + and button semantics, visible blur/focus node identity, permissions, immutable + baselines, unknown outcomes and existing read/write fences. +- New route integration tests use the actual inventory page and host loader: + stable tab DOM during a held loader, seven total collection reads across + category/detail/back/forward transitions, direct links, immediate/batched + navigation management readiness, in-flight create fencing, and fresh reads on + principal, logout, denial, hidden/pagehide, explicit revalidation and unknown + query changes. These do not mock Datum components. +- Consumer: `pnpm --dir ui/consumer test`, typecheck and production build pass. Consumer implementation is untouched. +- Seven focused session-boundary, tab-navigation, exact-staging, stable-control, + visible-focus-save, navigation-safety and revalidation-safety files pass three + consecutive runs. The inherited settled async `mountHost` + synchronization remains unchanged. The cached-create navigation test now + asserts the removed recorder/reference controls are absent rather than filling + obsolete fields; it still checks draft clearing and zero stale writes. +- Documentation: `bash hack/validate-doc-links.sh`; whitespace: `git diff --check`. +- Merged API contract: `go test ./internal/api/inventory/v1alpha1` passes. + Both UI builds retain the existing Module Federation warning about differing + transitive `undici` versions; dependencies and lockfiles are not changed. +- Synthetic rendering: the existing `session-fixture.html` uses in-memory API + responses and never writes a live API. The test Vite config now includes the + existing Tailwind plugin so this harness compiles the same Datum tokens and + component utilities instead of inspecting unprocessed CSS. +- Before the exact-base merge, local headless Brave/Chromium 146 checks at 1280px + and 390px inspected directory, + create, display-name edit, reported-location edit and rack rendering, light/dark + tokens, horizontal overflow, keyboard rack-face activation, exact visible + blur/focus markup/counters, stable tab nodes during held host loading and denied + read redaction. Seven collection reads across loaded category/detail transitions; + fourteen after an explicit denied refresh; zero writes and no page errors. + Shared preview snapshots timed out, so these checks used a fresh local headless + browser profile, not an authenticated browser session. + These are prior rendering evidence, not a new browser acceptance of this merge. + +To inspect the same synthetic harness locally: + +```sh +pnpm --dir ui/provider exec vite --config vitest.config.ts --host 127.0.0.1 --port 7793 +``` + +Open `/session-fixture.html`; the existing `inventorySessionFixture` exposes held +host responses, principal changes, denial and read/write counters. Local screenshots +are transient verification artifacts, not checked-in production evidence. diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md new file mode 100644 index 00000000..0c7d7a6f --- /dev/null +++ b/docs/development/device-custody.md @@ -0,0 +1,1587 @@ +# Device custody and operations + +[Documentation overview](../README.md) · [Implementation status](README.md) + +This page records how Fleet implements the [device custody and operations +proposal](https://github.com/datum-cloud/fleet/pull/174) (#174, pinned at +`d4d17f9`). The proposal's API names are provisional. Each piece below is +marked **implemented and verified**, **implemented and inert**, or +**proposed**. + +## Status + +| Increment | What it covers | Status | +| --- | --- | --- | +| A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and verified**, except the capacity projector, which is **implemented and inert**. Verified with unit tests and with tests against a real API server. Increment C wires the rest into every mode. | +| B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | +| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | +| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | +| Commissioning, step 1 | `DeviceCommissioning`, `DeviceCommissioningPlan` and `DeviceCommissioningPlanApproval`: CRDs, ProtectedResources, roles, the creator webhook route, the kind and its rows, plan qualification and the current plan. See [Commissioning](#commissioning). | **Implemented and inert.** Verified by tests against a real API server. No site runs a commissioning worker yet, and no mode creates one. | +| Power P1: control plane | `DevicePowerOperation`, its registry entry, rows, checks, evidence and settle hook, its roles, and the Device field for offered reset types. See [Device power operations](#device-power-operations). | **Implemented.** The kind ships with the component in every root C wires, and the creator webhook, standalone's creator policy and each coordinator's access cover it. Nothing creates power operations yet. Discovery records the reset types each server offers. | +| Power P2: site worker | The power worker behind the site worker contract, registered at Redfish sites | **Implemented.** No end-to-end run creates power operations yet; see [Worker gaps that remain](#worker-gaps-that-remain). | +| Power P3: customer power | The Metal provider's power request from `Machine.spec.powerState`, the projector's proven power, and the simulator's power worker | **Implemented and verified** against a real API server with the simulator site. No running provider calls it yet. | +| Power P4 | The UI | **Proposed** | + +## What Increment A adds + +- **Kinds.** `DeviceCustody` and the operation kinds in + `fleet.datumapis.com`, served only in provider project control planes. The + component that registers them, with their ProtectedResources, roles and + webhook, is in the production Milo root. The synthetic Milo root has it + without the webhook, and the standalone cluster has only the CRDs. + `TestComponentRoots` pins this, and no root ships the test-only kinds. +- **Custody.** One `DeviceCustody` per Device, with the same name. Its fields + are in `spec`, like a Lease, and it has no status. The finalizer + `fleet.datumapis.com/custody` stays until the holder is `Retired`. CEL keeps + the fence from decreasing, keeps `Retired` terminal, and requires the active + operation to carry the current fence. +- **Operations.** Every kind starts with one envelope: `creator`, `deviceRef` + (the Device's name) and `authority` (exactly one of `allocationRef` and + `serviceRequest`). The spec is immutable after create. Status phases move + forward only, and an ended phase is final. `Pending` may end + `OutcomeUnknown`, because rebuild holds an operation whose status still + says `Pending`. +- **The coordinator** (`internal/custody`) is the only writer of custody and of + operation status. Every custody change is one update that carries the + resourceVersion just read. On a conflict it reads again and decides again. +- **The creator webhook** (`internal/custody/creatorwebhook`) admits a create + only when `spec.creator` is the authenticated caller's username, plus its UID + when the caller has one, and an update only when the creator is unchanged. +- **The capacity projector** is a pure function that derives `Prepared`, + `Healthy` and `Available`. [Capacity status](#capacity-status) wires it. + +Creating or importing a Device creates `Unverified` custody. That sends +nothing to a BMC and makes no capacity `Available`. + +## Site execution (Increment B) + +Increment B adds the site framework (`internal/site`) and the Redfish +install and wipe workers (`internal/site/redfishwork`). It is **implemented and +verified**. Increment C delivers assignments to it and deletes the old +executors and their site-wide journals. Every site, simulator, local VM and +Redfish, now runs on it. + +### Where a site stores fences and its journal + +Each site keeps one directory per Device on its retained volume, under an +owner-only root. A Device's directory holds one state file and its lock. The +state file records the highest fence the site has seen, the highest fence for +which older workers are confirmed stopped, and the journal. The directory +also holds per-operation records, such as boot admissions, and the site's +copy of results. Every write replaces the file atomically and syncs it, so the +site still refuses older fences after a restart. Each Device has its own lock, +so work on one Device never waits for another. + +### What the framework owns + +- **Fences.** An assignment below the stored fence is refused and stores no + result. An equal fence is accepted again, because delivery is replayed from + custody after a crash. The fence is checked when a step is journaled and + again just before it is sent. +- **Older-worker stop.** One worker runs per Device. A newer assignment raises + the fence, then waits for the run lock. The older worker sees the higher + fence within a second, stops, and releases the lock, and a worker that dies + releases it with its process. The newer worker then records the stop + confirmation, and the coordinator reads it as the site's `Stopped` fence. A + `DeviceRecovery` is delivered the same way and runs nothing else. +- **The journal.** Each step is journaled before it is sent and marked done + after. The journal refuses any step below the stored fence. A step found + journaled but not done is observed instead of sent again. If the observation + cannot show it took effect, the outcome is unknown. Only a step that is safe + to repeat, such as powering off before a boot was requested, is sent again. +- **Deadlines and shutdown.** A worker stops at its deadline exactly. If the + journal holds nothing for the operation, it reports `Failed`. Otherwise it + reports `OutcomeUnknown`. A worker stopped from outside, such as a Pod + being shut down, stores no result, so its replacement resumes from the + journal. +- **One worker per assignment.** A redelivered assignment that already has a + result returns it. One that finds a worker for the same assignment holding + the run lock stores nothing and leaves the result to that worker. A copy + that waits for the lock checks for a stored result again once it holds the + lock, and returns that result without running, so it never sends after the + first worker recorded the outcome. A newer + assignment that cannot stop an older worker before its deadline ends + `Failed`, or `OutcomeUnknown` if the journal holds steps for it. +- **Checks before any effect.** The inputs must match the admitted digest. The + site's enrollment must match the snapshot's BMC endpoint, system UUID and boot + MAC. The per-Device credential Secret must exist, its operator-approved pin + must equal the key discovery recorded at admission (O9), and the BMC is read + only over a connection pinned to that key. A different key aborts the TLS + handshake before any request, so no credential is sent. Each failure is a + named refusal. It ends the operation `Failed` when the journal holds + nothing for it, and `OutcomeUnknown` when an earlier worker for the same + operation journaled steps. +- **Results.** Each result carries the operation's fence and typed evidence, + and messages never carry a BMC response or an endpoint. A stored result is + final: nothing replaces it. The site keeps its copy until the coordinator + accepts it or rejects it for a stale fence. +- **The fence report.** Each site reports, for each Device it is configured to + serve, the fence it has seen and the fence for which it confirmed the stop. +- **Boot admissions.** A network boot is served only while the operation's + admission is open, unexpired, and at the Device's stored fence, so a + superseded operation can never boot the server. The boot server reads + admissions from the site store. + +### The Redfish workers + +The install and wipe workers port the executor's phases: power off, arm a +one-time boot, power on once, then wait for exactly one console receipt and, +for a network boot, the boot server's delivery evidence. Power-on is the only +step that is not repeated after a crash; it is observed instead. Each site +enrolls one disk per server, named `disk-0`, with its size (O12). An +installation or wipe that names other disks is refused before anything is +sent. Each verified phase is journaled, so a resumed worker continues from +the next phase. + +The port differs from the old executor in three ways: + +- After a crash or a lost response, a power-on is observed and never sent + again. The old executor sent `On` again, up to a small budget, when the + server was still off and armed after a settle window. +- Synchronized DHCP reservations are supported from Increment C. The feed + reads the site store, and the worker waits for the DHCP owner's reports. See + [Boot network](../operations/boot-network.md). +- Its timing values match the old executor's, including the five-minute + power-off bound and the 30-second wait for a receipt after power-off, and + each is configurable. + +### Access to the server + +How the framework reaches a server is behind an `Access` interface. +`RedfishAccess` performs the credential, pin and identity checks above. The +simulator and local VM sites use `fixture.Access`, which checks the site's +enrollment against the snapshot and has no BMC. Each has its own workers. That +added no change to the worker contract. + +## Cutover (Increment C) + +Increment C moves every mode onto custody and deletes the old path. All of it +is **implemented**. The standalone smoke (`task standalone:test`) and both +multi-plane runs, local VM and Redfish, verify it end to end. Increment C adds +no migration and no compatibility code. The Secret-backed coordinator and its +records are gone, and a person re-imports records where an environment needs +them. + +| Piece | Status | +| --- | --- | +| MachineAllocation, allocation, installation and release | **Implemented and verified** by tests against a real API server and the standalone smoke | +| Quota claim | **Implemented and verified** by unit tests. **Inert** end to end: no run exercises it | +| Delivery and the coordinator loop | **Implemented and verified** by the standalone smoke and both multi-plane runs | +| Federation handoffs | **Implemented and verified** by unit tests and both multi-plane runs | +| Creator webhook in the production Milo root | **Implemented and verified** by unit tests and a test against a real API server. The root registers it, and nothing runs the coordinator there | +| Simulator site | **Implemented and verified** by the standalone smoke | +| Local VM site | **Implemented and verified** by unit tests and the multi-plane local VM run | +| Redfish site workers | **Implemented and verified** by unit tests and the multi-plane Redfish run | +| Synthetic staging mode | **Implemented.** The manager's flag handling is unit tested, and no run exercises the mode | +| Power projector | **Implemented and verified** by the standalone smoke | +| Synchronized DHCP feed on the site store | **Implemented and verified** by a unit test. Not exercised at a site | +| Boot addresses from IPAM as installation and wipe inputs | **Implemented and verified** by tests against a real API server with a stand-in for IPAM's claim API. **Inert** end to end: no run sets a provisioning class. See [Boot network](../operations/boot-network.md) | + +### MachineAllocation + +A `MachineAllocation` holds the allocation's private facts (O8). It lives in the +provider project, and only the Metal provider writes it. + +- **Spec (immutable).** The consumer as a typed reference, the Machine by + namespace and name, the capacity, the Device by name, the accepted class + and profile pinned by generation and spec digest, the CPU and memory, the + hardware snapshot, the admission authority, an optional quota claim, a copy + of the capacity's `CleaningPolicy` with its name, generation and digest, the + boot interface and the target disks. +- **Labels.** `fleet.datumapis.com/machine-uid`, + `fleet.datumapis.com/consumer-uid` and + `fleet.datumapis.com/device-uid` record the incarnations the allocation was + made for. See [No object UIDs in spec](#no-object-uids-in-spec). +- **Status.** A phase, `Active`, `Releasing` or `Released`, and the latest wipe. +- **Name.** `alloc-` and the first 16 hex characters of the SHA-256 of + `/`. See [the decision](#cutover-decisions). +- **Secrets.** None. Staff recovery operators may read it. + +### Consumers + +An allocation names its consumer with `consumerRef`, a typed reference of API +group, kind and name in the shape of Milo's quota consumer reference. The +consumer's UID is never in the spec; the allocation's name and +`consumer-uid` label carry it. + +| Consumer | `consumerRef` | Served by | +| --- | --- | --- | +| Milo project | `{apiGroup: resourcemanager.miloapis.com, kind: Project, name: consumer-a}` | The managed and multi-plane modes, through project discovery | +| Standalone namespace | `{apiGroup: "", kind: Namespace, name: fleet-project-a}` | The standalone mode, where each namespace stands in for a project | + +The allocator and the API both refuse any other kind. The allocator refuses +it before it reserves quota or looks for capacity. + +A published MachineClass names its source the same way: +`source: {publisherRef: {apiGroup, kind, name}, name}`, the provider that +publishes the class and the source class's name. The same kinds are allowed. +A claim allocates through a published class only when its `publisherRef` +resolves to the provider incarnation that published it. + +One tenancy interface resolves a reference to the consumer's current +incarnation, its UID, and the client of its API. The allocator, release, +quota claims, the Machine power projector, staging and the standalone and +multi-plane runners reach a consumer only through it. The managed mode +resolves a project through the engaged project runtimes, so a project that is +not engaged is unavailable, never assumed gone. Only a Milo project has +quota. A quota claim is never made in a project recreated under the same +name, and releasing the Machine's claim in a recreated project finds nothing, +because the claim went with the earlier project. + +### Allocation, installation and release + +`internal/allocation` writes in this order: the quota claim, then the +MachineAllocation (create only), then the custody claim (a conditional +update). A retry finds the same allocation by its name. + +- **A lost race.** An allocation whose Device another holder took, and which + never held it, is deleted, and the allocator selects again. +- **Lost custody.** An `Active` allocation that no longer holds its Device is + not repaired. The allocator returns `ErrCustodyLost`, the Machine reports + `Pending` with reason `CustodyLost`, and an operator resolves it. +- **Installation.** The `DeviceInstallation` is named from the allocation and the + Installation UID, which its `fleet.datumapis.com/installation-uid` label + records. Its predecessor must be the Machine's current installation. + Bootstrap data goes through the [sealed store](machine-images.md). +- **Release.** The allocation's holder moves to `Release` with all six gates + open. Then: + - Access closes at once. + - Network and Address close when every interface claim the allocation + recorded is gone. See [Network attachment](../operations/network-attachment.md). + - Operations closes when no installation of the allocation is active or + unended. + - Cleaning creates a `DeviceWipe`, step 1. A wipe that ended `Failed` sent + nothing, so it gets a new step, up to step 3. Then the release stops with + `ErrWipeFailed`. A wipe that ended `OutcomeUnknown` gets a new wipe only + after a `DeviceRecovery` `Retry`, under the name custody gives it. + - Quota deletes the claim and observes it gone. +- **Done.** Custody returns the Device to `None` only when no gate, hold or + operation remains. Then the allocation becomes `Released`. + +### Quota claim + +`internal/milo` creates a Milo `ResourceClaim` named `fleet-machine-` and the same +16 hex characters, in the Machine's namespace. Release deletes it and waits until +it is gone. No mode in this repository has Milo quota. The claim is **implemented +and verified** by unit tests, but **implemented and inert** end to end: no run +exercises it. + +### Delivery and the coordinator loop + +`internal/delivery` builds each assignment from custody's active operation and +the operation spec exactly as admitted. It delivers the assignment to the sites +serving the Device once the admission is copied to operation status. It collects +results and accepts them by fence. The coordinator loop runs reconcile, deliver, +collect and the retention sweep. The coordinator configuration names the sites +that serve each Device. + +### Identities + +Every mode uses three identities, one per component: + +| Identity | Writes | +| --- | --- | +| The custody coordinator | Custody, operation status. It is the only custody writer. | +| The Metal provider | MachineAllocations and DeviceInstallations | +| The release controller | DeviceWipes | + +An operation's creator is the identity a `SelfSubjectReview` reports. + +- **Standalone** enforces the same creator rule as the webhook with a + ValidatingAdmissionPolicy (`config/standalone/site.yaml`). +- **The production Milo root** (`config/milo`) includes the device-operations + component, with the creator webhook served by `fleet-registration`. +- **The synthetic Milo root** (`config/milo-synthetic`) includes the kinds, + ProtectedResources and roles, but not the webhook, because it installs no + registration webhook. +- **The multi-plane local Milo** enforces the CRD rules but registers no creator + webhook. This is a gap. See [Points for a person](#points-for-a-person). + +### Sites + +- **The simulator is a site.** `cmd/fleet-simulator` serves a site HTTP API + (`internal/site/siteapi`). Its workers (`internal/site/simwork`) keep the + simulated server in fenced records in the site store. +- **The local VM site** (`internal/site/vmwork`) ports the old executor. It + gives each installation an exclusive disk. It proves the installer boot with one + console receipt, and in PXE mode also with boot deliveries and a DHCP lease. It + then does a disk boot. A boot is started once and is observed after a crash. + The boot server serves only an open admission at the Device's stored fence. A + wipe deletes every installation disk of the Device. +- **The Redfish workers** (`internal/site/redfishwork`) are live. Each reads the + Device's own credential Secret by the [BMC discovery](../operations/bmc-discovery.md) + contract. There is no shared credential. The boot server and the synchronized + DHCP feed read the site store. +- **Fixture access and discovery** (`internal/site/fixture`) serve synthetic + Devices that have no BMC. Access checks the enrollment against the snapshot. + Fixture discovery writes Device status the way BMC discovery would. Who writes + it depends on the mode; see [Modes](#modes). + +### Boot delivery methods (prototype) + +A prototype of [#227](https://github.com/datum-cloud/fleet/pull/227). The +operations guide describes how it runs in the [Redfish lab](../operations/redfish-lab.md#virtual-media-suite-prototype). + +- **Every installation records its method.** `spec.delivery` names + `NetworkBoot` or `VirtualMedia`, and for virtual media the central media + service, the address mode, the fetch and report windows, and the + Machine's report address. The Metal provider claims that address from the + same source as a network boot's provisioning address, and admission checks + it is still bound to the operation's own claim. The media service takes the + first-boot report only from it. A virtual + media installation's deadline is the sum of its windows. +- **Sites declare their methods in their enrollment.** Each site's + enrollment lists its methods in its order of preference. The site reports + that declaration with its fence report, and `custody.Sites` returns it + through `DeliveryMethods`. The coordinator keeps no copy. Admission sees + the methods every serving site offers, and the Metal provider selects from + the same report. A site that has not reported a current, valid + declaration decides nothing: admission leaves the operation `Pending`, and + the provider creates no installation until the site reports one. +- **Admission checks the method** under the custody update: offered, + qualified, consistent with the other inputs, and every installer download + pinned by digest. The admission snapshot records the method, so a + recovery hold records it too. A settling installation must use the held + method, and a wipe cannot settle a virtual media hold. +- **Wipes and commissionings need network boot.** Both only network-boot, + so admission refuses either with `DeliveryMethodNotOffered` unless every + serving site offers network boot. The Metal provider makes no release wipe, + and claims no boot address for one, at a site that does not offer it, and + the release reports why. A site that declares only virtual media, or + nothing, therefore never uses its DHCP, boot addresses or boot NIC + attachment. +- **Burn-in timing stays network boot only.** Burn-in starts when the boot + server finished delivering the image, from its `write-complete` lines. + Virtual media writes none: the central media service records the BMC's + fetches. No burn-in runs over virtual media, because commissioning + records no delivery method and admission refuses it without network boot. +- **Workers dispatch on the method.** The Redfish install worker hands the + install to the method's own steps; network boot is unchanged. The local + VM and simulator workers refuse any method but network boot. + +### Federation + +`internal/coordination` carries one site assignment per `MachineAllocationHandoff` +(`spec.device` and `assignmentJSON`), or a request for a Device's fence report. +The cell observer writes the fence report and the stored result to the handoff's +status. The coordinator accepts only this cell's observation of exactly the +assignment the handoff carries. It then labels the handoff answered, and the cell +deletes its copy of the result. + +Worker Jobs are created by kro as before. A worker exits 65 for a handoff that +is not for this cell, or for an assignment below the Device's stored fence. The +private custody namespace on the hub host is gone. + +### Modes + +| Mode | Where the coordinator runs | Site | Fixture discovery writer | Status | +| --- | --- | --- | --- | --- | +| Standalone smoke | A Deployment | The simulator | The simulator site | **Implemented and verified** by `task standalone:test`. The phases run as the Metal provider, with the coordinator's and release controller's tokens. | +| Synthetic staging | `fleet-manager`, under its leader lease | The simulator | The manager | **Implemented.** The manager's flag handling is unit tested. No run in this repository exercises it. | +| Multi-plane, local VM and Redfish | A workstation process for the run (`hack/multiplane/coordinator.sh`) | The cell, over Karmada | A separate discovery identity on the workstation | **Implemented and verified** by both runs. | + +- **Synthetic staging.** The manager runs the coordinator loop and fixture + discovery. Its flags are `--synthetic-coordinator-client-cert-dir`, + `--synthetic-release-client-cert-dir`, `--synthetic-site-enrollment-file` and + `--synthetic-device-namespace`. The coordinator and the release controller + each sign in to Milo with their own client certificate, on the manager's + endpoint and server CA and without its credentials. The overlay mounts two + environment-supplied cert-manager Secrets, + `fleet-custody-coordinator-client-cert` and + `fleet-release-controller-client-cert`, each with `tls.crt` and `tls.key`, + and a `fleet-synthetic-site-enrollment` ConfigMap. The ConfigMap in the overlay + holds a synthetic placeholder, and an environment replaces it. An environment + must also make sure its records exist and create the two client-certificate + identities; see [Points for a person](#points-for-a-person). +- **Multi-plane.** The provider project gets the inventory and custody CRDs and one + token per component. The lab BMC serves TLS with a key generated per run, and + each Device's credential carries that key's digest as its pin. Real BMC + discovery is not part of the run. This is a lab gap. One lab BMC serves both + targets with one key, and custody refuses a key that two active Devices + record, so only target A is a Device. Target B stays enrolled at the site, + with its own credential, to prove isolation. + +### Machine power + +The manager's `PowerProjector` is the only writer of `Machine.status.power`. It +reports `Unknown` while a recovery hold exists or custody is unverified, and +otherwise the power state discovery last observed. A Machine with no active +allocation has no power. The harness runners call the same projection. In the +manager, custody, allocation and Device events in the provider project wake +the consumer's Machines, so a new hold shows as `Unknown` without a Machine +event. + +Admission keeps power to that one writer. RBAC alone cannot: Milo authorizes a +status write with the Machine's `update` and `patch` permissions, which the +consumer and claimant roles hold, and the manager's other status writers share +the projector's identity. + +| Mode | Guard | Writer | +| --- | --- | --- | +| Production Milo root (`config/milo`) | The Machine power webhook, served by `fleet-registration` at `/validate-machine-power`. Only status writes that change `status.power` are routed, fail-closed. | The username in `fleet-registration`'s `--machine-power-writer` flag: the manager's Milo identity. Unset, every power change is refused. Set it before a power projector runs against this root. | +| Standalone (`config/standalone`) | A ValidatingAdmissionPolicy on `machines/status` | The smoke runner's service account, which runs the projector for its fixtures | +| Synthetic Milo root and multi-plane local Milo | None. Neither runs `fleet-registration`, and Milo ignores policies stored in a project. RBAC grants Machine status only to the manager, but the consumer roles' `update` permission still reaches it. | See [Points for a person](#points-for-a-person) | + +Who can write Machine status, and who can change power: + +| Identity | Machine status | Power | +| --- | --- | --- | +| The manager: the power projector, the staging handler and the requested-hardware projector | All fields | The only writer, once the flag names it | +| The standalone smoke runner | Its fixture Machine | The only writer in standalone | +| Milo consumer and claimant roles | All fields, through `update` and `patch` | Refused | +| The Metal provider and allocator, the release controller, the custody coordinator, discovery, the inventory and operation roles, Karmada, kro and federation | None | None | + +Within the manager, the staging handler, the requested-hardware projector and +the runners carry power forward unchanged; admission cannot tell them apart +from the projector. A render check over every root in `config` fails if any +other Kubernetes role gains Machine status writes, or any other Milo role gains +a Machine status, update or patch permission. + +### Deleted, with no compatibility + +- The Secret-backed coordinator and its records, the private-record RBAC, the + private namespace and its admission policy, and the manager's private-namespace + plumbing (`--private-namespace` is removed). +- The executor client, the simulator store, the local VM and Redfish executors and + their journals, and the shared Redfish credential. +- The old handoff `requestJSON` shape. +- The single-plane local VM harness (`hack/local-vm/run.sh`, + `task local-vm:acceptance`, `cmd/fleet-local-vm`). The multi-plane local VM + mode runs the same workers. This is a decision for a person; see [Points for a + person](#points-for-a-person). + +### Unchanged and still open + +- Only isolated tests deliver bootstrap data to federated network-boot workers. See + [OS images and bootstrap data](machine-images.md). +- `DeviceRecovery` needs no second person. + +## Failure scenarios (Increment D) + +Both multi-plane runs, local VM and Redfish, run the #174 acceptance tests +end to end. The [coverage +inventory](../../test/acceptance/coverage.md#device-custody-and-operations) maps +each test to its phase, and the [multi-plane +phases](../operations/multiplane.md#acceptance-phases) describe each one. + +| Scenario | How the run produces it | +| --- | --- | +| Importing sends nothing | Checked before any allocation: no operation, assignment, worker Job, journal entry or BMC effect | +| Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | +| Contention | Custody names the one MachineAllocation, the winner's | +| Tenant isolation | The losing consumer's project has no Device API, and an installation for its unheld allocation is refused before delivery | +| Deadline | The coordinator restarts with a short installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | +| Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | +| Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | +| A wipe settles the hold | The release wipe is admitted above the held fence after the worker stopped | +| Rebuild | Custody is deleted while the site observer is stopped, so no fence report arrives | +| Pin mismatch | The Redfish probe connects with another key's digest and reaches no request | + +The scenarios found two site gaps, both fixed: + +- **A worker stopped at its deadline left its boot admission open** until the + boot window expired, so the server could still fetch the installer when + nothing could resume or observe the operation. Both workers now close it at + the deadline. A worker stopped from outside still leaves it open for its + replacement. +- **The local VM wipe refused to run while a guest was up**, so it could never + settle an installation stopped at its deadline, which leaves its guest + running. The wipe now powers the guest off first, as a Redfish wipe does, + and still refuses if the guest keeps running. + +The shorter installation deadline is a flag of the acceptance binary's +coordinator, and only the deadline scenario sets it. The boot hook lives in +the acceptance binary's boot service, and only the local multi-plane site's +Flux source configures it, which no production root may reference. +`TestOnlyTheLabSiteSourceSetsTheWithholdHook` fails if any production root +references that source or any other package names it, and +`TestNothingElseInTheRepositorySetsTheWithholdHook` fails if any file outside +the docs, the acceptance binary and the lab steps names it, or the boot +service sets it more than once. The hook counts each boot it denies, and the +`deadline-hold` phase requires at least one denial, so a boot that never +arrived for another reason does not pass as withheld. The emulator lab's limits +are listed in the coverage inventory. + +## Implementation decisions + +Each decision lists the open point from the implementation brief it settles. + +### Who created an operation (O14) + +- The client sets `spec.creator` to its own username, and to its UID only when + its credential carries one. A caller is identified by username, as Kubernetes + RBAC identifies it, because some credentials, such as client certificates, + carry no UID. The webhook rejects any other value and any change. That is + how #174 at `d4d17f9` reads, so "clients cannot set the creator" becomes + "clients can set only themselves". CEL also makes the creator immutable, as + part of the spec. +- Milo's root API server calls the webhook, because Milo v0.32.5 does not + evaluate admission policies stored in a project. The webhook reads the + original caller from the admission request, with the project in Milo's + extras, and refuses a caller outside the configured provider projects. It + reads nothing else and keeps no state. +- The existing `fleet-registration` server serves the webhook on its own + path, `/validate-operation-creator`. It shares that server because the caller, + the transport and the provider-project scope are the same, and the handler + keeps no state. The production Milo root registers it (Increment C). +- The coordinator classifies a creator by configuration. Each service class, + such as the Fleet provider for Metal or the release controller, maps to + configured principals by username. A principal configured with a UID + matches only a creator with that UID; one without a UID matches the username + alone. Any other creator is staff. IAM decides which staff may create which + kind, and the API server has already authorized the create. No identity is + hard-coded. + +### Admission + +- **The rule table is data.** Each row names a kind, an optional variant (such + as a recovery decision), a creator class, an authority type, the holders and + custody state it admits from, how it treats a recovery hold, and whether it + queues. A kind's rows are matched only against operations of that kind, so + adding a row never changes how another row is evaluated. +- **Queueing.** Provider and release rows queue. They wait in `Pending` while + another operation runs, while custody is `Unverified`, while discovery is + not current, or while a recovery hold that they cannot settle exists. Each + of these can clear, and a queued operation's name is deterministic, so it + could not be created again. Staff rows never queue: those conditions end a + staff operation `Failed`. +- **Phases for refusals (O5).** A refusal ends `Failed` with a reason, and + nothing is sent. Expired, superseded and no-longer-matching operations end + `Cancelled`. A `Pending` operation whose holder no longer matches is + `Cancelled`. One that never matched is `Failed`. Kinds add their own + reasons. +- **Shared reasons.** The admission reasons use the names of #174's table: + + | Reason | Refused by | + | --- | --- | + | `CustodyUnverified` | Rule 1 | + | `CreatorNotPermitted` | Rule 2 | + | `HolderMismatch` | Rule 2 or 3 | + | `OperationInProgress` | Rule 4 | + | `DeviceIdentityMismatch` | Rule 5, both a mismatched identity and discovery that is not current | + | `SharedPublicKey` | Rule 6 | + | `RecoveryHold` | A recovery hold | + + Rule 7 is a kind's own checks of its inputs, with its own reasons. They run + before the shared identity and key checks of rules 5 and 6, so a kind's more + specific reason, such as power's `SystemUUIDNotRecorded`, is the one + reported. All rules must hold either way; the order decides only the + reason. A rule 7 refusal may wait instead, for a condition that can clear + by itself: an operation on a queue row then stays `Pending` with that + reason for a bounded time the refusal sets, counted from when the operation + was created or the Device's last operation finished, whichever is later, + and ends `Failed` only after that. A staff row never waits. A staff + operation not admitted within five minutes ends `Cancelled` with reason + `Expired`. This implementation adds `NameMismatch`, for an operation not + named by its rule, and outcome reasons: `Superseded`, `Withdrawn`, + `DeadlineExceeded`, `SiteNotConfirmed`, `SiteCouldNotProve`, + `InvalidEvidence`, `SnapshotInvalid` and `UndeclaredReason`. +- **Retries.** An operation created after a `Retry` is named from the held + operation: its name, `-retry-`, and the number of `Retry` decisions for it, + which custody records with the hold. This applies to every kind whose + settlement needs a `Retry`, such as a wipe, and the kind's own naming rule + does not apply to it. Until the `Retry` is applied, the retried operation + waits in `Pending`, a staff one included, and does not expire while it + waits. The `Retry` is used when that operation is admitted. If + the retried operation also ends unknown, its hold keeps the original name + and count, so the next retry is named `-retry-2`, not `-retry-1-retry-1`. + Rebuild reads that lineage back from the names. +- **Replacement.** Only an operation that passes the creator, authority, + holder and allocation checks on a row that queues can replace an older + pending one, of the same kind under the same allocation. A request refused + its permission check therefore replaces nothing, and staff requests, whose + rows never queue, never replace one another. +- **Settling operations come first.** Pending replacement never cancels an + operation that settles the hold. Other operations wait in `Pending` until the + hold is settled, and they do not hold back the operation that settles it. +- **Holders under a hold.** A row can admit from a holder only to settle a + hold of its kind. The staff power row, "`None`, or `Service` under a power + hold", is two rows: one from `None`, and one from `Service` that requires a + hold the operation settles. +- **Current identity (O9).** Identity is current when BMC discovery reports + `IdentityMatched` true for the Device's current generation, its last complete + inventory read is at most two hours old (twice the default discovery + interval), and it recorded the BMC key at the current endpoint. Admission + check 6 compares the observed key digest across Devices that are not + retired. The snapshot carries the observed digest, and the site worker must + check it against the operator-approved pin before sending anything + (Increment B). +- **Only `Retire` and `Resolve` skip checks 5 and 6.** A `DeviceRecovery` + with `Retire` or `Resolve` skips current discovery and the shared-key check, + because it must work when a BMC is unreachable, for example to retire a dead + server. The operation's `device-uid` label is always checked against the + Device's UID. `Settle` still needs current + discovery: settling a power hold needs fresh discovery evidence of the power + state, as the #174 settlement table says. `Retry` needs no evidence of its + own, and it still passes both checks. The settling operation it authorizes + goes through normal admission as well. Only a + kind that cannot reach the server may skip these checks, and the registry + refuses any other. +- **Names.** A row may set its own naming rule, such as generated names for + staff power and generation-based names for provider power; otherwise the + kind's rule applies. An operation that does not follow its rule ends + `Failed` with `NameMismatch`. A `DeviceInstallation` is named from its allocation and + a digest of the Installation UID in its `installation-uid` label. A `DeviceWipe` is named from its allocation + and step. Staff kinds must use a generated name. +- **Order.** Pending operations are admitted oldest first. Ties break on kind, + then name, then the object UID, so every coordinator picks the same one. +- **Refusals use current custody.** The coordinator reads custody, lists the + operations, and reads custody again. It decides only if custody did not + change in between. A claim followed by its installation's create is + therefore seen before the installation could be refused. +- **Racing refusals.** Delivery must wait until operation status shows + `Admitted`. If a racing coordinator ends an operation, or it is deleted, + after custody admitted it but before the status copy, custody withdraws it + (`Cancelled`, `Withdrawn`). Nothing was delivered, and the fence stays + raised. +- **Fences.** Admission raises the fence above both custody's fence and every + fence a serving site reports having seen. Each site reports two fences: the + highest it has seen, and the highest for which it confirmed that older + workers stopped. A site report at or above an admission's fence therefore + proves the site received that admission. + +### Deadlines and clock skew (O4) + +| Kind | Deadline | +| --- | --- | +| `DeviceInstallation` | 40 minutes, the Redfish executor's install bound | +| `DeviceWipe` | 40 minutes, the Redfish executor's cleanup bound | +| `DevicePowerOperation` | 8 minutes: the two-minute start-by window, four BMC requests of at most 30 seconds, the three-minute observation, and a minute of margin | +| `DeviceRecovery` | 10 minutes to collect the sites' fence reports | + +The worker stops at the deadline exactly (Increment B). The coordinator +declares `OutcomeUnknown` only after the deadline plus a two-minute skew +margin. A staff operation that is not admitted within five minutes expires. +Each value is configurable. + +### Unknown outcomes and recovery (O2, O3, O6, O7) + +- `OutcomeUnknown` moves the operation from `activeOperation` to + `recoveryHold` in the same update, keeping its kind, name and fence. + The holder stays. +- A result whose evidence does not match the kind's schema proves nothing, and + ends `OutcomeUnknown` with `InvalidEvidence`. +- A settling operation records the hold it settles. If it succeeds, the hold + is cleared, unless its kind settles only on some results: a commissioning + settles only with a `Passed` verdict. If it also ends unknown, its hold + replaces the old one. +- A `DeviceRecovery` is admitted like any operation and raises the fence. The + coordinator applies it only after every site serving the Device confirms + that every worker below that fence stopped. If no site + confirms before its deadline, it ends `Failed` with `SiteNotConfirmed`, and + the hold stays. It does not end `OutcomeUnknown`, because it cannot change + the server. +- `Settle` clears a hold only when the held kind provides a settle check, and + that check accepts the evidence. Installation and wipe holds have no such + check: later operations settle them. +- `Retry` marks the hold so that the held operation's requester can create one + settling operation. The hold carries what #174 asks of it: the held + operation, its `Retry` count (`retries`), and whether a `Retry` is unused + (`retryAuthorizedBy`). Admission accepts a `Retry` only for a hold whose + settlement row requires one, meaning the held kind is `Retryable` and a kind + settles it after a `Retry`, and refuses one while an earlier `Retry` is + unused. Applying a `Retry` raises the count, and admitting the settling + operation uses it. +- `Retire` needs a hold and a `Service` or `Release` holder. Retiring from + `Release` requires a disk disposal record. +- `Resolve` is the only operation `Unverified` custody admits. It records the + holder (`None`, `Allocation`, `Release` or `Retired`), marks custody + `Verified`, and adopts the current Device UID in custody's `device-uid` + label. The holder must agree with + the Device's live MachineAllocations, both at admission and when it is + applied: `None` or `Retired` when none names the Device, and `Allocation` + or `Release` with the one that does. A rebuilt hold stays, to be settled + separately. +- Nothing retries an operation automatically. + +### Rebuilding custody (O13, O15, O16) + +- Missing custody is created `Unverified` from the Device's lifecycle and + succeeded `Retire` recoveries, its MachineAllocations that are not + `Released`, and its operations. A releasing allocation rebuilds `Release` + with every gate open. +- Every admitted operation that has not ended is held, even if its status + says `Pending`, because custody is written before the rest of its status. + Its status is ended `OutcomeUnknown` with reason `Rebuilt`, and it is never + admitted again. An operation records its admission before custody names + it, so one without an admission record was never admitted and is not held. +- An operation that ended `OutcomeUnknown` is held again unless something + later settled it: a succeeded operation with a higher fence whose kind + settles the held kind with the evidence it recorded, or a succeeded + recovery that cleared that exact hold. +- If several operations would be held, the one with the highest fence is + held and custody stays `Unverified`, so a `Resolve` must decide and the hold + is never dropped. +- Two live allocations, holder sources that disagree, a Device UID that + differs from custody's `device-uid` label, or a missing Device also keep + custody `Unverified` + until a `Resolve`. +- Custody becomes `Verified` only after every site configured to serve the + Device reports its stored fence. The new fence is above every fence those + sites and the operations have used. A Device no site serves stays + `Unverified`. Sites are configured explicitly and never inferred from + placement. +- The site's fence store must be durable, beside the journal on its retained + volume, so a site refuses older fences after a restart (Increment B). + +### Where an allocation's private facts live (O8) + +Decided: the allocation's facts live on its MachineAllocation, in the provider +project, and only Fleet writes it. This follows the [MachineAllocation +record](../enhancements/machine-lifecycle/README.md#machineallocation-record) +of the machine lifecycle: identity, the accepted contract, the hardware +snapshot, authority and quota evidence, and lifecycle and release obligations. +Immutable accepted inputs go in spec. Lifecycle goes in status. Each +allocation is named from its Machine UID, per #174. Nothing secret goes on it, +and staff roles may read it. Increment C implements this (**implemented**; see +[MachineAllocation](#machineallocation)). It replaces the private `AssetRecord` +and the other Secret records, which are deleted. + +### Release gates (O17) + +The gates are the machine lifecycle's release obligations: `Operations`, +`Access`, `Network`, `Address`, `Cleaning` and `Quota`. The release +controller closes each one with evidence. A gate the coordinator does not know +stays open. The Device returns to `None` only when no gate, hold or operation +remains. + +### Staff access and customer data (O10) + +- The **device operations viewer** reads custody and operations, but not + MachineAllocations, so it does not see which customer holds a server. +- The **device recovery operator** inherits the viewer, creates + `DeviceRecovery`, and reads MachineAllocations, because a `Resolve` must + name an allocation and staff identify the customer through it. +- A `DeviceRecovery` does not need a second person in this increment. The + creator is recorded and the role is narrow. This is listed under [Points for + a person](#points-for-a-person). +- Staff roles may read MachineAllocations, because nothing secret is on them. + Only the recovery operator role grants that read today. +- Bootstrap data lives in the [sealed store](machine-images.md). Only the + coordinator role can read it, the installation requester can only create + it, and no role reads a Secret or a bootstrap payload. A test walks every + role the repository ships to check this. + +### Other decisions + +- **Retention.** Finished operations are deleted 30 days after they end, + unless custody still names them as active or as the hold. A succeeded + retirement is kept until inventory retires the Device, because until then + it is the only record rebuild can read. +- **Rejected results.** A result whose fence or operation does not match the + active operation is refused, and custody counts it and records the last one + for monitoring. It never changes the holder. A retry of a result already + recorded is accepted without a second write. +- **Boot interface (O12).** `bootInterface` resolves by name against the + Device's interfaces, and the snapshot records its MAC. Target disks stay a + site-local enrollment fact that the worker checks (Increment B). +- **Cleaning policy (O11).** See [Cleaning policies](#cleaning-policies). +- **Capacity (O1).** Settled by commissioning: see [Capacity + status](#capacity-status). + +### No object UIDs in spec + +No resource spec holds an object UID (#211). A deterministic name, a label or +status pins each incarnation. The one exception is an operation's +`creator.uid`, the authenticated caller's UID when its credential carries one, +as in a Kubernetes CertificateSigningRequest. Each same-name recreation is +guarded, and a test fails if its guard is removed: + +| Recreated | Guard | Test | +| --- | --- | --- | +| Machine or consumer | The allocation's name hashes both UIDs, and its `machine-uid` and `consumer-uid` labels must match | `TestAnAllocationForAnotherMachineIncarnationIsAConflict` | +| Machine or consumer, against the authority | The allocator refuses an admission authority that records the Machine or consumer UID, so the decision is named by name | `TestTheAllocationAuthorityNamesNoIncarnation` | +| Consumer, under another kind or name | The allocation's `consumerRef` must name the Machine's consumer | `TestAnAllocationForAnotherConsumerIsAConflict` | +| Publisher, against a published class | A published class's `publisherRef` must resolve to the provider incarnation that published it | `TestAClassFromAnotherPublisherIsRejected` | +| Consumer project, against quota | Quota resolves the project and requires the incarnation the Machine was admitted in | `TestQuotaServesOnlyTheMachinesProjectIncarnation` | +| Device | Custody's `device-uid` label must match the Device, or custody stays `Unverified` until a `Resolve` | `TestARecreatedDeviceLeavesCustodyUnverified` | +| Device, against free capacity | Custody for another Device incarnation is never free | `TestCustodyForAnotherDeviceIncarnationIsNotFree` | +| Device, against a release wipe | The release controller plans a wipe only if the Device's UID is the allocation's `device-uid` label | `TestAWipeIsNeverPlannedForARecreatedDevice` | +| Wipe, against a drive disposal | `DisposeDrive` reads the held drives custody recorded with the hold, never the wipe object | `TestWipeAdmissionChecksThePlan` (a wipe recreated under the held wipe's name) | +| Wipe, after rebuild | A rebuilt hold records no drives, so `DisposeDrive` is refused | `TestARebuiltHoldCannotBeDisposed` | +| Device, against a claim | `Claim` takes the Device incarnation the allocation names, and refuses unless both the live Device and custody's label match it | `TestCustodyForAnotherDeviceIncarnationIsNeverClaimed`, `TestARecreatedDeviceIsNeverClaimedUnderItsStaleLabel`, `TestARecreatedDeviceIsNeverClaimedForTheEarlierIncarnation` | +| Device, against an operation | An operation's `device-uid` label must match the Device at admission | `TestAdmissionPreconditions` | +| Device, against an existing operation | The Metal provider and release controller require an existing same-name operation to carry the same labels | `TestAnOperationForAnotherDeviceIncarnationIsAConflict` | +| Installation | The `DeviceInstallation` name hashes the Installation UID, so a same-name Installation gets a new operation | `TestAllocateInstallReleaseReuse` | +| Operation, as the active operation | Custody names an operation by kind and name with the fence it admitted it at, and an operation matches only if its `status.admission.fence` carries that fence | `TestARecreatedActiveOperationNeverGetsItsResult` | +| Operation, as the last result | The same match: the result is never copied to a same-name operation created later | `TestARecreatedOperationNeverInheritsItsLastResult` | +| Operation, as the recovery hold | The same match: a same-name operation is neither held nor excluded as the held one | `TestARecreatedHeldOperationNeverTakesTheHold` | +| Operation, as a Retry's settling operation | The same match: a same-name operation is never admitted or settled as the Retry's | `TestARecreatedRetryIsNeverCountedAsTheRetry` | +| Operation, as a later retry at rebuild | A later retry supersedes a held operation only if it carries an admission record | `TestARecreatedRetryNeverSupersedesARebuiltHold` | + +The coordinator writes `status.admission.fence` to the operation before it +writes custody, so custody never names an operation that cannot prove it is +the one admitted. A same-name object created later has no admission record, +so it never matches custody's active operation, last result, hold or Retry +lineage. An operation without an admission record was never admitted, so +rebuild holds only operations that carry one. + +The site keys its journal, results and boot records by the admission, not by +an object UID: `..`, with the name replaced by +its digest if the key would exceed the site store's 128-character limit. A +same-name operation admitted later has a higher fence and so another key. + +### Cleaning policies + +This section records how Fleet implements the [cleaning +proposal](https://github.com/datum-cloud/fleet/pull/183) (#183). The first +increment is **implemented and verified** with unit tests and tests against a +real API server. The rest of #183 is **proposed**. + +- **Kind.** `CleaningPolicy` in `fleet.datumapis.com`, served only in provider + project control planes, with its ProtectedResource and a + `cleaning-policy-admin` role that can create and delete but not update. The + viewer role reads policies, and the Metal provider role can get one. The CRD + keeps the spec immutable. +- **Validation.** `internal/cleaning` rejects a policy whose methods cannot + reach its assurance, that applies a method to the wrong protocol, that uses a + check a method does not allow, or that qualifies `CryptographicErase` for a + model that does not always encrypt. The `fleet-registration` server serves it + as a webhook at `/validate-cleaning-policy` in `config/milo`, for creates + only, because the spec cannot change. The synthetic Milo root and the + standalone cluster have no such webhook. +- **Pinning.** The allocator reads the capacity's policy, validates it again, + and copies its name, generation, SHA-256 digest and spec into the + MachineAllocation. No spec holds the policy's UID: the copy and its digest + pin the content, so a policy deleted and recreated under the same name, even + at the same generation, changes no existing pin. Capacity whose policy is + missing or invalid is skipped, and nothing is claimed. If no capacity is + left, the error names the skipped policy. Each release `DeviceWipe` names + the pinned policy, so release does not need the policy to exist. +- **Fixtures.** The standalone fixtures and the multi-plane seed create a + `Clear` policy that overwrites and reads back, the only method the sites run. + Synthetic staging ships a fixture policy that operators apply to the + provider project, because the manager writes no policies. No capacity is + allocated until it exists. + +BMC discovery records each System's drives from Redfish in Device status, and +fixture discovery reports one simulated drive per enrolled disk. The Redfish +lab's targets each have one emulated NVMe drive. + +- **Manifest.** The allocator pins every drive the server reports, named + `disk-0`, `disk-1` and so on by protocol and serial number, with the rule + that covers it. A server whose drives are unknown, back a RAID volume, lack + a serial number, or have no planned method is skipped as uncovered. + Installation target disks must be names in the manifest. +- **Plan.** One shared planner turns the pin and current discovery into one + step per drive. It matches a pinned drive by serial number and requires + the same model, protocol, media type and capacity; firmware may change but + must still be qualified. A drive that shares its serial number with another, + or reports none, is `Uncovered`. The release controller writes the plan into + each `DeviceWipe`, and admission plans again and refuses a wipe whose plan + differs, with reason `PlanMismatch`. Such a refusal does not count toward + the release's three failed steps, but a release stops after 16 steps. A + retried create that finds a wipe with another plan keeps it, because + admission plans it again. +- **Missing and uncovered drives.** While a planned drive is `Missing` or + `Uncovered`, the release controller sets the allocation's `Cleaning` + condition to `False` with reason `DriveMissing` or `DriveUncovered`, and + waits 10 minutes (the allocator's `CleaningGrace`) for discovery to report + the drive again. A brief gap in discovery therefore spends no wipe step and + pages nobody. After the grace it creates the wipe. Admission checks its + plan, then admits it and ends it `OutcomeUnknown` with that reason in the + same custody update (a kind's `HoldOnAdmit`), so the fence rises, nothing is + delivered, and the server is under a recovery hold. If that wipe was + settling an installation hold, the drive hold replaces it: every drive the + installation could have written is then wiped by a later step or recorded + as disposed of, which is what settling it requires. A rebuild holds the + installation again, which fails closed. Each blocked plan gets its own + grace: settling a drive hold restarts it. +- **DisposeDrive.** A `DeviceRecovery` with decision `DisposeDrive` names the + hold, the drive, and how it was destroyed or removed, with a reference. It + is admitted only from a `Release` holder under that hold, for a drive the + held wipe planned as `Missing` or `Uncovered` and that discovery no longer + reports, so an uncovered drive is pulled first. When it forms the hold, the + coordinator records in custody, with the hold, each drive the wipe could + not clean, by name, serial number and state. `DisposeDrive` reads only that + record, never the wipe object, so a wipe recreated under the same name, + which never matches custody, cannot authorize a disposal. Discovery proves only that + no drive reports the planned serial number; for a drive whose serial + changed, the recorded method and reference are the proof. Retry is refused for this + hold, because a retried wipe would plan the same drive. Like every + recovery, it applies once the sites report its fence. It clears the hold + and records the drive in custody's `holder.disposedDrives`; the planner + omits it only while its serial number remains absent. If discovery reports + the serial again, the planner marks it `Uncovered` and the normal drive + hold applies after the grace period. If every pinned drive was disposed + of and discovery reports no drives, no wipe remains and the `Cleaning` gate + closes. The record ends when the holder leaves `Release`; rebuilt custody + does not have it, so staff record the disposal again. The recovery operator + role, which creates `DeviceRecovery`, can record it. +- **Sites.** Every site cleans only by overwriting each planned drive and + reading it back, and refuses any other plan before sending anything. Sites + match planned drives to their enrolled disks by name, and fixture drives' + serial numbers sort in enrollment order so the names agree. Matching by + serial number on the server comes with the wipe environment. + +Not implemented yet: drive inventory from commissioning, the in-band methods +other than overwrite and their evidence, the evidence check and its reasons, +and the plan-derived deadline. + +### Cutover decisions + +Each decision was made while building Increment C. Each is open for review by a +person. + +- **Allocation names.** An allocation is named from the Machine UID within its + consumer project, and its labels record both UIDs. A retried create then + collides with the first, and equal Machine UIDs in two consumer projects + never share an allocation. +- **Lost custody is not repaired.** An allocation that never held its Device is + deleted and the allocator selects again, because it exposed nothing. An `Active` + allocation that lost custody means the records disagree about who holds a + server a customer may be using. Fleet leaves it to an operator. +- **Release gates.** Access closes at once, because no mode provisions it. + Network and Address close on the absence of every interface claim, because + the network owner keeps a claim until it detached the port. +- **Wipe retries.** A wipe that ended `Failed` sent nothing, so a new step is safe. + A wipe that ended `OutcomeUnknown` may have written to disks, so only a + `DeviceRecovery` `Retry` allows another. +- **Sites are configuration.** The sites that serve a Device are explicit + coordinator configuration, because inventory has no sites field yet. They are + never inferred from placement. +- **Three identities in every mode.** The coordinator is the only custody writer. + The provider and the release controller each create only their own operation + kinds. One identity per component keeps one writer per surface and lets the + creator rule tell the callers apart. +- **The creator webhook shares `fleet-registration`.** The caller, transport and + provider scope are the same, and the handler keeps no state. +- **Fixture discovery writer by mode.** In standalone the simulator site writes it. + In synthetic staging the manager writes it, because the staging site has no API + credential. In multi-plane a separate discovery identity on the workstation + writes it, in both modes. +- **No migration.** The old records are deleted and nothing reads them. Fleet + keeps no legacy compatibility, and re-importing records is acceptable. +- **Quota follows the Machine.** The quota claim is named from the Machine, as + its allocation is. A Machine deleted before its allocation existed, such as + one still waiting for capacity, releases its claim by that name. +- **Each worker reads only its Device's credential.** Each Device has its own + BMC credential Secret, named from the Device (`bmc-` and 20 hex digits of + the Device's SHA-256), bound to it by the discovery contract and its + approved pin; there is no shared credential. No handoff field names a + Secret. kro derives the name from the Device the operation's own assignment + names, as the site does, and grants the operation's worker `get` on exactly + that Secret, with no list or watch. Only a handoff whose Device is its + assignment's gets that Role; any other gets no grant, and its worker + refuses it. The API refuses a handoff that names a credential, so no input + can get a worker another Device's Secret. The worker + refuses a handoff whose Device is not its assignment's, reads the Secret + with one get, and still requires the contract's annotations and pin. + Admission lets kro create a credential Role only of that shape. The + `delivery-faults` phase forges a handoff naming another Device's credential, + and one whose assignment names another Device, and checks that the first is + refused, the second gets no Role, and no Role grants that Secret. +- **The observer deletes answered results.** The site observer is the only + handoff status writer, and it deletes the site's copy of a result once the + coordinator answered it. Its mount of the site store is therefore writable. +- **One staging process, three identities.** Synthetic staging runs the + coordinator, the Metal provider and the release controller in the manager + process with three credentials. Each write carries its component's identity, + but one process can act as all three. This is the synthetic seam, not + production separation. + +### Extension points for power and commissioning + +The agent rebuilding `DevicePowerOperation` on this foundation asked for +these seams. Each is decided here. + +| # | Seam | Decision | Status | +| --- | --- | --- | --- | +| 1 | Kind checks see the Device the snapshot records, an injected clock and the discovery interval | Checks get the Device object the snapshot is built from, `Admission.Now` and `Admission.DiscoveryInterval`. Before the custody update, the coordinator reads the Device again. If its resourceVersion changed, it decides again, so discovery cannot change between the check and the update unseen. | Implemented and inert | +| 2 | Pending replacement is scoped to the kind and the authority | A newer pending operation replaces only an older one of the same kind under the same authority. A power request never cancels a pending installation. | Implemented and inert | +| 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | +| 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | +| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal, or a site result, with an undeclared reason is recorded as `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. The site framework's own reasons are shared, and the Redfish workers' reasons are declared on their kinds. | Implemented and inert | +| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it, and the operation created after a `Retry` is named from the held operation and that count, as [Retries](#admission) describes. | Implemented and inert | +| 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse 19 forbidden writes, eleven of them to the commissioning kinds, and removes them. | Implemented and verified in the local end-to-end runs | +| 8 | Journal steps carry a kind's payload | A step records a payload of at most 1 KiB, such as the send time or the power state before, journaled before it is sent. Observation after a crash reads it back. | Implemented and inert | +| 9 | Delivery carries the admission time, and kinds declare a start-by window | A kind that implements `StartBy` refuses as `Stale` when its worker starts later than the window after admission, with nothing sent. A worker resuming steps an earlier worker sent is not stale. | Implemented and inert | +| 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only, through the Redfish client's identity walk. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, and drives the System through a connection bound to it. | Implemented and inert | +| 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. Whether anything was sent comes from the journal. | Implemented and inert | +| 12 | The single writer of `Machine.status.power` | The manager's `PowerProjector` is the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists, or custody is unverified, it reports power `Unknown`. Otherwise it reports the power state discovery last observed. A Machine with no active allocation has no power. The harness runners call the same projection. A power operation's evidence becomes a second source when the power kind exists. | Implemented and verified by the standalone smoke, which reads the projected state | +| 13 | A deadline from the operation's inputs | `DeadlineFor` replaces the kind's fixed `Deadline` at admission. Commissioning uses its plan's burn-in duration plus one hour. | Implemented and verified by `TestCommissioning` | +| 14 | Evidence kept past retention | `KeepsLatest` keeps each Device's latest succeeded operation of the kind. Commissioning uses it, because the capacity projector reads it. | Implemented and verified by `TestCommissioning` | + +Rows 1 to 11 keep the status recorded when Increment A added them. The +install and wipe kinds use some of them, such as step payloads and the refusal +rule. No power kind exists yet, and commissioning uses neither, so no shipped +kind uses the settle hook or `Supersedes`. None of these conflicts with #174. + +## Commissioning + +This implements the kinds of the [commissioning +proposal](https://github.com/datum-cloud/fleet/pull/185). Step 1 is +**implemented and inert**: custody admits, holds and settles commissioning, +but no site runs its worker. Staff with the commissioning operator role can +still create one. It then holds the Device as `Service` until its deadline +and ends `OutcomeUnknown`, leaving a commissioning hold that only a later +commissioning settles. Every mode's coordinator role can read the new kinds, +which a test pins, because the coordinator lists every registered kind. + +- **Plans.** `DeviceCommissioningPlan` has an immutable spec with a creator, a + non-empty Device selector, plans it supersedes, the content the site runs, + and an evidence lifetime of 1 hour to 365 days. Burn-in runs 1 minute to 24 + hours. No spec holds an object UID. An approval's name is the plan's name + and a suffix derived from the plan's UID (`custody.ApprovalName`), and its + spec names the plan's generation and the digest of its whole spec + (`custody.PlanDigest`). A commissioning names the plan the same way plus + the approval's name, which pins the plan incarnation. The creator webhook + governs all three, so each creator is the caller. +- **Qualified.** An approval qualifies its plan when it has the plan's + approval name, names the plan's current generation and digest, and its + creator is someone else: both creators have a username and the usernames + differ ignoring case. A client certificate carries no UID, so UIDs are + compared only when both creators have one, and then they must differ. A plan re-created under the same name has + another approval name, so it inherits no approval, and no commissioning + under the old plan is admitted under it. +- **Two people in IAM.** The username comparison is only the last check. The + rule it backs is an IAM rule: the plan author and plan approver roles are + never bound to the same principal, nor to groups that share a member, and + no role grants both. Fleet does not own IAM bindings, so it cannot refuse + such a binding when it is made; the role descriptions state the rule for + whoever binds them. A test pins what Fleet packages: no role, counting the + roles it inherits, both writes and approves plans, and no packaged + PolicyBinding grants one subject both. +- **Residual window.** Admission reads the plan and its approval before the + custody update, which re-checks only the Device. A plan revoked in between + can still be admitted once. The capacity projector reads the Device's + current plan, and so its qualification, again on every pass, so that run + cannot make a server `Prepared` under a revoked plan (see [Capacity + status](#capacity-status)). +- **Current plan.** The qualified plans whose selector matches the Device's + labels, minus those another of them supersedes. One left is the current + plan. None left with none matching is `NoCurrentPlan`. More than one, or + none left because the matching plans supersede each other, is + `PlanAmbiguous`. A supersession reaches only Devices the superseding plan + selects, and revoking it restores the old plan. `supersedes` names plans, + so a plan re-created under a superseded name stays superseded. That fails + closed: the plan inherits no approval, only the supersession. +- **Admission.** Two staff rows: from `None`, and from `Service` only to settle + a commissioning hold. The kind refuses a Device that is not `Active`, one + without a `primary` interface MAC (`BootInterfaceUnknown`), a plan that is + missing, re-created or not qualified (`PlanNotQualified`), a copied + content, generation or digest that differs from the plan (`PlanMismatch`), and a plan that is + not the Device's current plan (`PlanNotCurrent`). +- **Results.** A proven verdict ends `Succeeded` with result `Passed` or + `Failed` in its evidence. Every result must record the serial number, + system UUID and BMC key the admission snapshot holds, so no verdict is + about another server. A `Passed` result must also record hardware that + meets the plan, every firmware baseline at its version, and a passed + burn-in at least as long as the plan's. A `Failed` result must name the + phase and what failed. Other evidence proves nothing, and the operation + ends `OutcomeUnknown`. Evidence is limited to 16 KiB. +- **Retention.** Each existing Device incarnation's latest succeeded + commissioning is kept past retention. Once the Device is deleted or + re-created, the old incarnation's record ages out normally. +- **Holds.** Only a later commissioning that ends `Succeeded` with a + `Passed` result settles a commissioning hold. A `Failed` verdict proves the + server unfit, not that an earlier run cut off mid-flash or mid-burn-in + left it as the plan says, so the hold and the `Service` holder stay. + Rebuild applies the same rule to the evidence the operation recorded. It + needs no `Retry`. + +The boot interface is fixed at `primary`, like the allocator's in every mode. + +### The Redfish commissioning worker + +The Redfish worker for `DeviceCommissioning` is **implemented**. It is tested +against a TLS BMC stub, and the multi-plane Redfish site runs it against the +lab emulator in its `commission` phase (see [Capacity +status](#capacity-status)). The lab adapter reports each target's serial, its +one disk and a firmware inventory. No production site registers it yet. + +- **Preflight.** It reads the system's identity, processors, memory, storage, + network interfaces and firmware inventory with GETs only. A serial number + or system UUID other than the admission snapshot's gets no verdict: the + operation is refused with `DeviceIdentityMismatch` before anything is sent. + Otherwise it compares the hardware and firmware with the plan, and a + mismatch is a `Failed` result with nothing sent. The passing evidence is + stored before burn-in sends anything, and a resumed worker reuses it. +- **Collections.** Every member of each hardware and firmware collection is + read, following `Members@odata.nextLink`, so no component goes uncounted + or unchecked. A collection that reaches 1,024 members or 64 pages, or a + Storage controller set that links 1,024 drives, fails the inspection + rather than being read in part. Each GET is bounded by the Redfish + client's per-request timeout, 30 seconds for a pinned client, and the + whole inspection by the operation's deadline. +- **Firmware.** A baseline component matches the inventory entry whose `Id` + it names. Only when no entry has that `Id` does it match by `Name`, and + only a `Name` exactly one entry has: a BMC may list a previous version + beside the running one under the same name. +- **Health.** Only `Warning` or `Critical` is unhealthy. Redfish lets a + component omit its health, and an omitted health counts as healthy. +- **Disks.** Drives come from `Storage`, or from `SimpleStorage` when + `Storage` yields no disk, as on a BMC that links an empty `Storage` + collection. A drive may sit under the System or under a Chassis, and a + drive linked twice counts once. +- **Memory.** An `Absent` or `Disabled` module does not count. +- **Burn-in.** The site serves one burn-in image, and a plan that names + another digest is refused before anything is sent. The worker powers the + server off, arms a one-time network boot, powers it on once, and waits for + exactly one result receipt. The boot server passes the plan's duration to + the image. Burn-in starts when the boot server finished delivering the + image, not at power-on, so firmware start and the network boot do not + count. It ends at the last time a worker saw the console without the + receipt, which is never after the image reported. A worker stores that + time at least every 30 seconds while burn-in runs, and exactly when it + sees the receipt appear. A worker restarted after the receipt appeared + uses the stored time, so a restart can shorten the recorded burn-in but + never lengthen it. With no stored time, the burn-in measures zero. A + burn-in shorter than the plan's duration is a `Failed` result. Its + mismatch says the image reported early when a worker watched the receipt + appear, and that the burn-in could not be proven long enough across a + worker restart when none did, so staff know a re-run may pass. The boot + server and the worker share the site's clock. The local VM worker times + burn-in the same way. +- **Evidence.** Strings the BMC supplies are cut to 128 bytes, and the + component lists are dropped before the verdict if the evidence would pass + the kind's limit. + +## Capacity status + +The capacity projector is **implemented** in every mode, and verified by tests +against a real API server and by the standalone smoke. It derives +`Prepared`, `Healthy`, `Available` and the hardware of every MachineCapacity +from the [commissioning proposal](https://github.com/datum-cloud/fleet/pull/185)'s +inputs, and nothing else writes them. + +- **Where it runs.** The coordinator loop runs it after each pass, with the + projector's own identity: the `fleet.datumapis.com-capacity-projector` role + in Milo, a `fleet-capacity-projector` ServiceAccount in standalone, the + `--synthetic-projector-client-cert-dir` client certificate in synthetic staging, and a + `projector` token in the multi-plane run. The Metal controller role no + longer holds `machinecapacities.updateStatus`. +- **The allocator does not read conditions.** It asks the projector to + evaluate each candidate from live inputs (`Offer`), matches the profile + against the hardware that evaluation returns, and pins that hardware on the + allocation. Custody still decides. It reads each candidate's Device and + custody first and evaluates only identified, visibly free capacity. One + pass lists the provider project's Devices, plans, approvals and + commissionings once, not once per capacity, and so does each projector + pass. A capacity whose reads or evaluation fail is skipped; the error is + returned only when nothing is offered. +- **Grants.** Every identity that evaluates capacity, the Metal provider and + the projector, lists Devices across the provider project, because a + duplicate in any namespace withdraws an offer. + `TestEveryEvaluatorListsDevicesProjectWide` pins that in every mode. `TestOnlyEvidenceOffersCapacity` edits a + failed server's status to `Available` and shows the allocator refuses it and + the projector restores the derived status. +- **Inputs.** The Device and its lifecycle, custody for the same Device UID, + the Device's current plan, its latest succeeded commissioning for the same + Device UID, discovery currency by the admission rule, the cleaning policy + resolver, and whether another Device in the namespace shares an identity + alias anywhere in the provider project. Registration admission checks the + other provider projects when capacity is registered and enabled; the + projector does not read across projects. Aliases moved from registration to + the inventory API package, so both compute them the same way. +- **Device pin.** Registered capacity counts its Device only while the + Device's UID is the one registration recorded when it created the + capacity. Capacity behind a Device recreated under the same name is not + `Prepared` (`DeviceReplaced`), so the allocator never offers it. +- **Hardware ID.** A Device without a hardware ID never backs capacity + ([#131](https://github.com/datum-cloud/fleet/issues/131)). The projector + calls `inventory.CapacityBackingError` on the Device it reads and, when it + fails, reads nothing else and leaves the capacity not `Prepared` + (`DeviceUnidentified`). The allocator makes the same check on the Device it + reads, whatever the evaluation offered. + `TestAServerWithoutAHardwareIDIsNeverOffered` and + `TestTheAllocatorNeverSelectsAServerWithoutAHardwareID` pin both. +- **Plan pin.** `Prepared` needs the latest commissioning's evidence to name + the current plan's name, generation, digest and approval name. The approval + name is derived from the plan's UID, so evidence under a plan recreated with + the same name and content proves nothing (`PlanChanged`). +- **Cleaning policy.** The projector takes a resolver that returns a digest, + `ErrUnresolved`, or another error, which makes `Available` `Unknown`. Standalone, synthetic staging and the multi-plane lab read and validate the + named CleaningPolicy in the provider namespace. The allocator re-reads it + before pinning its exact content. +- **Simulated commissioning.** The simulator site runs a `DeviceCommissioning` + worker that inspects the hardware and firmware its enrollment records for + the Device. Its burn-in sends nothing and takes no time: it journals one + step named `simulated-burnin` and records the plan's duration, so its + evidence is synthetic and says so. The enrollment gains `hardware` and + `firmware` fields for it. +- **Standalone.** A `commission` phase runs before `allocate`, as three + ServiceAccounts: a plan author, an approver and an operator. The fixture + Device carries a `fleet.datumapis.com/hardware-model` label that the plan + selects. The smoke checks that the provider cannot write capacity status + and that the author cannot approve. +- **Multi-plane.** The provider project gets the projector, the three staff + identities and a capacity operator, and the Metal provider reads + commissioning evidence. The seed no longer writes capacity conditions. A + `commission` phase runs before `allocate` in both runs: the plan author + writes the local plan, another identity approves it, the operator + commissions the Device, and the phase waits until the projector offers the + capacity. The seeded Device carries the `fleet.datumapis.com/hardware-model` + label the plan selects. The plan requires the fixture profile's hardware + and a one-minute burn-in of the site image. In Redfish mode it also requires + the lab's firmware inventory; the local VM reports no firmware, so its plan + has no baseline. + - The site needs a worker before any allocation exists, while the install + must still be delivered before any worker Job for the partition scenario. + So one source revision enables dispatch for the commissioning and the next + disables it again, and kro prunes the finished commissioning's Job. Its + handoff stays delivered and answered, and the install's scenarios count + only the other assignments. When dispatch is enabled again, or the graph + lifecycle recreates the workers, kro recreates the commissioning's Job: + it replays a verified no-op, or the site refuses it at exit 65 once the + install raised the Device's fence. It sends nothing either way. + - The local VM site runs a `DeviceCommissioning` worker. The local VM has + no BMC, so inspection compares the hardware the site enrolls for the + Device, which describes the guest it defines, with the plan. Burn-in is + real: one network boot of the site image in burn-in mode on a scratch + disk, proven by its one console receipt, after which the scratch disk is + removed. It is timed like the Redfish worker's, from the boot server's + delivery to the last sighting without the receipt, so a site that boots + its guest directly, with no boot server, refuses commissioning. + - The Redfish site registers the Redfish worker against the lab emulator. + The `redfish-commission-mark` step requires exactly one effective `On` to + target A, one passed burn-in receipt and no effect on target B, and the + later Redfish counts start after it. + - The harness keeps commissionings out of its install and wipe evidence by + their site key. +- **Synthetic staging.** The staging handler no longer writes capacity + status; the projector does. + +## Points for a person + +These need a decision before the increment that depends on them. + +- **Who approves commissioning plans.** No team holds the plan approver role + in any deployed environment yet, so no plan qualifies there. The roles keep + the author and the approver apart by username. +- **O10: the sealed store for bootstrap payloads.** Chosen and implemented as + `SealedPayload`; see [OS images and bootstrap data](machine-images.md). +- **Machine status writes by consumers in Milo.** Milo's authorizer, with + subresource authorization off, checks a status write against `update` and + `patch`, which the consumer and claimant roles hold. The power webhook refuses + their power changes, but they can still write every other Machine status + field. Closing it needs subresource authorization enabled in Milo, the + Machine ProtectedResource to declare its status subresource, and the + controller role alone to hold `machines/status.update` and `.patch`. +- **The power guard in synthetic staging and the multi-plane local Milo.** + Neither runs `fleet-registration`, so neither has the power webhook, as + neither has the creator webhook. +- **A second person for `DeviceRecovery`.** Not required yet. A person + accepted this for now, and it stays open for a later decision. +- **Synthetic staging needs its records imported again, new credentials and + roles, and its old namespace deleted.** The cutover deletes the old records + and reads none of them. Before the new manager runs in an environment, a + person must, in order: + 1. Release every old synthetic allocation, or discard the synthetic state. + 2. Make sure each Device, with its BMC endpoint and identity, and each + capacity exists in the provider project. Records GitOps already manages + stay with it; import by hand only the ones it does not. + 3. Create three Milo identities that sign in with client certificates, + bound to the `fleet.datumapis.com-device-coordinator`, + `fleet.datumapis.com-device-wipe-requester` and + `fleet.datumapis.com-capacity-projector` roles, and issue each a + cert-manager client certificate. + 4. Grant the manager's own identity, the Metal provider, the + `metal.datumapis.com-controller`, + `fleet.datumapis.com-device-installation-requester` and + `fleet.datumapis.com-inventory-discoverer` roles in the provider project. + Bind these roles and the projector's on the project, not on one + namespace: evaluating capacity lists Devices in every namespace. + 5. Supply the site's enrollment. + 6. Delete the old `fleet-system-private` namespace and its Secrets. + 7. Delete the publisher's copy of the MachineClass in the consumer project. + Its source names the old `project` field and is immutable, so the + publisher recreates it with `publisherRef`. + 8. After rollout, verify a fresh allocation and a verified release. + + The commands are in [Moving from the Secret-backed + staging](../../config/README.md#moving-from-the-secret-backed-staging). No + run in this repository exercises synthetic staging, so a person runs these + steps in a staging environment before merge. +- **Retiring the single-plane local VM harness.** C removed + `hack/local-vm/run.sh`, `task local-vm:acceptance` and `cmd/fleet-local-vm`, + because the multi-plane local VM mode runs the same workers. A person should + confirm that the single-plane run is not needed. +- **The multi-plane creator webhook gap.** The local Milo in the multi-plane run + enforces the CRD rules but registers no creator webhook. A forged + `spec.creator` is therefore not refused in that run, and the run does not + prove the webhook. A person decides whether the run must install it. + +Already decided by a person: [where an allocation's private facts +live](#where-an-allocations-private-facts-live-o8), that [only `Retire` and +`Resolve` skip checks 5 and 6](#admission), and that a `DeviceRecovery` that +no site confirms ends `Failed`, not `OutcomeUnknown`. The [cutover +decisions](#cutover-decisions) are recorded for review and are not yet +confirmed by a person. + +## Adding an operation kind + +A new kind, such as `DevicePowerOperation` or `DeviceCommissioning`, plugs into +four seams. It needs no change to the coordinator. The test-only kinds in +`internal/custody/testkinds_test.go` use every seam. Copy them. + +1. **Register the kind.** Add a `custody.Kind` to the registry with: + - its GroupVersionKind, constructors, and an `Items` adapter; + - a digest of its exact inputs (`custody.SpecDigest` covers the whole + spec); + - its naming rule: `DeterministicName` with a `Name` function for provider + and release kinds, or `GeneratedName` for staff kinds. A row can override + it with its own `Naming` and `Name`. An operation created after a `Retry` + is named by the coordinator's retry rule instead; + - its `Deadline`, and `Effectful` if it can reach the server; + - `Supersedes`, if a newer pending operation of the same kind and the + same authority should cancel an older one, as power needs. It never + cancels another kind's operation; + - `Check` for kind-specific admission checks. They run after the shared + preconditions, before the custody update, and return a named refusal, + such as power's `SystemUUIDMismatch` or `DiscoveryNotCurrent`. A check + sees the same Device object the snapshot records, the coordinator's + injected clock as `Admission.Now`, and `Admission.DiscoveryInterval`. + A refusal whose condition can clear by itself sets `Wait`, the most a + queue row's operation waits for it in `Pending`; + - `Reasons`, every refusal reason the kind raises, each marked as raised + by the coordinator, the worker, or both. A refusal with a reason that is + neither shared nor declared is recorded as `UndeclaredReason`; + - `SnapshotExtra`, for bounded fields the kind adds to the snapshot, such + as the reset types discovery offered. The worker and a recovery see + what admission saw; + - `Settles`, the held kinds a success settles, with `RequiresRetry` when a + `DeviceRecovery` `Retry` must come first. It may be empty; + - `Retryable`, if a `DeviceRecovery` with `Retry` applies to the kind's + holds. + + Embed `OperationEnvelope` inline in the spec, and use `OperationStatus` as + the status. Add the CRD with the same envelope, the immutable-spec rule and + the phase rule, plus a ProtectedResource and roles. +2. **Add its rows.** Add one `custody.Rule` per row of the #174 operations + table: the creator class, the authority type, the holders it admits from, + its hold behavior, and whether it queues. A holder admitted only under the + kind's own hold, such as `Service` under a power hold, is a separate row + with `HoldSettlesRequired`. Staff rows never queue. To admit + a new service principal, add its class to the coordinator's principal + configuration. Never hard-code an identity. +3. **Implement its site worker.** Implement `site.Kind`: `Check` runs after the + framework's checks and must not change the server, and checks the + capabilities the kind uses. `Run` performs every effect through + `Work.Step` with a `site.Step`. Give each step a bounded `Payload` for what + its observation needs, and an `Observe` that reads the server and that + payload to show whether the step took effect, for replay after a crash or + a lost response. Mark a step `Idempotent` only if sending it twice is + harmless. Implement `site.StartBy` if the work must begin soon after + admission. Return the + typed evidence. The framework owns the fence, the journal, the credential + lookup, the TLS pin and identity checks, the deadline, and result delivery, + and a kind never implements them. A Redfish kind reads its connection from + `Work.Connection` as a `*site.RedfishConnection`. Register the worker in + the site's `Runner.Kinds` under the kind's name. See + `internal/site/redfishwork` and its tests. +4. **Define its evidence.** Set `Evidence` to `custody.StrictEvidence` over a + typed, bounded Go struct. Its validator receives the operation, and sees + the evidence of every phase, so it checks only what holds for all of them. + Set `EvidenceRequired` if a success without evidence proves nothing, and + `ProvesSuccess`, with `custody.TypedProof`, to require what only a success + must prove, such as reset proof for a restart. A success it rejects ends + `OutcomeUnknown` with `InvalidEvidence`, under a hold. Unknown fields, oversized evidence and trailing + data are rejected, and the result then proves nothing. Evidence never + carries a credential or a raw BMC response. If a `DeviceRecovery` `Settle` + can settle a hold of the kind, set `RecoverySettle` to validate the staff + evidence. The hook sees the hold, with when the held operation ended + (`Since`), its deadline and its admission snapshot, and the Device as read + when the hook runs. A hold that rebuild created may lack the deadline and + snapshot, and its `Since` is the rebuild time. Power, for example, accepts only a power state that + discovery read after the operation ended. + +Test the kind with the shared harness in `internal/custody`: register it +beside the defaults, and run its refusals, admission, results and holds +against a real API server. + +## Device power operations + +This section records how Fleet implements the power kind of the [device power +operations proposal](https://github.com/datum-cloud/fleet/pull/173) (#173, +pinned at `d6744ab`) on this foundation. Step P1, the control plane, is +**implemented**: the coordinator admits, holds and settles power operations in +every mode the cutover wires. Step P2, the site worker, is **implemented** +behind the site worker contract. Nothing creates power operations yet. It +follows [Adding an operation kind](#adding-an-operation-kind), and adds the +two [foundation seams](#foundation-seams-power-added) below. The worker +changes no coordinator behavior and no site framework code, and adds only +reasons to the kind's reason table. The kind joins the creator webhook's +governed kinds, standalone's creator policy and each coordinator's access, and +`TestEveryOperationKindIsGoverned` requires every operation kind to be +governed. + +| Piece | Decision | +| --- | --- | +| Inputs | `action` is `On`, `ForceOff`, `ForceRestart` or `PowerCycle`. A staff operation requires `expectedSystemUUID`, in lowercase canonical form. Its reason is the envelope's `serviceRequest.reason`, which is already required, rather than a second field. A provider operation omits `expectedSystemUUID` and requires `machineGeneration`. CEL enforces both. | +| Names | The kind's rule is a generated name, which the staff rows use. The provider row sets its own rule: `-power-`, so its allocation name is at most 200 characters. A retry takes the foundation's retry name, and a staff retry created before its `Retry` waits in `Pending`. | +| Rows | The Fleet provider for Metal, with `allocationRef`, from holder `Allocation`, queued. Staff, with `serviceRequest`, from holder `None`, and from `Service` only to settle a power hold. | +| Admission checks | `SystemUUIDMismatch` compares `expectedSystemUUID` with the recorded UUID. `DiscoveryNotCurrent` requires the inventory read to come from the current BMC endpoint, within twice the discovery interval on the injected clock, and to include the recorded system. `ResetTypeNotOffered` refuses only when discovery observed the system's reset actions and they lack this one. Otherwise, as when the BMC offers none or discovery could not read its ActionInfo, admission goes ahead and the worker checks the live BMC, ending `Failed` with nothing sent if the action is not offered. Discovery marks each system whose reset actions it read in that pass, even when the list is empty, and only that mark counts as observed. `SystemUUIDNotRecorded` refuses a staff request for a Device with no recorded UUID. These run before rules 5 and 6, so their reasons are the ones reported. Discovery can return, so a provider operation refused `DiscoveryNotCurrent` waits in `Pending` for up to twice the discovery interval, counted from when it was created or the Device's last operation finished, and only then ends `Failed`. A staff operation fails at once. | +| Snapshot | `resetTypes`, the power actions the system offered; `systemID`; and `resetTypesObservedAt`, when discovery read them. | +| Replacement | The kind sets `Supersedes`, so a newer pending provider operation for the same allocation replaces an older one. It never replaces another kind's operation or the operation that settles a hold. Under a hold, newer operations wait in `Pending`. Only an operation the provider row admits replaces anything, so staff requests, and a staff request naming a customer's allocation, replace nothing. | +| Holds | A power success settles only a power hold, and only after a `DeviceRecovery` with `Retry`. Power is `Retryable`. | +| Settle | The Device's discovery must have read the BMC after the held operation ended, from its current endpoint, and read the recorded system `On` or `Off`. The recovery must cite that state in `evidence.data.powerState`, with an `observedAt` after the operation ended. Otherwise the recovery ends `Failed` with `PowerEvidenceNotCurrent`, `PowerEvidenceWrongEndpoint`, `PowerStateNotSettled` or `PowerEvidenceMismatch`. | +| Evidence | `requestSentAt`, `power.before`, `power.after` and `resetEvidence`, typed in the CRD and decoded strictly, at most 1 KiB, and required for a `Succeeded` result. Observations are in time order. `resetEvidence` needs a sent command, and only a restart or power cycle may carry it. A success must also prove itself: both reads, `power.after` in the requested state (`Off` for `ForceOff`, `On` otherwise), a sent command unless `power.before` already showed that state, and for a restart or power cycle, a sent command and `resetEvidence`. Anything less ends `OutcomeUnknown` with `InvalidEvidence`, under a hold. They are recorded in `status.evidence`, where every kind's evidence lives, not at the top level of status as #173's example shows. | +| Roles | The **device power operator** inherits the viewer and creates only `DevicePowerOperation`. It does not read MachineAllocations. The **device power requester** is the Fleet provider for Metal's role. The viewer and coordinator cover the new kind. | +| Discovery | Power reads the `ComputerSystem.Reset` types the Device's observed System offers, which BMC discovery records with GETs only. | + +### The power worker + +| Piece | Decision | +| --- | --- | +| Before the command | The framework checks the credential, the pin and the System's identity. The worker then checks the expected system UUID against that System (`SystemUUIDMismatch`) and that the BMC still offers the action (`ResetTypeNotOffered`). It reads the power state once: a transition state refuses with `PowerStateNotSettled`, and a restart or power cycle of a server that is off refuses with `NotPoweredOn`. Each refusal sends nothing and ends `Failed`. | +| Start-by window | Two minutes after admission. A later start with nothing sent ends `Failed` with the shared reason `Stale`. | +| Already in the requested state | `On` of a server that is on and `ForceOff` of one that is off send nothing and succeed, with no `requestSentAt`. | +| The one reset | One journaled step. Its payload records when the command was sent, the power state read before it, and the BMC's `LastResetTime` as the baseline. A response the BMC returns refusing the command is an error. A lost response is not: the worker watches for the effect. | +| Success | `On` and `ForceOff`: the requested state appears within three minutes of the command. A restart or power cycle: the BMC's `LastResetTime` moves past the baseline, or the worker sees the server off, and then the server is on again. `resetEvidence` records which. When the BMC reported no reset time before the command, only seeing the server off proves a restart. A restart the server made by itself between the baseline read and the command would also move the reset time; the window is one request long, and the BMC's clock is not trusted enough to compare against the send time. | +| Crash or lost response | A resumed worker reads the journaled payload instead of reading the server again, and watches for the effect. It never sends a second reset. | +| Not proven | A reset whose effect does not appear in time, a BMC that refused the command, and a BMC that starts reporting another system after the command all end `OutcomeUnknown`, which places a recovery hold. | +| Registration | A Redfish site registers the worker as `DevicePowerOperation`. The local VM and simulator sites have no BMC and no power worker, so they refuse a power operation as an unsupported kind, with nothing sent. | + +The lab BMC records `LastResetTime` and adds faults for a withheld request, a +hidden reset time and an identity swap, as [the Redfish +lab](../operations/redfish-lab.md) describes. + +### Customer power + +| Piece | Decision | +| --- | --- | +| Request | The Metal provider asks the allocator for the Machine's power. `powerState` `On` is the action `On`, and `Off` is `ForceOff`. `powerState` has no default: unset means Fleet does not manage the Machine's power, and no operation is created whatever the server's state, so a freshly installed server that boots on is never forced off. A request created before `powerState` was cleared still runs. Machines stored with `Off` before the default was removed keep it, and stay managed. The operation is named from the allocation and the Machine generation, so a refused one is not created again until the generation changes. A request whose discovery lapsed waits in `Pending` instead, as [the admission checks](#device-power-operations) describe, and runs once discovery reads the server again. If discovery stays away past that bound, the request ends `Failed` and, like any refused one, is not created again until the generation changes. | +| When it is due | When `powerState` differs from the Machine's observed power, or when this allocation's request for another action has not run yet, so a newer request replaces it. A Machine generation runs at most one power operation, so power that drifts after it succeeded is not corrected until the generation changes. Observed power must be `On` or `Off`, so power not yet observed, or `Unknown`, asks for nothing, and no server is forced to a state before its power is known. | +| During a power hold | Observed power is `Unknown`, so nothing is created. After staff apply a `Retry`, the provider creates the retry under the foundation's retry name, repeating the held operation's inputs, and only while `powerState` still maps to the held action. Otherwise staff settle the hold, and the newer request runs after it. | +| Observed power | The manager's power projector stays the only writer of `Machine.status.power`. It reports `Unknown` during any hold or unverified custody, and otherwise the newer of discovery's power state and the state custody's last succeeded power operation proved, a tie going to the operation. When any other operation except a recovery finished at or after discovery's read, power is `Unknown` until discovery reads it again, because that operation may have changed it. | +| Simulator | The simulator site registers a power worker for its simulated servers, and its fixture discovery reports each server's power and offers every action. A restart is proven only by the server's reset time moving to the command. The reset step journals the power read before the command and the send time. A resumed run, whether the step finished or not, reports both, and never treats the command's effect as a server that needed none. A test-only fault makes a server ignore resets, so a power operation ends unknown. | +| Not yet wired | No running provider calls the power request. The synthetic staging provider accepts only Machines that ask for power `Off`, and the harness runners do not change power. | + +### Foundation seams power added + +Power needed two general seams in the foundation, and adds them rather than +working around their absence: + +- **A kind check can wait.** Rule 7 runs before rule 5, and a kind check + could only refuse, so a short discovery lapse failed a provider power + request for good: it is named from the Machine generation, and is not + created again until the generation changes. A check refusal now sets + `Wait` for a condition that can clear by itself, and a queue row's + operation waits for it in `Pending`, bounded as above. +- **A kind can require proof of a success.** The evidence hook sees every + phase's evidence, so it could not require what only a success proves, and + a `Succeeded` restart with no reset proof, or with the empty object `{}`, + was accepted. `ProvesSuccess` runs on a `Succeeded` result's evidence only. + +### Worker gaps that remain + +Each needs a change in the site framework or the harness, and none is worked +around here. + +- **No end-to-end run creates a power operation yet.** Both multi-plane runs + and the synthetic staging write fixture discovery, which reports every + server off and records no reset types. Admission then leaves the reset-type + check to the worker's live read, but no run's phases create a power + operation, and a `Settle` has no real power state to cite. The power phases + need real BMC discovery in the Redfish run, or fixture discovery that + reports the server's power. +- **The two-minute start window against delivery latency.** A power worker + that starts more than two minutes after admission refuses as `Stale`, with + nothing sent. The multi-plane harness allows up to about eight minutes for + Karmada delivery, kro and the worker Pod, so a slow delivery would fail a + power operation safely once a run creates one. +- **A swap before the command is reported as `DeviceIdentityMismatch`.** The + framework verifies the System's identity before a kind runs, with the + shared reason. #173 names this refusal `SystemUUIDMismatch` at the worker. + Power raises `SystemUUIDMismatch` only for a swap after the framework's + check. +- **A command the BMC refused ends `OutcomeUnknown`, not `Failed`.** Once a + step is journaled, the framework ends any refusal as `OutcomeUnknown`. + #173 asks for `Failed` when the BMC refused and the power state did not + change. The result is safe, but it places a hold that a recovery must + settle. + +## Tests + +Run `task test:envtest`. It runs these tests with the race detector against +a real API server: + +| Area | Tests | +| --- | --- | +| Every admission precondition, names, kind checks, the sealed bootstrap payload check, staff expiry | `TestAdmissionPreconditions` | +| Every holder transition, pending order, supersede, cancellation on holder change, stale fences, results, deadlines | `TestLifecycle`, `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing` | +| Holds and settlement through the test-only kind, install and wipe holds, `Retry`, `Retire`, retention | `TestRecovery` | +| Rebuild from each source, each conflict, `Resolve`, custody deleted and restored | `TestRebuild` | +| Rebuild holds unproven and unfinished installations and wipes without admitting them again, settled outcomes, several unproven outcomes, `Resolve` against live allocations, fences above the site's, retirements kept past retention | `TestRebuildKeepsUnprovenOutcomes` | +| Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | +| A claim and its installation landing between the custody read and the operation list | `TestARefusalNeverUsesCustodyReadBeforeAHolderChange` | +| Admission above the fence a site has seen; a recovery confirmed only by the stopped fence; a held operation never a candidate | `TestFencesFollowTheSiteReport`, `TestAHeldOperationIsNeverACandidate` | +| Replacement only after the permission checks, staff never replacing, naming per row, a kind's reason before the shared identity check, a staff retry waiting for its Retry, evidence checked against its operation and required | `TestRowsAndReplacement` | +| The extension points: the Device the checks see, scoped replacement, snapshot fields, the settle hook's hold fields, declared reasons, `Retryable`, a worker refusal returning a staff holder to `None` | `TestExtensionSeams`, `TestRegistryValidatesDeclaredReasons` | +| A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | +| CEL rules | `TestCRDRules` | +| Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | +| Creator recording and caller preservation, including callers whose credential carries no UID | `TestHandler`, `TestCreatorAgainstAPIServer`, `TestStandaloneCreatorPolicyAgainstAPIServer`, `TestCreatorIdentifiesTheCallerByUsername` | +| CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | +| Power: each refusal with custody unchanged, both rows and every other pair, staff racing an allocation, replacement only by the provider row and waiting under a hold, expiry, an early staff retry settling after `Retry`, `Settle` evidence, required evidence, a provider request waiting for discovery (its bound, its replacement, and two coordinators admitting it once), and proof of a success, including a retry's | `TestPowerOperations` | +| A check refusal that waits only on a queue row, within its bound from when the Device was last free, and only with a declared reason; proof of success needs required evidence | `TestExtensionSeams`, `TestRegistryRequiresEvidenceForProofOfSuccess` | +| Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` | +| Customer power: an unset `powerState` leaving power unmanaged after an install until the Machine asks for `Off`, power under an allocation, waiting behind an installation, a newer request replacing a pending one, a hold reporting `Unknown` through release and settling with fresh discovery, a retry repeating only the held action, a request waiting through a discovery lapse | `TestCustomerPower` | +| Power worker: one reset per action and its proof, sending nothing when already in the requested state, each refusal with nothing sent, a lost response, a request never applied, an unprovable restart, a swap after the command, a resumed worker, two workers for one assignment | `go test ./internal/site/powerwork` | +| The BMC's reset time and the lab's power faults | `TestObserveReadsTheLastResetTime`; the lab adapter self-test | + +Increment A has no site, so "nothing was sent" means custody admitted nothing +and the fence did not rise. Increment D's phases prove it end to end, with the +site journal and, in the Redfish run, the lab BMC audit. + +Both local end-to-end runs include the `custody-crd-rules` phase. It proves +that a Milo project API refuses every write the CRD rules forbid, which +envtest alone cannot show, because Milo ignores admission policies stored in a +project. + +Increment B's site tests run with `go test -race ./internal/site/...`: + +| Area | Tests | +| --- | --- | +| Stale fences and steps refused, also after a restart; replay observed | `TestStoreRefusesOlderFencesAndSurvivesARestart`, `TestStoreReplaysAJournaledStepAsAnObservation` | +| Two workers on one Device, two Devices in parallel | `TestTwoWorkersOnOneDevice`, `TestTwoDevicesInParallel`, `TestANewerFenceStopsTheOlderWorker` | +| A TLS pin mismatch and an identity mismatch send nothing, against TLS servers | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing` | +| Every pre-effect refusal, stale assignments, deadlines, result deletion, payload validation | `TestPreEffectRefusalsSendNothing`, `TestAStaleAssignmentIsRefusedAndStoresNothing`, `TestAWorkerStopsAtItsDeadline`, `TestResultsAreDeletedOnceTheCoordinatorAnswers`, `TestAssignmentValidation` | +| One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | +| Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | +| Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | +| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap data the installer verifies on disk, bootstrap refused without a payload | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestTheInstallerVerifiesBootstrapDataOverRedfish`, `TestBootstrapWithoutAPayloadSendsNothing` | + +Increment C's tests run with `task test:envtest`, and the smoke runs with +`task standalone:test`: + +| Area | Tests | +| --- | --- | +| Allocation, a losing contender, a retried allocation, installation, reinstallation, release with a wipe, and reuse under a higher fence, against a real API server and a simulator site | `TestAllocateInstallReleaseReuse` | +| Six allocators race for one Device; one allocation remains and custody names it | `TestConcurrentAllocatorsOneWinner` | +| An allocation that never held its Device is deleted and the allocator selects again | `TestAnAllocationThatLostItsDeviceIsReplaced` | +| The quota claim is named from the Machine and granted once; release is observed, not assumed | `TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce`, `TestReleaseIsObservedNotAssumed` | +| Federation: an assignment's round trip, only this cell's observation accepted, a stale fence report ignored, a cell runs only its own assignments | `TestAssignmentRoundTrip`, `TestReflectionIsRejectedUnlessItIsThisCellsObservation`, `TestAStaleFenceReportIsNoReport`, `TestTheCellRunsOnlyItsOwnAssignments` | +| The local VM site: install then wipe, a wipe that powers off a running guest first and is not proven while the guest keeps running, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | +| Synchronized DHCP follows the open admission; a worker waits for the reservation and for its withdrawal | `TestSyncedDHCPFollowsTheOpenAdmission` | +| The simulator site's token, enrollment and server bounds | `TestReadToken`, `TestReadEnrollmentRequiresCompleteTargets`, `TestNewServerHasFiniteResourceBounds` | +| The manager's synthetic flags, and the creator webhook's trusted caller | `TestSyntheticFlagsRequireAndScopeStaging`, `TestRemovedSingleProjectFlagsAreRejected`, `TestWebhookRequiresTrustedAPIServerClient` | +| Where the component ships | `TestComponentRoots` | +| The standalone smoke: contention, install, a simulator restart and recovery, reinstall, release with a wipe, reuse, and the role checks that keep one writer per kind | `task standalone:test` | + +Increment D's site tests run with `go test -race ./internal/site/...`: + +| Area | Tests | +| --- | --- | +| A worker stopped at its deadline closes its boot admission, in both workers | `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission` | +| A local VM wipe powers off a running guest, and is not proven while it keeps running | `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven` | + +Increment D also adds coordinator tests, run with `task test:envtest`, that +fail if the use of site fence reports is weakened. Each was checked against +the change it guards: + +| Guard | Test | +| --- | --- | +| A recovery on a Device that no site serves is never confirmed | `TestARecoveryOnADeviceNoSiteServesIsNeverConfirmed` | +| A recovery records the lowest fence its sites confirmed, and waits for every site | `TestARecoveryConfirmsTheLowestFenceOfItsSites` | +| A Resolve raises custody's fence above every fence a site has seen | `TestAResolveRaisesTheFenceAboveEverySeenFence` | + +`TestFencesFollowTheSiteReport` already fails if admission ignores the seen +fence, if a recovery is confirmed by the seen fence alone, or if an +unreported site counts as confirmed. + +The multi-plane local VM and Redfish runs (`task multiplane:acceptance` and +`task multiplane:redfish-acceptance`) run the same workers and the failure +scenarios. The acceptance state of each #174 test is in the [coverage +inventory](../../test/acceptance/coverage.md#device-custody-and-operations). diff --git a/docs/development/device-reported-placement.md b/docs/development/device-reported-placement.md new file mode 100644 index 00000000..196fcdff --- /dev/null +++ b/docs/development/device-reported-placement.md @@ -0,0 +1,126 @@ +# Device-reported placement + +[Physical inventory](../operations/physical-inventory.md) · [Staff inventory UI](staff-inventory-ui.md) + +## Implemented contract + +`Device.spec.reportedPlacement` is optional observational data on the existing +physical asset, not another inventory, allocation, or installation identity. +Authorized managers can add the first report or correct an existing report using +ordinary direct API PATCH/PUT. A reported location can change without a new or +superseded installation. This is record correction, **not acceptance of a physical +move, handover, reservation, verified occupancy, availability, or active binding**. +Device identity and claimRef remain immutable. Typed +claim lifecycle and placement constraints remain unchanged. No hardware, status, +capacity, provisioning, allocator, network, IPAM, or routing effects are introduced. + +The first report has `revision: 1`; every changed report increments revision by +exactly one. Unchanged reports need no increment. A report cannot be removed; correcting all its +location fields to unknown retains its revision and evidence. The report is the +**latest snapshot, not append-only history**. Resource audit logs, not a second +per-Device history or bespoke correction service, are the history integration. + +Reports have `observedAt`, a required `reason` and evidence `reference`, optional +`facilityRef`/`rackRef`, and independently optional `position`, `height`, `face`, +`fullDepth`, or a non-unit `mount`. Omission means unknown. `face` is the +mounted rack face, the face the chassis front points toward; readers fall back +from an absent `fullDepth` to the Device and then the DeviceType model shape +([semantics](../operations/physical-inventory.md#rack-faces-depth-and-component-faces)). The editor does not +infer actual geometry from a model or claim. Positive +fractional position/height is valid but only complete integral in-range geometry +is drawn in an elevation. Position is 1–100; height is greater than zero and at +most 100; position + height cannot exceed 101. Geometry requires a rack, and mount +and unit geometry are mutually exclusive. A correction may cite an older +observation. Name-only references are local to the +Device namespace. There is no new cross-object admission or reference transaction: +CEL cannot verify existence, incarnation, actual rack height, or facility/rack +agreement. The editor re-reads selected locations and checks those facts before +dispatch, but a referenced object can subsequently change. + +### Report evidence + +- `reason` and `reference` (evidence) are required and nonblank, each at most + 1024 characters. A report does not say which writer or system produced it: + resource audit logs record who wrote it, and a writer that needs to remember + where the facts came from uses its own labels and annotations. +- Old objects without reports remain valid on creation and unchanged updates. + No migration, delete/recreate, identity replacement or claim rebind is required. + Earlier reports may have carried `method` or `snapshotDigest`; the API server + prunes those fields. A stored report without `reason` or `reference` must gain + both the next time it changes. + +## Authorization and UI + +The existing manager role grants create/update/patch for six inventory kinds +project-wide; this change adds **no privilege**, delete/status or hardware grant. +It does not introduce owner or namespace isolation. Managed-field/Flux markers +are a UI exclusion for GitOps-owned records, not server authorization. +Operator-managed records are eligible for ordinary manager corrections. +Absence of a marker does not prove ownership, and direct API RBAC still applies. +The separate display-name editor retains its older, narrower UI policy. + +Device detail offers **Add reported location** or **Correct location**, an +evidence reference and reason, observation time, unknown geometry and +optional readable facility/rack choices. Forms freeze the target UID and +resourceVersion on open. Saving renews exact patch permission and re-reads the +Device and selected references, checking operation authority after every awaited +prerequisite, including failed reads. JSON Patch tests UID and resourceVersion +**before** adding the report. Stale baselines, replacement, +session switches, blur, navigation, revalidation and unmount cannot authorize a +new dispatch. Rejected patch admission/preconditions require reopening the form. + +Already-dispatched uncertainty remains unknown, with no blind retry. Reference +denials purge restricted choices, input names and cached records. A successful +response must retain UID, advance resourceVersion and match submitted report +fields before success is shown. Inventory queries are invalidated after success, +refreshing directory/filter/location/rack projections. There is no background sync. + +Readers prefer the report; a partial report never borrows claim geometry. Without +a report they retain labelled **Claim-derived fallback**, not verified current +location. Full-depth and continuous multi-U/overlap rendering remain supported. +Multiple registrations do not select an active asset by time or revision. + +## Existing resource audit integration: source-reviewed, not live verified + +The following pinned source revisions were inspected. No +authenticated audit event, deployed audit policy or storage retention was queried +or verified by this implementation. This is not a claim of live audit completeness. + +| Evidence | Source-reviewed coverage and limitation | +| --- | --- | +| [Infra audit policy at e9426d5](https://github.com/datum-cloud/infra/blob/e9426d5676a555ba02a990c89d12c144d750d241/apps/datum-control-plane-system/core-control-plane/base/milo-system/apiserver-configs/audit-policy-config.yaml) | ResponseComplete is retained. Fleet is absent from the mutation RequestResponse groups and therefore falls through to **Metadata**: authenticated user/resource/verb/outcome, not change bodies, correction reasons or before/after documents. Auth checks, watches and unauthenticated requests are excluded. | +| [Infra API-server wiring](https://github.com/datum-cloud/infra/blob/e9426d5676a555ba02a990c89d12c144d750d241/apps/datum-control-plane-system/core-control-plane/base/milo-system/apiserver-kustomization.yaml) and [webhook](https://github.com/datum-cloud/infra/blob/e9426d5676a555ba02a990c89d12c144d750d241/apps/datum-control-plane-system/core-control-plane/base/milo-system/apiserver-configs/audit-webhook-config.yaml) | Existing shared policy and batched webhook to Activity's Vector sidecar. Not a transactional, per-edit audit commit prerequisite. Fleet does not own or replace this configuration. | +| [Milo default policy at 3c2a160](https://github.com/milo-os/milo/blob/3c2a160d6d5614d6dc7bf119b8d022fc641c5d4f/config/components/apiserver-audit-logging/audit-policy-configmap.yaml) | Also defaults unlisted API groups to Metadata; the Infra deployment overrides this default. Editing only the default would not fix that override. | +| [Activity schema at 8958fc5](https://github.com/milo-os/activity/blob/8958fc5ba8e96ec02e246edabe3ba33c1b5ee98f/migrations/001_initial_schema.sql) and [storage model](https://github.com/milo-os/activity/blob/8958fc5ba8e96ec02e246edabe3ba33c1b5ee98f/docs/architecture/data-model.md) | Stores raw event JSON and materialized actor, audit ID, scope, resource and status. Audit TTL moves data to cold storage after 90 days, without a delete TTL in this schema; derived Activities have a 60-day delete TTL. This is configuration evidence, not a guaranteed production retention period or delivery SLA. | + +**Exact gap / smallest integration:** the Infra owner should add +`fleet.datumapis.com` to the existing RequestResponse mutation rule (or a +devices-only create/update/patch RequestResponse rule before the Metadata +catch-all). That reuses existing actor/change logging; no Fleet correction +service, new mandatory storage, or duplicate history is needed. RequestResponse +retains the patch/PUT and response, not an independent pre-change snapshot. +Confirm one authorized canary's audit ID, authenticated principal, target UID, +patch and response through Activity after deployment, plus actual retention and +delivery configuration. Do not claim full change-body history until then. This +specific logging integration gap does not disable ordinary authorized edits. + +## Validation scope + +```sh +go test ./internal/api/inventory/v1alpha1 +go test ./... +go test -race ./internal/api/inventory/v1alpha1 ./internal/controller/... +pnpm --dir ui/provider test +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider build +pnpm --dir ui/consumer test +pnpm --dir ui/consumer typecheck +pnpm --dir ui/consumer build +bash hack/validate-doc-links.sh +git diff --check +``` + +Local CEL/schema, JSON Patch, IAM configuration, mocked API/editor +tests verify the implemented contracts and regressions. They do not prove live +IAM enforcement, deployed audit coverage, browser acceptance, cross-object +transactions or readiness to operate hardware. diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md new file mode 100644 index 00000000..7a9372e5 --- /dev/null +++ b/docs/development/hardware-catalog.md @@ -0,0 +1,315 @@ +# Shared hardware catalog: implemented additive slice + +[Implementation status](README.md) · [Physical inventory](../operations/physical-inventory.md) + +This implementation builds on staging branch `feat/manual-inventory-records` at +`5b60656759033b61674ee202a9ad94f4d49f4a64`, including PR106 +(`11778ec901812747ad7cb5e915f6c7658836bc04`), Site/Facility membership and +Device reported placement. It preserves the target's provenance-free inventory +contract and does not replace those APIs or their writers. +The [pinned inventory proposal](../proposals/fleet-management/inventory-reference.md#asset-identity-and-typed-components) +already describes a reusable model/port shape, initially a document rather than a +public kind. This authorized implementation promotes that concept to Manufacturer +and DeviceType records. It does **not** implement the proposal's accepted-plan +shape pinning, physical qualification, reservations, or component reconciliation. + +## Implemented contracts + +- `fleet.datumapis.com/v1alpha1` Manufacturer and DeviceType are namespaced, + operator-written catalog records served in the provider's Milo Project. + There is no catalog controller, status writer, capacity publication, allocation, + installation, node, networking, provisioning, or IAM membership effect. +- Manufacturer has a mutable `canonicalName`, human `displayName`, and optional + descriptive `aliases`. ASCII labels are bounded and cannot have leading/trailing + spaces; case-insensitive aliases must be distinct within one object and cannot + repeat its canonical name. Aliases never merge identities or resolve references. +- DeviceType has an immutable `manufacturerRef: {name}` and normalized `model` + identity key (`[a-z0-9]+(-[a-z0-9]+)*`). `displayName` is its mutable human model + label. Stable metadata names are operator-selected, not regenerated from labels. + Distinct hardware variants need distinct reviewed model keys. +- Shared `modelShape` reuses the existing height-in-rack-units/full-depth shape. + Absent values mean unknown and are never defaulted; a Device's + `fullDepth` overrides its DeviceType's. It is **nominal**, never a measured + installation or observed occupancy, but rack elevations use `fullDepth` to + decide which faces a Device occupies. `componentTemplates` reuse the component type, connector, + position, name and stable local-ID vocabulary, but have no serial, asset tag or + source-instance identity. They do not create installed ports, topology or assets. + A template may set a chassis-relative `face` (`Front` or `Rear`; absent means + unknown), which a Device component with the same id inherits. See + [rack faces, depth and component faces](../operations/physical-inventory.md#rack-faces-depth-and-component-faces). + `modelShape.width` (`Full` or `Half`) is optional on both kinds and follows + the same rules; see [faceplate layout](#faceplate-layout-implemented). +- Both kinds use `metadata.creationTimestamp` and resource audit logs, not + spec provenance, imported source identities, or synthetic timestamp advances. + A catalog edit changes no Device, claim, installed component, recorded hardware + observation, or reported placement. +- Device gains an optional `deviceTypeRef: {name}` outside immutable `identity`. + Once attached, the reference cannot be removed or rebound. Existing inline + manufacturer/model, serial, system UUID and claimRef remain unchanged and + immutable. Catalog edits never overwrite recorded observations. Neither catalog + nor physical records accept the removed provenance/source-identity fields. + +## Faceplate layout (implemented) + +These fields were proposed in the faceplate design and are now implemented in +the Go types, the CRD and `ui/shared/fleet-api.ts`. Every field is optional, +none is defaulted, and absence means "not recorded". + +Layout is nominal catalog data on DeviceType only. A Device inherits it through +`deviceTypeRef` and the template-id convention, and cannot override it. It +carries no state: whether a port is cabled comes from Cable records, and there +is still no observed health. + +**Joining components to templates.** The template-id convention means a Device +component whose `id` equals a template's `id` takes that template's face and +cell. Imported records can break the convention: their component ids are +importer instance ids (`interfaces-3362`), and their template ids are template +ids (`interface-templates-34`). For drawing only, the staff UI then falls back +to the one template with the same name and type; see +[template join](staff-inventory-ui.md#faceplate-drawing). That fallback +positions a component on the drawing and changes nothing else. The long-term +fix is for the importer to record each component's template id (gap P7). +Changing component ids is not the fix, because Cables reference component ids. +Connector text maps to a drawn kind through one fixed table; see +[connector kinds](staff-inventory-ui.md#faceplate-drawing). + +Positions are cells of a **bank grid**, never millimetres. A bank is one +cluster of identical cells on one face, such as a 2×12 RJ45 block or a PSU +bay. Row and column inside a bank give the usual odd-top, even-bottom switch +numbering. + +| Field | Status | Meaning | +| --- | --- | --- | +| `spec.faceplate.banks[]` | Implemented (was proposal) | Up to 32 banks, a list map keyed by `id` (1 to 63 characters). | +| `banks[].face` | Implemented (was proposal) | `Front` or `Rear`, chassis-relative. Required. | +| `banks[].rows`, `banks[].columns` | Implemented (was proposal) | The grid, 1 to 8 rows and 1 to 64 columns. Required. | +| `banks[].offset` | Implemented (was proposal) | The bank's left edge as a fraction (0 to 1) of the usable face width. All or none per face. With none, banks flow left to right in list order. | +| `banks[].cellMM {width, height}` | Implemented (was proposal) | Nominal module cell size in millimetres (width 1 to 450, height 1 to 400), for PSUs, drive bays and fans. With none, readers use the nominal size of the cell's connector. | +| `componentTemplates[].layout {bank, row, column}` | Implemented (was proposal) | The template's cell. 1-based. Required together. | +| `componentTemplates[].layout.span` | Implemented (was proposal) | Columns covered to the right, 1 to 64. Unset means 1. There is no row span. | +| `modelShape.width` | Implemented (was proposal) | `Full` or `Half`, on DeviceType and Device, as for `fullDepth`. Unset is unknown; drawings assume full width and say so. Which half a Device occupies is a placement fact and is not recorded. | + +**Decorative marks are not implemented.** The design's optional `marks[]` +(power buttons, LEDs, vents, labels) were dropped to keep the schema to the +fields above. Drawings show only components, and empty space stays empty. + +### Admission rules + +The CRD's CEL rules reject: + +- a template `layout` without a template `face`, without a `faceplate`, or + naming a bank that is missing or on the other face; +- a row past the bank's rows, or a column plus span past its columns + (minimums are schema bounds); +- two templates whose cells overlap in one bank row, spans included; +- offsets set on some banks of a face but not all; +- more than 128 templates with a layout. + +Banks are per face, so a cell that is unique in its bank is unique on its face. +CEL cannot check physical fit, such as banks that together are wider than the +face or that overlap each other. The staff UI drawing scales such a layout and +warns; it does not reject it. + +**CEL cost outcome.** The overlap rule compares every pair of templates. Its +static estimate is about 4.4M against the 10M per-expression limit, so the CRD +installs, and the layout rules total about 5.2M against the 100M CRD limit. +At runtime, though, 256 laid-out templates can exceed the 1M per-call limit. +Measured on the costliest valid shape found (32 one-row banks with 63-character +IDs, every template in row 1), the cost passes 1M between 176 and 192 laid-out +templates. The smallest safe change was a cheap cap: at most 128 templates may +carry a layout. That keeps the worst case at about 627K. `componentTemplates` +keeps its 256-item limit. Templates past the cap simply have no layout and no +position on the drawing; the staff UI lists them in its "Not on the faceplate" +tray. + +The cap rule runs before the overlap rule, so an over-cap object reports the +cap rather than a cost error. `faceplate_test.go` pins the estimates and the +worst-case runtime cost with 25% headroom. `faceplate_envtest_test.go` checks +every rule and the worst case against a Kubernetes 1.37.0 API server. If real +hardware needs more than 128 laid-out templates, such as a 2U 96-port patch +panel with front and rear ports, move overlap detection to a reviewed +admission webhook rather than raising the cap. + +### Example (synthetic) + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceType +metadata: + name: example-1u-server + namespace: example-inventory +spec: + displayName: Example 1U server + manufacturerRef: {name: example-vendor} + model: example-1u + modelShape: {heightUnits: 1, fullDepth: true, width: Full} + faceplate: + banks: + - {id: bays, face: Front, rows: 1, columns: 8, cellMM: {width: 40, height: 18}} + - {id: psu-1, face: Rear, rows: 1, columns: 1, offset: 0, cellMM: {width: 40, height: 38}} + - {id: ocp, face: Rear, rows: 1, columns: 2, offset: 0.13} + - {id: mgmt, face: Rear, rows: 1, columns: 1, offset: 0.34} + - {id: psu-2, face: Rear, rows: 1, columns: 1, offset: 0.89, cellMM: {width: 40, height: 38}} + componentTemplates: + - {id: bay-1, name: Bay 1, type: Module, connector: 2.5in bay, face: Front, layout: {bank: bays, row: 1, column: 1}} + - {id: eth0, name: Ethernet 0, type: NetworkPort, connector: SFP28, face: Rear, layout: {bank: ocp, row: 1, column: 1}} + - {id: eth1, name: Ethernet 1, type: NetworkPort, connector: SFP28, face: Rear, layout: {bank: ocp, row: 1, column: 2}} + - {id: bmc, name: BMC, type: NetworkPort, connector: RJ45, face: Rear, layout: {bank: mgmt, row: 1, column: 1}} + - {id: psu-1, name: PSU 1, type: PowerInlet, connector: IEC C14, face: Rear, layout: {bank: psu-1, row: 1, column: 1}} + - {id: psu-2, name: PSU 2, type: PowerInlet, connector: IEC C14, face: Rear, layout: {bank: psu-2, row: 1, column: 1}} + # Recorded, not laid out: its position on the face is not recorded. + - {id: console, name: Console, type: ConsolePort, connector: RJ45, face: Rear} +``` + +The front bank flows because none of its face's banks sets `offset`. The rear +banks are placed because all of them do. + +## Scope, guarantees, and reader safety + +References always resolve in the referring object's namespace and provider +Project. No spec accepts a UID or an explicit cross-namespace reference. Ordinary +Kubernetes unknown-field pruning is **not** rejection: clients must use +`fieldValidation=Strict`. Disposable API tests exercise strict decoding of +references and removed fields as well as conflict handling. + +These are name references, not incarnation pins. Missing or deleting targets are +unavailable; recreating a name resolves to the replacement object. This never +proves physical continuity or triggers instance changes. Do not reuse names during +routine catalog maintenance. Preventing reuse requires a separately reviewed +retention/tombstone policy, not a UID added to the spec. + +CRD admission validates **one object's** syntax, alias uniqueness, immutable +fields. It cannot atomically enforce uniqueness of a normalized +model across objects within a manufacturer, canonical manufacturer names across +objects, or the existence/authorization of references. +Distinct resource names can still describe the same model. No webhook or global +uniqueness reservation is claimed. Writers must adjudicate collisions; reads of +existing records are not a transaction and races remain possible. + +The Go reader requires a caller-authorized `client.Reader`; do not substitute an +unrestricted controller credential for a staff caller. It reads both targets and +returns no partial catalog/error detail when either is unavailable. UI collection +reads use existing provider proxy and session-generation fencing. Denial or +unavailability of Manufacturers suppresses dependent DeviceTypes, including deep +links, search and filters. Device labels use the catalog only when both references +are readable; otherwise the Device's independently authorized recorded hardware +observation remains available. Catalog fallback does not query aliases or leak +denied reference names. Existing session, focus and late-response safety tests +remain intact; only their collection cardinality increases from seven to nine. +If a selected catalog becomes unreadable during registration, the form retains +an unavailable selection without disclosing its label and blocks the write. It +does not silently clear the attachment and create an unassigned Device instead. + +Inventory viewer gains catalog get/list/watch. Importer inherits those reads and +gains catalog create only, without update, patch, or delete permissions. The +exact-role regression test checks these grants alongside every inventory kind. +Manager gains create/update/patch; +editor also has delete, consistent with the existing editor role. No status, +wildcard, consumer, membership or operational permission is added. Deploying +these definitions does not bind anyone to these roles. + +## Deferred external import + +PR106 deliberately removed the physical NetBox importer and placement planner. +Integration with that target also removes this feature's newly introduced offline +NetBox catalog importer, dependent fixtures/tests, and CI steps. No external +catalog import or deduplication command is implemented in this slice. Restoring +source identity, provenance receipts, or the old importer to enable catalog +creation would contradict the current inventory contract. + +Authorized direct-API writers may create catalog records with ordinary Kubernetes +metadata and the model fields documented here. External imports, source mappings, +cohort collision handling, migration and recurring synchronization require a +separately reviewed contract. Any external attribution belongs in writer-owned +labels/annotations and audit logs; Fleet does not interpret it or acquire ownership +from it. Creating catalog records remains observational, never a capacity or +provisioning action. + +## Manufacturer detail (implemented) + +Manufacturer detail now shows recorded overview fields, linked DeviceTypes with +associated Device counts, and linked Devices with their model and reported +location. Joins use same-namespace `manufacturerRef` and `deviceTypeRef` only; +inline manufacturer text and aliases never establish relationships. Rows/counts +are deduplicated by namespace/name. Deleting or missing targets remain unresolved. +Locations use the Device's report only, with links to readable Facility/Rack +records; plans and nominal templates never fill in physical observations. + +Display names lead catalog tables, links and registration choices, with resource +names as fallback and contextual identifiers only for colliding labels. The +manufacturer's metadata is collapsed under Technical details. Existing Datum +tables, page chrome, query/history behavior and authorized collection cache are +reused, without new reads, forms, mutations, session policies or backend changes. +Unavailable model/device collections produce unknown counts, not zero; unreadable +dependencies lose their labels and links immediately. Resolved subsets remain +visible with missing-reference guidance. Initial loading stays in the page shell. + +Focused tests cover reference scope, unrelated and +dangling records, duplicate rows/counts/labels, fallback labels, catalog picker +choices, denied/partial collections, actual destination URLs, reported-only +location, loading and history/filter retention. Existing session, write-precondition +and visible-focus regressions also pass. Shared/consumer code is unchanged, so +consumer validation is not required. No browser/host acceptance, live reads or +writes, migration, deployment, physical verification or readiness is claimed. + +## Explicitly deferred user-visible work + +Staff can browse Manufacturers/DeviceTypes and see catalog-backed Device labels, +recorded observations and nominal template details. New manual Device registrations +offer an optional same-namespace catalog selection, with fresh authorized reads +and UID/resourceVersion checks of both targets immediately before create. Strict +field validation prevents an older Device schema silently dropping the reference. +Selection never copies labels, components or shape into recorded observations; +inline observed model data remains required. These reads are not an atomic +cross-object lock: a later recreation follows the documented name semantics. +Catalog create/edit forms and attachment/correction forms for **existing** Devices +are not implemented. Creating catalog records does not attach +existing or new Devices; shape/template import, legacy-source migration, +assignment correction/rebinding and accepted-plan revision pinning need follow-up. + +An explicit direct-API attachment must use the Device's current owner, require +fresh authorized reads of both same-namespace targets, retain exact inputs, and +test metadata UID and resourceVersion before adding the reference. Attachment +must not invent provenance or a recording timestamp. +UIDs are request preconditions, never spec references. Use Strict +field validation. A failed or uncertain request requires readback, not a blind +retry. No live attachment is performed here. Correcting an already attached +reference requires a reviewed compatibility contract; do not weaken identity +immutability, delete/recreate the Device, or transfer its claim to work around it. + +## Validation and rollout gates + +```sh +go test ./... +go test -race ./... +go vet ./... +pnpm --dir ui/provider typecheck && pnpm --dir ui/provider test && pnpm --dir ui/provider build +pnpm --dir ui/consumer typecheck && pnpm --dir ui/consumer test && pnpm --dir ui/consumer build +kustomize build config/milo >/dev/null +kustomize build config/inventory >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +Set `KUBEBUILDER_ASSETS` to the repository's pinned envtest assets to include the +disposable API checks; without it that test is explicitly skipped. These checks +are not proof of real Milo authorization or live NetBox parity. + +Validation of the PR106 integration passed the full Go suite, race suite and vet, +with local Kubernetes 1.37.0 envtest assets including catalog concurrency and +strict rejection of retired fields. The provider and consumer suites, both +typechecks and both production builds pass. +The five CI manifest roots, synthetic-staging render, overlay isolation and its +regression tests, standalone render, Milo acceptance packaging, documentation +links and whitespace checks also pass. These are local synthetic checks, not +remote CI completion, live authorization verification, or deployment acceptance. + +The parent task owns CI and the feature-branch merge; further review is waived +for this merge. No staging deployment or live mutation is part of this work. +Roll out additive CRDs and least-privilege IAM definitions, then denial-aware +readers, **before any writer**. Confirm existing Site/Facility/Device placement +behavior and unreadable/missing catalog fallback on staging. Never roll back by +pruning CRDs or catalog/occupied records, downgrading schemas to prune retained +fields, deleting Devices, or rebinding identity. Roll back readers first while +retaining additive schemas, records and existing writer authority. Live migration +and any ownership transition remain separately approved operations. diff --git a/docs/development/imported-device-uuid.md b/docs/development/imported-device-uuid.md new file mode 100644 index 00000000..93682024 --- /dev/null +++ b/docs/development/imported-device-uuid.md @@ -0,0 +1,33 @@ +# Completing a serial-only Device identity + +Stock Device identity is immutable. The optional admission path permits an authorized operator to add a freshly observed UUID to an existing serial-only Device. It does not contact hardware, register [capacity](inventory-capacity-registration.md), or change custody. + +## Enable admission + +No per-Device deployment configuration is required. The webhook evaluates each request against the caller's effective permission and current project inventory. + +1. Freeze conflicting Device writes and drain in-flight requests across all serving planes. Confirm every replica uses the same authority and complete provider scope, that no direct write route bypasses admission, and that the importer preserves an enriched Device's UID and UUID. Do not proceed on a partial restore or unverified topology. +2. Keep the stock identity rule in place while installing the [fail-closed webhook](../../config/components/device-uuid-completion/webhook.yaml) with the correct serving CA and authenticated API-server clients on every plane. Verify UUID-bearing CREATE is denied on every route, including outside `default`, and fails closed when the service is unavailable. Serial-only CREATE and ordinary non-identity updates should still work. UUID-only imports are not supported in this mode. +3. Audit all Devices, including retired ones, across the entire provider scope. Resolve conflicts before enabling writes. Compose the [permission component](../../config/components/device-uuid-permission/kustomization.yaml) with the Milo root configuration. Separately grant the operator `patch` and `completeuuid` on the **named** Device in `default`; neither status nor ConfigMap access is needed. +4. Only after verifying guards and rollout convergence, apply the [tested CRD transition](../../config/components/device-uuid-completion/transition.json) on the appropriate serving planes with `kubectl patch crd devices.fleet.datumapis.com --type=json --patch-file=config/components/device-uuid-completion/transition.json`. No default overlay enables the transition. Keep conflicting identity writers quiesced until completion is verified. + +**Upgrading from reservations:** before deploying or reconciling the new manifests, exclude the old namespace, its ConfigMaps and their protection policies/bindings from GitOps pruning; preserve their backups. Review the prior records for conflicts. The new binary neither reads nor migrates them. Remove obsolete reader grants separately once old replicas are drained. Do not delete records or disable their protection as part of this upgrade. + +## Complete and verify + +Admission re-reads the live Device, requires current discovery conditions and one matching system observed at its current endpoint within 15 minutes, checks the caller's permission, and searches for duplicate identities. The old UID, resourceVersion and claim must match the live Device. Only the observed UUID may be added; clearing or replacing it is denied. `go run ./cmd/fleet-uuid-preflight < device.json` checks snapshot evidence but cannot authorize a write. In the target provider context: + +```sh +kubectl -n default patch devices.fleet.datumapis.com example-device --type=json -p='[ + {"op":"test","path":"/metadata/uid","value":"example-device-uid"}, + {"op":"test","path":"/metadata/resourceVersion","value":"123"}, + {"op":"test","path":"/spec/claimRef/name","value":"example-claim"}, + {"op":"add","path":"/spec/identity/systemUUID","value":"aaaa1000-0000-4000-8000-000000000001"} +]' +``` + +After a timeout, conflict, or denial, read the authoritative Device again. Only the same UID with the reviewed UUID confirms completion; a serial-only Device requires fresh evidence and a newly pinned retry. Never transfer the UUID or recreate a Device to bypass denial. + +**Concurrency limit:** the duplicate scan checks recorded identities, not pending writes. Two concurrent completions on different Devices can both pass before either UUID is visible, even in the same project on the same webhook replica. A resourceVersion check protects only the targeted Device. Serialize potentially conflicting identity writes across the provider scope and verify the result before starting the next one. There is no reservation after deletion. + +**Rollback:** freeze and drain writes, then restore and verify the stock immutable CRD rule on every plane before removing the webhook. Removing the webhook also removes its UUID-bearing create guard. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md new file mode 100644 index 00000000..d2a011ec --- /dev/null +++ b/docs/development/inventory-capacity-registration.md @@ -0,0 +1,933 @@ +# Inventory-backed capacity registration + +[Implementation status](README.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Enrollment contract](../proposals/fleet-management/bare-metal-provisioning.md#enrollment-and-explicit-preparation) + +Stage 1 registers inert, `Disabled` capacity. [Stage 2](#stage-2) lets +registered capacity be enabled, removed when orphaned, and written only by +the capacity projector, as the [commissioning +proposal](https://github.com/datum-cloud/fleet/pull/185) describes. Sections +below that describe stage 1 say where stage 2 changed them. Registration is +not hardware enrollment, preparation, allocation or verification. It supersedes the blocker-only UI +guardrail in PR140 (`12439e1fdf0d229352b4e32c27d9985993ca117d`). The synthetic +name-derived Device reference, invented cleaning default, allocation checkbox, +and unrestricted frontend create helper remain removed. Existing capacity +listing and legacy values remain visible; no existing object is migrated. + +## Decision: no registration ledger + +An earlier revision kept a private ledger in host-cluster Secrets. Its job was +to remember Device identities after a Device was deleted, and it grew into +tombstones, incarnation fences, permanent alias retention, `Unknown` outcomes, +a mutable tail with sealed segments, signed expansion and activation, epochs +and growth limits. The user decided this was overengineering and replaced it +with the following: + +1. **In-service Devices are not deleted.** A reusable ValidatingAdmissionPolicy + component denies a Device `DELETE` unless the Device is `Retired`, its + namespace is being deleted, or the caller is a cleanup identity that the + deploying repository lists. No root in this repository includes it; + deploying repositories opt in. See + [Device lifecycle](#device-lifecycle) and + [Device deletion protection](#device-deletion-protection). +2. **No signed activation.** The bootstrap/activation gate, `/activationz`, + `/status`, the operator control key and ConfigMap, + `cmd/fleet-registration-control` and signed controls are gone. The + registration webhook is an ordinary fail-closed webhook (`failurePolicy: + Fail`) with mutual TLS, scoped credentials and least privilege. +3. **Registration checks live objects.** The webhook keeps no state. It + checks the live Device and capacities through the API server on every + request. + +Rationale: when in-service Devices are never deleted, the live Device list +already holds every identity the ledger used to remember, so a second store +adds failure modes without adding information. A Device leaves the list only +after someone has retired it on purpose, deleted its namespace, or deleted its +project through a configured cleanup identity. Environments +that do not include the component, such as test and synthetic environments, do +not hold real machines and do not need identity retention. + +## Public contract and authority + +The staff form selects an existing `Device` in `default` and keeps its UID and +resourceVersion as an immutable selection baseline. It POSTs to the provider +project's `MachineCapacity` API through the staff portal's caller-preserving +proxy. The admitted create is: + +```yaml +metadata: + name: device- + namespace: default + annotations: + fleet.datumapis.com/registration-device-uid: + fleet.datumapis.com/registration-device-version: + fleet.datumapis.com/registration-operation: +spec: + deviceRef: {name: selected-device} + allocationPolicy: Disabled + reclaimPolicy: Retain + cleaningPolicyRef: {name: ""} +``` + +`spec.deviceRef` remains a name-only reference. The capacity name is no longer +authored: it is `device-` followed by the Device UID (43 characters). This +changes the earlier contract, where staff typed an independent name. All other +fields and the three annotations are unchanged. The annotations are request +preconditions and traceability, not authentication or ownership proofs. The +operation ID is no longer used for deduplication. + +An empty cleaning-policy name explicitly means **unconfigured**, not a policy +named `default`, synthetic cleaning, or authorization to prepare. The CRD +permits it only while Disabled. Updates and deletes of [inventory-backed +capacity](#scope-inventory-backed-capacity-only) follow the [stage 2 +rules](#stage-2); stage 1 denied all of them. An update that would move +capacity out of `Disabled` while its Device is `Decommissioning` or `Retired` +is denied for that reason; the webhook first checks that the caller can read +the Device. Real policy resolution and policy-use authorization +are future prerequisites for a separately designed transition; there is no +stage-1 preparation endpoint. + +`cmd/fleet-registration` serves the validating webhook. For each create of +inventory-backed capacity it: + +1. requires Milo's authenticated `iam.miloapis.com/parent-*` extras naming a + single Project in the configured provider scope, and an actor username. As + in Kubernetes RBAC, the username identifies the actor. Its UID is optional, + because some credentials, such as client certificates, carry none; +2. requires the `default` namespace, the exact shape above, and a name equal + to `device-`; +3. resolves the current Project lifetime through the root Milo client; +4. runs SubjectAccessReviews with the caller's username, UID when present, + groups and extras for `machinecapacities.create` and named `devices.get` in + `default`. Denials, errors and incomplete evaluations fail closed. This + happens before the Device is read, so an unauthorized caller cannot learn + whether a Device exists; +5. reads the Device uncached. A missing Device is denied. Its UID and + resourceVersion must equal the annotations, it must not be deleting, and + its [lifecycle](#device-lifecycle) must be `Active`; +6. requires both a non-placeholder serial and a canonical system UUID, and a + complete provider host reference when one is present; +7. lists Devices and capacities in **all namespaces of every configured + provider project** and denies when: + - another Device shares a normalized alias (below); + - any capacity already references this Device by name or by its UID + annotation; + - any capacity has unresolved physical identity, so non-conflict cannot be + established; or + - any capacity is backed by a Device that shares an alias. + +### Provider-project scope + +Step 1 is the only check that decides which project a request is judged in. +Nothing after it is limited to the provider projects on its own: `Resolve` +resolves whatever project name it is given, the webhook match conditions do +not look at the project, and the SubjectAccessReviews carry the request's own +user and extras. If step 1 let a project through, every later check would run +against that project. So a request whose project is outside +`--provider-projects` is denied before any project is resolved, any Device or +capacity is read, or any SubjectAccessReview is sent. The same holds for an +update that would leave `Disabled`. Separately, if `Resolve` returns a project +whose route name differs from the one requested, the request is denied before +that project's client is used. `internal/registration/tenancy_test.go` and +`tenancy_envtest_test.go` pin both checks with project clients and +SubjectAccessReview stubs that fail the test if they are called. + +**Stage 1 did not check who called the webhook** +([#149](https://github.com/datum-cloud/fleet/issues/149)); stage 2 does, as +[Who may call the webhook](#who-may-call-the-webhook) describes. Before that +change: Any holder of a +client certificate from the webhook's client CA can post an AdmissionReview +directly and read the verdict, and a verdict can name Devices and their +lifecycle. Such a caller writes the review's user and extras itself, so the +SubjectAccessReviews do not limit it: it can claim any identity. Until #149 is +fixed, the provider-project scope check is the only thing that bounds what it +learns, and it bounds it to the configured provider projects. Treat every +certificate from that CA as read access to Device names and lifecycle across +the provider scope. + +## Scope: inventory-backed capacity only + +The webhook governs only **inventory-backed** capacity, meaning capacity that +registration creates from a Device. Other capacity, such as synthetic +capacity that a GitOps controller applies, capacity whose status a synthetic +provider writes, and hand-made capacity, is not routed to it at all. + +The marker is registration's own metadata: + +- any annotation whose key starts with `fleet.datumapis.com/registration-` + (the three annotations above), on the new or the old object; or +- on create only, a name starting with `device-`, the derived name. + +The marker is reliable because the webhook admits no create of +inventory-backed capacity without all three annotations and the derived +name, and no later update may add, change or remove a registration +annotation, so the annotations cannot be removed or changed after creation. A label was not used: registration +sets none, adding one would change the portal's wire contract, and a match +condition can read annotations directly. The name is part of the marker only +on create, so that the derived name space is reserved for registration and +no unannotated create can occupy a Device's derived name. Capacity is not +renamed, so the annotations alone identify it afterwards. + +The packaged webhook routes requests with one rule and one match condition: + +```yaml +rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [machinecapacities, machinecapacities/status] + scope: Namespaced +matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) +``` + +`object` is null for a delete and `oldObject` is null for a create. Checking +both objects routes, and so denies, an update that adds a registration +annotation to unmarked capacity, which would make it look inventory-backed, +and an update or delete that removes or changes the annotation on marked +capacity, which would let it escape the gate. `failurePolicy: Fail` applies +to a match condition that fails to evaluate. + +The handler applies the same test as defence in depth: a request for capacity +without the marker that reaches it anyway is allowed without reading Devices +or the provider project. A marked request is handled as before: creates are +gated in full, and updates, deletes and any routed subresource are denied. + +**Stage 2 routes status writes** to registered capacity and admits them only +from the capacity projector; see [Stage 2](#stage-2). In stage 1, +`machinecapacities/status` was not in the rule. Stage 1 has no status writer for inventory-backed capacity, but a +provider may need one later, and the webhook would then have to be changed +first. Status writes are governed by RBAC alone; in the packaged IAM roles +only the capacity projector role holds `machinecapacities.updateStatus`. This is +acceptable because a status write cannot widen what capacity offers: + +- the CRD's status subresource ignores changes to `metadata` and `spec`, so a + status write cannot strip the marker or move capacity out of `Disabled`; +- allocation requires `spec.allocationPolicy: Enabled`, which status cannot + set. + +The envtest suite confirms the first point on Kubernetes 1.37.0. A future +stage that lets status influence availability must revisit this. + +**Unmarked capacity is not gated.** Capacity without the marker, including +legacy capacity created before registration admission, can again be created, +updated and deleted by any caller RBAC allows, with no Device check and no +Disabled requirement. It is not inventory-backed and makes no claim about a +Device. Registration still reads it: a create of inventory-backed capacity is +denied while any capacity in the provider scope references the Device, or has +unresolved physical identity. + +The webhook writes nothing. Dry-run requests are evaluated like real ones +(`sideEffects: None`). Controller credentials supply reads and SAR evaluation, +not the caller's registration authority. Errors about records in another +provider project do not name them. + +The webhook accepts only mutually authenticated TLS from a dedicated API-server +client CA. Do not use a broad tenant/client CA: an AdmissionReview received from +an untrusted client is not evidence of an authenticated actor. + +## Physical identity and duplicates + +Aliases are the digests of the normalized serial, system UUID and, when +present, provider host system/type/ID tuple. Normalization trims and lowercases +values. A shared alias between two Devices, including inconsistent +serial/UUID pairs, is ambiguous: registration is denied for both until a person +resolves the duplicate. Neither is merged or adopted. MAC addresses, BMC +endpoints, installation claims, rack placement and asset tags are not chassis +identifiers in this stage. + +This is **not universal physical deduplication** or proof of real hardware +identity. Hardware outside the provider scope or absent from inventory cannot +be compared. Recording identity does not establish physical verification or +ownership. + +### One capacity per Device + +Two creates for the same Device carry the same derived name, so the API server +rejects the second with `AlreadyExists` even when both pass admission +concurrently. The webhook also refuses a Device that a legacy capacity already +references under another name. A replacement Device created under a deleted +Device's name is refused too, because the old capacity still references that +name. + +### The documented duplicate race + +The duplicate check is a point-in-time list. It does not close this race: + +- Device A is being registered while Device B, which shares A's serial, is + being created. If B is not yet visible when A's registration lists Devices, + A's capacity is admitted. + +No reservation store closes this, by decision. The consequences are bounded: + +- B can never be registered, because A now exists and shares its alias. +- In stage 1, A's capacity was `Disabled`, and the webhook denied every + update of inventory-backed capacity, so it could never become available. +- The staff registration form lists every Device and marks each one that + shares an alias with another as **Conflicting**, so both A and B show the + conflict until a person resolves it. +- Any future transition that enables capacity must recheck duplicates against + live Devices at that time. + +**In stage 1 this race was open, and it blocked stage 2.** Stage 2 makes it +harmless rather than closing it; see [The duplicate race](#the-duplicate-race). The bounds above hold only while +inventory-backed capacity stays `Disabled`. Allocation must not be enabled for +inventory-backed capacity, by the webhook allowing an update out of +`Disabled` or by any other path, until this race is closed. A recheck at +enable time narrows the window but does not close it, because a duplicate +Device can still appear after the recheck. + +Two registrations racing for two already-existing Devices that share an alias +both fail, because each sees the other Device. Device status has no writer +today, so there is no server-side eligibility condition to set; reporting +conflicts through Device status is a follow-up. + +## Device lifecycle + +`Device.spec.lifecycle` records whether the asset is in service. It is part of +spec, so the inventory editor role, which can update Devices, can set it; no +extra RBAC exists. + +| Value | Meaning | +| --- | --- | +| `Active` | In service. The CRD default when the field is unset. | +| `Decommissioning` | Leaving service. Can return to `Active`. | +| `Retired` | Out of service. Terminal. | + +The CRD enforces transitions with transition rules (`oldSelf`) on `spec`: + +- `Active` to `Decommissioning`, `Decommissioning` to `Active`, and + `Decommissioning` to `Retired` are allowed. Leaving the value unchanged is + always allowed. +- `Active` to `Retired` is rejected: move the Device to `Decommissioning` + first. +- Nothing leaves `Retired`. Removing the field defaults it to `Active`, so + that is rejected too. + +The rules apply to updates only; a Device may be created in any lifecycle, for +example to record hardware that is already out of service. Other spec edits to +a Retired Device are still subject only to the existing rules. + +Registration semantics, enforced by the registration webhook: + +- Only an `Active` Device can get new capacity. +- Capacity whose Device is `Decommissioning` or `Retired` cannot leave + `Disabled`. Stage 2 enforces this when it enables capacity. +- A Retired Device still takes part in the duplicate-identity check for as + long as it exists. Deleting it removes its identity from that check. + +Lifecycle is a record, not an effect. Moving a Device changes no capacity, +allocation, provider or network state. + +## Device deletion protection + +`config/components/device-deletion-protection` is a reusable Kustomize +component with a ValidatingAdmissionPolicy and binding named +`fleet-device-deletion-protection`. It matches every `DELETE` on +`devices.fleet.datumapis.com` (all versions, all namespaces) and admits it only +when: + +1. the Device's namespace is being deleted: the policy's `namespaceObject` + has `metadata.deletionTimestamp` set. A missing namespace object does not + match; +2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`; or +3. the request's `userInfo.username` is listed exactly in the + `cleanupUsernames` key of the binding's parameter ConfigMap. The policy's + `paramKind` is core `v1` `ConfigMap`. This exception is off as shipped; see + [Cleanup identity](#cleanup-identity). + +Every other `DELETE` is denied with reason `Forbidden` (HTTP 403). The message +lists the three ways a delete is allowed and says to move the Device to +`Decommissioning`, then `Retired`, first. The policy uses +`failurePolicy: Fail` and the binding `validationActions: [Deny]`, so an +evaluation error also denies. + +- **Who includes it.** No root in this repository renders the policy. + Production-specific configuration lives in the deploying repository, which + adds the component to the root it applies to the Milo control plane. Devices + are stored and admitted there: `config/components/inventory` registers the + CRD in Milo, and records live in provider projects. Management-cluster host + overlays have no Device CRD. Like the registration webhook, the policy relies + on Milo running its root admission policies for project-routed requests + (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` plugin). + Confirm this on the deployed Milo before relying on it. +- **Validation.** `hack/validate-overlay-isolation.sh` renders the component + on its own and fails unless it is exactly this policy: the same name, + expression, a `paramKind` of exactly core `v1` `ConfigMap`, + `failurePolicy: Fail`, `Deny` only, no `paramRef` on the binding, and no + match conditions, selectors, exclusions or variables. Because the expression + is compared exactly, the validator rejects wildcard or prefix username + matching, a group-based exemption, a null `params` treated as allow-all, a + dropped empty-username guard and an always-true clause. It also rejects a + `paramRef` in the component, including one with + `parameterNotFoundAction: Allow`: deploying repositories add the `paramRef`. + It fails if any root in this repository renders the policy, under its own + name or another, and if the inventory component exists without this + component. +- **The cleanup identity is the only subject exemption.** Apart from exact + usernames in the deploying repository's ConfigMap, the policy does not look + at the request's user, group or service account. Cluster administrators are + held to the same rule. Anyone able to delete or edit the binding, or to write + the parameter ConfigMap, is outside the guarantee. +- **deletecollection, garbage collection and finalizers.** The API server + admits each object of a collection delete individually as a `DELETE`, so a + collection delete that reaches a Device that is not Retired is denied and + leaves that Device in place. Retired Devices and other objects it reached + first may already be gone; it may also stop before reaching every Retired + Device, so repeat the delete per Device. Owner-reference cascades issue + the same `DELETE`. A denied Device gets no deletion timestamp, so its + finalizers never run. +- **Namespace deletion is the escape hatch.** Deleting a namespace is a + privileged act. Once the namespace has a deletion timestamp, the namespace + controller's Device deletions are admitted, so the namespace finishes + terminating and takes its Devices with it, whatever their lifecycle. Their + identities leave the duplicate check. The policy reads the namespace from the + API server's namespace cache, which observes the deletion mark shortly after + it is set. +- **Project deletion.** In pinned Milo `v0.36.9`, project purge + (`internal/controllers/projectpurge`) first issues a collection delete for + every namespaced resource in every namespace, `default` included, and only + then deletes the namespaces. It never deletes `default`, which it drains in + place. In that first phase no namespace is marked yet, so the + deleting-namespace exception never applies, and a denied collection delete + aborts the purge before it deletes any namespace. The purge runs as the Milo + controller-manager's own identity against the project's control plane. + - With the [cleanup identity](#cleanup-identity) configured to list that + username, the purge's collection deletes are admitted whatever the + Devices' lifecycle, and project teardown completes. + - Without it, a project that holds a Device that is not Retired does not + finish purging while the component is installed. Retire every Device + first. + + This comes from reading the pinned Milo source and from the envtest + simulation below, not from a live Milo test. +- **Capacity is not deleted with its Device.** The registration webhook + admits the delete of registered capacity only once it is `Disabled` and its + Device is gone or Retired, so a namespace or project teardown that removes + Devices still stops at enabled capacity; see the next section. + +### Cleanup identity + +The cleanup identity is a stopgap. Milo's project cleanup deletes namespaced +resources before it marks any namespace for deletion, and it never deletes +`default`, so the namespace exception cannot cover project teardown. Milo +should mark every namespace it purges, `default` included, before deleting +its contents. The policy can then rely on that namespace signal and drop the +subject exemption. + +The binding ships without a `paramRef`. The policy then evaluates with +`params == null`, the third exception is off, and only the namespace and +Retired exceptions apply. A policy that declares `paramKind` does not need a +`paramRef` on its binding: Kubernetes evaluates such a binding with a null +`params` and no error. The envtest suite confirms this on Kubernetes 1.37.0. + +A deploying repository turns the exception on in the root it applies to Milo: + +1. Add a ConfigMap with a `cleanupUsernames` key that lists the usernames, one + per line or separated by commas. Entries are trimmed and empty entries are + ignored. Matching is exact and case-sensitive. Groups, prefixes and + wildcards never match, and an empty username never matches. List only the + identity that runs project cleanup: in pinned Milo, the controller-manager's + base identity. +2. Patch the binding with a `paramRef` that names that ConfigMap, sets its + `namespace` explicitly, and sets `parameterNotFoundAction: Deny`. Without + an explicit namespace, the API server looks for the ConfigMap in the + Device's own namespace. + +A synthetic example, rendered with `kustomize build`: + +```yaml +# kustomization.yaml in the deploying repository's Milo root. The component +# path stands in for however that repository vendors or references Fleet. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +components: + - ../fleet/config/components/device-deletion-protection +resources: + - device-cleanup-identity.yaml +patches: + - target: + group: admissionregistration.k8s.io + kind: ValidatingAdmissionPolicyBinding + name: fleet-device-deletion-protection + patch: |- + - op: add + path: /spec/paramRef + value: + name: fleet-device-cleanup + namespace: example-system + parameterNotFoundAction: Deny +--- +# device-cleanup-identity.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-device-cleanup + namespace: example-system +data: + cleanupUsernames: | + system:serviceaccount:example-system:example-controller-manager +``` + +Consequences to plan for: + +- **A missing ConfigMap denies every Device delete.** With + `parameterNotFoundAction: Deny`, a `paramRef` whose ConfigMap does not exist + denies every Device `DELETE`. That includes a Retired Device, a Device in a + deleting namespace and the listed identity's deletes, so namespace and + project teardown stop until the ConfigMap exists. This is the fail-closed + behaviour: an absent or deleted ConfigMap never widens who may delete. The + API server reports it as `422 Invalid` with the message ``no params found + for policy binding with `Deny` parameterNotFoundAction``, not as the + policy's 403. Apply the ConfigMap with the patch, or before it. Never use + `parameterNotFoundAction: Allow`: a missing ConfigMap would then skip the + policy and admit every Device `DELETE`. +- **Impersonation grants the exemption.** Anyone allowed to impersonate a + listed username is admitted as that username and can delete any Device. + Ordinary RBAC on `impersonate` applies. List only the cleanup controller's + identity, and restrict impersonation of it, and writes to the ConfigMap and + the binding, as tightly as the controller itself. +- **Where the ConfigMap lives in Milo.** The admission plugin reads the + ConfigMap through its informers. In pinned Milo `v0.36.9` those informers + run against the root control plane, not a project, so the ConfigMap belongs + in the root. This is inferred from the Milo source, as is the policy's use of + Milo's root admission for project-routed requests. Confirm on the deployed + Milo that the cleanup identity admits a project purge before relying on it. + +### Deleting a Device + +Deleting a Device that backs capacity, whether it is Retired, its namespace is +being deleted, or the component is not installed, leaves the capacity in +place, still `Disabled`. It cannot be enabled, because enabling needs its +Device. No owner reference links the two: the webhook rejects owner +references on registration and on every later update. Stage 2 lets a person +remove it; see [Removing orphaned capacity](#removing-orphaned-capacity). + +The deletion policy narrows when this happens but does not prevent it: a +Retired Device, a Device in a deleting namespace, and a delete by a cleanup +identity are all still admitted. No root in this repository installs the +policy, so in an environment built from these roots alone any authorized +caller can delete a Device, including one that a registration checked just +before its capacity was admitted. + +The resulting orphaned capacity is in this state: + +- It stays `Disabled`: an update out of `Disabled` is denied with `its Device + does not exist`. In stage 1 it was also immutable and could not be + deleted. +- It keeps its Device UID annotation and its `spec.deviceRef` name. A + replacement Device created under the same name cannot register, because + the capacity already references that name. +- Its Device reference no longer resolves, so it has unresolved physical + identity. Registration denies **every** create in the provider scope while + such capacity exists, not only the same-name replacement, with + `capacity default/ has unresolved physical identity`. + `TestOrphanedCapacityBlocksUnrelatedRegistration` pins this. + +Stage 2 removes such capacity directly: see [Removing orphaned +capacity](#removing-orphaned-capacity). The stage-1 remediation, still valid: + +1. Re-record the deleted machine as a Device under its **old name**, with its + original serial and system UUID, created directly in `Retired` (a Device + may be created in any lifecycle). The capacity's reference resolves again, + so other Devices can register. The Retired Device cannot register, the + capacity stays `Disabled`, and the machine's identity is back in the + duplicate check. The same test pins this. +2. Register the real replacement machine under a **new** Device name. The old + name stays bound to the old capacity. +3. Where the deletion policy is installed, do not delete the re-recorded + Retired Device: the policy admits that delete, and the capacity would be + orphaned again. + +In stage 1 nothing could remove the orphaned capacity itself while the +webhook was installed. + +## Production packaging and rollout + +- `config/milo` includes the mandatory fail-closed registration webhook + (`config/components/registration-admission`). Its one entry matches + capacity create, update and delete, and capacity status writes, in every + namespace, narrowed by the [inventory-backed match + condition](#scope-inventory-backed-capacity-only) and with no selectors. An + unreachable service blocks writes to inventory-backed capacity, including + the projector's status writes, and nothing else: unmarked capacity, Device, + namespace and Project writes do not pass through the registration webhook. +- `config/milo` also includes the fail-closed + [Machine power webhook](device-custody.md#machine-power) on the same + service. It matches only Machine status writes that change `status.power`, + so an unreachable service also blocks power changes, and no other Machine + write. +- The same server serves the creator webhook for Device operations. Its + `--client-identities` pin applies to all three webhooks, so until an environment sets the + real API-server identities, the base manifest's placeholder refuses every + caller: no capacity registration and no operation create succeeds. `args` + is a list, so an overlay replaces it as a whole. +- No root in this repository includes Device deletion protection. A + deploying repository adds `config/components/device-deletion-protection` to + the root it applies to Milo when it must keep in-service Devices. +- `config/overlays/management-plane` includes a separate two-replica + registration Deployment and TLS Service. The pod does not mount a service + account token and has no host RBAC. It does not enable production lifecycle + handlers. +- The synthetic staging overlay excludes the registration workload; pair it + with `config/milo-synthetic`, which installs neither the webhook nor the + deletion policy. Never use synthetic roots in production. +- The handler trusts parent context from Milo's admission extras. In pinned + Milo `v0.36.9`, `ProjectRouterWithRequestInfo` establishes the project from + the routed path and `ProjectContextAuthorizationDecorator` overwrites the + parent extras before authorization and admission. The pinned filter + regression verifies that conflicting caller extras are overwritten while + actor identity is preserved, and that nested Organization/User contexts do + not present as a Project. Only a singleton + `Project`/`resourcemanager.miloapis.com` context is accepted. +- Writes to inventory-backed capacity fail closed. Legacy and other unmarked + capacity is not governed by the webhook; its writes are subject to RBAC + alone. + +Environment-owned inputs, none of which this repository supplies: + +1. Keep the existing `fleet-manager-config` authority and discovery paths. + Supply `fleet-registration-milo-kubeconfig` (Project reads) and + `fleet-registration-project-kubeconfig` (Device and capacity get/list + across the complete provider scope, CleaningPolicy get, and SubjectAccessReview create). It + needs no public writes, allocation permissions or provider credentials. +2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key` and a dedicated + `client-ca.crt`. Configure Milo's admission webhook client with an + API-server client certificate signed by that CA, patch the webhook URL for + reachability, and set `clientConfig.caBundle` to the serving CA. Do the + same for the Machine power webhook, or every power change fails closed. +3. Keep `--provider-projects` equal to the complete provider scope. Set + `--client-identities` to the subjects of the API-server webhook client + certificates, and `--capacity-projectors` to the capacity projector's + username. The projector writes status through the provider project, so + its requests carry the project context the webhook requires. + Before a power projector runs against the root, set `--machine-power-writer` + to the username Milo reports for the manager in a routed project request. + A mismatch refuses every power change. +4. Decide whether the Milo root you apply includes + `config/components/device-deletion-protection`. With it, the only Device + deletes admitted are of Retired Devices, of Devices in a deleting namespace, + and by a configured [cleanup identity](#cleanup-identity); without it, any + authorized caller can delete a Device. If you include it, configure the + cleanup identity, or project deletion stays blocked until every Device in + the project is Retired. +5. Before rolling out the UI, verify caller-preserving project routing, named + Device read denial, registration denial, capacity mutation denial, TLS + rejection, Device deletion denial where installed, lifecycle transitions, and duplicate handling + in the target environment. This change performs **no live writes or + deployment**, so it does not claim those checks. + +### Leftover ledger objects + +Removing the ledger deletes nothing that the ledger service or its operator +created at runtime. GitOps prune removes only what the old manifests applied. +The ledger revisions created these objects on the host cluster: + +| Object | Namespace | Created by | Removed by prune | +| --- | --- | --- | --- | +| Secret `fleet-capacity-registration-v1` (the ledger root) | `fleet-system-private` | the operator, once, at bootstrap | no | +| Immutable Secrets `fleet-registration-segment--` (sealed segments) | `fleet-system-private` | the registration service, on expansion | no | +| ConfigMap `fleet-registration-control` (`public.pem`, `request.json`) | `fleet-system` | the environment owner | only if the owner applied it with GitOps and has stopped | +| ValidatingAdmissionPolicies and bindings `fleet-registration-ledger-protection` and `fleet-registration-namespace-protection` | cluster | `config/base/registration` | yes | +| Role and RoleBinding `fleet-registration-ledger` | `fleet-system-private` | `config/base/registration` | yes | + +Remove the Secrets and the ConfigMap by hand. The current service never reads +them, and they hold Device identity digests, project names and signed control +requests that no longer protect anything. If you want a record of the +identities the ledger retained, export the Secrets to private storage outside +Git first. After the Device custody cutover nothing keeps records in the +`fleet-system-private` namespace, so delete it as the last step of [moving +from the Secret-backed staging](../../config/README.md#moving-from-the-secret-backed-staging). + +Delete in this order, on the host cluster, after the current registration +release is running and no older registration pod remains: + +```sh +# 1. The retention policies must be gone, or they deny the Secret delete. +kubectl get validatingadmissionpolicybindings \ + fleet-registration-ledger-protection fleet-registration-namespace-protection +# Expect NotFound for both. If either exists, prune did not run; fix that +# first rather than deleting the policies by hand. + +# 2. The ledger root and its segments. +kubectl -n fleet-system-private delete secret fleet-capacity-registration-v1 --ignore-not-found +kubectl -n fleet-system-private get secrets -o name \ + | grep '^secret/fleet-registration-segment-' \ + | xargs -r kubectl -n fleet-system-private delete + +# 3. The control ConfigMap, after removing it from the environment overlay. +kubectl -n fleet-system delete configmap fleet-registration-control --ignore-not-found +``` + +Environments that never deployed the registration service have none of these +objects and nothing to clean. + +## Stage 2 + +Stage 1 kept registered capacity `Disabled` until three blockers closed. Stage +2 closes each, and lets capacity be enabled. It is **implemented**, and +verified by tests against a real API server behind the packaged webhook +(`TestStageTwoEnablesRegisteredCapacity`) and by handler tests. + +### Enabling registered capacity + +The webhook admits an update of registered capacity that changes only +`spec.allocationPolicy`, `spec.cleaningPolicyRef` and the +`fleet.datumapis.com/capacity-pool` label. Every other change, including the +registration annotations and other labels, is denied. + +- While the capacity is `Disabled`, the three fields change freely. +- While it is `Enabled`, the only permitted change is to `Disabled`. +- Moving to `Enabled` requires, at the time of the update: the caller's + `update` permission on the capacity and `get` on its Device; the annotated + Device incarnation, `Active`, not deleting, and still recording a complete, + non-placeholder identity; a pool label; a cleaning policy that resolves; + and no other Device in the provider scope, Retired ones included, that + shares an identity alias. +- An update that changes none of the three fields, such as an unchanged + apply, is admitted. + +Enabling does not require commissioning. The capacity projector offers the +capacity only once it is `Prepared` and `Healthy`. + +**The pool label.** The capacity operator sets the pool label at registration +or while the capacity is `Disabled`. It is frozen while the capacity is +`Enabled`, so a MachineClass never gains or loses capacity without the +capacity being disabled first. + +**The cleaning policy.** The webhook resolves the policy name through a +resolver that returns a digest, `ErrUnresolved`, or another error. The webhook reads the named CleaningPolicy with its provider-project client in the +capacity namespace and validates the spec. Missing or invalid policy denies enablement; +a failed read is not evidence of a usable policy. The allocator separately pins the +policy it reads at allocation time. + +### The duplicate race + +The race in [The documented duplicate race](#the-documented-duplicate-race) +is not prevented: no object can make one Device's create and another +Device's registration atomic. Stage 2 makes the duplicate harmless instead. + +- Commissioning reads the serial number and system UUID from the BMC and + fails if they differ from the Device's. Admission refuses a BMC key that + another Device records. A `Prepared` server is the one its record names. +- Enabling, the projector's `Available`, and the allocator each refuse a + Device with a duplicate, at the moment they act. +- The window left is between the allocator's check and its custody claim. + Nothing catches a duplicate recorded in it, but that duplicate does not + change which server the customer gets, because commissioning proved the + serial number and system UUID over the BMC. The provider host tuple is not + proven by the BMC; for that alias the recheck is the only protection. + +To resolve a conflict, correct the wrong record's identity, or move it to +`Decommissioning`, then `Retired`, and delete it. + +### Removing orphaned capacity + +The webhook admits the delete of registered capacity when it is `Disabled`; +its annotated Device is missing, another incarnation, or `Retired`; no +MachineAllocation in its namespace that is not `Released` names it; and the +caller may delete it. Enabling needs an `Active` Device of the annotated +incarnation, so the capacity stays `Disabled`. An allocator that selected the +capacity while it was enabled re-reads it after creating its allocation, and +withdraws the allocation, before claiming the Device, if the capacity is gone +or `Disabled`. Any other delete of registered capacity is still denied. + +### Disabling races a claim already past its check + +Disabling stops every new selection, and every claim that has not yet +re-read the capacity. It does not stop a claim already past that re-read. +The custody claim is a conditional update of the Device's custody alone, and +Kubernetes has no write conditional on a second object, so the claim cannot +also require the capacity to be unchanged. An allocation whose claim passed +the check holds the Device as if it had been made a moment before the +capacity was disabled. It is released the normal way, and while it is not +`Released` the capacity cannot be removed. A test pins this interleaving. + +### The Device incarnation + +Registered capacity records its Device's incarnation in metadata, never in +its spec: the name is `device-` and the Device UID, and the +`registration-device-uid` annotation repeats it. Registration keeps both +unchanged. A Device recreated under the same name inherits nothing: the +webhook refuses to enable the old capacity for it, and the projector reports +the capacity not `Prepared` (`DeviceReplaced`), so the allocator never offers +it. The allocator also skips such capacity when it reads the Device after the +offer, and withdraws an allocation that has not claimed its Device once the +Device is no longer the incarnation the allocation names. A Device recreated +after that last check is still not claimed: the custody claim takes the +incarnation from the allocation's `device-uid` label and refuses unless both +the live Device and custody name it, so the allocation is withdrawn and the +allocator selects again (`TestADeviceRecreatedAfterTheLastCheckIsNotClaimed`). +These checks land with stage 2 because enabling is what makes a recreated +Device reachable: before it, registered capacity could not leave `Disabled`, +so it was never offered. The custody claim's check of the live Device +predates stage 2; stage 2 adds the test above, which fails without it. +The name carries the raw UID rather than a hash of it, as stage 1 named it; it +is deterministic and holds one capacity per incarnation. The no-UIDs-in-spec +rule allows a UID in a name, so the naming stays. + +### Status writes + +`machinecapacities/status` is in the webhook rule. A status write to +registered capacity is admitted only from a username in +`--capacity-projectors`. The webhook fails closed, so an outage stops status +updates. The allocator evaluates capacity from live evidence and never reads +the conditions, so stale or edited status cannot make a server allocatable. +Status writes to unmarked capacity are still not routed. + +### Who may call the webhook + +The webhook accepts a client only if its certificate chains to the dedicated +client CA **and** its subject common name is in `--client-identities`. Any +other certificate is refused during the TLS handshake, before a request is +read. The flag is required. The environment must keep the CA dedicated to the +API servers that call the webhook; the identity list is a second check, not a +replacement for that. + +### Configuration + +| Flag | Meaning | +| --- | --- | +| `--client-identities` | Required. Subjects of the API-server webhook client certificates. The base manifest carries a placeholder that admits no caller. | +| `--capacity-projectors` | Usernames of the capacity projector. Empty denies every status write to registered capacity. | + +## UI + +The Datum dialog uses the existing host-session boundary and isolated read +cache. Without a verified session or registration permission, the Register +capacity button is disabled and its tooltip gives the reason. The dialog shows +the derived capacity name instead of a name field. A confirmed registration +closes the dialog without a message; the new row in the Capacity table is the +confirmation. Missing +host authority, denied registration, unavailable Devices, Devices that are not +Active, partial identity and conflicting identities, including a conflict with +a Retired Device, have explicit explanations. The inventory detail panel shows +a Device's lifecycle; the UI does not edit it. Selecting a Device +snapshots its baseline; neither refetch nor browser blur/focus changes it. A +named current read immediately precedes dispatch. Session changes fence +pending work. After dispatch, an uncertain result keeps the selection, disables +retry in that form, and asks the operator to check whether the derived capacity +exists. A repeat cannot create a second record. The unfenced legacy deletion +helper is never used for rollback. + +The registration form sets no pool label. The capacity operator sets it +while the capacity is `Disabled`; see [Enabling registered +capacity](#enabling-registered-capacity). The UI does not yet edit it. + +## Verification + +Run with Kubernetes 1.37.0 envtest assets: + +```sh +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race -count=1 ./... +./hack/validate-overlay-isolation.sh stale_after_seconds`. Stale + values are shown greyed and labelled "Stale · 3 h ago", never green, and + never count as a disagreement or as load. +- A **missing** series is "Not reported", never 0. A reported 0 is shown as + 0 with its age. +- Capacity comparisons use the feed's recorded rating: single-phase + `S = V × I`, three-phase `S = √3 × V × I` (line-to-line voltage), DC + `P = V × I`; the continuous limit is 80% of that. Load above 80% of the + continuous limit is "high", above the limit "over"; both get a glyph as + well as colour. A rating is not available power. + +## What exists today + +- `ui/provider/src/lib/telemetry.ts` defines the `TelemetrySource` + interface: `read({ kind, namespace, name, componentID? })` returns + `PowerTelemetry` (`powerW`, `apparentPowerVA`, `currentA`, `outputState`, + `health`), each an `Observed` with `origin` (collector kind and + instance), `observedAt`, `staleAfterSeconds` and an optional 24-hour + `series`. +- The default source is `none`: every view reads "Not reported" and "No + telemetry source configured". This is what staging and production show. +- `ui/provider/src/lib/telemetry-mock.ts` is a synthetic source for the + fixture preview only, with `normal`, `high-load`, `stale`, `missing` and + `mismatch` scenarios (`?telemetry=`, or `none`). It is loaded + behind the same build-time flag as the fixture inventory, and + `src/test/production-bundle.test.ts` builds the production bundle and fails + if any mock-only string is in it. +- Views show telemetry as a load tint and status marks on outlet and PSU + tiles, one "Updated N s ago" line per outlet group, and the values in the + component card's Telemetry section. The collector, instance, observed time + and freshness window are behind the card's More. See + [Power path and telemetry](staff-inventory-ui.md#power-path-and-telemetry-implemented-telemetry-mocked). +- There is no metrics client. A real source would implement + `TelemetrySource` by querying the platform metrics store through the + portal's existing proxy, using the labels above, and would return nothing + for identities the reader cannot read. + +## Open questions + +- Which platform metrics endpoint the staff portal proxy may query, and with + what authorization, so that a reader without inventory access learns + nothing from series labels. +- Whether feed-level load should come only from the recording rule, or also + from facility branch-circuit monitoring when a facility provides it. +- Whether PSU Fault and breaker-tripped summaries should become Device status + conditions, and which collector would own that writer. diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md new file mode 100644 index 00000000..619baf8f --- /dev/null +++ b/docs/development/machine-images.md @@ -0,0 +1,172 @@ +# OS images and bootstrap data + +[Documentation overview](../README.md) · [Implementation status](README.md) + +This page records how Fleet implements the [OS images and bootstrap data +proposal](https://github.com/datum-cloud/fleet/pull/184) (#184). The +proposal's API names are provisional. Each piece below is marked +**implemented and verified**, **implemented in lab compositions only**, or +**proposed**. + +## Status + +| Increment | What it covers | Status | +| --- | --- | --- | +| 1: image catalog | `MachineImage` and `MachineImagePublication` kinds, publication, admission-time resolution to a pinned digest, architecture and firmware mode checks, the worker's firmware mode check, and IAM | **Implemented and verified.** The CRD rules are checked with the API server's own schema validator, resolution and publication with a fake API server, and installs of a resolved image against a real API server and in the standalone smoke. The multi-plane runs are not yet verified. | +| 2: sealed bootstrap store | `SealedPayload`, the coordinator's check and sweep, delivery to the operation's worker, deletion at the site, IAM | **Implemented and verified** through the simulator site, by unit tests, tests against a real API server, and the standalone smoke. Admission refuses bootstrap data for a Device served through federation, which the local VM and Redfish labs use. | +| 3: federation and network-boot seed prototype | Per-operation payload transport, worker authorization, installer readback and scrubbing | **Test-only.** No runtime flag, deployment or acceptance fixture enables customer seed delivery. | + +## What increment 1 adds + +- **Kinds.** `MachineImage` holds either a provider `definition` or a published + `source`: a `publisherRef` and the image's name there. CEL makes the + definition and the source immutable and lets the provider change only + `availability`. `MachineImagePublication` is the immutable record, in the + provider project, of one consumer copy published from one provider image + incarnation and digest. Its `consumerRef` names the consumer tenant. Its + name derives from the tenant reference and UID, the copy's namespace, name + and UID, and the provider image's name and UID. Its spec holds only names + and the digest, never a UID. +- **Tenant references.** `publisherRef` and `consumerRef` are typed + `{apiGroup, kind, name}` references with names only. A Milo `Project` is + the tenant in multi-plane mode, and a `Namespace` in standalone mode, where + the provider namespace is the publisher. The CRD rules and the catalog + refuse every other kind, and the catalog writes nothing for one. The + catalog takes its consumer from the shared tenancy resolver, with the + reference, incarnation and API client together, and uses the same typed + reference and source shape as MachineClass. +- **Publication.** The publisher writes the consumer copy, then the record. + Until the record exists the copy entitles nothing, so a crash between the + writes fails closed and a retry completes it. +- **Resolution.** Admission reads the consumer copy and the provider image, + derives the record's name from their incarnations and the consumer + tenant's, and refuses unless that record exists and matches the names and + the provider image's digest. A recreated tenant, copy or provider image + finds no record and is refused. The digest comes from the record, never from + the copy's status. The provider definition is immutable, so the digest pins + its content; `availability` is read live. A Fleet deployment serves one + publisher, which also holds every allocation, so a copy must name that + publisher. +- **Republishing.** A record never changes. If a copy or its source is + recreated, publishing it again writes a new record under its own name. The + old record entitles nothing, and the publisher may delete it. +- **Compatibility.** Commissioning records the observed firmware mode (Redfish discovery + or synthetic site enrollment). The capacity projector carries that evidence into + the allocator’s hardware snapshot. Catalog publication never writes capacity + status. Admission refuses an image whose architecture differs, whose + firmware modes do not include the server's, or which takes no bootstrap data + when the Installation has some. An unknown firmware mode installs nothing. +- **Retention.** The DeviceInstallation keeps the image name, digest and + firmware modes, so later catalog changes never change an admitted install. + The Installation reports `status.resolvedImage`. +- **Worker check.** The Redfish worker reads the system's + `BootSourceOverrideMode` and refuses with `ImageIncompatible` before sending + anything if the image does not list it. Redfish defines that property as the + mode of the next override boot, which is the boot the installer uses. A BMC + that does not report it installs nothing. The Redfish lab reports `Legacy`. + Physical BMCs are not qualified. The local VM worker refuses any image that + does not list BIOS, which its guests boot. +- **IAM.** Customer roles may only read and use images. Only the provider and + publisher roles write images, only the publisher writes records, and only + the publisher and the Fleet provider read records. + +## What increment 2 adds + +- **Bootstrap Secret.** A Secret of type `metal.datumapis.com/bootstrap` with + `userData`, `sshAuthorizedKeys`, or both, as UTF-8 text, at most 64 KiB and + at most 96 KiB once encoded, so a site always receives it whole. Admission + refuses anything else with `BootstrapInvalid`, and a missing or unreadable + Secret with `BootstrapNotFound`. +- **Sealed store.** `SealedPayload` in `fleet.datumapis.com`, in the provider + project. Its spec never changes. It holds a random 32-byte salt and the data, + and its digest covers both. Its name derives from the operation name and the + digest. +- **Admission.** If the DeviceInstallation already exists, admission returns + it and reads nothing. Otherwise the Fleet provider seals the data, creates + the payload, then creates the operation, which carries only the payload's + name and digest. Of two concurrent admissions, one operation wins and the + other's payload is swept. +- **Coordinator check.** At the custody update, every site serving the Device + must be able to receive payloads, or the operation fails with + `BootstrapUnsupported`. The payload must exist under the derived name, name + the operation, and match a digest recomputed from its salt and data, or the + operation fails with `BootstrapUnavailable`. Either way nothing is sent. The + coordinator reads through to the API server, and a failed read refuses, as + in every kind check. +- **Sweep.** Each coordinator pass deletes, with a UID precondition, every + payload whose operation ended, whose operation names another payload, or + that has no operation and an allocation that is not `Active`. +- **Delivery.** The courier reads the payload, checks it again, and sends it to + the site beside the assignment. The site takes the payload reference from + the admitted inputs, not from the transport, stores the payload only if it + matches, and the runner checks it again before anything is sent. +- **Site deletion.** The site deletes the payload when the result is stored, + when the coordinator answers the result, and whenever it raises the Device's + fence, for a newer operation or a recovery, which removes every payload + below it, including one whose worker never ran. A worker stopped from + outside keeps it for its replacement. +- **Evidence.** A successful install's evidence records, as installer-verified, + the salted digest of the bootstrap data on the target disk: the simulator + recomputes it from what it wrote, and a lab installer from what it read + back. Custody accepts a success only if it equals the admitted digest, and + only if it is empty when there was no bootstrap data. +- **IAM.** Only the coordinator role reads `SealedPayload`; the installation + requester may only create it. A test walks every Milo role the repository + ships, resolves inheritance, and fails if any other role can read it or holds + a wildcard. + +## What increment 3 adds + +These contracts are exercised with synthetic fixtures in package tests only. Ordinary hubs refuse before writing a payload or handoff; cells and HTTP boot services independently refuse a seed. Neither the lab harness nor staging enables this path. + +- **Federation.** The hub writes each payload as a `MachineAllocationPayload` + beside its handoff, before the handoff that names it. It is its own kind, + not a Secret, because Karmada's member identity watches every kind it + propagates across the whole cell, and the lab BMC's credentials are + Secrets. A worker that runs before the payload arrives sends nothing, + stores no result, and is retried; a payload it cannot read is an error, + and one that does not decode refuses the handoff. +- **Deletion.** The hub deletes a payload when the coordinator answers its + result, and after every complete coordinator pass it deletes each payload + whose operation is no longer delivered: ended, cancelled, superseded, or + never given a handoff. Deleting the hub's copy deletes the cell's. +- **Site RBAC.** Each worker may get its own handoff and its own payload, by + name. kro, which creates every worker, holds only get on payloads, so it + can grant that without escalate or bind; it can already run a worker as + any operation's identity, so this grants it nothing new. Admission policies + admit only the per-operation Role and RoleBinding shapes on create and + update, refuse every cluster-wide RBAC write by kro, and admit only Jobs + that run the site worker for their own handoff and take environment from + literals and the site enrollment. A test against a real API server runs + each refused shape as kro and shows that it is admitted once the clauses it + names are removed. +- **Guest.** The worker renders the verified payload as a NoCloud seed archive + and attaches it to the operation's boot admission. The boot service serves + it as a second initrd only while the admission is open. The site drops the + seed when the admission closes, when the operation's result is stored + however it ended, and when a newer fence for the Device is raised, so no + failed, expired or superseded install leaves it behind. The installer copies + the seed to the target disk, puts the user data where NoCloud reads it and + the keys in the default user's `authorized_keys`, reads it all back from the + disk past the page cache, and reports the salted digest. The worker requires + exactly that digest before it lets the disk boot run; a wrong, truncated or + missing report fails the install. This installer readback is a test assertion, not production installation success. A direct kernel boot, + which has one initrd, refuses bootstrap data. +- **Transport and success.** The #227 virtual-media path requires certificate-verified HTTPS and an authenticated first-boot report from the installed OS. Installer readback or console output is not that proof. Customer bootstrap via virtual media is refused. Only the installed NoCloud files and authorized keys belong on the disk; the network installer keeps its raw JSON and salt in the initramfs. + +## Not implemented yet + +- The validating webhook that rejects image writes from anyone but the + publisher, and definitions outside provider projects. IAM alone keeps + customers from writing images today. +- A Milo IAM image-use check. The standalone and multi-plane compositions use a + fixture authorizer that allows every creator. +- Artifact mirroring by digest from a provider registry. Each lab site holds + one pinned image and serves only that one. +- Firmware mode from BMC discovery. Lab fixtures write it on the capacity. +- The Milo check that the Installation's creator can read the bootstrap + Secret. The lab compositions read it with their own identity. +- Encryption at rest for `SealedPayload` and `MachineAllocationPayload`, on + the provider project, the federation hub and its Work objects, and the + cell, and an audit policy that omits their bodies. +- Verified transport for a customer network-boot seed. HTTP seed serving stays disabled outside package tests. diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index c3d7282b..9f842409 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -43,6 +43,20 @@ mandatory ongoing guest agent. Two consumer projects share provider inventory without double allocation. Lost responses, stale executors, access revocation, and incomplete cleaning cannot cause duplicate effects or premature reuse. +### Device custody and operations + +The [device custody and operations work](device-custody.md) replaces +per-allocation fencing with one custody record per Device, ahead of real +hardware qualification. Increment A (the control-plane foundation), Increment B +(site execution) and Increment C (the cutover) are implemented. C moves every +mode onto custody and deletes the Secret-backed path. An allocation's private +facts live on its MachineAllocation. The standalone smoke and both multi-plane +runs, local VM and Redfish, verify C. Increment D (end-to-end failure +scenarios) is implemented, and both multi-plane runs verify it. + +Acceptance: the #174 acceptance tests pass, in envtest and in fresh local +end-to-end runs, with "nothing sent" proven by the lab BMC audit. + ## 4. Adopt rented capacity and managed clusters Normalize servers.com/NetActuate facts, retain existing identities and diff --git a/docs/development/site-facility-relationship.md b/docs/development/site-facility-relationship.md new file mode 100644 index 00000000..2ab40ddb --- /dev/null +++ b/docs/development/site-facility-relationship.md @@ -0,0 +1,187 @@ +# Operational Sites and physical Facilities + +[Physical inventory](../operations/physical-inventory.md) · [Architecture](../architecture/design.md) · [Staff inventory](staff-inventory-ui.md) + +## Implemented scope, not deployment acceptance + +This additive implementation starts from staging feature revision +`0bc37cf23ca949df97b6ede8bc78f2a71c670ac4`. It adds an operator-written `Site` +record, Facility premises identifiers, observational readers, IAM declarations, +and staff directory views. It does not install these +changes, mutate live records or assert authenticated staging acceptance. + +A clarification of the form **operational Site EX3 relates to provider premises +EX1** describes two concepts, not two Facilities. It is conceptual evidence only, +not permission to migrate existing records. No such mapping is seeded by this +change. Tests and +preview records use synthetic `EX3` / `example-provider / EX1` identities. + +## Ownership and cardinality + +The [pinned Site proposal](../proposals/fleet-management/cluster-lifecycle.md#site-and-cluster-resources) +describes an operational placement and capacity-sharing boundary with explicit +allocation selection. The [inventory appendix](../proposals/fleet-management/inventory-reference.md#facility-and-rack-contracts) +assigns premises to Facility and physical containment to racks and installations. +This implementation reserves the same `fleet.datumapis.com/v1alpha1` Site concept +but implements **identity and observed membership only**, not the proposed +`allocation.facilitySelector`, cluster placement, or capacity-sharing authority. +`facilityRefs` must never be interpreted as the proposed eligibility selector. +Future policy needs a separately authorized contract and admission checks. + +Actual geography and service readiness already belong to the Milo +`locations.miloapis.com` Location projection and service-catalog ServiceAvailability +used by `internal/location.Resolver`. Neither its authority revision nor its +eligibility inputs consume inventory Site records. Facility's existing optional +`locationRef` remains unchanged. Site does not introduce another geographic +resource, provider metro code, account grouping, or Location readiness claim. + +- A Facility owns physical premises. Racks continue to reference exactly one + Facility through their existing `facilityRef`; nothing rewrites these references. +- A Site may record zero to many name-only Facility references (bounded at 64 per record). + A Facility may participate in zero to many Sites. This permits multiple + operational boundaries at shared premises and a boundary spanning premises + without inventing duplicated buildings. Zero means unmapped, never all premises. +- Operational membership is not physical containment. A device's reported or + claim-derived placement is unchanged. A Facility association does **not** assign + every device, installation, allocation, or NodeClaim there to that Site. + Per-consumer operational membership remains with its future owning contract. +- Site and Facility are namespaced provider-project inventory records with the + same explicit direct-API writer discipline. This adds no mapping + service, controller, synchronization owner, or GitOps ownership for records. + +## Stable identity and references + +`Site.spec.code` is the mutable internal human code; `displayName` is a mutable +label. Neither is a reference key or globally unique identifier. Resource names +are API addresses scoped by namespace and project; `metadata.uid` is the server's +resource incarnation identity, never desired-state configuration. References use +the established namespace/name conventions, never human codes or UIDs in spec. +Changing a human code or label does not require rename, deletion, recreation or +metadata UID changes. + +`Site.spec.facilityRefs` reuses `LocalReference`: `{name}` entries scoped to the +Site's own namespace and project. Duplicate names and missing names fail schema +admission. Neither a namespace override nor an incarnation pin is part of the +local reference. `ReadSiteFacilities` reads through the caller-provided authorized +reader, returns no partial result on failure, checks namespace and deletion, and +redacts read error details. It is not a policy resolver. Its caller must +already be authorized to read the Site; it neither grants credentials nor bypasses +the supplied reader's authorization. A privileged reader is not a user IAM check. + +CRD CEL cannot perform cross-object existence/authorization checks. A structurally +valid but missing or deleting target remains **unresolved**, not accepted placement +or authority. A same-name Facility in another namespace does not resolve the local +reference. UI readers use these same namespace/name semantics. + +**Name reuse rebinds:** deleting a Facility and recreating it under the same name +in the same namespace makes an existing Site reference resolve to the replacement, +even though its server UID differs. This does not preserve historical incarnation +identity or prove physical continuity; the spec may remain unchanged. Operators +must review reused names and physical evidence, not treat a resolved reference as +verification, capacity or authority. A reference edit still requires explicit +operator review. This is observational validation, not +atomic graph admission or a referential-integrity controller. + +No new status fields are necessary: there is no Site reconciler or observation +writer requiring retained incarnation tracking. If that later becomes necessary, +observed server identity belongs in status, not desired-state spec. Existing +ephemeral client UID/resourceVersion checks and frozen mutation baselines remain +unchanged; they protect an individual edit, not indefinite reference binding. + +### UID audit for PR100 + +The only UID-bearing spec field introduced by the first PR100 revision was +`Site.spec.facilityRefs[].uid`; it has been removed from Go and TypeScript types, +CRD schema, fixtures and examples. The reference +now reuses the existing `LocalReference` type, and deep copies retain name-only +references independently while preserving server metadata. Site status remains +empty. Provider identifiers and Site codes introduce no resource UID fields. + +Separately, the preexisting `Device.spec.identity.systemUUID` field is a hardware +SMBIOS UUID, not a Kubernetes resource UID; it is unchanged. No other explicit +resource UID spec fields were found in the existing public API types and CRD +schemas inspected for this change. Internal lifecycle custody/authority records +and ephemeral UI mutation baselines retain their existing UID fencing; this is +not an unrelated legacy API migration. + +`Facility.spec.identifiers` is an optional bounded list of +`{provider, type, value}`. `provider` is a canonical provider namespace (for example +`example-provider`), not its mutable display label. Types are `PremisesCode`, `PremisesAlias` +and `PremisesID`. Multiple identifiers, aliases, and provider namespaces are +supported. Identical code values under different providers are distinct; exact +duplicate entries are rejected. These are sourced descriptive facts, not resource +references or global uniqueness claims. A repeated qualified identifier on +different Facilities requires human adjudication; it never merges records. +Provider metro, account, service and host identifiers are not premises identifiers. + +## Staff access and compatibility + +The existing inventory viewer/editor/manager role definitions gain only equivalent +Site read/write verbs. No memberships, consumer roles, status writer permissions, +allocation permissions or operational permissions are changed. The staff directory +adds an Operational sites category, internal code details, provider-qualified +premises identifiers, and reverse Site membership on Facilities. Site writes and +identifier/membership edits remain direct API operations; there is no new UI form. +Existing inventory forms and their session, operation and frozen revision guards +are unchanged. Human label edits preserve the new fields. + +Site 403/404/transport failure does not hide legacy physical records or imply +unmapped membership: the UI says operational Site details are unavailable. A +successful Site list with no matching membership says explicitly unmapped. Denied +Facility reads suppress related identifiers and links from Site details. Search +uses only accessible identities. Existing global session-denial/cache fencing +also covers the additional collection. No credentials or secret-bearing fields +are added to search, details or forms. + +Old Facilities without identifiers remain valid and browsable, and all existing +rack/device/claim references, resource UIDs, immutable identity bindings, +reportedPlacement revisions and unknown geometry retain their contracts. +No allocation, installation, provisioning, capacity, reservation or verification +effects result from any new record. Empty rack units and missing Site mappings +remain observations, not available capacity or readiness. + +## Rollout and remaining gates + +1. Review and deploy CRD/IAM definitions through the existing packaging path, + then the provider UI. Do not apply any example records. The UI tolerates Site + API absence before rollout while keeping physical inventory browsable. +2. Read existing records privately and preserve stable names, UIDs, + ownership and revision baselines. Agree canonical provider namespaces and + verify individual premises identity before adding descriptive identifiers. +3. Separately authorize any Site creation or membership edit. Use names from + authorized reads for spec references. Preserve ephemeral metadata UID and + resourceVersion preconditions for corrections outside the spec. Review name + reuse explicitly. No delete/recreate migration is required or allowed here. +4. Independently review IAM and authenticated staging behavior before rollout. + This task changes no live counts or memberships and does not deploy. Existing + reported-placement corrections and their separate audit companion are out of scope. + +Future allocation policy, canonical provider namespace governance, cross-record +identifier uniqueness adjudication, and atomic relationship admission remain +explicit design/qualification gates. Synthetic tests cannot establish real-world +premises truth or production readiness. + +## Local validation + +```sh +go test -race ./internal/api/inventory/v1alpha1 ./internal/location +(cd ui/provider && pnpm test && pnpm typecheck && pnpm build) +(cd ui/consumer && pnpm test && pnpm typecheck && pnpm build) +bash hack/validate-doc-links.sh +git diff --check +``` + +Tests cover additive schema, provider qualification/collisions, legacy records, +name references despite label changes, name-reuse rebinding, invalid relationships, +read denial/redaction and existing independent safety +scenarios. Existing six-collection request-count assertions now count seven; +their denial, session lifetime, operation and no-write assertions remain intact. + +Local validation on this implementation passed the full `go test -race ./...` +suite with Kubernetes 1.37 envtest assets, provider (392) and consumer (44) +tests/typechecks/builds, inventory and Milo manifest +rendering, local documentation links and +whitespace checks. This is not authenticated staging acceptance. Mobile inspection +was attempted at 390×844 with synthetic fixtures, but both browser snapshots timed +out; the alternate browser host reported unavailable. Visual mobile acceptance +remains a review gate, not a claimed pass. diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md new file mode 100644 index 00000000..e1a98af8 --- /dev/null +++ b/docs/development/staff-inventory-ui.md @@ -0,0 +1,1667 @@ +# Staff physical inventory UI + +## Inventory and Catalog navigation (implemented) + +List pages follow staff-portal's list style (its Customers page): one toolbar +row directly on top of a compact sortable table, then the "rows per page · +1–N of M" footer. This replaces the earlier two rows of group and kind tabs. + +| Page | Navigation | Categories | +| --- | --- | --- | +| Inventory | A category switcher (like staff-portal's `SectionSwitcher`): a datum-ui Popover of links grouped by Equipment, Locations and Installation plans | Devices, Cables, Power feeds · Operational sites, Facilities, Racks · Installation plans | +| Catalog (its own Bare Metal tab) | A two-option pill toggle (like staff-portal's `ViewTabs`) | Manufacturers, Device types | + +Manufacturers and Device types are reference descriptions and templates, not +installed equipment or capacity, so they live on the Catalog page. A record +link always reaches the page its kind lives on: links are absolute, and a kind +requested on the other page is redirected there, which keeps old bookmarks and +relative links working. + +- The navigation renders outside the session boundary and is laid over the left + end of the toolbar row by the page frame (`.inventory-list-frame`); the row + reserves its measured width (`--inventory-switcher-w`). On detail pages + (`.inventory-detail-frame`) it is hidden but stays mounted. At phone width it + sits above the row and the Filter button shows only its icon. +- Each category carries its count ("Devices 18"): the switcher trigger shows the + current one, and the menu and Catalog toggle show every one. A filtered + directory shows "shown/total" and a denied collection "?". The count is the + link's accessible description, never part of its name. `PhysicalInventory` + reports counts through `InventoryCountsProvider` only after the session + boundary resolves, so the public shell and pending and unavailable states + render no number. +- The switcher opens on the current category; arrow keys move between + categories. Choosing the current category is not a navigation. Devices is the + Inventory default and Manufacturers the Catalog default. Directories have no + breadcrumb, visible title or description; an `sr-only` `h1` names the page. +- The toolbar row: a borderless search (applies as the reader types; Enter + applies at once), one **Filter** popover for facility and model with + **Clear filters**, an icon-only Refresh named "Refresh inventory", then + Create. Same-category links retain `q`, `location` and `model`; switching + categories starts an unfiltered directory; Back and Forward restore prior URLs. +- The table is datum-ui's `DataTable.Client` at compact density: sortable + uppercase headers, one-line cells, the whole row opens the record. Columns + come from `inventory-directory-rows.ts` per record type. A row that needs a + second look keeps its coloured edge (red for a conflict, amber for + unavailable data) and its reasons as the row tooltip (`data-attention` and + `title`, set on each row by `InventoryListTable`). +- Same-principal presentation navigation reuses loaded collections and keeps the + page on screen while the host loads; see + [Session boundary](#session-boundary-a-change-of-signed-in-user-implemented). + +## Page design rules + +Most people open this dashboard to find one record and confirm it is the right +one. Detail and list pages follow these rules so that they are not slowed down +by unnecessary or duplicated information. Follow them when adding a kind, +field or view. + +1. **Compact header.** The header shows the display name and one summary line: + lifecycle (only when it is not the normal state), location and issue + badges. A Device adds one strip of identity facts under it. A control + that is unavailable explains why in its tooltip and accessible + description, not in a sentence beside it. Page actions, including + **Edit display name**, sit in the header beside **Refresh inventory**. + The generated resource name and creation date close every record page + as one quiet **Record** line ("Record example-rack-a01 · created + 2026-10-01"), plus any fact the page shows nowhere else. The namespace + (always `default`), the UID and a per-record verification row are not + shown. No page has a general History tab; it returns when an activity + timeline exists. A Device's Operations tab lists its power operations. The breadcrumb is the way back; there is no separate back link. +2. **One primary view per kind**, above the fold: + + | Kind | Primary view | + | --- | --- | + | Device | The device picture, then the dense component table (see [Device page](#device-page-picture-and-component-table)) | + | Cable | A one-lane Cable is one line, "Compute a01-01 · eth0 ⟷ Leaf a01 · swp1". More lanes are a table, one line per lane, with an end device (and port) every lane shares named once in its column head. An end another Cable also names is red, naming and linking that Cable, with the reason as tooltip and accessible text | + | PowerFeed | The power path: upstream, feed rating and capacity, outlet tiles for the feed and each PDU, then device PSUs (see [Power path](#power-path-and-telemetry-implemented-telemetry-mocked)) | + | Facility | None: Racks, Without a rack, Power feeds and Cables tabs (see [Locations and catalog pages](#locations-and-catalog-pages-implemented)) | + | Rack | Its elevation | + | Site | None: Facilities (unless the header names its one facility), Racks, Devices and Installation plans tabs | + | DeviceType | The faceplate drawn from the model's layout, then a dense component table | + | Manufacturer | None: Device types and Devices tabs | + | Claim | Placement, expected hardware (linked to its DeviceType when exactly one readable model matches the manufacturer and model key) and registered devices. A registered device that reports another model is red, with the reason as tooltip and accessible text. No lifecycle badge or registration count; the Planned connections tab appears only when the plan names Cables | + +3. **Secondary detail goes in tabs held in the URL** (`?tab=`), for example + a Device's Location and Hardware & management. Tabs hold + only what the primary view does not already show. A tab label carries its count, or `?` when the collection is + unreadable. A count that needs checking (`17+` when incomplete, `?` with a + reason) is amber, with the reason as its tooltip and in the tab's + accessible name, instead of a sentence on the page. Every panel stays mounted and inactive panels are `hidden`, so + open dialogs and permission checks keep their state. `tab` is in the session + boundary's presentation allowlist, so switching tabs never refetches + inventory. Links to other records never carry `tab`. +4. **Say each fact once.** Do not repeat a facility or rack name in rows when + the header or breadcrumb states it. Put type words and shared values (for + example "Power outlets · IEC C19") in the group header, not on every row. + Do not show a field in both the summary and the body. Replace a related + records list with a count that links to the tab holding the list. + `ui/provider/src/lib/display-names.ts` holds the helpers for this, next to + the rack page's `condensedName` for port tiles. +5. **Issues first, quiet when normal.** Disagreements, unknown placement, + conflicts and unreadable or missing records become short banners at the top + of the page that link to the problem (`IssueBanners`), unless the primary + view already shows them: the Device page leaves Cable disagreements to its + picture, its table rows and the count line, where "n disagree" is red. Empty and "not + recorded" fields are hidden by default (`Facts`). Keep an absent value + visible only when the absence itself matters: verification is unknown, + power budget is unknown, and "No cable recorded" stays on outlets because + it means unknown, not free. +6. **State, not caveats.** Pages carry no legend lines or caveat prose + ("not verified", "not free", "does not prove…"). States are shown + visually and named in words where they apply: "No cable recorded", red + and amber edges, "?" counts, with the reason as the tooltip and + accessible name. Nothing may look free, available or verified, and when + a collection is unreadable, counts and states read as unknown, never + zero or empty. +7. **List pages are search-first and dense.** Search and filters sit at the + top and keep their URL parameters (`q`, `location`, `model`); search + matches the text the row shows. Directory tables use `inventory-dense-table`: + one line per row, long cells cut with an ellipsis and the full text in the + tooltip. Each kind has its own columns (`inventory-directory-rows.ts`): + + | Kind | Columns | + | --- | --- | + | Devices | Name, Rack, U, Face, Model, Serial, Asset tag, Power (feeds the PSUs reach) | + | Cables | Name, Medium, A end, B end, Lanes | + | Power feeds | Name, Location, Type, Voltage, Breaker, Capacity, Load | + | Operational sites | Name, Code, Facilities, Racks, Devices | + | Facilities | Name, Code, Site, Racks, Devices | + | Racks | Name, Height, Devices, Used ("12/42U"), Power, Feeds | + | Installation plans | Name, Rack, U, Face, Model, Device, State | + | Manufacturers | Name, Aliases, Device types, Devices | + | Device types | Name, Manufacturer, Model key, Height, Depth, Ports, Devices | + + Facility appears before Rack only when more than one facility exists. + Serial, Asset tag, Power, Lanes and Aliases appear only when some row has + a value. Devices and plans sort by location (facility, rack, top of rack + first), with unplaced devices last; other kinds sort by name. A cable end + is "Leaf a01 · swp1", and a breakout end that reaches several devices is + "4 devices · eth0" with each lane in the tooltip. Related records show + their display names, never record names, except to tell apart catalog + records whose display names collide. A non-Active device has its + lifecycle as a muted word after the name. + + State is colour, not words in cells. A row whose records disagree + (multiple registrations, two cables on one port, overlapping rack + placements) has a red edge; a missing or unreadable peer, an unknown + position, a planned-only location or a placement that differs from its plan + has an amber edge. The reason is the row tooltip and part of the name + cell's accessible text. Unknown values read "?", with the reason in the + tooltip and accessible text; Used units never show free space and read "?" + when any placement lacks a position. Clicking a row opens the record; the + name stays the keyboard link. +8. **Mobile.** At 390 px the header, primary view and tabs must work without + horizontal page scroll. `pnpm screenshots` fails a page that overflows. + +Write controls stay available but quiet: display-name editing and Refresh sit +in the header actions, and reported-location correction is on the Device's +Location tab. Their dialogs, task pages, dirty-dismiss confirmation and +unknown-outcome handling are unchanged. + +The building blocks are in `ui/provider/src/components/inventory-record-layout.tsx` +(`RecordSummary`, `IssueBanners`, `RecordTabs`, `Facts`, `FactSection`, +`RecordFooter`), and the per-kind views are in `inventory-record-detail.tsx`. +`inventory-record-layout.test.tsx` covers the disclosure, tab URL state, issue +banners, hidden empty fields, list columns, and the Device page's header +strip, picture, table, one count line and tab contents. + +## Form controls (implemented) + +Every control in the staff and consumer plugins comes from datum-ui: +Select, Input, Button, Table and the `picker` DateTimePicker. Neither plugin +renders a native ``, `