From 8afb4523ac18c92c8be7f085d097fb3508080d3c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 10:30:05 -0600 Subject: [PATCH 01/12] docs: propose PXE installation architecture --- README.md | 3 + docs/enhancements/pxe-installation/README.md | 375 ++++++++++++++++++ .../diagrams/architecture.svg | 133 +++++++ .../diagrams/installation-workflows.svg | 107 +++++ .../diagrams/user-journeys.svg | 115 ++++++ 5 files changed, 733 insertions(+) create mode 100644 docs/enhancements/pxe-installation/README.md create mode 100644 docs/enhancements/pxe-installation/diagrams/architecture.svg create mode 100644 docs/enhancements/pxe-installation/diagrams/installation-workflows.svg create mode 100644 docs/enhancements/pxe-installation/diagrams/user-journeys.svg diff --git a/README.md b/README.md index 778018b3..010548c4 100644 --- a/README.md +++ b/README.md @@ -47,5 +47,8 @@ today. Then choose a topic: The [Bare Metal CLI enhancement](docs/enhancements/metal-cli/README.md) proposes `datumctl metal` discovery, machine management, and safe recovery workflows. +The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) +proposes managed images and bounded delegation to customer PXE. + Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md new file mode 100644 index 00000000..f911a507 --- /dev/null +++ b/docs/enhancements/pxe-installation/README.md @@ -0,0 +1,375 @@ +--- +status: provisional +stage: alpha +--- + +# PXE installation and delegated network boot + +- [Summary](#summary) +- [Motivation](#motivation) +- [Proposal](#proposal) + - [User stories](#user-stories) + - [Installation modes](#installation-modes) + - [Managed golden image](#managed-golden-image) + - [Delegated customer PXE](#delegated-customer-pxe) +- [Design details](#design-details) + - [Control-plane placement](#control-plane-placement) + - [API design](#api-design) + - [Admission and authority](#admission-and-authority) + - [Location execution](#location-execution) + - [Completion and evidence](#completion-and-evidence) + - [Release and recovery](#release-and-recovery) + - [Security boundaries](#security-boundaries) + - [Acceptance tests](#acceptance-tests) +- [Production readiness review questionnaire](#production-readiness-review-questionnaire) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) +- [Open design questions](#open-design-questions) +- [Infrastructure needed](#infrastructure-needed) + +## Summary + +Fleet will support two ways to install an allocated bare-metal machine. Fleet can +automatically install a platform-approved golden image, or it can temporarily +chain the machine to a customer-supplied PXE service. Both paths use the same +immutable `Installation`, allocation, federation handoff, power, boot fencing, +and release contracts. + +The Fleet management control plane admits the exact operation before any effect. +The Federation Control Plane delivers that operation to one selected location +control plane. The location prepares networking, controls one-time network boot, +executes the selected installation mode, and returns attributable evidence. + +Fleet does not adopt a separate provisioning platform. A location may use +Kubernetes CRDs, Jobs, and Kube Resource Orchestrator (KRO) to compose local work, +but those resources are execution details and cannot allocate a machine, expand +the admitted operation, or release capacity. + +![Control-plane architecture for managed and delegated PXE installation](diagrams/architecture.svg) + +## Motivation + +Some customers want a ready machine built from a supported platform image. Other +customers already operate an installation system and need Fleet to hand an +allocated machine to that system without giving it broad DHCP, BMC, or provider +inventory access. + +Treating those as unrelated workflows would duplicate boot, power, fencing, and +recovery logic. Giving a customer direct control of a shared provisioning network +would let its system affect machines outside its allocation. Requiring Fleet to +understand each customer installer would create an unnecessary backend contract. + +### Goals + +- Install approved golden images through an automated PXE workflow. +- Chain one allocated machine to a customer PXE endpoint for a bounded session. +- Keep Fleet in control of allocation, power, the first boot decision, fencing, + release, and provider cleanup. +- Use one immutable Installation and one durable handoff protocol for both modes. +- Keep DHCP, IPAM, switch configuration, and routing with their existing owners. +- Report what Fleet verified without claiming knowledge of an opaque customer OS. + +### Non-goals + +- Running or adopting Tinkerbell, Metal3, Ironic, or another provisioning control + plane as part of Fleet. +- Giving customers BMC credentials or authority to answer DHCP on a shared + provisioning network. +- Supporting a permanently network-booted workload in the first release. +- Continuously managing or monitoring the installed operating system. +- Making KRO, a Job, or a location-local record an allocation authority. + +## Proposal + +### User stories + +- A customer selects a supported golden image and receives an installed machine + without operating a provisioning service. +- A customer with an existing PXE service installs its own operating system on + an allocated machine while Fleet retains power and boot control. +- A provider controls which MachineClasses permit managed images or delegated PXE. +- An operator can recover a lost response without repeating a destructive action + or exposing uncertain capacity to another customer. + +The two customer journeys share admission and fencing but differ in who supplies +the installer and what Fleet can verify: + +![Customer journeys for managed images and delegated PXE](diagrams/user-journeys.svg) + +### Installation modes + +An Installation has exactly one source: + +| Mode | Installer and image owner | Fleet verifies | +| --- | --- | --- | +| `ManagedImage` | Fleet resolves a platform-approved image and qualified recipe. | Exact image and recipe, target disk evidence, boot fencing, and required first-boot evidence. | +| `DelegatedPXE` | The customer supplies a PXE endpoint and controls its installer. | Exact delegation target, boot session, customer result, boot fencing, and the configured post-install boot observation. | + +MachineClass policy advertises supported modes. It does not grant permission to +use them. Fleet checks current source-use authority, allocation identity, class +revision, endpoint policy, networking feasibility, and predecessor state when it +admits each Installation. + +### Managed golden image + +Fleet resolves the approved image, bootstrap configuration, hardware compatibility, +and location recipe. It retains their exact identities, bytes or digests, and +revisions before dispatch. The selected location then: + +1. obtains provisioning-network readiness from its owner; +2. authorizes one network boot for the selected machine; +3. boots a small Fleet installer; +4. writes and verifies the pinned image on the admitted target disk; +5. revokes network boot and requests local-disk boot; and +6. returns installation and required first-boot evidence. + +### Delegated customer PXE + +The customer provides an HTTPS iPXE endpoint, trust configuration, optional +endpoint credentials, and a completion policy. Fleet retains protected copies of +those inputs before dispatch. The location boot service remains the first boot +decision point and chains only the admitted machine to the customer endpoint. + +The customer does not receive BMC credentials or DHCP authority. Its system may +install any OS allowed by service policy, then sends an operation-scoped completion +callback. The location revokes delegation, requests local-disk boot, and returns +the evidence required by the Installation contract. + +The first release requires delegated PXE to finish with local-disk boot. A +permanently network-booted runtime needs a separate design because it retains boot +authority for the life of the allocation. + +## Design details + +### Control-plane placement + +The design follows the Fleet management control-plane boundaries: + +| Boundary | Responsibility | +| --- | --- | +| Provider project API | MachineClass policy, MachineCapacity, physical inventory, and provider eligibility. | +| Consumer project API | Machine and immutable Installation requests and projected status. | +| Fleet private storage | Exact allocation, caller authority, admitted inputs, operation journal, credentials, and cleanup custody. | +| Fleet management runtime | Admission, allocation coordination, handoff creation, and result validation. | +| Federation hub | Canonical admitted location handoff and cell-owned execution status. | +| Selected location control plane | Network integration, PXE authorization, power, installation execution, fencing, and evidence. | + +The Fleet runtime's deployment cluster is not the canonical store for project +objects or federation intent. Kubernetes UIDs are local evidence and do not cross +project, hub, or cell API boundaries as authored references. + +### API design + +The following shapes are proposals, not implemented schemas. `Installation.spec` +remains immutable and keeps the existing predecessor contract. + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: + name: example-os-1 + namespace: default +spec: + machineRef: {name: example} + expectedPredecessor: {type: None} + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} +``` + +A delegated request selects the other union member: + +```yaml +spec: + machineRef: {name: example} + expectedPredecessor: {type: None} + source: + delegatedPXE: + endpoint: + url: https://pxe.customer.example/boot.ipxe + trustBundleRef: {name: customer-pxe-ca} + authorizationRef: {name: customer-pxe-credentials} + correlation: + workflowID: example-workflow-1 + templateDigest: sha256:example + completion: + mode: Callback + postCompletionBoot: LocalDisk +``` + +The API server applies defaults before Fleet captures the request digest. Fleet +resolves referenced Secrets under the caller's authority and retains protected +copies needed for recovery. Credentials and rendered bootstrap content do not +enter the federation handoff. + +MachineClass definitions add policy describing supported installation modes and +boot capabilities. Publication exposes only the permitted summary. The exact +provider executor, BMC enrollment, installer recipe, and boot-service configuration +remain private location state. + +### Admission and authority + +Before dispatch, Fleet retains: + +- provider and consumer Project identities; +- Machine, MachineAllocation, MachineCapacity, and Installation incarnations; +- the MachineClass and MachineProfile revisions; +- the consumed predecessor and operation identity; +- target location, boot interface, and qualified firmware mode; +- image, recipe, bootstrap, endpoint, trust, and credential digests as applicable; +- current IAM, entitlement, quota, and source-use decisions; and +- an executor fencing token and required completion evidence. + +The handoff contains the exact admitted target and non-secret execution inputs or +protected capability references. Delivery to a cell is not fresh authorization. +The cell cannot select another machine, endpoint, image, or installation mode. + +### Location execution + +A qualified location runs a small platform boot service. Provider DHCP directs +eligible firmware to that service. With no active admitted boot session, the +service returns local boot. With a valid session, it serves the Fleet installer or +chains through an allocation-scoped proxy to the admitted customer endpoint. + +The proxy validates the endpoint and TLS policy, prevents unapproved redirects, +keeps endpoint credentials away from the machine, and records the response digest. +Customer artifacts referenced by the returned script must use approved HTTPS +origins or the same scoped proxy. + +Location implementation may use: + +- a Deployment or facility-edge DaemonSet for boot scripts and callbacks; +- a private execution CRD for the delivered handoff; +- Jobs for bounded Redfish, power, verification, and fencing actions; and +- KRO to create and order those local resources. + +Jobs must recover a retained provider operation before retrying. Job completion +does not by itself prove a remote effect. A KRO instance is derived state and +cannot replace the hub handoff, operation journal, or provider fence. + +![Shared installation workflow and mode-specific execution](diagrams/installation-workflows.svg) + +### Completion and evidence + +The cell issues a short-lived callback capability for delegated PXE. The callback +can report the retained operation's result but cannot choose another target, +extend authority, request release, or write public status. + +Managed-image success proves the qualified image and recipe evidence required by +the class. Delegated success normally proves only that Fleet delegated the correct +machine, the customer reported completion, Fleet revoked the delegation, and the +configured local boot was observed. Public status identifies the result mode and +assurance rather than describing an opaque customer OS as platform verified. + +Fleet validates the target, operation revision, fencing token, evidence freshness, +and required conditions before setting Installation `Ready=True`. Installation +readiness reports completion of the admitted contract, not continuing guest health. + +### Release and recovery + +A timeout or lost response does not prove that an installer stopped. Fleet marks +the outcome unknown, retains the allocation, and recovers the same operation. A +takeover must fence the old executor at the boot, network, power, and provider +effect boundaries before continuing. + +Release closes new boot and power admission, revokes PXE and console sessions, +fences provisioning networking, settles in-flight work, and performs required +provider cleanup. Capacity returns to supply only after cleanup is verified. +Consumer project deletion does not remove these provider-side obligations. + +### Security boundaries + +- The platform remains the first DHCP and iPXE decision point. +- A delegated endpoint applies to one allocation and one admitted operation. +- Customer endpoint access is restricted against server-side request forgery and + cross-allocation data exposure. +- BMC, provider, bootstrap, and endpoint credentials remain in protected stores. +- Boot requests authenticate more than a caller-supplied MAC address. +- Callback capabilities are short lived, single operation, and non-authoritative. +- Logs and evidence retain correlation and digests without secret content. + +### Acceptance tests + +Qualify one UEFI, Redfish, non-Talos hardware and OS combination. Test both modes +through real project admission, federation delivery, networking, and disposable +hardware. + +Acceptance requires: + +- only the allocated machine can use a boot session; +- a managed install writes the retained image and boots from the selected disk; +- a delegated endpoint cannot affect another machine or shared DHCP; +- duplicate delivery and duplicate Jobs recover one retained operation; +- endpoint, cell, image, predecessor, and fencing mismatches cause no effects; +- lost callbacks and cell outages remain unknown rather than ready; +- revocation prevents another network boot after completion; +- release cannot expose capacity before network and provider cleanup; and +- customer project deletion preserves recovery and cleanup custody. + +## Production readiness review questionnaire + +### How is the feature enabled or disabled? + +Enable installation modes per accepted MachineClass and qualified location. +Rollback stops new admission while preserving handoff recovery, boot revocation, +and release. Disabling a controller does not cancel remote work. + +### What must operators monitor? + +Monitor active and expired boot sessions, handoff delivery lag, endpoint failures, +unknown operations, stale callbacks, fencing failures, cleanup age, and quarantined +capacity. Correlate each event with the retained allocation and operation. + +### How are failures recovered? + +Query the retained operation and location evidence before retrying. Reuse its +identity and exact inputs. Fence the previous executor before takeover. Missing or +conflicting evidence blocks readiness and capacity reuse. + +### What must upgrades preserve? + +Preserve allocation custody, immutable Installation inputs, handoff revisions, +executor fencing, active boot sessions, callback correlation, and cleanup +obligations. Test mixed versions and restore while both installation modes run. + +## Drawbacks + +The platform must operate a boot service and small ephemeral installer at each +qualified location. Delegated PXE adds endpoint security and weaker OS assurance. +Strict fencing can keep a machine unavailable when a customer system or location +cannot prove that work stopped. + +## Alternatives + +- **Adopt a provisioning platform:** rejected because it adds overlapping hardware, + workflow, networking, and lifecycle authorities. +- **Give customers direct DHCP or BMC access:** rejected because it can affect + machines outside the allocation and is difficult to revoke safely. +- **Treat delegated PXE as allocate-only with no Fleet operation:** insufficient + when Fleet must provide one-time PXE, power, network isolation, and recovery. +- **Create a public ProvisioningClass now:** deferred. MachineClass policy and the + immutable Installation source establish the first required contract without a + second offering hierarchy. + +## Open design questions + +- Exact MachineClass policy and Installation union schemas. +- Portable handoff encoding and the location status writer contract. +- Boot identity beyond MAC address for the first qualified hardware. +- Customer endpoint connectivity, TLS trust, proxying, and artifact-origin policy. +- The managed installer image, action format, target-disk selector, and signing. +- Callback authentication and the minimum delegated completion evidence. +- Whether repeated endpoint configuration later warrants a reusable public kind. +- Durable journal, credential broker, evidence retention, and restore protocols. + +Record these decisions and their rationale before enabling hardware effects. + +## Infrastructure needed + +Testing needs one provider project, two consumer projects, a federation hub, one +selected location control plane, networking-owner integration, a platform boot +service, an independent customer PXE endpoint, protected artifact and credential +storage, and disposable Redfish/UEFI hardware. Failure injection must cover lost +responses, duplicate delivery, stale workers, endpoint outages, control-plane +outages, credential revocation, and storage restoration. diff --git a/docs/enhancements/pxe-installation/diagrams/architecture.svg b/docs/enhancements/pxe-installation/diagrams/architecture.svg new file mode 100644 index 00000000..b3474131 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/architecture.svg @@ -0,0 +1,133 @@ + + Fleet PXE installation control-plane architecture + Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and returns evidence. + + + + + + + + + PXE installation follows Fleet's existing authority boundaries + + + PROJECT CONTROL PLANES + + + Provider project API + MachineClass policy + MachineCapacity + Fleet physical inventory + Provider and allocator-owned state + remains canonical here. + + + Consumer project API + Machine + Immutable Installation + ManagedImage or DelegatedPXE + Customers write requests; + Fleet projects verified status. + + + Fleet private storage + Allocation custody + Exact admitted inputs + Journal, credentials, cleanup + Not reconstructed from status. + + + MANAGEMENT AND DELIVERY + + + Fleet management + Authenticate and authorize + Allocate and hold quota + Resolve and pin inputs + Admit one exact operation + Validate returned evidence + Its deployment cluster is not + the canonical project store. + + + Karmada federation hub + MachineAllocationHandoff + Exact target and operation + Selected-cell delivery + Management writes intent; + the cell writes execution status. + + + SELECTED LOCATION / CELL + + + Cell execution + Local handoff adapter + Jobs and optional KRO + Provider operation recovery + Cannot change the admitted target. + + + Networking owner + Provisioning attachment + Address and switch state + Cleanup or fencing evidence + Fleet is not another IPAM writer. + + + Platform boot service + First iPXE decision + One-machine boot session + Installer or endpoint proxy + Callback and evidence + No session means local boot. + + + Provider executor + Redfish power and boot + Operation ID and fencing + Local boot transition + Release and cleaning + Credentials remain private. + + + Bare-metal machine + Fleet installer or customer installer + Then local-disk boot + Never becomes allocation authority. + + + Customer PXE endpoint + Customer-owned script and workflow + Operation-scoped callback + Used only for DelegatedPXE. + + + + + + + + + + + + + + + + targeted delivery + admitted request + result + verified status + diff --git a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg new file mode 100644 index 00000000..cc512f36 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg @@ -0,0 +1,107 @@ + + Managed image and delegated PXE installation workflows + A shared admission and network preparation flow branches into a managed golden-image installation or a delegated customer PXE installation. Both paths converge on PXE revocation, local boot, verification, and status projection. + + + + + + + + + Both modes share admission, fencing, and release + + + 1. Installation request + ManagedImage or + DelegatedPXE + + + 2. Admit exact inputs + Authority, predecessor, quota + + + 3. Deliver handoff + One selected location + + + 4. Prepare network + Owner returns network + readiness evidence + + + 5. Arm one PXE boot + Retained operation and fence + + + + + + + + + + MANAGED GOLDEN IMAGE + + Serve Fleet installer + Pinned installer and recipe + Machine and disk identity check + + + Write golden image + Verify artifact digest + Return target-disk evidence + + + + DELEGATED CUSTOMER PXE + + Proxy admitted endpoint + Pinned origin, trust, credentials + Record served boot response + + + Customer installs OS + Customer-owned workflow + Operation-scoped callback + + + + + 6. Revoke PXE and fence executor + Disable delegation, close network capability, + and prove the previous worker cannot continue + + + + + + 7. Boot local disk + Provider executor controls BMC + + + 8. Validate evidence + Mode-specific assurance + + + 9. Project status + Ready only after required proof + + + + + + + Unknown outcome + Retain allocation; recover + + timeout, lost response, stale worker + diff --git a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg new file mode 100644 index 00000000..ef98de05 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg @@ -0,0 +1,115 @@ + + Managed image and delegated PXE user journeys + Two swimlanes show a customer requesting a managed golden image or supplying a PXE endpoint. Fleet admits each request, the selected location performs bounded boot work, and the machine returns to local boot before Fleet reports completion. + + + + + + + + + Two customer journeys, one Fleet lifecycle + + + + + + + + + + CUSTOMER + FLEET MANAGEMENT + SELECTED CELL + INSTALLER OWNER + MACHINE + + Managed golden image + + + Select image + Create immutable + Installation + + + Admit request + Pin image and authority; + target and prior state + + + Prepare and boot + Network ready; one-time PXE; + provider power operation + + + Fleet installer + Write and verify + golden image + + + Boot local disk + Return required + first-boot evidence + + + + + + + + Validate evidence + Project Ready status + + + Receive result + Qualified image installed + + Delegated customer PXE + + + Supply endpoint + URL, trust, credentials, + workflow correlation + + + Admit delegation + Check class policy; + pin endpoint and target + + + Prepare and chain + One-machine PXE session; + proxy admitted endpoint + + + Customer installer + Install chosen OS; + send scoped callback + + + Boot local disk + PXE delegation revoked; + local boot observed + + + + + + + + Validate evidence + Report delegated assurance + + + Receive result + Contract complete; OS opaque + From bfea7d8ea5f1adaef824e7e4dbbaa4e36ddc66bd Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 11:58:23 -0600 Subject: [PATCH 02/12] docs: align PXE authority with offerings and BMC lifecycle --- docs/architecture/README.md | 30 ++- docs/architecture/design.md | 26 ++- docs/enhancements/machine-lifecycle/README.md | 183 +++++++++------- .../machine-lifecycle/acceptance-tests.md | 9 +- .../machine-lifecycle/api-examples.md | 133 +++++++----- .../diagrams/public-resources.svg | 13 +- docs/enhancements/pxe-installation/README.md | 196 +++++++++++++++--- .../diagrams/architecture.svg | 25 ++- .../diagrams/installation-workflows.svg | 17 +- .../diagrams/user-journeys.svg | 14 +- 10 files changed, 459 insertions(+), 187 deletions(-) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 510c6d48..4d305dfe 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -58,6 +58,7 @@ 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. | +| `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; no physical inventory CRDs or real provider executor are 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`. | @@ -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, diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 125d7209..21082fb8 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -37,7 +37,7 @@ All names below describe proposed resources, not implemented schemas. | Subsystem | Responsibilities and principal resources | | --- | --- | | Inventory | `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`: approved installation plans, actual assets, physical reservations, and verification evidence. | -| Capacity publication | Provider `MachineClass` definitions and consumer-local references; discovery and safe summaries through service enablement and IAM. Publication does not reserve capacity or grant source-use permission. | +| Capacity publication | Provider `MachineOffering` owns capability policy; `MachineOfferingAssignment` grants acquisition access; consumer `MachineClass` is a one-hop published view. `MachineProfile` contains immutable requirements. Publication does not reserve capacity or grant runtime authority. | | Machine allocation | Provider `MachineCapacity`, customer `Machine`, and private `MachineAllocation`: exclusive reservation, admission of consumer operations, activation, and release across provider and consumer projects. | | Bare-metal provisioning | Typed provider resources and adapters: execute admitted preparation, installation, power, console, and cleanup operations against exact assets. Backend workflows remain private. | | OS configuration | `MachineImage`, `InterfaceClass`, `Installation`, and `OSConfigPolicy`: approved artifacts, immutable installation requests, configuration composition, and one selected executor per incarnation. | @@ -57,6 +57,21 @@ 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 [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 @@ -72,15 +87,20 @@ their owning services. Fleet consumes these contracts and their evidence. 3. **Use one allocator.** Standalone consumers and managed clusters compete through the same durable reservation protocol. Create one immutable, terminal MachineAllocation between the customer Machine and provider MachineCapacity; - retain current authorization, quota holds, class revisions, and local source + retain current authorization, quota holds, accepted offering identity and + contract/profile, installation/management capabilities, and local source object identity as private admission evidence. Names, not cross-control-plane Kubernetes UIDs, are authored references. Overlapping classes must not duplicate supply. 4. **Separate discovery from authorization.** Consumer MachineClasses reference a - provider definition in one hop. Check current source-use permission, + provider MachineOffering in one hop. Check effective acquisition assignment, + current source-use permission, entitlement, quota, and placement feasibility at allocation commit. A copied reference, cached status, namespace, or privileged controller identity is not proof of consumer access. + Withdrawal blocks new allocations, not retained runtime rights. Reinstall uses + retained capabilities plus current install/image/secret/endpoint permissions + and explicit safety/suspension checks. Cleanup retains authority independently. 5. **Persist exact inputs before effects.** Retain admitted plans, artifacts, digests, target identities, predecessor preconditions, execution authority, and operation correlation. Timeouts mean unknown outcomes; recover the existing diff --git a/docs/enhancements/machine-lifecycle/README.md b/docs/enhancements/machine-lifecycle/README.md index 9dd3cbad..4d4351ba 100644 --- a/docs/enhancements/machine-lifecycle/README.md +++ b/docs/enhancements/machine-lifecycle/README.md @@ -38,9 +38,9 @@ stage: alpha ## Summary -Fleet will let consumers allocate and install machines in their project. -Five public resources define the contract: `MachineClass`, `MachineProfile`, -`MachineCapacity`, `Machine`, and `Installation`. Fleet keeps immutable +Metal defines the common public contract; Fleet is an optional provider +implementation. Consumers use `MachineClass`, `MachineProfile`, `Machine`, and +`Installation`; providers expose supply through `MachineCapacity`. Fleet keeps immutable allocation and operation records in the provider project. These internal records retain ownership, execution authority, exact inputs, and cleanup obligations. @@ -126,7 +126,9 @@ machine. Deleting a completed Installation leaves the OS and allocation in place ### Resource relationships across projects -Classes describe provider offerings; profiles describe hardware requirements. +MachineOffering owns provider policy; MachineClass publishes its consumer view. +MachineOfferingAssignment controls acquisition access; profiles contain immutable +hardware requirements, not installation or management policy. An offering can support several profiles, and a profile can serve several offerings. Consumers can define custom profiles where the offering permits them. @@ -192,61 +194,57 @@ not copy an opaque revision, UID, or epoch between requests. #### MachineClass -Provider operators own definitions; the publication service owns consumer -references. The example uses provider types from the -[bare-metal proposal][allocation]. +Provider operators own `MachineOffering` in `provider.metal.datumapis.com`; +MachineClass is a publisher-owned one-hop consumer view, never a provider policy +definition. MachineOfferingAssignment controls acquisition access. These proposed +contracts replace earlier draft shapes without migration or compatibility rules; +they do not describe the current alpha CRD implementation. ```yaml -apiVersion: metal.datumapis.com/v1alpha1 -kind: MachineClass -# Classes span the provider project so namespaces can share an offering. +apiVersion: provider.metal.datumapis.com/v1alpha1 +kind: MachineOffering metadata: name: standard-metal -# The definition owns offering policy; profiles own hardware requirements. -# Its mode cannot change after creation. spec: - # Named profiles select provider-local contracts by name. - # Fleet retains their resolved identities internally. - # Custom profiles default to disabled and require provider validation. profilePolicy: allowedProfiles: - name: accelerated-16c-64g customProfiles: enabled: false - - # Access describes supported operations, not permission to perform them. - # The first implementation supports power control but no console sessions. - access: - consoleModes: [] - powerControl: true - - # Capacity limits selection to existing supply in one provider namespace. - # Labels identify candidates; they confer no eligibility or purchase authority. - capacity: - machineCapacities: - namespace: infra-ops - selector: - matchLabels: - fleet.datumapis.com/capacity-pool: general-metal - - # Provider backend qualification and BMC enrollment are private cell state. - # Public classes select admitted capacity, not an implementation-specific CRD. - -# The projector reports the definition that the class evaluator accepted. -# Acceptance validates the offering; it does not reserve or promise capacity. + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + completionContracts: + - {mode: VerifiedImage, assurance: QualifiedImage} + - {mode: CustomerCallback, assurance: DelegatedContract} + management: + profiles: [ReadOnly, Provisioning] + provisioningSteps: [OneTimePXE, Reset, LocalDisk] + powerControl: true status: - evaluatedRevision: class-revision-example + evaluatedRevision: offering-revision-example conditions: - - {type: Accepted, status: "True"} + - type: Accepted + status: "True" + observedGeneration: 1 + lastTransitionTime: "2026-11-14T12:00:00Z" + reason: OfferingValid + message: "Profile and capability contracts accepted; no capacity reserved." ``` +The offering is a portable service promise. Fleet inventory selectors, executor +configuration, and BMC enrollment belong to private provider implementation state, +not MachineOffering. The permitted source/driver/completion combinations and +management steps follow the [PXE contract](../pxe-installation/README.md). + An offering must allow named profiles, custom profiles, or both. Enabling custom profiles still requires provider validation of the complete configuration at the requested location. Approval applies to a profile's lifetime. A missing or recreated profile blocks its entry. The provider must select a new name or remove and re-add the entry in -separate accepted class revisions to approve a replacement. +separate accepted offering revisions to approve a replacement. Publication, quota, image, and network policy remain separate from the definition. The publication service creates the consumer reference: @@ -262,6 +260,8 @@ metadata: # cannot become a definition or override its policy. spec: source: + apiGroup: provider.metal.datumapis.com + kind: MachineOffering project: provider name: standard-metal @@ -270,8 +270,8 @@ spec: status: # The revision identifies the evaluated offering independently of this # reference object's generation. It does not grant source-use permission. - evaluatedRevision: class-revision-example - resolvedClass: + evaluatedRevision: offering-revision-example + resolvedOffering: # Publication maps allowed provider profiles to protected local copies. # These local names do not expose provider inventory or grant use. profilePolicy: @@ -279,15 +279,19 @@ status: - name: accelerated-16c-64g customProfiles: enabled: false - access: - consoleModes: [] - powerControl: true + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + management: + profiles: [ReadOnly, Provisioning] + powerControl: true conditions: - {type: SourceResolved, status: "True"} ``` -Resolution follows one hop to a definition and rejects cycles, chains, and mixed -modes. Fleet checks current offering policy and authorization at Machine admission; +Resolution follows one hop to MachineOffering and rejects cycles, chains, and +consumer-authored policy overrides. Fleet checks current offering policy and authorization at Machine admission; accepted Machines retain the source identities, revision, and requirements through later edits. [Publication and access rules](#authorization-and-publication) control who receives and may use an offering. @@ -629,11 +633,15 @@ dispatch new work. A named profile must be the provider-approved profile or its protected published copy. Matching names or requirements do not establish that relationship. Other profiles take the custom path, including profiles from another provider. The -class must permit custom profiles, the adapter must accept the complete +offering must permit custom profiles, the adapter must accept the complete configuration, and published sources still require use permission. -A MachineAllocation retains its accepted requirements and hardware snapshot through source -changes or deletion. Later observations can change readiness, but a bound Machine +A MachineAllocation retains the accepted offering identity and contract, immutable +profile requirements, installation/management capabilities, and hardware snapshot +through source changes or deletion. Offering/assignment withdrawal blocks new +allocations, not retained runtime rights; reinstall still checks current action, +image, secret and endpoint permissions and explicit safety/suspension controls. +Cleanup remains authorized by retained obligations, even after withdrawal. Later observations can change readiness, but a bound Machine never moves to another Machine. Owner references cannot replace Fleet's release protocol. @@ -722,23 +730,28 @@ metadata: name: example-os-1 namespace: default # The entire spec is immutable so recovery uses the same authorized inputs. -# Machine and approved image are required. Fleet checks install and image-use -# permissions and internally pins the Machine lifetime, image artifacts, and digests. spec: machineRef: {name: example} # This required precondition prevents competing installs from replacing # an unexpected OS. None identifies a blank allocation with no admitted install. expectedPredecessor: type: None - imageRef: {name: qualified-linux} - - # Optional bootstrap data comes from a Secret in this namespace under - # explicit caller authority. Protected copies of its identity, digest, and bytes - # preserve the accepted input through Secret changes or deletion. - bootstrapConfigRef: {name: example-bootstrap} + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk # The projector reports the retained installation outcome, not guest health. status: + sourceMode: ManagedImage + completionMode: VerifiedImage + assurance: QualifiedImage completedAt: "2026-10-27T12:00:00Z" conditions: - {type: Accepted, status: "True"} @@ -746,6 +759,27 @@ status: - {type: Ready, status: "True"} ``` +Exactly one non-null `source.managedImage` or `source.delegatedPXE` is required; +both, neither, and mixed member fields are invalid. The entire spec, including +predecessor, driver, and explicit completion mode/required assurance, is immutable. +The [delegated example](api-examples.md#delegated-pxe-installation) uses the same +allocation and predecessor rules. ManagedImage requires VerifiedImage / +QualifiedImage; delegated PXE initially supports CustomerCallback / +DelegatedContract only, with LocalDisk completion for both. Pending or unknown +work has no achieved assurance. Ready describes completion of this explicit +contract, not guest health. Managed consumers must require QualifiedImage at +admission and activation/join (including initial-installation gates); delegated +Ready cannot satisfy them. + +A provisioning-profile management session must bind an already admitted +Installation and its exact operation. ProviderAutomatic and CustomerRedfish are +mutually exclusive drivers, not independent boot authorities. CustomerRedfish is +initially permitted only for delegated PXE. Sessions, automatic PXE, runtime power, +and release share per-allocation serialization and provider fencing. Session +closure and callbacks do not prove a running installer stopped. Independent +executor fencing, PXE/network revocation, and local boot evidence are mandatory; +unknown work holds the allocation. See the [shared BMC execution contract](../pxe-installation/README.md#shared-bmc-and-installation-execution). + A reinstall names the Machine's current `status.currentInstallationRef` in `spec.expectedPredecessor`: @@ -762,7 +796,7 @@ with one nonempty name. `None` is valid only for a verified blank allocation tha has never admitted an installation. Fleet resolves the named predecessor in the same project and namespace and privately pins its exact incarnation and allocation; name reuse cannot replace it. A predecessor reference does not replace install or -image-use permission. +the current permissions required by the selected installation source. Admission atomically consumes the precondition and retains the operation before effects. Only one request can win. A retry of that request recovers its retained @@ -824,9 +858,10 @@ Each resource defines its conditions: - **MachineProfile:** `Accepted` validates structure without promising class compatibility, authorization, or supply. -- **MachineClass:** `Accepted` requires a resolved profile policy and provider - contract. `SourceResolved` requires an authorized, resolved definition. Neither - condition promises capacity or grants every reader source-use permission. +- **MachineOffering:** `Accepted` validates provider profile and capability policy; + it neither reserves capacity nor grants acquisition access. +- **MachineClass:** `SourceResolved` requires an authorized, resolved one-hop + offering. It promises neither capacity nor source-use permission to every reader. - **Machine:** `Prepared` requires preparation evidence; `Healthy` requires health evidence. `Available` also requires eligible policy and no live allocation or cleanup obligation. @@ -839,7 +874,9 @@ Each resource defines its conditions: remains true until cleanup and quota release finish. - **Installation:** `Accepted` requires an admitted operation with exact inputs. `Executing=False` alone cannot establish success. `Ready=True` and `completedAt` - require verified installation and platform handoff, not guest health. Verified + require the explicit completion contract, achieved assurance, executor fencing, + and platform handoff, not guest health. Managed consumers require QualifiedImage + even when a delegated Installation is Ready. Verified failure or cancellation yields `Ready=False`; an uncertain outcome yields `Unknown`. @@ -929,7 +966,8 @@ The initial deployment accepts enrollment only from operator-controlled provider #### Request authority Machine admission checks the initiating principal's local create permission, -provider-project `machineclasses.use`, and local `machineprofiles.use`. Published +provider-project `machineofferings.use` and effective acquisition access through +MachineOfferingAssignment, and local `machineprofiles.use`. Published profiles also require `machineprofiles.use` on their canonical provider source; custom profiles require no provider-profile grant. Cross-project checks preserve the caller and change only the target scope, as the [IPClass checker][ipam-class-use] @@ -949,8 +987,10 @@ use current Machine permissions and the retained contract; the creator's departu does not reclaim the machine. Each action needs separate admission. Installations require Machine `install`, -image-use permission, and access to bootstrap input. Power changes retain their -own caller and generation. Network resolution checks the caller's network-use +image-use permission for managed images, and current secret/endpoint permissions +for their selected source. They use retained capabilities rather than reacquiring +a withdrawn offering or assignment; explicit safety/suspension still applies. +Power changes retain their own caller and generation. Network resolution checks the caller's network-use permission in each selected namespace and the required address authority. These checks are Fleet integration requirements, not permissions granted by references. @@ -966,7 +1006,7 @@ The following are protected service records, not fields a customer authors: ```text (consumer project, local class name + private incarnation evidence) - -> (provider project, definition name + private incarnation evidence, contract digest) + -> (provider project, MachineOffering name + private incarnation evidence, contract digest) (consumer project, local profile name + private incarnation evidence) -> (provider project, source profile name + private incarnation evidence, requirements) ``` @@ -997,8 +1037,9 @@ Retain the following information: - **Identity:** immutable `metadata.name`, state, consumer and provider project context, customer Machine and provider MachineCapacity names, their private object-incarnation evidence, request digest, and canonical asset identity. -- **Accepted contract:** class and local/source profile names with private - incarnation evidence and contract digests, exact +- **Accepted contract:** offering identity, accepted contract revision and + installation/management capabilities, class publication provenance, and + local/source profile names with private incarnation evidence and digests, exact requirements, dependency identities/content, provider configuration/catalog revision, hardware snapshot, and logical-to-physical device mapping. - **Authority:** authenticated principal, authorization decision, @@ -1182,8 +1223,10 @@ sessions. Lifecycle integration must handle these triggers: - **Project or entitlement suspension:** Deny new allocations, installations, and consumer power actions. Bring committed work to a safe boundary and allow authorized release without automatically wiping active machines. -- **Class/profile withdrawal or Machine disablement:** Block future allocations, - preserve active contracts, and admit reclaim separately. +- **Offering/assignment/profile withdrawal or capacity disablement:** Block future + allocations, preserve active contracts and retained runtime capabilities, and + admit reclaim separately. Runtime safety/suspension is an explicit control, not + an inference from catalog withdrawal; cleanup remains authorized. Milo's [project controller][milo-cleanup] waits for cleanup before reclaiming the control plane, while [suspension admission][milo-suspension] permits deletes and diff --git a/docs/enhancements/machine-lifecycle/acceptance-tests.md b/docs/enhancements/machine-lifecycle/acceptance-tests.md index b611e74a..cab606be 100644 --- a/docs/enhancements/machine-lifecycle/acceptance-tests.md +++ b/docs/enhancements/machine-lifecycle/acceptance-tests.md @@ -2,6 +2,13 @@ Required validation for the [machine lifecycle contract](README.md). +The proposed PXE/Redfish extension additionally requires the concrete +[cross-system acceptance scenarios](../pxe-installation/README.md#acceptance-tests): +competing boot/power/release operations, session closure with a live installer, +offering withdrawal followed by reinstall, hub/cell partitions and stale reflected +results, and managed-consumer assurance enforcement. These scenarios are not +implemented or executed by this documentation change. + Implement the following tests through Milo tenancy, IAM, entitlement, and quota. No implementation tests exist yet. @@ -25,7 +32,7 @@ component, lose responses, and delay old workers to verify recovery. - **Consumer copies a named profile or reuses its name:** Require the custom path or protected publication provenance; reject lifetime substitution. - **Provider recreates an allowed profile under the same name:** Block use until - the provider removes and re-adds the entry in separate accepted class revisions, + the provider removes and re-adds the entry in separate accepted offering revisions, or selects a new name. An unrelated class edit cannot renew approval. - **Custom profiles are disabled, unsupported, or temporarily unverifiable:** Report the specific admission result without reserving capacity or purchasing. diff --git a/docs/enhancements/machine-lifecycle/api-examples.md b/docs/enhancements/machine-lifecycle/api-examples.md index 706484a1..d9b9ce5c 100644 --- a/docs/enhancements/machine-lifecycle/api-examples.md +++ b/docs/enhancements/machine-lifecycle/api-examples.md @@ -5,67 +5,52 @@ They show different lifecycle points, not one simultaneous observation. Names, identifiers, and timestamps are synthetic. They define no implemented APIs or production timing requirements. The enhancement owns field semantics and lifecycle rules. -- [Provider MachineClass](#provider-machineclass) +- [Provider MachineOffering](#provider-machineoffering) - [Consumer MachineClass](#consumer-machineclass) - [MachineProfile](#machineprofile) - [MachineCapacity](#machinecapacity) - [Machine](#machine) - [Installation](#installation) +- [Delegated PXE Installation](#delegated-pxe-installation) - [Reinstallation predecessor](#reinstallation-predecessor) The exact MachineProfile CPU and memory shape, `Machine.status.requestedHardware`, and the `RequestResolved` condition are implemented; the rest of these responses remain proposed. -## Provider MachineClass +## Provider MachineOffering ```yaml -apiVersion: metal.datumapis.com/v1alpha1 -kind: MachineClass -# Classes span the provider project so namespaces can share an offering. +apiVersion: provider.metal.datumapis.com/v1alpha1 +kind: MachineOffering metadata: - generation: 1 name: standard-metal -# The definition owns offering policy; profiles own hardware requirements. -# Its mode cannot change after creation. spec: - # Named profiles select provider-local contracts by name. - # Fleet retains their resolved identities internally. - # Custom profiles default to disabled and require provider validation. profilePolicy: allowedProfiles: - name: accelerated-16c-64g customProfiles: enabled: false - - # Access describes supported operations, not permission to perform them. - # The first implementation supports power control but no console sessions. - access: - consoleModes: [] - powerControl: true - - # Capacity limits selection to existing supply in one provider namespace. - # Labels identify candidates; they confer no eligibility or purchase authority. - capacity: - machineCapacities: - namespace: infra-ops - selector: - matchLabels: - fleet.datumapis.com/capacity-pool: general-metal - - # Provider backend qualification and BMC enrollment are private cell state. - -# The projector reports the definition that the class evaluator accepted. -# Acceptance validates the offering; it does not reserve or promise capacity. + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + completionContracts: + - {mode: VerifiedImage, assurance: QualifiedImage} + - {mode: CustomerCallback, assurance: DelegatedContract} + management: + profiles: [ReadOnly, Provisioning] + provisioningSteps: [OneTimePXE, Reset, LocalDisk] + powerControl: true status: - evaluatedRevision: class-revision-example + evaluatedRevision: offering-revision-example conditions: - type: Accepted status: "True" observedGeneration: 1 - lastTransitionTime: "2026-10-27T12:00:00Z" - reason: DefinitionValid - message: "Profile policy and provider contract resolved." + lastTransitionTime: "2026-11-14T12:00:00Z" + reason: OfferingValid + message: "Profile and capability contracts accepted; no capacity reserved." ``` ## Consumer MachineClass @@ -82,6 +67,8 @@ metadata: # cannot become a definition or override its policy. spec: source: + apiGroup: provider.metal.datumapis.com + kind: MachineOffering project: provider name: standard-metal @@ -90,8 +77,8 @@ spec: status: # The revision identifies the evaluated offering independently of this # reference object's generation. It does not grant source-use permission. - evaluatedRevision: class-revision-example - resolvedClass: + evaluatedRevision: offering-revision-example + resolvedOffering: # Publication maps allowed provider profiles to protected local copies. # These local names do not expose provider inventory or grant use. profilePolicy: @@ -99,9 +86,13 @@ status: - name: accelerated-16c-64g customProfiles: enabled: false - access: - consoleModes: [] - powerControl: true + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + management: + profiles: [ReadOnly, Provisioning] + powerControl: true conditions: - type: SourceResolved status: "True" @@ -463,8 +454,6 @@ metadata: name: example-os-1 namespace: default # The entire spec is immutable so recovery uses the same authorized inputs. -# Machine and approved image are required. Fleet checks install and image-use -# permissions and internally pins the Machine lifetime, image artifacts, and digests. spec: machineRef: name: example @@ -472,17 +461,22 @@ spec: # an unexpected OS. None identifies a blank allocation with no admitted install. expectedPredecessor: type: None - imageRef: - name: qualified-linux - - # Optional bootstrap data comes from a Secret in this namespace under - # explicit caller authority. Protected copies of its identity, digest, and bytes - # preserve the accepted input through Secret changes or deletion. - bootstrapConfigRef: - name: example-bootstrap + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk # The projector reports the retained installation outcome, not guest health. status: + sourceMode: ManagedImage + completionMode: VerifiedImage + assurance: QualifiedImage completedAt: "2026-10-27T12:00:00Z" conditions: - type: Accepted @@ -523,3 +517,42 @@ expectedPredecessor: type: Installation name: example-os-1 ``` + +## Delegated PXE Installation + +This alternative successor uses the same retained allocation and consumes its +predecessor atomically. It cannot run concurrently with another installation. +The source union, execution driver, and completion contract are immutable. A +provisioning session may attach only after this request is admitted; it cannot +change its endpoint or create another boot operation. Required assurance is not +achieved assurance: pending/unknown status must not claim DelegatedContract. + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: + name: example-os-2 + namespace: default +spec: + machineRef: {name: example} + expectedPredecessor: {type: Installation, name: example-os-1} + source: + delegatedPXE: + endpoint: + url: https://pxe.customer.example/boot.ipxe + trustBundleRef: {name: customer-pxe-ca} + authorizationRef: {name: customer-pxe-credentials} + execution: + driver: CustomerRedfish + completion: + mode: CustomerCallback + requiredAssurance: DelegatedContract + postCompletionBoot: LocalDisk +``` + +After independently verified executor shutdown, PXE/network revocation, local +boot, and management validation of the reflected result, status may report +`sourceMode: DelegatedPXE`, `completionMode: CustomerCallback`, +`assurance: DelegatedContract`, and `Ready=True`. Neither the callback nor session +closure proves shutdown. Managed consumers requiring QualifiedImage reject this +contract and cannot use its Ready condition to open their activation/join gate. diff --git a/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg b/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg index 172d1c76..2b223aa1 100644 --- a/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg +++ b/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg @@ -1,6 +1,6 @@ Public resources across project boundaries - A consumer Machine references a project-wide MachineClass and MachineProfile. Its Installation references the Machine. Each requested interface selects an existing networking.datumapis.com Network in the consumer project. Networking owns its Galactic VPC realization; MachineCapacity remains in the provider project. The local class references a provider definition, which selects provider MachineCapacity and permits named profiles. A dashed arrow shows publication of a provider profile as a protected consumer copy. Public references use scoped names; object-incarnation evidence remains private. Reinstallation names the current Installation as a precondition. + A consumer Machine references a project-wide MachineClass and MachineProfile. Its immutable Installation references the Machine and selects exactly one managedImage or delegatedPXE source with explicit completion and assurance. Each requested interface selects an existing networking.datumapis.com Network in the consumer project. Networking owns its Galactic VPC realization; MachineCapacity remains in the provider project. The local class references a provider MachineOffering, which owns capabilities and permits named profiles. MachineOfferingAssignment grants acquisition access. Fleet capacity selection is private provider implementation state. A dashed arrow shows publication of a provider profile as a protected consumer copy. Public references use scoped names; object-incarnation evidence remains private. Reinstallation names the current Installation as a precondition. @@ -23,8 +23,8 @@ MachineClass Local reference - MachineClass - Offering definition + MachineOffering + Capabilities / provider.metal MachineProfile Published or custom @@ -44,7 +44,9 @@ Machine - Installation + Installation + managedImage | delegatedPXE + Explicit completion + assurance MachineCapacity @@ -59,7 +61,8 @@ network name - selects + private fulfillment + Assignment grants acquisition, not boot. Capacity stays in the provider project. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index f911a507..faabba4d 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -16,6 +16,7 @@ stage: alpha - [Control-plane placement](#control-plane-placement) - [API design](#api-design) - [Admission and authority](#admission-and-authority) + - [Shared BMC and installation execution](#shared-bmc-and-installation-execution) - [Location execution](#location-execution) - [Completion and evidence](#completion-and-evidence) - [Release and recovery](#release-and-recovery) @@ -29,12 +30,30 @@ stage: alpha ## Summary -Fleet will support two ways to install an allocated bare-metal machine. Fleet can +Metal defines the common public installation contract; Fleet is an optional +provider implementation, not a prerequisite for publishing or consuming it. +This proposal describes two ways to install an allocated bare-metal machine. Fleet can automatically install a platform-approved golden image, or it can temporarily chain the machine to a customer-supplied PXE service. Both paths use the same immutable `Installation`, allocation, federation handoff, power, boot fencing, and release contracts. +All behavior below is proposed, not implemented or hardware-qualified. These are +target contracts, with no compatibility or migration requirement for earlier +draft shapes. The [canonical lifecycle design](../machine-lifecycle/README.md) +and [examples](../machine-lifecycle/api-examples.md) use the same source union. + +Companion review on 2026-11-14 used [BMC #41](https://github.com/datum-cloud/fleet/pull/41) +at `b72c314624bd0b05849059815619c9783607818c`, +[control planes #51](https://github.com/datum-cloud/fleet/pull/51) at +`16e7cb2a268cf20bc58d490493b5a3fef9237027`, and +[offerings #58](https://github.com/datum-cloud/fleet/pull/58) at +`031477d011090ea6ec378d526e975bbfae07a060`. The decisions here replace those drafts' +provider MachineClass policy, direct cell-to-hub status writing, and independent +provisioning-session boot authority where they differ. Companion branches must +converge on these contracts; this PR does not edit their branches or rewrite the +[pinned source provenance](../../proposals/fleet-management/MIGRATION.md). + The Fleet management control plane admits the exact operation before any effect. The Federation Control Plane delivers that operation to one selected location control plane. The location prepares networking, controls one-time network boot, @@ -87,7 +106,7 @@ understand each customer installer would create an unnecessary backend contract. without operating a provisioning service. - A customer with an existing PXE service installs its own operating system on an allocated machine while Fleet retains power and boot control. -- A provider controls which MachineClasses permit managed images or delegated PXE. +- A provider controls installation and management capabilities on MachineOffering. - An operator can recover a lost response without repeating a destructive action or exposing uncertain capacity to another customer. @@ -105,10 +124,22 @@ An Installation has exactly one source: | `ManagedImage` | Fleet resolves a platform-approved image and qualified recipe. | Exact image and recipe, target disk evidence, boot fencing, and required first-boot evidence. | | `DelegatedPXE` | The customer supplies a PXE endpoint and controls its installer. | Exact delegation target, boot session, customer result, boot fencing, and the configured post-install boot observation. | -MachineClass policy advertises supported modes. It does not grant permission to -use them. Fleet checks current source-use authority, allocation identity, class -revision, endpoint policy, networking feasibility, and predecessor state when it -admits each Installation. +`MachineOffering` in `provider.metal.datumapis.com` owns installation and +management capability policy. `MachineClass` in `metal.datumapis.com` is only a +consumer-published, one-hop view of that offering. `MachineOfferingAssignment` +grants acquisition access, not runtime boot authority. `MachineProfile` contains +immutable hardware requirements, never installation, management, or audience policy. + +Allocation retains the accepted offering identity and contract revision, exact +profile identity and requirements, and installation/management capabilities. +Offering or assignment withdrawal blocks new allocations, not retained runtime +rights. A reinstall uses that retained contract even if the catalog copy or +offering is gone; it cannot acquire capabilities added after allocation. Admission +still checks current Machine install permission, image-use permission for managed +images, secret-use and endpoint permission as applicable, explicit safety or +suspension controls, network feasibility, and predecessor state. Unavailable +authorization is unknown, not permission. Cleanup remains authorized by retained +provider obligations despite withdrawal, suspension, or project deletion. ### Managed golden image @@ -132,8 +163,9 @@ decision point and chains only the admitted machine to the customer endpoint. The customer does not receive BMC credentials or DHCP authority. Its system may install any OS allowed by service policy, then sends an operation-scoped completion -callback. The location revokes delegation, requests local-disk boot, and returns -the evidence required by the Installation contract. +callback. That is only a customer assertion. The location separately proves the +installer stopped, revokes delegation, performs the admitted local-disk transition, +and returns the evidence required by the Installation contract. The first release requires delegated PXE to finish with local-disk boot. A permanently network-booted runtime needs a separate design because it retains boot @@ -147,17 +179,26 @@ The design follows the Fleet management control-plane boundaries: | Boundary | Responsibility | | --- | --- | -| Provider project API | MachineClass policy, MachineCapacity, physical inventory, and provider eligibility. | +| Provider project API | MachineOffering capability policy and MachineOfferingAssignment acquisition access; Fleet-backed providers additionally own MachineCapacity and inventory. | | Consumer project API | Machine and immutable Installation requests and projected status. | | Fleet private storage | Exact allocation, caller authority, admitted inputs, operation journal, credentials, and cleanup custody. | | Fleet management runtime | Admission, allocation coordination, handoff creation, and result validation. | -| Federation hub | Canonical admitted location handoff and cell-owned execution status. | -| Selected location control plane | Network integration, PXE authorization, power, installation execution, fencing, and evidence. | +| Federation hub | Management-authored admitted intent and Karmada-reflected selected-cell results. | +| Selected location control plane | Delivered intent, locally written execution results, network integration, PXE, power, fencing, and evidence. | The Fleet runtime's deployment cluster is not the canonical store for project objects or federation intent. Kubernetes UIDs are local evidence and do not cross project, hub, or cell API boundaries as authored references. +The only status path is management-authored hub intent -> selected-cell delivery +-> cell-local results -> Karmada reflection -> management validation -> public +projection. Cells have no hub or project API credentials. Karmada transports +results, not authority or readiness decisions. Management validates selected-cell +identity, retained operation and revision, allocation, fencing token, and evidence +freshness before projection. Wrong-cell, duplicated, stale, or conflicting results +cannot advance readiness. A partition leaves results pending or unknown; absence +of a result never proves completion or cancellation. + ### API design The following shapes are proposals, not implemented schemas. `Installation.spec` @@ -176,6 +217,12 @@ spec: managedImage: imageRef: {name: qualified-linux} bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk ``` A delegated request selects the other union member: @@ -193,18 +240,30 @@ spec: correlation: workflowID: example-workflow-1 templateDigest: sha256:example - completion: - mode: Callback - postCompletionBoot: LocalDisk + execution: + driver: CustomerRedfish + completion: + mode: CustomerCallback + requiredAssurance: DelegatedContract + postCompletionBoot: LocalDisk ``` -The API server applies defaults before Fleet captures the request digest. Fleet +Exactly one non-null `source.managedImage` or `source.delegatedPXE` is required; +both, neither, and fields from the other member are rejected. Source, predecessor, +execution driver, and completion contract are immutable. Completion and assurance +are explicit, not inferred from a callback or `Ready`. ManagedImage requires +`VerifiedImage` and `QualifiedImage`; delegated PXE initially supports only +`CustomerCallback` and `DelegatedContract`. Both require `LocalDisk`. Other +combinations are rejected until a separate qualified evidence contract exists. + +The API server applies any other defaults before Fleet captures the request digest. Fleet resolves referenced Secrets under the caller's authority and retains protected copies needed for recovery. Credentials and rendered bootstrap content do not enter the federation handoff. -MachineClass definitions add policy describing supported installation modes and -boot capabilities. Publication exposes only the permitted summary. The exact +MachineOffering defines allowed source modes, execution drivers, completion and +assurance combinations, and management profiles/Redfish steps. Publication exposes +only the permitted summary through MachineClass; it cannot override the source. The exact provider executor, BMC enrollment, installer recipe, and boot-service configuration remain private location state. @@ -214,17 +273,77 @@ Before dispatch, Fleet retains: - provider and consumer Project identities; - Machine, MachineAllocation, MachineCapacity, and Installation incarnations; -- the MachineClass and MachineProfile revisions; +- the retained MachineOffering identity, accepted contract and capability policy, + MachineClass publication provenance, and immutable MachineProfile requirements; - the consumed predecessor and operation identity; - target location, boot interface, and qualified firmware mode; - image, recipe, bootstrap, endpoint, trust, and credential digests as applicable; -- current IAM, entitlement, quota, and source-use decisions; and +- current action/source permissions and explicit safety/suspension decisions, + plus the allocation's retained acquisition and quota evidence; and - an executor fencing token and required completion evidence. The handoff contains the exact admitted target and non-secret execution inputs or protected capability references. Delivery to a cell is not fresh authorization. The cell cannot select another machine, endpoint, image, or installation mode. +Retain the operation's validity interval and allowed step budget before dispatch. +Disconnected cells may only recover/execute within that retained scope and +validity; expiry prevents new effects but does not prove a running installer +stopped. Renewal is a management decision for the same exact operation, never a +cell-local expansion. Fencing and cleanup continue under retained obligations. + +Admission atomically consumes the exact predecessor with the operation record. +`None` means a verified blank allocation with no previously admitted installation; +otherwise use the current Installation name, resolved to its retained incarnation. +Competing successors cannot both win. Active or uncertain work offers no usable +predecessor. Request deletion, session closure, or a callback does not restore it. +After failure, a successor requires proven fencing and intact prior state; +partial or uncertain effects require recovery of the same operation or release. + +### Shared BMC and installation execution + +A provisioning-profile `MachineManagementSession` must name an already admitted +Installation in the same project/namespace and allocation. Admission privately +binds its exact incarnation, operation, selected cell, fence, driver, and permitted +step set. Missing, foreign, stale, or completed bindings fail closed. A session +cannot create an Installation, select another endpoint or image, or arm independent +boot authority. Read-only observation does not grant provisioning permissions. +Current session create/use permissions and explicit suspension checks still apply; +neither the retained capability nor knowledge of an Installation name grants access. + +Exactly one execution driver is selected at Installation admission. The public +`ProviderAutomatic` name is provider-neutral: Fleet runs the automatic sequence +when Fleet fulfills the offering; another provider implements the same retained +authority and evidence contract without deploying Fleet: + +| Driver | Effect authority | +| --- | --- | +| `ProviderAutomatic` | The provider (Fleet in this design) orders all boot/power steps. Customer provisioning-session writes are rejected; observation may be allowed. | +| `CustomerRedfish` | The customer submits the offering-permitted Redfish steps through a bound provisioning session. The gateway journals and executes only steps of the admitted Installation; Fleet does not run an automatic competing sequence. | + +CustomerRedfish is permitted only for delegated PXE in the initial qualification. +The gateway maps allowed one-time PXE, reset, and local-disk transitions to the +retained plan; arbitrary boot targets, persistent overrides, virtual media, and +unadmitted resets are rejected. Source choice and execution driver are distinct: +delegated PXE may also use ProviderAutomatic. Switching drivers requires settlement +and a new admitted successor, not editing a session. + +All automatic, gateway, runtime power, and release effects share one durable +per-allocation serialization and fencing domain. A provisioning session attaches +to the Installation's reservation, not a second operation authority. Concurrent +sessions cannot duplicate a step. Power intent queues or fails with an explicit +conflict while installation owns the reservation. Release closes new admission, +revokes sessions, and takes over only through verified fencing and settlement; +there is no lock-free emergency reset path. Recovery deduplicates provider steps +using retained operation identity, including after a lost Redfish response. + +Closing or expiring a session revokes access but does not settle an installer +already running in RAM or remotely. A callback proves neither executor shutdown +nor boot revocation. Completion requires independent stop/fence evidence for all +old effect paths, verified PXE/network revocation, and observed local-disk boot. +If those cannot be proven, keep the Installation unknown and capacity occupied. +Safety/release fencing is retained recovery authority, not a second install driver. + ### Location execution A qualified location runs a small platform boot service. Provider DHCP directs @@ -257,10 +376,17 @@ can report the retained operation's result but cannot choose another target, extend authority, request release, or write public status. Managed-image success proves the qualified image and recipe evidence required by -the class. Delegated success normally proves only that Fleet delegated the correct +the retained offering. Delegated success proves only that Fleet delegated the correct machine, the customer reported completion, Fleet revoked the delegation, and the -configured local boot was observed. Public status identifies the result mode and -assurance rather than describing an opaque customer OS as platform verified. +configured local boot was observed, with the old executor demonstrably stopped. +Public status reports `sourceMode`, `completionMode`, and achieved `assurance` +(`QualifiedImage` or `DelegatedContract`), separately from conditions. Pending or +unknown work has no achieved assurance. An opaque customer OS is not platform verified. + +Managed consumers must explicitly require `QualifiedImage` at admission and +activation/join gates; `Ready=True` with `DelegatedContract` cannot satisfy them. +The same rule applies to a Machine's initial-installation gate for that consumer. +There is no callback-based promotion from delegated to qualified assurance. Fleet validates the target, operation revision, fencing token, evidence freshness, and required conditions before setting Installation `Ready=True`. Installation @@ -295,7 +421,8 @@ Qualify one UEFI, Redfish, non-Talos hardware and OS combination. Test both mode through real project admission, federation delivery, networking, and disposable hardware. -Acceptance requires: +These are required cross-system tests, not executed tests in this documentation +PR. In addition to the cases below, acceptance requires: - only the allocated machine can use a boot session; - a managed install writes the retained image and boots from the selected disk; @@ -307,11 +434,23 @@ Acceptance requires: - release cannot expose capacity before network and provider cleanup; and - customer project deletion preserves recovery and cleanup custody. +| Scenario and fault injection | Required observable result | +| --- | --- | +| Submit both/neither source members, mixed fields, an unsupported completion/assurance pair, or a provisioning session without an admitted Installation (including foreign/recreated names). | Reject before effects; no predecessor consumption or boot authority for invalid requests. Session access also requires current create/use permission. | +| Race ProviderAutomatic PXE with a provisioning-session boot override, two successor requests, and runtime power-on. | One predecessor consumption and one install driver; session write rejected, other successor conflicts, power blocked; provider journal has no duplicate or competing effect. | +| CustomerRedfish sends duplicate resets through two sessions; lose the provider response, then recover gateway and Fleet workers. | Both sessions bind the same admitted operation; one retained step is recovered, never blindly replayed. No automatic installer driver starts. | +| Close the provisioning session or send a successful callback while its installer remains active; concurrently release. | No Ready or usable predecessor; release blocks new steps, fences all old paths and verifies cleanup before reuse. Closure/callback alone never settles work. | +| Withdraw offering/assignment and delete the published class after allocation; request a reinstall and a new Machine. | New allocation denied; reinstall retains original offering/profile/capabilities and succeeds only with current install/source permissions. A later offering capability expansion is not inherited. | +| Repeat that reinstall with revoked image/secret/endpoint permission or explicit runtime suspension. | No new install effects; an authorization outage is unknown. Retained cleanup still completes without reacquiring the withdrawn offering. | +| Partition hub from selected cell during boot; expire authority, duplicate delivery, inject wrong-cell and stale-fence results, then reconnect. | Cell writes only local results, has no hub credentials, and starts no effects beyond its retained validity. Karmada reflects; management rejects mismatches and reconciles the same operation without inferring stop from expiry. | +| Customer callback and local boot succeed but image evidence is absent. | At most DelegatedContract after independent fencing proof; managed admission/join/initial gates requiring QualifiedImage remain closed even if Installation Ready is true. | +| Managed image has wrong digest or stale first-boot evidence; later deliver valid qualified evidence through reflection. | No initial readiness or assurance on invalid evidence; only the validated exact operation can report QualifiedImage and open the managed gate. | + ## Production readiness review questionnaire ### How is the feature enabled or disabled? -Enable installation modes per accepted MachineClass and qualified location. +Enable installation modes per accepted MachineOffering and qualified location. Rollback stops new admission while preserving handoff recovery, boot revocation, and release. Disabling a controller does not cancel remote work. @@ -331,7 +470,8 @@ conflicting evidence blocks readiness and capacity reuse. Preserve allocation custody, immutable Installation inputs, handoff revisions, executor fencing, active boot sessions, callback correlation, and cleanup -obligations. Test mixed versions and restore while both installation modes run. +obligations. Test restore while both installation modes run. This proposal imposes +no backwards-compatibility contract on earlier draft APIs. ## Drawbacks @@ -348,14 +488,14 @@ cannot prove that work stopped. machines outside the allocation and is difficult to revoke safely. - **Treat delegated PXE as allocate-only with no Fleet operation:** insufficient when Fleet must provide one-time PXE, power, network isolation, and recovery. -- **Create a public ProvisioningClass now:** deferred. MachineClass policy and the +- **Create a public ProvisioningClass now:** deferred. MachineOffering policy and the immutable Installation source establish the first required contract without a second offering hierarchy. ## Open design questions -- Exact MachineClass policy and Installation union schemas. -- Portable handoff encoding and the location status writer contract. +- Detailed MachineOffering capability schema and union validation implementation. +- Portable handoff encoding and Karmada reflection enforcement. - Boot identity beyond MAC address for the first qualified hardware. - Customer endpoint connectivity, TLS trust, proxying, and artifact-origin policy. - The managed installer image, action format, target-disk selector, and signing. diff --git a/docs/enhancements/pxe-installation/diagrams/architecture.svg b/docs/enhancements/pxe-installation/diagrams/architecture.svg index b3474131..681ee6b4 100644 --- a/docs/enhancements/pxe-installation/diagrams/architecture.svg +++ b/docs/enhancements/pxe-installation/diagrams/architecture.svg @@ -1,6 +1,6 @@ Fleet PXE installation control-plane architecture - Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and returns evidence. + Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and writes local evidence. Karmada reflects selected-cell results; management validates before public projection. Cells have no hub credentials. Fleet is an optional Metal provider implementation. @@ -18,22 +18,22 @@ - PXE installation follows Fleet's existing authority boundaries + Metal contract / optional Fleet execution: one retained authority PROJECT CONTROL PLANES Provider project API - MachineClass policy + MachineOffering policy MachineCapacity - Fleet physical inventory + Assignments: acquisition access Provider and allocator-owned state remains canonical here. Consumer project API - Machine + Machine + published MachineClass Immutable Installation ManagedImage or DelegatedPXE Customers write requests; @@ -65,17 +65,17 @@ Exact target and operation Selected-cell delivery Management writes intent; - the cell writes execution status. + Karmada reflects local results. SELECTED LOCATION / CELL Cell execution - Local handoff adapter + Delivered intent / local results Jobs and optional KRO Provider operation recovery - Cannot change the admitted target. + No hub or project credentials. Networking owner @@ -94,8 +94,8 @@ Provider executor - Redfish power and boot - Operation ID and fencing + One admitted execution driver + PXE / power / release fence Local boot transition Release and cleaning Credentials remain private. @@ -124,8 +124,11 @@ - + + + Reflected results to validation + Dashed return: Karmada reflection, not a cell hub write targeted delivery admitted request result diff --git a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg index cc512f36..65fe2409 100644 --- a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg +++ b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg @@ -26,7 +26,8 @@ 2. Admit exact inputs - Authority, predecessor, quota + Offering and predecessor; + one execution driver 3. Deliver handoff @@ -39,7 +40,8 @@ 5. Arm one PXE boot - Retained operation and fence + PXE / power / release + share one fence @@ -71,7 +73,7 @@ Customer installs OS Customer-owned workflow - Operation-scoped callback + Callback is not shutdown proof @@ -88,12 +90,12 @@ Provider executor controls BMC - 8. Validate evidence - Mode-specific assurance + 8. Reflect / validate + Local result → Karmada → Fleet 9. Project status - Ready only after required proof + Required assurance + fencing @@ -103,5 +105,6 @@ Unknown outcome Retain allocation; recover - timeout, lost response, stale worker + Timeout or stale evidence + One admitted driver: ProviderAutomatic or bound CustomerRedfish steps. Managed consumers require QualifiedImage, not delegated Ready. diff --git a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg index ef98de05..14ea003f 100644 --- a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg +++ b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg @@ -48,7 +48,7 @@ Prepare and boot Network ready; one-time PXE; - provider power operation + one admitted driver Fleet installer @@ -71,7 +71,7 @@ Receive result - Qualified image installed + QualifiedImage required Delegated customer PXE @@ -82,12 +82,12 @@ Admit delegation - Check class policy; + Use retained offering; pin endpoint and target Prepare and chain - One-machine PXE session; + Automatic or bound Redfish; proxy admitted endpoint @@ -97,7 +97,7 @@ Boot local disk - PXE delegation revoked; + Fenced; PXE revoked; local boot observed @@ -107,9 +107,11 @@ Validate evidence - Report delegated assurance + DelegatedContract Receive result Contract complete; OS opaque + Return: cell-local results → Karmada reflection → management validation + Callback / session closure ≠ installer stopped; independent fencing required From dfecccda3ece290a52e9a4105b47d06bd36c395d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 12:01:03 -0600 Subject: [PATCH 03/12] docs: keep PXE summary additive to shared Fleet design --- docs/architecture/design.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 21082fb8..05cbfcc8 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -37,7 +37,7 @@ All names below describe proposed resources, not implemented schemas. | Subsystem | Responsibilities and principal resources | | --- | --- | | Inventory | `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`: approved installation plans, actual assets, physical reservations, and verification evidence. | -| Capacity publication | Provider `MachineOffering` owns capability policy; `MachineOfferingAssignment` grants acquisition access; consumer `MachineClass` is a one-hop published view. `MachineProfile` contains immutable requirements. Publication does not reserve capacity or grant runtime authority. | +| Capacity publication | Provider `MachineClass` definitions and consumer-local references; discovery and safe summaries through service enablement and IAM. Publication does not reserve capacity or grant source-use permission. | | Machine allocation | Provider `MachineCapacity`, customer `Machine`, and private `MachineAllocation`: exclusive reservation, admission of consumer operations, activation, and release across provider and consumer projects. | | Bare-metal provisioning | Typed provider resources and adapters: execute admitted preparation, installation, power, console, and cleanup operations against exact assets. Backend workflows remain private. | | OS configuration | `MachineImage`, `InterfaceClass`, `Installation`, and `OSConfigPolicy`: approved artifacts, immutable installation requests, configuration composition, and one selected executor per incarnation. | @@ -87,20 +87,15 @@ credentials. Partitions or uncertain results never imply readiness or settlement 3. **Use one allocator.** Standalone consumers and managed clusters compete through the same durable reservation protocol. Create one immutable, terminal MachineAllocation between the customer Machine and provider MachineCapacity; - retain current authorization, quota holds, accepted offering identity and - contract/profile, installation/management capabilities, and local source + retain current authorization, quota holds, class revisions, and local source object identity as private admission evidence. Names, not cross-control-plane Kubernetes UIDs, are authored references. Overlapping classes must not duplicate supply. 4. **Separate discovery from authorization.** Consumer MachineClasses reference a - provider MachineOffering in one hop. Check effective acquisition assignment, - current source-use permission, + provider definition in one hop. Check current source-use permission, entitlement, quota, and placement feasibility at allocation commit. A copied reference, cached status, namespace, or privileged controller identity is not proof of consumer access. - Withdrawal blocks new allocations, not retained runtime rights. Reinstall uses - retained capabilities plus current install/image/secret/endpoint permissions - and explicit safety/suspension checks. Cleanup retains authority independently. 5. **Persist exact inputs before effects.** Retain admitted plans, artifacts, digests, target identities, predecessor preconditions, execution authority, and operation correlation. Timeouts mean unknown outcomes; recover the existing From bc21d504a8684d8d75e30761e35f983a7e534c0a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 12:01:49 -0600 Subject: [PATCH 04/12] docs: separate PXE overview link from companion additions --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 010548c4..bf883dd0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ 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. + ## Learn more Start with the [product overview and documentation guide](docs/README.md) to @@ -47,8 +50,5 @@ today. Then choose a topic: The [Bare Metal CLI enhancement](docs/enhancements/metal-cli/README.md) proposes `datumctl metal` discovery, machine management, and safe recovery workflows. -The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) -proposes managed images and bounded delegation to customer PXE. - Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). From 0a51385e75b79b75ddee0b6eb25c0dfc65c01bc5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:14:50 -0600 Subject: [PATCH 05/12] feat(executor): bind terminal results to the exact request Executor results now carry InputDigest, a SHA-256 commitment to the exact request (minus its ID) computed by simulator.RequestDigest. The coordinator rejects any terminal result whose digest does not match the request it retained, treating the mismatch as an unknown outcome rather than success, and returns the digest with each InstallationResult. The standalone install phase checks the retained simulator history against it. The executor contract documents exact-request replay and the meaning of Lookup's not-found/unknown answers, and Lookup rejects dot-segment IDs. Adversarial tests cover wrong-asset evidence, path-segment IDs and digest binding of every request field. Co-Authored-By: Claude Opus 5.5 --- .../controller/evidence_adversarial_test.go | 66 +++++++++++++++++++ internal/controller/lifecycle.go | 19 ++++-- internal/controller/lifecycle_test.go | 6 +- internal/executor/client.go | 10 ++- internal/executor/path_adversarial_test.go | 23 +++++++ internal/milo/adapter_test.go | 6 +- .../simulator/binding_adversarial_test.go | 36 ++++++++++ internal/simulator/store.go | 20 ++++-- internal/simulator/store_test.go | 34 ++++++++++ internal/staging/handler_test.go | 6 +- internal/standalone/runner.go | 6 +- 11 files changed, 214 insertions(+), 18 deletions(-) create mode 100644 internal/controller/evidence_adversarial_test.go create mode 100644 internal/executor/path_adversarial_test.go create mode 100644 internal/simulator/binding_adversarial_test.go diff --git a/internal/controller/evidence_adversarial_test.go b/internal/controller/evidence_adversarial_test.go new file mode 100644 index 00000000..affd3f71 --- /dev/null +++ b/internal/controller/evidence_adversarial_test.go @@ -0,0 +1,66 @@ +package controller + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +// Return a valid terminal result for the same operation name but a different +// physical target. Exercise both direct completion and lost-response recovery. +type substitutedCleanupExecutor struct { + result simulator.OperationResult + lost bool +} + +func (e *substitutedCleanupExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { + request.AssetID += "-different-physical-asset" + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + now := time.Now() + e.result = simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CompletedAt: &now} + if e.lost { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return e.result, nil +} + +func (e *substitutedCleanupExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return e.result, true, nil +} + +func TestAdversarialCleanupEvidenceCannotReleaseAnotherAsset(t *testing.T) { + for _, lost := range []bool{false, true} { + name := "direct" + if lost { + name = "recovered" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + owner, waiter := f.request("owner"), f.request("waiter") + for _, request := range []AllocationRequest{owner, waiter} { + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + } + if _, err := f.coordinator.Allocate(ctx, owner); err != nil { + t.Fatal(err) + } + f.coordinator.executor = &substitutedCleanupExecutor{lost: lost} + result, err := f.coordinator.Release(ctx, owner.Claim.UID) + if !errors.Is(err, executor.ErrOutcomeUnknown) || result.SafeToRemoveFinalizer { + t.Errorf("wrong-asset cleanup authorized release: result=%+v err=%v", result, err) + } + if _, err := f.coordinator.Allocate(ctx, waiter); !errors.Is(err, ErrInsufficientCapacity) { + t.Errorf("wrong-asset cleanup exposed occupied capacity: %v", err) + } + }) + } +} diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index 87b41e63..3243c04b 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -1224,8 +1224,9 @@ func installationClaimScope(request InstallationRequest) (ClaimScope, error) { } type InstallationResult struct { - Revision string - Record InstallationRecord + Revision string + Record InstallationRecord + RequestDigest string } func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) (InstallationResult, error) { @@ -1294,11 +1295,16 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if operation.InstallationNamespace != request.Installation.Namespace || operation.InstallationName != request.Installation.Name || operation.InstallationUID != request.Installation.UID || operation.NamespaceUID != request.NamespaceUID || operation.ClaimNamespace != request.Claim.Namespace || operation.ClaimName != request.Claim.Name || operation.ClaimUID != request.Claim.UID || operation.ClaimScope != scope || operation.ConsumerProject != request.ConsumerProject || operation.AssetID != asset.AssetID || operation.BindingID != asset.BindingID || operation.Epoch != asset.Epoch || operation.Predecessor != predecessor || operation.ImageName != request.Installation.Spec.ImageRef.Name || operation.Admission != request.Admission { return InstallationResult{}, ErrPredecessorConflict } + execRequest := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} + requestDigest, err := simulator.RequestDigest(execRequest) + if err != nil { + return InstallationResult{}, err + } if operation.State == OperationSucceeded { if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { return InstallationResult{}, err } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation}, nil + return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil } if asset.CurrentInstallationName != predecessor || (asset.ActiveOperationID != "" && asset.ActiveOperationID != operation.OperationID) { return InstallationResult{}, ErrPredecessorConflict @@ -1306,7 +1312,6 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if err := c.activateOperation(ctx, asset.AssetID, asset.ClaimUID, predecessor, operation.OperationID); err != nil { return InstallationResult{}, err } - execRequest := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} if _, err := c.executeAndRecover(ctx, execRequest); err != nil { return InstallationResult{}, err } @@ -1317,7 +1322,7 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { return InstallationResult{}, err } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation}, nil + return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil } func predecessorValue(value fleetv1.InstallationPredecessor) (string, error) { @@ -1541,6 +1546,10 @@ func (c *Coordinator) executeAndRecover(ctx context.Context, request simulator.R } func validateTerminalResult(request simulator.Request, result simulator.OperationResult) error { + digest, err := simulator.RequestDigest(request) + if err != nil || result.InputDigest != digest { + return fmt.Errorf("%w: executor evidence does not bind the exact request", executor.ErrOutcomeUnknown) + } if result.ID != request.ID || result.Kind != request.Kind || result.Phase != "Succeeded" || result.CompletedAt == nil { return fmt.Errorf("%w: executor result is not the correlated terminal operation", executor.ErrOutcomeUnknown) } diff --git a/internal/controller/lifecycle_test.go b/internal/controller/lifecycle_test.go index 5420f2ff..0b68368f 100644 --- a/internal/controller/lifecycle_test.go +++ b/internal/controller/lifecycle_test.go @@ -99,7 +99,11 @@ func (e *memoryExecutor) Execute(_ context.Context, request simulator.Request) ( e.requests = append(e.requests, request) now := time.Now() evidence := map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind] - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: evidence, CompletedAt: &now} + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: evidence, InputDigest: digest, CompletedAt: &now} if e.malform { result.CompletedAt = nil } diff --git a/internal/executor/client.go b/internal/executor/client.go index 540d3af3..67120813 100644 --- a/internal/executor/client.go +++ b/internal/executor/client.go @@ -31,7 +31,11 @@ var ( // Client is the exact provider-executor contract used by the standalone // lifecycle library. Implementations must preserve the operation ID and return -// only a verified terminal result. +// only a verified terminal result. Execute must accept exact-request replay under +// the same operation ID without duplicating effects. Lookup returning false and +// ErrOutcomeUnknown means a retained unfinished operation may be resumed by +// replaying its exact request. Transport failures must use a different error; +// true with any error never authorizes recovery or establishes success. type Client interface { Execute(context.Context, simulator.Request) (simulator.OperationResult, error) Lookup(context.Context, string) (simulator.OperationResult, bool, error) @@ -138,8 +142,8 @@ func (c *HTTPClient) Execute(ctx context.Context, request simulator.Request) (si } func (c *HTTPClient) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { - if operationID == "" || strings.Contains(operationID, "/") { - return simulator.OperationResult{}, false, errors.New("operation ID is empty or contains a path separator") + if operationID == "" || operationID == "." || operationID == ".." || strings.Contains(operationID, "/") { + return simulator.OperationResult{}, false, errors.New("operation ID is empty, a dot segment, or contains a path separator") } response, err := c.do(ctx, http.MethodGet, path.Join("v1/operations", url.PathEscape(operationID)), nil) if err != nil { diff --git a/internal/executor/path_adversarial_test.go b/internal/executor/path_adversarial_test.go new file mode 100644 index 00000000..fbb19dcb --- /dev/null +++ b/internal/executor/path_adversarial_test.go @@ -0,0 +1,23 @@ +package executor + +import ( + "context" + "net/http" + "testing" +) + +func TestAdversarialLookupRejectsDotSegmentsBeforeTransport(t *testing.T) { + for _, id := range []string{".", ".."} { + t.Run(id, func(t *testing.T) { + called := false + client := clientForHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + called = true + t.Logf("unexpected lookup path: %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + }), "synthetic-token") + if _, _, err := client.Lookup(context.Background(), id); err == nil || called { + t.Fatalf("dot-segment ID reached transport or was accepted: called=%v err=%v", called, err) + } + }) + } +} diff --git a/internal/milo/adapter_test.go b/internal/milo/adapter_test.go index 958f562c..e4526e53 100644 --- a/internal/milo/adapter_test.go +++ b/internal/milo/adapter_test.go @@ -33,7 +33,11 @@ func (e *testExecutor) Execute(_ context.Context, request simulator.Request) (si defer e.mu.Unlock() e.requests = append(e.requests, request) now := time.Now() - return simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind], CompletedAt: &now}, nil + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + return simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind], InputDigest: digest, CompletedAt: &now}, nil } func (e *testExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { return simulator.OperationResult{}, false, nil diff --git a/internal/simulator/binding_adversarial_test.go b/internal/simulator/binding_adversarial_test.go new file mode 100644 index 00000000..9f35720f --- /dev/null +++ b/internal/simulator/binding_adversarial_test.go @@ -0,0 +1,36 @@ +package simulator + +import ( + "errors" + "path/filepath" + "reflect" + "testing" +) + +func TestAdversarialReplayCannotRetargetAuthorityAfterRestart(t *testing.T) { + for name, mutate := range map[string]func(*Request){ + "asset": func(r *Request) { r.AssetID = "other-asset" }, + "binding": func(r *Request) { r.BindingID = "other-binding" }, + "epoch": func(r *Request) { r.Epoch++ }, + "fence": func(r *Request) { r.FenceToken = "other-fence" }, + "image": func(r *Request) { r.Inputs = []byte(`{"image":"different-image"}`) }, + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + store := openStore(t, path) + request := operationRequest("retained-install", "install", 1, `{"image":"synthetic-image"}`) + if _, _, err := store.Submit(request); err != nil { + t.Fatal(err) + } + store = openStore(t, path) + before := store.Snapshot() + mutate(&request) + if _, _, err := store.Submit(request); !errors.Is(err, ErrConflict) { + t.Fatalf("retargeted replay: %v", err) + } + if !reflect.DeepEqual(before, store.Snapshot()) { + t.Fatal("rejected replay changed authority or effects") + } + }) + } +} diff --git a/internal/simulator/store.go b/internal/simulator/store.go index 7207e15a..cc70acde 100644 --- a/internal/simulator/store.go +++ b/internal/simulator/store.go @@ -52,6 +52,7 @@ type Operation struct { type OperationResult struct { ID string `json:"id"` + InputDigest string `json:"inputDigest,omitempty"` Kind string `json:"kind"` Phase string `json:"phase"` Result string `json:"result,omitempty"` @@ -61,7 +62,7 @@ type OperationResult struct { func (o Operation) ResultView() OperationResult { return OperationResult{ - ID: o.ID, Kind: o.Kind, Phase: o.Phase, + ID: o.ID, InputDigest: o.InputDigest, Kind: o.Kind, Phase: o.Phase, Result: o.Result, CreatedAt: o.CreatedAt, CompletedAt: cloneTime(o.CompletedAt), } } @@ -559,13 +560,20 @@ func cloneTime(in *time.Time) *time.Time { return &out } +func RequestDigest(request Request) (string, error) { + request.ID = "" + encoded, err := json.Marshal(request) + if err != nil { + return "", err + } + sum := sha256.Sum256(encoded) + return hex.EncodeToString(sum[:]), nil +} + func digest(r Request) string { - copy := r - copy.ID = "" - b, err := json.Marshal(copy) + value, err := RequestDigest(r) if err != nil { panic("marshal validated simulator request") } - sum := sha256.Sum256(b) - return hex.EncodeToString(sum[:]) + return value } diff --git a/internal/simulator/store_test.go b/internal/simulator/store_test.go index 4110048e..f209d797 100644 --- a/internal/simulator/store_test.go +++ b/internal/simulator/store_test.go @@ -241,6 +241,40 @@ func openStore(t *testing.T, path string) *Store { return store } +func TestResultDigestCommitsExactRequestWithoutExposingInputs(t *testing.T) { + request := operationRequest("digest-operation", "install", 1, `{"image":"debian@sha256:1"}`) + store := openStore(t, filepath.Join(t.TempDir(), "state.json")) + operation, _, err := store.Submit(request) + if err != nil { + t.Fatal(err) + } + want, err := RequestDigest(request) + if err != nil || len(want) != 64 || operation.ResultView().InputDigest != want { + t.Fatalf("request commitment mismatch: %v", err) + } + for _, field := range []string{"asset", "binding", "epoch", "fence", "image", "kind"} { + changed := request + switch field { + case "asset": + changed.AssetID += "-other" + case "binding": + changed.BindingID += "-other" + case "epoch": + changed.Epoch++ + case "fence": + changed.FenceToken += "-other" + case "image": + changed.Inputs = json.RawMessage(`{"image":"debian@sha256:2"}`) + case "kind": + changed.Kind = "cleanup" + } + got, err := RequestDigest(changed) + if err != nil || got == want { + t.Fatalf("digest did not bind %s: %v", field, err) + } + } +} + func operationRequest(id, kind string, epoch int64, inputs string) Request { return Request{ ID: id, Kind: kind, AssetID: "asset-1", BindingID: "binding-a", diff --git a/internal/staging/handler_test.go b/internal/staging/handler_test.go index f9f5e201..2b768d74 100644 --- a/internal/staging/handler_test.go +++ b/internal/staging/handler_test.go @@ -25,7 +25,11 @@ type executor struct { func (e *executor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { now := time.Now().UTC() - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", CreatedAt: now, CompletedAt: &now} + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CreatedAt: now, CompletedAt: &now} e.results[request.ID] = result return result, nil } diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 9ba449e5..d03ef281 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -150,10 +150,14 @@ func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator return err } imageDecision := "local-test-" + imageDigest(r.Options.ImageName) - _, err = coordinator.Install(ctx, controller.InstallationRequest{Claim: claim, Installation: &installation, NamespaceUID: namespace.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: admission.PrincipalUID, DecisionID: "standalone-install-" + string(installation.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: imageDecision}}) + result, err := coordinator.Install(ctx, controller.InstallationRequest{Claim: claim, Installation: &installation, NamespaceUID: namespace.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: admission.PrincipalUID, DecisionID: "standalone-install-" + string(installation.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: imageDecision}}) if err != nil { return fmt.Errorf("install synthetic image: %w", err) } + retained, found, err := r.Executor.Lookup(ctx, result.Record.OperationID) + if err != nil || !found || retained.ID != result.Record.OperationID || retained.Kind != "install" || retained.Phase != "Succeeded" || retained.Result != "installed" || retained.CompletedAt == nil || result.RequestDigest == "" || retained.InputDigest != result.RequestDigest { + return fmt.Errorf("%w: simulator installation history is missing or does not match retained authority and inputs", executor.ErrOutcomeUnknown) + } now := metav1.NewTime(r.Now().UTC()) installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, Conditions: []metav1.Condition{condition("Accepted", metav1.ConditionTrue, installation.Generation, "SyntheticFixtureAccepted", "The standalone fixture admitted this request; this is not Milo authorization."), condition("Executing", metav1.ConditionFalse, installation.Generation, "Completed", "The persistent simulator returned a verified terminal result."), condition("Ready", metav1.ConditionTrue, installation.Generation, "Installed", "The synthetic provider verified installation completion.")}} if err := r.Client.Status().Update(ctx, &installation); err != nil { From f6828a849c3ae44992a5a9192be537a0f6637798 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:16:09 -0600 Subject: [PATCH 06/12] feat(standalone): add a reinstall phase and a disposable kind smoke The standalone runner gains a reinstall phase: a distinct Installation that names the initial Installation as its predecessor, on the same allocation, recovering the same successor operation across retries and restarts. Before each install the claim's Ready condition is set Unknown, so an unverified completion closes readiness and keeps the capacity occupied. hack/run-standalone-smoke.sh runs the full allocate, install, reinstall and release lifecycle in a disposable kind cluster (task standalone:test). CI runs its offline tests and a standalone-smoke job that executes it end to end. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 ++ Taskfile.yaml | 5 + cmd/fleet-standalone-smoke/main.go | 2 +- config/standalone/fixtures.yaml | 8 + config/standalone/rbac.yaml | 4 +- config/standalone/smoke-cronjobs.yaml | 23 ++ docs/development/README.md | 6 +- docs/operations/standalone-smoke.md | 43 +++- hack/run-standalone-smoke.sh | 156 ++++++++++++ hack/standalone-smoke.sh | 11 + hack/test-run-standalone-smoke.sh | 212 ++++++++++++++++ hack/test-standalone-preflight.sh | 59 +++++ hack/validate-standalone-render.sh | 16 +- internal/standalone/reinstall_test.go | 347 ++++++++++++++++++++++++++ internal/standalone/runner.go | 53 ++-- 15 files changed, 939 insertions(+), 33 deletions(-) create mode 100755 hack/run-standalone-smoke.sh create mode 100755 hack/test-run-standalone-smoke.sh create mode 100644 internal/standalone/reinstall_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d15c3ed..696977f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,4 +29,31 @@ jobs: - run: ./hack/test-standalone-source-id.sh - run: ./hack/test-standalone-preflight.sh - run: ./hack/test-standalone-build-context.sh + - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh + 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/Taskfile.yaml b/Taskfile.yaml index 55ffedb5..37c35206 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,11 @@ version: '3' tasks: + standalone:test: + desc: Run the synthetic lifecycle in a disposable local kind cluster. + cmds: + - ./hack/run-standalone-smoke.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 06124f34..8f388da7 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -22,7 +22,7 @@ import ( func main() { options := standalone.DefaultOptions() var phase, simulatorURL, tokenFile string - flag.StringVar(&phase, "phase", "", "required smoke phase: allocate, install, or release") + flag.StringVar(&phase, "phase", "", "required synthetic smoke phase: allocate, install, reinstall, 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") diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 40b9f723..269582b1 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -55,3 +55,11 @@ spec: machineRef: {name: allocation} expectedPredecessor: {type: None} imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} +--- +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@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index f684b667..7ad110cf 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -60,11 +60,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 diff --git a/config/standalone/smoke-cronjobs.yaml b/config/standalone/smoke-cronjobs.yaml index 6f5251db..fd7e8749 100644 --- a/config/standalone/smoke-cronjobs.yaml +++ b/config/standalone/smoke-cronjobs.yaml @@ -46,6 +46,29 @@ spec: --- 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, --runtime-token-file=/var/run/fleet/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}}] +--- +apiVersion: batch/v1 +kind: CronJob metadata: {name: fleet-smoke-release, namespace: fleet-system} spec: schedule: "0 0 1 1 *" diff --git a/docs/development/README.md b/docs/development/README.md index 4a3f9287..38d597ec 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -138,7 +138,11 @@ 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 +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. Unknown completion closes readiness and +keeps the capacity occupied. The release phase verifies cleanup before finalizer removal and advances the retained asset epoch before the waiting claim binds. diff --git a/docs/operations/standalone-smoke.md b/docs/operations/standalone-smoke.md index fab63df5..0f7ccfd0 100644 --- a/docs/operations/standalone-smoke.md +++ b/docs/operations/standalone-smoke.md @@ -18,8 +18,20 @@ The scenario has one `us-central-1` Machine with 24 physical CPU cores and 128Gi of memory. Both consumers request it. Project A binds first while project B remains pending. Project A installs a digest-pinned synthetic Debian image. The script restarts the simulator and reruns the install phase to recover the -same retained operation. It then releases project A, verifies cleanup, and lets -project B bind at a later executor epoch. +same retained operation. A separate `debian-12-reinstall` Installation then names +`debian-12` as its expected predecessor and replaces it on the same allocation. +Another simulator restart and retry recover that exact successor operation. +Every install/reinstall run performs an authenticated simulator lookup and checks +the operation identity, terminal result, and digest of the exact retained request +(including allocation, epoch, fencing authority, and image inputs). Kubernetes +completion records alone cannot pass the restart persistence check. +Project B remains pending throughout. The scenario then releases project A, +verifies cleanup, and lets project B bind at a later executor epoch. + +Reinstall retries preserve the allocation binding and executor epoch. An unknown +executor result leaves the Machine's readiness unknown and retains custody; +neither retry nor release can expose that capacity before recovery and cleanup. +Tests exercise lost responses, concurrent retry, and stale predecessor rejection. No network interface is requested. The `NETWORK` and `ADDRESS` columns are therefore intentionally blank; this environment does not deploy or impersonate @@ -27,6 +39,30 @@ NSO, IPAM, or Galactic programming. ## Run with kind and Colima +For a complete disposable run, install Docker with a Linux container engine, +kind, kubectl, kustomize, Git, and Python 3, then run from the repository: + +```sh +./hack/run-standalone-smoke.sh +# Or: task standalone:test +``` + +The wrapper creates a uniquely named kind cluster and a private temporary +kubeconfig, runs the scenario, and deletes only its own cluster. It does not +change your current Kubernetes context. Failure, timeout, and interrupt paths +also attempt cleanup; unverified cleanup is reported as failure with the exact +cluster name. Command output is withheld by the wrapper to avoid leaking local +credentials. The final phase label identifies where a failure occurred. +`FLEET_SMOKE_TIMEOUT_SECONDS` defaults to 1200 for the whole run and +`FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS` defaults to 120 for cleanup. + +The `ci` workflow runs this same wrapper on `ubuntu-latest` for pull requests and +main pushes, using Docker and kind rather than self-hosted or nested-KVM runners. +That job exercises the synthetic control-plane lifecycle, not a real guest OS, +Milo production admission, or provider hardware qualification. Passing local +checks is not evidence that a particular GitHub Actions run passed. + +To retain a cluster for local inspection, use the lower-level script instead. Create or select a dedicated kind cluster named `fleet-core`, then run: ```sh @@ -50,7 +86,8 @@ metadata, credentials, documentation, and manifests are never sent to the builder. The script builds and loads both images and verifies each running pod uses the exact source-specific tag with image pulling disabled. Distinct clean commits therefore cannot silently reuse one local workload tag. -It then applies the CRDs and fixture and uses `kubectl wait`/rollout watches for +It applies the CRDs first and waits for establishment before applying fixtures, +then uses `kubectl wait`/rollout watches for phase completion. It never patches status, removes finalizers, or writes lifecycle records itself. The phase Job is the designated synthetic fixture and status writer; the lifecycle diff --git a/hack/run-standalone-smoke.sh b/hack/run-standalone-smoke.sh new file mode 100755 index 00000000..39021fa6 --- /dev/null +++ b/hack/run-standalone-smoke.sh @@ -0,0 +1,156 @@ +#!/bin/sh +set -eu + +root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +if ! command -v python3 >/dev/null 2>&1; then + echo 'standalone smoke requires python3' >&2 + exit 1 +fi +exec python3 - "$root" "$@" <<'PY' +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid + + +class Failure(Exception): + def __init__(self, message, status=1): + super().__init__(message) + self.status = status + + +interrupted = 0 + + +def interrupt(signum, frame): + global interrupted + interrupted = signum + + +def seconds(name, default): + value = os.environ.get(name, str(default)) + if not value.isascii() or not value.isdigit() or not 1 <= int(value) <= 3600: + raise Failure(name + ' must be an integer from 1 to 3600') + return int(value) + + +def run(label, command, environment, deadline, capture=False, cleanup=False, on_start=None): + print('standalone smoke: ' + label, flush=True) + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if time.monotonic() >= deadline: + raise Failure(label + ' timed out', 124) + with tempfile.TemporaryFile(dir=environment['TMPDIR']) as output: + process = subprocess.Popen(command, env=environment, stdin=subprocess.DEVNULL, + stdout=output, stderr=subprocess.DEVNULL, + start_new_session=True) + try: + if on_start: + on_start() + while process.poll() is None: + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if time.monotonic() >= deadline: + raise Failure(label + ' timed out', 124) + time.sleep(0.1) + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if process.returncode != 0: + raise Failure(label + ' failed (exit ' + str(process.returncode) + ')', + process.returncode if process.returncode > 0 else 1) + if capture: + output.seek(0) + return output.read().decode('utf-8') + finally: + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + pass + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=2) + + +def main(): + if len(sys.argv) != 2: + raise Failure('usage: hack/run-standalone-smoke.sh (no arguments)') + timeout = seconds('FLEET_SMOKE_TIMEOUT_SECONDS', 1200) + cleanup_timeout = seconds('FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS', 120) + for tool in ('docker', 'kind', 'kubectl', 'kustomize', 'git'): + if shutil.which(tool) is None: + raise Failure('missing required tool: ' + tool) + os.chdir(sys.argv[1]) + os.umask(0o077) + cluster = 'fleet-smoke-' + uuid.uuid4().hex + created = False + + def mark_created(): + nonlocal created + created = True + + status = 0 + deadline = time.monotonic() + timeout + with tempfile.TemporaryDirectory(prefix='fleet-smoke-') as directory: + kubeconfig = str(Path(directory) / 'kubeconfig') + Path(kubeconfig).touch(mode=0o600) + config = str(Path(directory) / 'kind.yaml') + Path(config).write_text('kind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\n' + 'nodes:\n- role: control-plane\n') + environment = dict(os.environ, KUBECONFIG=kubeconfig, TMPDIR=directory, + KIND_CLUSTER=cluster, KUBECTL_CONTEXT='kind-' + cluster, + ALLOW_KIND_CONTEXT_ALIAS='false', KIND_EXPERIMENTAL_PROVIDER='docker') + try: + operating_system = run('Docker preflight', ['docker', 'info', '--format', '{{.OSType}}'], + environment, min(deadline, time.monotonic() + 30), capture=True) + if operating_system.strip() != 'linux': + raise Failure('Docker must provide Linux containers') + clusters = run('kind preflight', ['kind', 'get', 'clusters'], environment, + min(deadline, time.monotonic() + 30), capture=True) + if cluster in clusters.splitlines(): + raise Failure('generated cluster name already exists; refusing to adopt or delete it') + print('standalone smoke: disposable cluster ' + cluster, flush=True) + run('create cluster', ['kind', 'create', 'cluster', '--name', cluster, + '--kubeconfig', kubeconfig, '--config', config, '--retain', + '--image', 'kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f', + '--wait', '120s'], environment, + min(deadline, time.monotonic() + 240), on_start=mark_created) + run('synthetic lifecycle', ['./hack/standalone-smoke.sh'], environment, deadline) + except Failure as error: + print('standalone smoke: ' + str(error), file=sys.stderr) + status = error.status + except (OSError, ValueError, subprocess.SubprocessError): + print('standalone smoke: command execution failed; raw diagnostics withheld', file=sys.stderr) + status = 1 + finally: + if created: + try: + run('delete cluster', ['kind', 'delete', 'cluster', '--name', cluster, + '--kubeconfig', kubeconfig], environment, + time.monotonic() + cleanup_timeout, cleanup=True) + except (Failure, OSError, ValueError, subprocess.SubprocessError): + print('standalone smoke: cleanup unverified for ' + cluster + + '; inspect this exact cluster before manual cleanup', file=sys.stderr) + status = status or 1 + return status or (128 + interrupted if interrupted else 0) + + +for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(signum, interrupt) +try: + sys.exit(main()) +except (Failure, OSError, ValueError) as error: + print('standalone smoke: ' + (str(error) if isinstance(error, Failure) + else 'local setup failed; raw diagnostics withheld'), file=sys.stderr) + sys.exit(error.status if isinstance(error, Failure) else 1) +PY diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 6ecd610b..9eaed6f2 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -65,6 +65,9 @@ done docker build -f build/simulator.Dockerfile -t "$simulator_image" . docker build -f build/standalone-smoke.Dockerfile -t "$smoke_image" . kind load docker-image --name "$cluster" "$simulator_image" "$smoke_image" +kustomize build config/base/crd >"$rendered" +kubectl --context "$context" apply -f "$rendered" +kubectl --context "$context" wait --for=condition=Established --timeout=60s -f "$rendered" kustomize build config/standalone | sed -e "s#fleet-simulator:standalone-local#$simulator_image#g" -e "s#fleet-standalone-smoke:standalone-local#$smoke_image#g" >"$rendered" if grep -q 'standalone-local' "$rendered"; then @@ -110,6 +113,14 @@ kubectl --context "$context" -n fleet-project-a get installations,machines test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12 -o jsonpath='{.status.phase}')" = "Ready" test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.currentInstallationRef.name}')" = "debian-12" +run_phase reinstall fleet-smoke-reinstall-run +kubectl --context "$context" -n fleet-system rollout restart statefulset/fleet-simulator +kubectl --context "$context" -n fleet-system rollout status statefulset/fleet-simulator --timeout=120s +run_phase reinstall fleet-smoke-reinstall-recovery-run +test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12-reinstall -o jsonpath='{.status.phase}')" = "Ready" +test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.currentInstallationRef.name}')" = "debian-12-reinstall" +test "$(kubectl --context "$context" -n fleet-project-b get machine allocation -o jsonpath='{.status.phase}')" = "Pending" + for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" for verb in get list watch create update patch delete; do diff --git a/hack/test-run-standalone-smoke.sh b/hack/test-run-standalone-smoke.sh new file mode 100755 index 00000000..bc453be5 --- /dev/null +++ b/hack/test-run-standalone-smoke.sh @@ -0,0 +1,212 @@ +#!/bin/sh +set -eu + +root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +exec python3 - "$root" <<'PY' +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time + + +mock = r'''#!PYTHON +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +tool = Path(sys.argv[0]).name +scenario = os.environ['SCENARIO'] +directory = Path(os.environ['CASE_DIRECTORY']) +arguments = sys.argv[1:] +stage = tool +if tool == 'kind': + stage = arguments[0] +record = {'stage': stage, 'arguments': arguments, + 'cluster': os.environ['KIND_CLUSTER'], 'context': os.environ['KUBECTL_CONTEXT'], + 'kubeconfig': os.environ['KUBECONFIG'], 'temporary': os.environ['TMPDIR'], + 'mode': Path(os.environ['KUBECONFIG']).stat().st_mode & 0o777, + 'directory_mode': Path(os.environ['TMPDIR']).stat().st_mode & 0o777, + 'provider': os.environ['KIND_EXPERIMENTAL_PROVIDER'], + 'alias': os.environ['ALLOW_KIND_CONTEXT_ALIAS']} +with (directory / 'trace').open('a') as trace: + trace.write(json.dumps(record) + '\n') +print('SYNTHETIC-SECRET-MUST-NOT-LEAK', file=sys.stderr, flush=True) +if tool == 'docker': + if scenario == 'docker_fail': + print('SYNTHETIC-SECRET-MUST-NOT-LEAK') + sys.exit(71) + print('windows' if scenario == 'wrong_os' else 'linux') +elif stage == 'get': + if scenario == 'list_fail': + sys.exit(73) + print('unrelated-cluster') + if scenario == 'collision': + print(os.environ['KIND_CLUSTER']) +elif stage == 'create': + assert '--retain' in arguments + assert arguments[arguments.index('--kubeconfig') + 1] == os.environ['KUBECONFIG'] + assert arguments[arguments.index('--name') + 1] == os.environ['KIND_CLUSTER'] + assert '@sha256:' in arguments[arguments.index('--image') + 1] + assert Path(arguments[arguments.index('--config') + 1]).read_text().endswith('- role: control-plane\n') + (directory / 'owned-cluster').touch() + if scenario == 'create_fail': + print('SYNTHETIC-SECRET-MUST-NOT-LEAK') + sys.exit(74) +elif stage == 'delete': + assert arguments[arguments.index('--name') + 1] == os.environ['KIND_CLUSTER'] + assert arguments[arguments.index('--kubeconfig') + 1] == os.environ['KUBECONFIG'] + if scenario in ('delete_fail', 'smoke_delete_fail'): + sys.exit(43) + if scenario != 'delete_timeout': + (directory / 'owned-cluster').unlink() +elif tool == 'standalone-smoke.sh': + assert Path.cwd() == (directory / 'repo').resolve() + print('SYNTHETIC-SECRET-MUST-NOT-LEAK', flush=True) + if scenario in ('smoke_fail', 'smoke_delete_fail'): + sys.exit(42) +else: + sys.exit(99) + +if scenario in (stage + '_timeout', stage + '_signal'): + signal.signal(signal.SIGTERM, signal.SIG_IGN) + child = subprocess.Popen([sys.executable, '-c', + 'import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)']) + (directory / 'descendant').write_text(str(child.pid)) + while True: + time.sleep(1) +'''.replace('#!PYTHON', '#!' + sys.executable, 1) + + +def check(condition, message): + if not condition: + raise AssertionError(message) + + +with tempfile.TemporaryDirectory(prefix='test-fleet-smoke-') as temporary: + suite = Path(temporary) + names = [] + + def case(scenario, expected, missing=None, timeout=None, send_signal=None, arguments=()): + directory = suite / (scenario + '-' + str(len(list(suite.iterdir())))) + directory.mkdir() + repository = directory / 'repo' + (repository / 'hack').mkdir(parents=True) + wrapper = repository / 'hack/run-standalone-smoke.sh' + shutil.copy2(Path(sys.argv[1]) / 'hack/run-standalone-smoke.sh', wrapper) + inner = repository / 'hack/standalone-smoke.sh' + inner.write_text(mock) + inner.chmod(0o755) + binaries = directory / 'bin' + binaries.mkdir() + for tool in ('docker', 'kind', 'kubectl', 'kustomize', 'git'): + if tool != missing: + target = binaries / tool + target.write_text(mock) + target.chmod(0o755) + for tool in ('python3', 'dirname'): + if tool != missing: + (binaries / tool).symlink_to(shutil.which(tool)) + home = directory / 'home' + (home / '.kube').mkdir(parents=True) + credentials = [home / '.kube/config', directory / 'first-config', directory / 'second-config'] + for credential in credentials: + credential.write_text('user-config-and-current-context-must-not-change\n') + scratch = directory / 'scratch' + scratch.mkdir() + environment = dict(os.environ, PATH=str(binaries), HOME=str(home), TMPDIR=str(scratch), + KUBECONFIG=str(credentials[1]) + ':' + str(credentials[2]), + KIND_CLUSTER='unrelated-cluster', KUBECTL_CONTEXT='production', + ALLOW_KIND_CONTEXT_ALIAS='true', KIND_EXPERIMENTAL_PROVIDER='podman', + SCENARIO=scenario, CASE_DIRECTORY=str(directory), + FLEET_SMOKE_TIMEOUT_SECONDS=timeout or '10', + FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS='1') + started = time.monotonic() + process = subprocess.Popen([str(wrapper), *arguments], env=environment, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + try: + if send_signal: + deadline = time.monotonic() + 5 + while not (directory / 'descendant').exists(): + check(process.poll() is None, scenario + ' exited before signal') + check(time.monotonic() < deadline, scenario + ' did not start') + time.sleep(0.02) + process.send_signal(send_signal) + output = process.communicate(timeout=15)[0].decode() + finally: + if process.poll() is None: + process.kill() + process.communicate() + check(process.returncode == expected, scenario + ': unexpected status ' + str(process.returncode) + '\n' + output) + check(time.monotonic() - started < 15, scenario + ': unbounded execution') + check('SYNTHETIC-SECRET' not in output, scenario + ': raw diagnostics leaked') + for credential in credentials: + check(credential.read_text() == 'user-config-and-current-context-must-not-change\n', scenario + ': changed user config') + check(not list(scratch.iterdir()), scenario + ': leaked private temporary files') + trace = directory / 'trace' + records = [json.loads(line) for line in trace.read_text().splitlines()] if trace.exists() else [] + stages = [record['stage'] for record in records] + for record in records: + check(record['cluster'].startswith('fleet-smoke-') and record['cluster'] != 'unrelated-cluster', 'unsafe name') + check(record['context'] == 'kind-' + record['cluster'], 'unsafe context') + check(record['provider'] == 'docker' and record['alias'] == 'false', 'unsafe inherited settings') + check(record['mode'] == 0o600 and record['directory_mode'] == 0o700, 'public credentials') + check(Path(record['kubeconfig']).parent == Path(record['temporary']), 'nonprivate kubeconfig') + check(Path(record['temporary']).parent == scratch, 'nonprivate scratch') + check(not Path(record['temporary']).exists(), 'temporary directory survived') + check(stages.count('delete') == (1 if 'create' in stages else 0), scenario + ': wrong cleanup authority') + check(len({record['cluster'] for record in records}) <= 1, scenario + ': changed cluster identity') + if 'create' in stages: + names.append(records[0]['cluster']) + if scenario not in ('delete_fail', 'smoke_delete_fail', 'delete_timeout'): + check(not (directory / 'owned-cluster').exists(), scenario + ': cluster leaked') + else: + check('cleanup unverified' in output, scenario + ': cleanup uncertainty concealed') + if scenario in ('collision', 'create_fail', 'create_timeout', 'create_signal'): + check('standalone-smoke.sh' not in stages, scenario + ': ran smoke without fresh cluster') + if scenario == 'success': + check(stages == ['docker', 'get', 'create', 'standalone-smoke.sh', 'delete'], 'incorrect success lifecycle') + descendant = directory / 'descendant' + if descendant.exists(): + process_id = int(descendant.read_text()) + state = subprocess.run(['ps', '-o', 'stat=', '-p', str(process_id)], + capture_output=True, text=True, check=False).stdout.strip() + check(not state or state.startswith('Z'), scenario + ': descendant survived process-group cleanup') + print('PASS ' + scenario + (': missing ' + missing if missing else '')) + + case('success', 0) + case('success', 0) + for tool in ('python3', 'docker', 'kind', 'kubectl', 'kustomize', 'git'): + case('missing', 1, missing=tool) + case('arguments', 1, arguments=('existing-cluster',)) + for value in ('0', '-1', 'oops', '3601'): + case('invalid_timeout', 1, timeout=value) + case('docker_fail', 71) + case('wrong_os', 1) + case('list_fail', 73) + case('collision', 1) + case('create_fail', 74) + case('smoke_fail', 42) + case('delete_fail', 1) + case('smoke_delete_fail', 42) + case('docker_timeout', 124, timeout='1') + case('get_timeout', 124, timeout='1') + case('create_timeout', 124, timeout='1') + case('standalone-smoke.sh_timeout', 124, timeout='1') + case('delete_timeout', 1) + case('get_signal', 143, send_signal=signal.SIGTERM) + case('create_signal', 143, send_signal=signal.SIGTERM) + case('standalone-smoke.sh_signal', 130, send_signal=signal.SIGINT) + case('standalone-smoke.sh_signal', 129, send_signal=signal.SIGHUP) + case('delete_signal', 1, send_signal=signal.SIGTERM) + check(len(names) == len(set(names)), 'cluster names reused across invocations') + print('All disposable standalone smoke tests passed; no real tools or clusters used.') +PY diff --git a/hack/test-standalone-preflight.sh b/hack/test-standalone-preflight.sh index 2dcad9e0..5edbc741 100755 --- a/hack/test-standalone-preflight.sh +++ b/hack/test-standalone-preflight.sh @@ -55,3 +55,62 @@ for manager in fleet-manager fleet-milo-manager; do fi done grep -q 'fleet-manager.*fleet-milo-manager' "$root/docs/operations/standalone-smoke.md" + +cat >"$temporary/docker" <<'EOF' +#!/bin/sh +exit 0 +EOF +cat >"$temporary/kustomize" <<'EOF' +#!/bin/sh +set -eu +case "$*" in + 'build config/base/crd') echo 'kind: CustomResourceDefinition' ;; + 'build config/standalone') + test -f "$ORDER_DIRECTORY/established" + echo 'kind: Installation' + ;; + *) exit 99 ;; +esac +EOF +cat >"$temporary/kubectl" <<'EOF' +#!/bin/sh +set -eu +case " $* " in + *" config view "*) printf '%s' 'https://127.0.0.1:6443' ;; + *" get deployments -A "*) exit 0 ;; + *" get "*) exit 1 ;; + *" apply -f "*) + for argument do manifest=$argument; done + if grep -q 'CustomResourceDefinition' "$manifest"; then + touch "$ORDER_DIRECTORY/crds-applied" + else + test -f "$ORDER_DIRECTORY/established" + grep -q 'Installation' "$manifest" + touch "$ORDER_DIRECTORY/fixtures-applied" + fi + ;; + *" wait --for=condition=Established "*) + test -f "$ORDER_DIRECTORY/crds-applied" + test "$ESTABLISHMENT_RESULT" = success + touch "$ORDER_DIRECTORY/established" + ;; + *" rollout status "*) echo 'ordering verified'; exit 97 ;; + *) exit 99 ;; +esac +EOF +chmod +x "$temporary/kustomize" +for result in success failure; do + order_directory="$temporary/$result" + mkdir "$order_directory" + if (cd "$root" && ORDER_DIRECTORY="$order_directory" ESTABLISHMENT_RESULT="$result" PATH="$temporary:$PATH" ./hack/standalone-smoke.sh >"$temporary/output" 2>&1); then + echo 'ordering fixture unexpectedly completed a live smoke' >&2 + exit 1 + fi + test -f "$order_directory/crds-applied" + if [ "$result" = success ]; then + test -f "$order_directory/fixtures-applied" + grep -q 'ordering verified' "$temporary/output" + else + test ! -e "$order_directory/fixtures-applied" + fi +done diff --git a/hack/validate-standalone-render.sh b/hack/validate-standalone-render.sh index 7faa9b1e..cba9052c 100755 --- a/hack/validate-standalone-render.sh +++ b/hack/validate-standalone-render.sh @@ -8,19 +8,21 @@ kustomize build config/standalone >"$rendered" require_count() { expected=$1 pattern=$2 - actual=$(grep -c "$pattern" "$rendered" || true) + actual=$(grep -c -- "$pattern" "$rendered" || true) if [ "$actual" -ne "$expected" ]; then echo "rendered manifest count for $pattern = $actual, want $expected" >&2 exit 1 fi } -# One simulator pod template and three suspended phase-job templates. -require_count 4 'runAsUser: 65532' -require_count 4 'runAsGroup: 65532' -require_count 4 'fsGroup: 65532' -require_count 4 'defaultMode: 288' -require_count 4 'imagePullPolicy: Never' +require_count 5 'runAsUser: 65532' +require_count 5 'runAsGroup: 65532' +require_count 5 'fsGroup: 65532' +require_count 5 'defaultMode: 288' +require_count 5 'imagePullPolicy: Never' +require_count 4 'suspend: true' +require_count 1 'name: fleet-smoke-reinstall' +require_count 1 '--phase=reinstall' require_count 1 'fsGroupChangePolicy: OnRootMismatch' require_count 1 'mountPath: /var/lib/fleet' require_count 1 'volumeClaimTemplates:' diff --git a/internal/standalone/reinstall_test.go b/internal/standalone/reinstall_test.go new file mode 100644 index 00000000..28d442f5 --- /dev/null +++ b/internal/standalone/reinstall_test.go @@ -0,0 +1,347 @@ +package standalone + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sync" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type unavailableResultExecutor struct { + storeExecutor + beforeEffect func(simulator.Request) +} + +type changedHistoryExecutor struct { + storeExecutor + change func(simulator.OperationResult) (simulator.OperationResult, bool, error) +} + +func (e changedHistoryExecutor) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { + result, _, err := e.storeExecutor.Lookup(ctx, operationID) + if err != nil { + return result, false, err + } + return e.change(result) +} + +func TestCompletedInstallationRequiresSimulatorHistory(t *testing.T) { + for _, phase := range []string{PhaseInstall, PhaseReinstall} { + for _, corruption := range []string{"missing", "unavailable", "identity", "inputs", "kind", "phase", "result", "completion"} { + t.Run(phase+"/"+corruption, func(t *testing.T) { + runner, store, _ := reinstallFixture(t) + ctx := context.Background() + if err := runner.Run(ctx, phase); err != nil { + t.Fatal(err) + } + before := store.Snapshot() + runner.Executor = changedHistoryExecutor{storeExecutor{store}, func(result simulator.OperationResult) (simulator.OperationResult, bool, error) { + switch corruption { + case "missing": + return simulator.OperationResult{}, false, nil + case "unavailable": + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + case "identity": + result.ID = "different-operation" + case "inputs": + result.InputDigest = "different-retained-request" + case "kind": + result.Kind = "cleanup" + case "phase": + result.Phase = "Pending" + case "result": + result.Result = "clean" + case "completion": + result.CompletedAt = nil + } + return result, true, nil + }} + if err := runner.Run(ctx, phase); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unverified replay = %v", err) + } + claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) { + t.Fatal("unverified history left machine ready") + } + if !reflect.DeepEqual(before, store.Snapshot()) { + t.Fatal("history verification executed a new effect") + } + assertWaitingConsumerBlocked(t, runner) + }) + } + } +} + +func (e unavailableResultExecutor) Execute(ctx context.Context, request simulator.Request) (simulator.OperationResult, error) { + if e.beforeEffect != nil { + e.beforeEffect(request) + } + if _, err := e.storeExecutor.Execute(ctx, request); err != nil { + return simulator.OperationResult{}, err + } + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} + +func (e unavailableResultExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} + +func reinstallFixture(t *testing.T) (Runner, *simulator.Store, string) { + t.Helper() + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + options := DefaultOptions() + objects := append(fixtureObjects(options), &fleetv1.Installation{ + ObjectMeta: metav1.ObjectMeta{Namespace: options.FirstNamespace, Name: options.ReinstallationName, UID: "reinstallation-uid", Generation: 1}, + Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: options.ImageName}}, + }) + kube := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}, &fleetv1.Installation{}).Build() + path := t.TempDir() + "/state.json" + store, err := simulator.Open(path) + if err != nil { + t.Fatal(err) + } + runner := Runner{Client: kube, Executor: storeExecutor{store}, Options: options, Now: time.Now} + for _, phase := range []string{PhaseAllocate, PhaseInstall} { + if err := runner.Run(context.Background(), phase); err != nil { + t.Fatal(err) + } + } + return runner, store, path +} + +func retainedAsset(t *testing.T, runner Runner) controller.AssetRecord { + t.Helper() + var secrets corev1.SecretList + if err := runner.Client.List(context.Background(), &secrets, client.InNamespace(runner.Options.PrivateNamespace), client.MatchingLabels{"fleet.datumapis.com/private-record": "asset"}); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 1 { + t.Fatalf("retained assets = %d, want 1", len(secrets.Items)) + } + var record controller.AssetRecord + if err := json.Unmarshal(secrets.Items[0].Data["record.json"], &record); err != nil { + t.Fatal(err) + } + return record +} + +func assertWaitingConsumerBlocked(t *testing.T, runner Runner) { + t.Helper() + ctx := context.Background() + coordinator, err := controller.NewCoordinator(runner.Client, runner.Options.PrivateNamespace, runner.Executor, controller.LocalDigestImageResolver{}, nil, runner.Options.EvidenceAge) + if err != nil { + t.Fatal(err) + } + claim, namespace, admission, err := runner.claim(ctx, runner.Options.SecondNamespace) + if err != nil { + t.Fatal(err) + } + var class fleetv1.MachineClass + var profile fleetv1.MachineProfile + var machine fleetv1.MachineCapacity + for _, object := range []client.Object{&class, &profile, &machine} { + key := client.ObjectKey{} + switch object.(type) { + case *fleetv1.MachineClass: + key.Name = runner.Options.ClassName + case *fleetv1.MachineProfile: + key.Name = runner.Options.ProfileName + default: + key = client.ObjectKey{Namespace: runner.Options.ProviderNamespace, Name: runner.Options.MachineName} + } + if err := runner.Client.Get(ctx, key, object); err != nil { + t.Fatal(err) + } + } + if apiMeta.IsStatusConditionTrue(machine.Status.Conditions, "Available") { + t.Fatal("reinstall exposed occupied capacity as available") + } + apiMeta.SetStatusCondition(&machine.Status.Conditions, condition("Available", metav1.ConditionTrue, machine.Generation, "SyntheticStaleAvailability", "Synthetic stale projection cannot override custody.")) + if _, err := coordinator.Allocate(ctx, allocationRequest(claim, namespace, admission, &class, &profile, &machine, time.Now())); !errors.Is(err, controller.ErrInsufficientCapacity) { + t.Fatalf("waiting allocation with stale Available=True: %v", err) + } +} + +func TestReinstallRecoversExactOperationAndRejectsStalePredecessor(t *testing.T) { + ctx := context.Background() + runner, store, path := reinstallFixture(t) + before := retainedAsset(t, runner) + var operationID string + runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}, beforeEffect: func(request simulator.Request) { + asset := retainedAsset(t, runner) + if asset.ActiveOperationID != request.ID || asset.CurrentInstallationName != runner.Options.InstallationName || asset.BindingID != before.BindingID || asset.Epoch != before.Epoch { + t.Fatalf("effect lacks retained predecessor/authority: %#v", asset) + } + var secrets corev1.SecretList + if err := runner.Client.List(ctx, &secrets, client.InNamespace(runner.Options.PrivateNamespace)); err != nil { + t.Fatal(err) + } + found := false + for _, secret := range secrets.Items { + var operation controller.InstallationRecord + if json.Unmarshal(secret.Data["record.json"], &operation) == nil && operation.OperationID == request.ID { + found = operation.InstallationUID == "reinstallation-uid" && operation.Predecessor == runner.Options.InstallationName && operation.BindingID == before.BindingID && operation.ImageName == runner.Options.ImageName && operation.Admission.DecisionID == "standalone-install-reinstallation-uid" + } + } + if !found { + t.Fatal("exact reinstall inputs not retained before effect") + } + operationID = request.ID + }} + if err := runner.Run(ctx, PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost result = %v", err) + } + claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) || claim.Status.CurrentInstallationRef.Name != runner.Options.InstallationName { + t.Fatalf("unknown reinstall advanced readiness: %#v", claim.Status) + } + assertWaitingConsumerBlocked(t, runner) + reopened, err := simulator.Open(path) + if err != nil { + t.Fatal(err) + } + restarted := Runner{Client: runner.Client, Executor: storeExecutor{reopened}, Options: runner.Options, Now: time.Now} + for range 2 { + if err := restarted.Run(ctx, PhaseReinstall); err != nil { + t.Fatal(err) + } + } + after := retainedAsset(t, restarted) + if after.BindingID != before.BindingID || after.Epoch != before.Epoch || after.ClaimUID != before.ClaimUID || after.CurrentInstallationName != runner.Options.ReinstallationName || after.ActiveOperationID != "" { + t.Fatalf("reinstall changed custody or failed completion: %#v", after) + } + snapshot := reopened.Snapshot() + if len(snapshot.Operations) != 2 || snapshot.Operations[operationID] == nil || !reflect.DeepEqual(snapshot.Operations[operationID], store.Snapshot().Operations[operationID]) { + t.Fatal("retry/restart changed the retained effect") + } + assertWaitingConsumerBlocked(t, restarted) + claim, _, _, err = restarted.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + var installed fleetv1.Installation + if err := runner.Client.Get(ctx, client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installed); err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionTrue(claim.Status.Conditions, "Ready") || claim.Status.CurrentInstallationRef.Name != installed.Name || installed.Status.Phase != "Ready" || installed.Status.CompletedAt == nil { + t.Fatal("verified reinstall did not project synthetic completion") + } + stale := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: runner.Options.FirstNamespace, Name: "stale-reinstall", UID: "stale-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: runner.Options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: runner.Options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: runner.Options.ImageName}}} + if err := runner.Client.Create(ctx, stale); err != nil { + t.Fatal(err) + } + staleRunner := restarted + staleRunner.Options.InstallationName = stale.Name + if err := staleRunner.Run(ctx, PhaseInstall); !errors.Is(err, controller.ErrPredecessorConflict) { + t.Fatalf("stale predecessor accepted: %v", err) + } + if !reflect.DeepEqual(snapshot, reopened.Snapshot()) { + t.Fatal("stale predecessor produced a simulator effect") + } + if err := restarted.Run(ctx, PhaseReinstall); err != nil { + t.Fatal(err) + } + if err := restarted.Run(ctx, PhaseRelease); err != nil { + t.Fatal(err) + } + if len(reopened.Snapshot().Operations) != 3 { + t.Fatal("release did not retain exactly two installs and one cleanup") + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-b-uid", 2) +} + +func TestUnknownReinstallBlocksReleaseAndCapacityReuse(t *testing.T) { + runner, store, _ := reinstallFixture(t) + runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}} + if err := runner.Run(context.Background(), PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + if err := runner.Run(context.Background(), PhaseRelease); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("release with unresolved reinstall = %v", err) + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) + assertWaitingConsumerBlocked(t, runner) + if len(store.Snapshot().Operations) != 2 { + t.Fatal("unknown reinstall allowed premature cleanup") + } +} + +func TestConcurrentReinstallConvergesWithoutDuplicateEffects(t *testing.T) { + runner, store, _ := reinstallFixture(t) + var workers sync.WaitGroup + results := make(chan error, 4) + for range cap(results) { + workers.Go(func() { results <- runner.Run(context.Background(), PhaseReinstall) }) + } + workers.Wait() + close(results) + for err := range results { + if err != nil && !apierrors.IsConflict(err) && !errors.Is(err, controller.ErrPredecessorConflict) { + t.Fatalf("unexpected concurrent outcome: %v", err) + } + } + if err := runner.Run(context.Background(), PhaseReinstall); err != nil { + t.Fatal(err) + } + if len(store.Snapshot().Operations) != 2 { + t.Fatal("concurrent retries duplicated installation effects") + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) +} + +func TestReinstallRequiresBoundedSuccessorFixture(t *testing.T) { + for _, variant := range []string{"missing", "same-name", "wrong-predecessor"} { + t.Run(variant, func(t *testing.T) { + runner, store, _ := reinstallFixture(t) + switch variant { + case "missing": + runner.Options.ReinstallationName = "" + case "same-name": + runner.Options.ReinstallationName = runner.Options.InstallationName + case "wrong-predecessor": + var installation fleetv1.Installation + if err := runner.Client.Get(context.Background(), client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installation); err != nil { + t.Fatal(err) + } + installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "None"} + if err := runner.Client.Update(context.Background(), &installation); err != nil { + t.Fatal(err) + } + } + if err := runner.Run(context.Background(), PhaseReinstall); err == nil { + t.Fatal("invalid successor fixture accepted") + } + if len(store.Snapshot().Operations) != 1 { + t.Fatal("invalid successor produced an effect") + } + }) + } +} diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index d03ef281..db3ad686 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -23,24 +23,26 @@ import ( ) const ( - PhaseAllocate = "allocate" - PhaseInstall = "install" - PhaseRelease = "release" + PhaseAllocate = "allocate" + PhaseInstall = "install" + PhaseReinstall = "reinstall" + PhaseRelease = "release" ) type Options struct { - PrivateNamespace string - ProviderNamespace string - FirstNamespace string - SecondNamespace string - ClassName string - ProfileName string - MachineName string - ClaimName string - InstallationName string - ImageName string - LocationName string - EvidenceAge time.Duration + PrivateNamespace string + ProviderNamespace string + FirstNamespace string + SecondNamespace string + ClassName string + ProfileName string + MachineName string + ClaimName string + InstallationName string + ReinstallationName string + ImageName string + LocationName string + EvidenceAge time.Duration } func DefaultOptions() Options { @@ -49,7 +51,8 @@ func DefaultOptions() Options { FirstNamespace: "fleet-project-a", SecondNamespace: "fleet-project-b", ClassName: "standard-metal", ProfileName: "general-purpose-24c-128g", MachineName: "central1-baremetal-01", ClaimName: "allocation", - InstallationName: "debian-12", ImageName: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb", + ReinstallationName: "debian-12-reinstall", + InstallationName: "debian-12", ImageName: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb", LocationName: "us-central-1", EvidenceAge: 5 * time.Minute, } } @@ -89,7 +92,12 @@ func (r Runner) Run(ctx context.Context, phase string) error { case PhaseAllocate: return r.allocate(ctx, coordinator) case PhaseInstall: - return r.install(ctx, coordinator) + return r.install(ctx, coordinator, r.Options.InstallationName) + case PhaseReinstall: + if r.Options.ReinstallationName == "" || r.Options.ReinstallationName == r.Options.InstallationName { + return errors.New("reinstall requires a distinct installation name") + } + return r.install(ctx, coordinator, r.Options.ReinstallationName) case PhaseRelease: return r.release(ctx, coordinator) default: @@ -140,13 +148,20 @@ func (r Runner) allocate(ctx context.Context, coordinator *controller.Coordinato return r.projectPendingClaim(ctx, second, profile, "InsufficientCapacity", "The only synthetic machine is allocated to another consumer.") } -func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator) error { +func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator, installationName string) error { claim, namespace, admission, err := r.claim(ctx, r.Options.FirstNamespace) if err != nil { return err } var installation fleetv1.Installation - if err := r.Client.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: r.Options.InstallationName}, &installation); err != nil { + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: installationName}, &installation); err != nil { + return err + } + if installationName == r.Options.ReinstallationName && installation.Spec.ExpectedPredecessor != (fleetv1.InstallationPredecessor{Type: "Installation", Name: r.Options.InstallationName}) { + return errors.New("synthetic reinstall must name the configured initial installation as predecessor") + } + apiMeta.SetStatusCondition(&claim.Status.Conditions, condition("Ready", metav1.ConditionUnknown, claim.Generation, "SyntheticInstallationUnverified", "The synthetic installation request has not yet returned verified completion.")) + if err := r.Client.Status().Update(ctx, claim); err != nil { return err } imageDecision := "local-test-" + imageDigest(r.Options.ImageName) From 0333f6eb1e0f84eaff0190372da80a5e0ac60965 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 13:59:16 -0600 Subject: [PATCH 07/12] fix(standalone): wait for the simulator Service before a smoke phase The kind smoke restarts the simulator and immediately runs the recovery phase. On a slow runner the phase's first request could reach no pod while the Service moved to the new one, and the lifecycle correctly reported that transport failure as an unknown outcome. The phase now waits, without effect, until the simulator answers readiness through its Service, so the recovery check measures recovery and not the handover. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-standalone-smoke/main.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 8f388da7..e8b4c484 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -57,6 +57,9 @@ func main() { if err != nil { fail(err) } + if err := awaitSimulator(simulatorURL, 2*time.Minute); err != nil { + fail(err) + } if err := (standalone.Runner{Client: kube, Executor: provider, Options: options}).Run(context.Background(), phase); err != nil { fail(err) } @@ -64,3 +67,25 @@ func main() { } func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) } + +// awaitSimulator waits until the simulator's Service answers readiness. A +// phase started just after a simulator restart can otherwise reach no pod, +// and the lifecycle correctly reports that transport failure as an unknown +// outcome. Readiness has no effect and is never operation evidence. +func awaitSimulator(base string, limit time.Duration) error { + c := &http.Client{Timeout: 5 * time.Second} + deadline := time.Now().Add(limit) + for { + resp, err := c.Get(strings.TrimRight(base, "/") + "/readyz") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return nil + } + } + if time.Now().After(deadline) { + return fmt.Errorf("simulator did not become reachable and ready within %s", limit) + } + time.Sleep(time.Second) + } +} From 5b65485f92bdf122d6a086c201a3da68e56795db Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:28:30 -0600 Subject: [PATCH 08/12] feat(localvm): install a real OS over firmware PXE into a disposable VM internal/localvm is a bounded libvirt executor behind the existing executor contract. It boots a blank disk over iPXE from a digest-pinned installer, admits one-time network boot only for the retained operation, verifies the installed receipt from serial output and the domain's disappearance, then boots disk-only. Recovery replays the retained request without a second installer start; cleanup deletes only that binding's disks after verifying no matching domain, and returns a request-bound clean result. cmd/fleet-local-vm and hack/local-vm/run.sh drive allocation, install, crash recovery, reinstall, cleanup and reuse through the shared lifecycle library against a disposable Kubernetes API (task local-vm:acceptance, TCG in the task-owned Colima profile). This is not KVM, hardware or production qualification. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .gitignore | 3 + Taskfile.yaml | 8 + cmd/fleet-local-vm/main.go | 230 ++++++ docs/development/README.md | 7 +- docs/operations/README.md | 1 + .../local-vm-adversarial-validation.md | 211 ++++++ docs/operations/local-vm.md | 309 ++++++++ hack/local-vm/Containerfile | 18 + hack/local-vm/boot | 10 + hack/local-vm/init | 37 + hack/local-vm/run.sh | 115 +++ hack/local-vm/start-libvirt | 16 + internal/localvm/boot.go | 258 +++++++ internal/localvm/boot_test.go | 123 +++ internal/localvm/lifecycle_test.go | 294 +++++++ internal/localvm/provider.go | 715 ++++++++++++++++++ internal/localvm/provider_test.go | 35 + .../localvm/pxe_review_adversarial_test.go | 189 +++++ internal/localvm/site_test.go | 116 +++ 20 files changed, 2695 insertions(+), 1 deletion(-) create mode 100644 cmd/fleet-local-vm/main.go create mode 100644 docs/operations/local-vm-adversarial-validation.md create mode 100644 docs/operations/local-vm.md create mode 100644 hack/local-vm/Containerfile create mode 100644 hack/local-vm/boot create mode 100644 hack/local-vm/init create mode 100755 hack/local-vm/run.sh create mode 100644 hack/local-vm/start-libvirt create mode 100644 internal/localvm/boot.go create mode 100644 internal/localvm/boot_test.go create mode 100644 internal/localvm/lifecycle_test.go create mode 100644 internal/localvm/provider.go create mode 100644 internal/localvm/provider_test.go create mode 100644 internal/localvm/pxe_review_adversarial_test.go create mode 100644 internal/localvm/site_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 696977f1..d9bc7d38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,7 @@ jobs: - run: ./hack/test-standalone-build-context.sh - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh + - run: shellcheck -S warning hack/local-vm/run.sh hack/local-vm/start-libvirt standalone-smoke: runs-on: ubuntu-latest timeout-minutes: 35 diff --git a/.gitignore b/.gitignore index d105526d..1e2ab3f7 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ # Local agent settings .claude/settings.local.json .claude/worktrees/ + +# Locally built binaries +/fleet-local-vm diff --git a/Taskfile.yaml b/Taskfile.yaml index 37c35206..058efe55 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -6,6 +6,14 @@ tasks: cmds: - ./hack/run-standalone-smoke.sh + local-vm:acceptance: + desc: Single-plane local VM PXE acceptance with explicit TCG in the task-owned Colima profile. + env: + DOCKER_CONTEXT: colima-fleet-acceptance-tcg + FLEET_LOCAL_VM_ACCEL: tcg + cmds: + - bash hack/local-vm/run.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/fleet-local-vm/main.go b/cmd/fleet-local-vm/main.go new file mode 100644 index 00000000..71ea5570 --- /dev/null +++ b/cmd/fleet-local-vm/main.go @@ -0,0 +1,230 @@ +// fleet-local-vm is an explicit local acceptance harness, not a deployed controller. +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + api "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/localvm" + "go.datum.net/fleet/internal/simulator" + core "k8s.io/api/core/v1" + meta "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/clientcmd" + "os" + "sigs.k8s.io/controller-runtime/pkg/client" + "strings" + "time" +) + +type crashAfterEffect struct{ *localvm.Provider } + +func (p crashAfterEffect) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + r, e := p.Provider.Execute(ctx, q) + if e == nil && q.Kind == "install" { + os.Exit(75) + } + return r, e +} + +func main() { + if e := work(); e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } +} +func work() error { + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) + defer cancel() + p, e := localvm.Open() + if e != nil { + return e + } + if len(os.Args) == 2 && os.Args[1] == "boot-denials" { + summary, err := p.CheckClosedBoot("") + if err != nil { + return err + } + return os.WriteFile(localvm.Root+"/boot-denials.txt", []byte(summary+"\n"), 0600) + } + if len(os.Args) == 2 && os.Args[1] == "boot-service" { + return p.ServeBoot() + } + if len(os.Args) == 2 && os.Args[1] == "image" { + fmt.Println(p.ImageReference()) + return nil + } + if len(os.Args) != 2 { + return errors.New("phase required") + } + config, e := clientcmd.BuildConfigFromFlags("", "/run/fleet/kubeconfig") + if e != nil { + return e + } + scheme := runtime.NewScheme() + core.AddToScheme(scheme) + api.AddToScheme(scheme) + k, e := client.New(config, client.Options{Scheme: scheme}) + if e != nil { + return e + } + var backend executor.Client = p + if os.Args[1] == "install-crash" { + backend = crashAfterEffect{p} + } + c, e := controller.NewCoordinator(k, "fleet-system-private", backend, controller.LocalDigestImageResolver{}, nil, time.Hour) + if e != nil { + return e + } + var capacity api.MachineCapacity + var class api.MachineClass + var profile api.MachineProfile + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{{client.ObjectKey{Namespace: "fleet-provider", Name: "central1-baremetal-01"}, &capacity}, {client.ObjectKey{Name: "standard-metal"}, &class}, {client.ObjectKey{Name: "general-purpose-24c-128g"}, &profile}} { + if e = k.Get(ctx, item.key, item.obj); e != nil { + return e + } + } + // Explicit operator-owned local inventory; no imported device is adopted. + capacity.Status.Hardware = api.Hardware{CPU: api.HardwareCPU{Architecture: "amd64", Cores: 2, Threads: 2, Sockets: 1}, Memory: api.HardwareMemory{Capacity: "2Gi"}} + now := time.Now().UTC() + for _, name := range []string{"Prepared", "Healthy", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, meta.Condition{Type: name, Status: meta.ConditionTrue, ObservedGeneration: capacity.Generation, LastTransitionTime: meta.NewTime(now), Reason: "LocalDisposableDevice", Message: "Operator-created local VM slot; private custody is authoritative."}) + } + if e = k.Status().Update(ctx, &capacity); e != nil { + return e + } + getClaim := func(ns string) (*api.Machine, *core.Namespace, error) { + m := &api.Machine{} + n := &core.Namespace{} + if e := k.Get(ctx, client.ObjectKey{Namespace: ns, Name: "allocation"}, m); e != nil { + return nil, nil, e + } + if e := k.Get(ctx, client.ObjectKey{Name: ns}, n); e != nil { + return nil, nil, e + } + return m, n, nil + } + allocate := func(ns string) (*controller.AssetRecord, error) { + m, n, e := getClaim(ns) + if e != nil { + return nil, e + } + auth := controller.AdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(m.UID)} + if e = c.EnsureClaimCustody(ctx, m, n.UID, auth); e != nil { + return nil, e + } + if len(m.Finalizers) == 0 { + m.Finalizers = []string{controller.MachineFinalizer} + if e = k.Update(ctx, m); e != nil { + return nil, e + } + } + return c.Allocate(ctx, controller.AllocationRequest{Claim: m, Class: &class, Profile: &profile, MachineCapacities: []api.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: now}, NamespaceUID: n.UID, Admission: auth, LocalClassName: class.Name, LocalClassUID: class.UID, LocalProfileName: profile.Name, LocalProfileUID: profile.UID}) + } + phase := os.Args[1] + switch phase { + case "allocate": + r, e := allocate("fleet-project-a") + if e != nil { + return e + } + if _, e = allocate("fleet-project-b"); !errors.Is(e, controller.ErrInsufficientCapacity) { + return fmt.Errorf("contention failed: %v", e) + } + fmt.Printf("exclusive allocation %s asset %s\n", r.BindingID, r.AssetID) + case "install", "install-crash", "reinstall": + m, n, e := getClaim("fleet-project-a") + if e != nil { + return e + } + name := "debian-12" + if phase == "reinstall" { + name += "-reinstall" + } + var in api.Installation + if e = k.Get(ctx, client.ObjectKey{Namespace: m.Namespace, Name: name}, &in); e != nil { + return e + } + m.Status.Phase = "Pending" + m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionUnknown, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalInstallationUnverified", Message: "Installation outcome has not been verified."}} + if e = k.Status().Update(ctx, m); e != nil { + return e + } + result, e := c.Install(ctx, controller.InstallationRequest{Claim: m, Installation: &in, NamespaceUID: n.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(in.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + strings.Split(p.ImageReference(), "@")[1]}}) + if e != nil { + return e + } + receipt, found, e := p.Lookup(ctx, result.Record.OperationID) + if e != nil || !found || receipt.InputDigest != result.RequestDigest { + return errors.New("exact provider receipt missing") + } + in.Status = api.InstallationStatus{Phase: "Ready", CompletedAt: &meta.Time{Time: *receipt.CompletedAt}, Conditions: []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: in.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Pinned Linux installer and disk boot verified through local libvirt."}}} + if e = k.Status().Update(ctx, &in); e != nil { + return e + } + m.Status.CurrentInstallationRef = &api.LocalReference{Name: name} + m.Status.Phase = "Ready" + m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Exact installation-bound disk boot and powered-off handoff verified."}} + if e = k.Status().Update(ctx, m); e != nil { + return e + } + fmt.Printf("verified installation %s operation %s\n", in.UID, receipt.ID) + case "release": + m, _, e := getClaim("fleet-project-a") + if e != nil { + return e + } + if m.DeletionTimestamp == nil { + if e = k.Delete(ctx, m, client.Preconditions{UID: &m.UID, ResourceVersion: &m.ResourceVersion}); e != nil { + return e + } + } + r, e := c.Release(ctx, m.UID) + if e != nil { + return e + } + if !r.SafeToRemoveFinalizer { + return errors.New("cleanup not verified") + } + current := &api.Machine{} + if e = k.Get(ctx, client.ObjectKeyFromObject(m), current); e != nil { + return e + } + if current.UID != m.UID { + return errors.New("consumer machine identity changed during release") + } + kept := current.Finalizers[:0] + for _, f := range current.Finalizers { + if f != controller.MachineFinalizer { + kept = append(kept, f) + } + } + current.Finalizers = kept + if e = k.Update(ctx, current); e != nil { + return e + } + + if _, e = allocate("fleet-project-b"); e != nil { + return e + } + fmt.Println("cleanup verified; capacity exclusively reused by second consumer") + case "evidence": + var installs api.InstallationList + if e = k.List(ctx, &installs); e != nil { + return e + } + b, _ := json.MarshalIndent(installs, "", " ") + return os.WriteFile(localvm.Root+"/installations.json", b, 0600) + default: + return errors.New("unsupported phase") + } + return nil +} diff --git a/docs/development/README.md b/docs/development/README.md index 38d597ec..eba7743f 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -18,7 +18,12 @@ 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. +admission, replayable Milo event adapters, and production provider integration are not implemented. +An opt-in [local KVM installation harness](../operations/local-vm.md) implements +a bounded libvirt executor and guest installer using the same lifecycle library. +It uses a disposable Kubernetes API and explicit local authority fixtures; it is +not wired into the production manager. + Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/operations/README.md b/docs/operations/README.md index 93a915ae..02f356ee 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -13,6 +13,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | --- | --- | --- | | Build and test locally or run the simulator | [Implementation commands](../development/README.md#build-test-and-run) | Behavior of the implemented code and synthetic provider | | Exercise allocation, install recovery, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | +| Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/local-vm-adversarial-validation.md b/docs/operations/local-vm-adversarial-validation.md new file mode 100644 index 00000000..9dced04a --- /dev/null +++ b/docs/operations/local-vm-adversarial-validation.md @@ -0,0 +1,211 @@ +# Local VM prototype: independent validation + +Review date: 2026-11-14. This report covers a shared, uncommitted working tree. +Only the three new adversarial test files and this report belong to this review. +Implementation files, existing tests, and pre-existing dirty changes were not edited. + +## Observed results + +Parent follow-up: both findings below are fixed in the shared working tree. +The coordinator now compares every terminal result's input digest with the exact +request, including cleanup and recovered results. Lookup rejects `.` and `..` +before transport. Synthetic executor fixtures now return genuine request digests. +`go test -race ./internal/controller ./internal/executor ./internal/simulator +./internal/milo ./internal/staging ./internal/standalone` passed, including both +new regression tests. This follow-up is not independent approval of the VM adapter. +The original review observations below describe the pre-fix implementation. + +Commands executed locally: + +```sh +go test ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone +go test -race ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone +git diff --check +``` + +Both Go commands failed on the two new regression tests described below. Simulator +and standalone packages passed; standalone results were cached. No race warning +was reported. Whitespace validation passed. No VM, Docker, kind, deployment, +external review, or hosted CI resources were started by this reviewer. + +### High: wrong-asset cleanup evidence releases custody + +At review time, `validateTerminalResult` in +[lifecycle.go](../../internal/controller/lifecycle.go) (line 1531) checks operation +ID, kind, phase, completion presence, and result text, but does not compare +`InputDigest` with the exact retained request. Both direct completion and lookup +recovery use this validator. + +[The regression test](../../internal/controller/evidence_adversarial_test.go) +returns a successful cleanup with the requested operation ID and a valid digest +computed for a different physical asset. Both direct and recovered responses +produce `State:Released`, `SafeToRemoveFinalizer:true`, and no error. The waiting +consumer then allocates the asset successfully. These are observed unit-test +results, not a hypothetical gap inferred only from code. + +Required fix: compare verified result evidence against the exact request before +any custody transition, including cleanup and recovery. Missing or mismatched +digests must remain unknown. Update synthetic executor fixtures to supply genuine +request digests rather than allowing absent evidence for compatibility. The +standalone runner's additional install-history digest check does not protect +the coordinator's cleanup path. + +### Medium: dot-segment lookup leaves the operation path + +[client.go](../../internal/executor/client.go) (lines 140–144) rejects slash-bearing +IDs but passes `.` and `..` through `path.Join`. The new +[lookup test](../../internal/executor/path_adversarial_test.go) observes requests +to `/v1/operations` and `/v1`, respectively. A 404 produces no error. This is an +HTTP path-confusion finding; it does not establish shell execution or filesystem +access. + +Required fix: reject dot segments before transport, or construct a URL whose +single opaque path segment cannot be normalized out of the operation endpoint. +Retain the negative tests for both values. + +### Passing adversarial coverage + +[The simulator test](../../internal/simulator/binding_adversarial_test.go) retains +an installation, reopens its store, and individually substitutes asset, binding, +epoch, fence, and image under the same operation ID. Every attempt returns +`ErrConflict` without changing the snapshot. This establishes simulator request +binding, not real executor fencing or artifact verification. + +## Existing coverage evaluated + +- [Lifecycle tests](../../internal/controller/lifecycle_test.go): exclusive + allocation, competing candidate selection, custody tombstones, release and + epoch reuse, missing authority, private predecessor checks, unknown-operation + recovery, malformed completion, retained routing identity, and network cleanup + ordering. Tests predominantly use an in-memory executor and fake Kubernetes + client; they do not demonstrate remote-worker fencing or API-server behavior. +- [Simulator tests](../../internal/simulator/store_test.go): serialized duplicate + submissions, request conflicts, fencing, cleanup retirement, lost responses, + persistence failure boundaries, corrupt-state rejection, and digest retention. + These test synthetic effects; no OS is installed. +- [Standalone reinstall tests](../../internal/standalone/reinstall_test.go): exact + operation recovery across simulator reopen, stale predecessors, concurrent + reinstall convergence, unknown result retaining custody, and rejection of + missing/substituted terminal history. These tests were already dirty/untracked + when this review began and were not authored or modified here. +- [Executor tests](../../internal/executor/client_test.go): authentication, token + rotation, lost-response lookup, malformed evidence, operation-specific result + text, and bounded HTTP timeout. They do not qualify libvirt commands or XML. + +## Real adapter inspection boundary + +During ordinary review, [the image build](../../hack/local-vm/Containerfile), +[installer](../../hack/local-vm/init), and [disk boot script](../../hack/local-vm/boot) +appeared. The installer partitions `/dev/vda`, writes a filesystem and receipt, +installs GRUB, and emits `FLEET-INSTALLED`. The boot script checks an ext4 root on +`/dev/vda1` and emits `FLEET-DISK-BOOT` with the receipt. This is source inspection +only. Separate markers are useful, but there is no observed VM execution here. + +The build generates SHA256SUMS, but its Debian base tag and apt package versions +are mutable. Generated checksums alone do not establish trusted artifact +provenance or prove that the executor enforces an admitted checksum. A reproducible +build and verification of the exact locally built bytes are distinct claims. + +No Go real-VM adapter was present in the inspected source inventory. Final adapter +validation remains pending. The parent should request a fresh review after the +adapter and its execution commands are available; this report is not approval of +implementation added after the inspection boundary. + +## Concrete acceptance assertions still required + +These are proposed checks, not successful results. Run destructive cases only +against uniquely scoped disposable domains and disks with a decoy resource to +detect unintended effects. + +1. **Exclusive allocation:** race two consumers for one capacity through the + shared coordinator. Exactly one immutable binding wins, including under stale + `Available=True`. Restart during selection/commit; never admit effects for the + loser or briefly expose occupied capacity. Keep Device, capacity, allocation, + Installation, operation, and libvirt domain identities distinct. +2. **Exact authority:** before the first external command, retain operation ID, + Installation incarnation, predecessor, asset, binding, epoch/fence, domain + UUID, canonical disk identity, artifacts, and configuration digests. Change each + field individually on replay and require rejection without commands. A result + for another target or old epoch must not complete installation or cleanup. +3. **Actual installation and disk boot:** record that the target disk is newly + blank and uniquely owned. Observe partition/filesystem and bootloader creation. + Require a separate subsequent boot with installer kernel/initrd/media removed + from the domain definition. Capture root-device evidence and an exact + installation-specific receipt tied to retained inputs from that boot. Installer + output, a generic login prompt, or a preinstalled image alone cannot pass. + Negative cases: stop after installer boot, omit disk boot, supply old serial + output, or return a predecessor receipt; readiness must remain unverified. +4. **Restart/retry:** interrupt before command, after effect but before journal + update, after completion but before response, and during evidence collection. + Reopen the executor and retry the same operation. Assert one domain/disk set, + stable IDs, no repeated format/install, and bounded recovery. Race two executor + processes, not just goroutines. Ambiguous crash windows retain custody instead + of blindly recreating or reinstalling resources. +5. **Reinstall predecessor:** require a new Installation naming the durable current + predecessor. Race two successors; only one may produce effects. Preserve the + allocation and epoch, change installation evidence, reject late predecessor + callbacks, and ensure stale serial receipts cannot complete the successor. +6. **Unknown outcomes:** inject timeout, command disconnect, missing/corrupt journal, + unavailable lookup, absent completion, and mismatched receipt/digest. Do not + mark ready, advance predecessor, remove finalizers, or admit another consumer. + Cleanup must not race an unresolved installer or surviving worker. +7. **Exact cleanup and reuse:** verify shutdown and absence of the exact retained + domain UUID, installer access, and owned disk artifacts before returning clean. + Preserve decoy domains/files even when names share prefixes. Replace a domain + under the same name or replace a disk path; reject changed identity. Inject + partial cleanup and failure to inspect resources; retain custody. A subsequent + allocation requires a later fence epoch and blank storage; stale cleanup and + install retries must not touch that allocation. +8. **Path/XML/command injection:** exercise traversal, absolute paths, symlinks, + path replacement races, dot segments, quotes, XML markup, newlines, shell + metacharacters, and option-prefixed values in every external-input field. + Capture argv and parse generated XML; assert literal values, bounded paths, + and no unexpected device, host filesystem, network, or command access. Unknown + asset IDs must not create arbitrary domains. Reject requests before effects. +9. **Artifact integrity:** change kernel, installer, disk payload, checksum file, + or symlink after admission. Require verification against an independently + retained expected digest before use, with a defined defense against replacement + between verification and execution. Unsupported/unpinned artifacts, truncated + content, or a valid checksum for another build must fail closed. Pin/check the + relationship between the admitted image and the actual installer payload. + +Real hardware and firmware, production Milo/IAM/quota/network integration, and +hosted CI qualification remain separate acceptance tracks. The synthetic +[standalone smoke](standalone-smoke.md) cannot qualify OS installation. + +## Follow-up: adapter durability and regression coverage + +A subsequent independent adapter review identified a missing directory sync +between disk creation and the `prepared` journal transition, plus insufficient +adapter-specific tests. The parent implementation now syncs the created disk and +its operation directory before advancing the journal. Verified serial evidence +files and their directory are also synced before recording the corresponding +verified stage. Journal writes retain their existing root-directory sync. + +Private provider fields allow tests to substitute a temporary state root, command +execution, and directory-sync failure without changing the production constructor +or exposing new configuration. The new +[adapter lifecycle tests](../../internal/localvm/lifecycle_test.go) exercise exact +request substitution, reopened journal replay without duplicate commands, +authority advancement only after cleanup, live-domain cleanup rejection, decoy +preservation, stale cleanup replay after reuse, directory-sync failure propagation, +exclusive disk creation after uncertain preparation, and absent/stale/wrong-stage +receipt recovery without repeating the installer. These are filesystem and fake +command tests, not completed guest installation evidence or power-loss tests. + +## PXE HTTP evidence correction + +Independent review of the PXE implementation corroborated firmware network boot, +DHCP, real installation, and disk-only boot in the saved acceptance run. It also +reproduced a logging defect: a zero-byte failed HTTP write still recorded the +intended response length as admitted delivery. The parent corrected this by +retaining `admitted` as an attempt and adding `write-complete` only when the +response writer reports the entire body written without error. Both adapter and +harness verification now require completed entries. Regression tests cover failed +writes, short writes without errors, and successful writes. + +A completed server write does not prove client receipt. The separate installer +and disk-boot receipts remain mandatory. The earlier saved PXE acceptance run +uses the old attempt-only logs; it is not evidence that this corrected logging +path has passed a fresh VM run. Subsequent end-to-end acceptance must capture the +new entries. Neither logging scheme alone proves successful OS provisioning. diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md new file mode 100644 index 00000000..45d7e3b5 --- /dev/null +++ b/docs/operations/local-vm.md @@ -0,0 +1,309 @@ +# Local Fleet PXE installation with KVM or explicit TCG + +This opt-in development harness uses the existing [lifecycle library](../development/README.md) +and a real disposable Kubernetes API. It does not deploy Fleet or contact a +production cluster. The production manager remains unwired to this provider. + +Run `hack/local-vm/run.sh` from a workstation with Go, Docker, kind, kubectl and +Python 3. The default KVM mode requires Linux amd64 Docker and working `/dev/kvm`. First build the +`fleet-vm-local` runtime described in infra PR 9332; the runner image supplies +libvirt, QEMU and `fleet-start-libvirt`. The harness builds its own guest installer +and Go executable. It never invokes the infrastructure smoke script. + +For a local runtime without reliable x86 KVM, explicitly select software execution: + +```sh +DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh +``` + +`task local-vm:acceptance` runs the same TCG command. + +The named Docker context must already identify your dedicated disposable runtime. +TCG builds a native amd64 or arm64 Debian libvirt/QEMU runner and boots the same +amd64 installer and blank disk, with no simulator or preinstalled guest image. +The installer build requires amd64 container execution (for example Rosetta on +an arm64 Colima runtime). TCG acceptance qualifies the real installation/control-plane +path, **not KVM acceleration**. There is no automatic fallback: invalid modes fail, +the runner checks `/dev/kvm` in KVM mode, and the provider rejects changing the +accelerator for a retained journal. Legacy journals without a mode mean KVM. +Evidence records the explicit accelerator, runtime architecture, and transferred +executable checksum. The executable is checksum-verified before being renamed +into its runnable path, preventing a truncated transfer from being executed. + +The wrapper creates a fresh kind cluster and privileged libvirt container on the +disposable Docker kind network. It mounts no host directories or libvirt sockets. +Installer guests have one e1000 NIC on an isolated libvirt bridge inside the +container. Disk-verification guests have **no NIC**. Libvirt/dnsmasq is the sole +local DHCP/network authority; there is no forwarding, host LAN DHCP, external +bridge, or published HTTP port. NSO, Milo, IAM and quota boundaries remain synthetic. Privilege is restricted operationally to this disposable +Docker environment; this is not a sandbox for untrusted users or guest images. +Failures retain the named container, cluster, private kubeconfigs and executor +journal for recovery. Inspect the printed resource name before removing only +those resources with `docker rm -f NAME` and `kind delete cluster --name NAME`. +Do not share the raw failure directory: it contains local kubeconfig credentials +and private fencing tokens. Successful runs remove credentials and redact tokens. + +## Implemented contract + +The operator-owned capacity fixture references a distinct Device slot; this is +local virtual inventory, not physical discovery or a new Device API implementation. +The harness sets its actual configured CPU/memory bounds and uses the existing +Coordinator to reserve the slot exclusively for a consumer Machine. A second +consumer must receive InsufficientCapacity. IAM, image admission and quota are +explicit local test authorities; NSO, Milo and production network policy are not +claimed. Importing a record does not invoke the adapter. + +The adapter implements `executor.Client`. It accepts one fixed asset, one +artifact-manifest-derived image reference, install and cleanup operations. All +resource names derive from hashes of retained operation IDs. Callers cannot +supply XML, commands, paths, URLs, boot arguments, or cleanup targets. One flock +serializes processes. Every exact request, request digest, authority and random +boot receipt is fsynced before effects. The journal survives process restart. +Changed retries conflict; unfinished operations block later operations. Cleanup +closes the allocation epoch; stale authority cannot reopen it. + +A pinned Debian base supplies a Linux kernel, BusyBox and GRUB. Package resolution +currently uses Debian repositories at image-build time, so rebuilding is **not +bit-reproducible**. The build emits SHA256SUMS; the executor verifies both artifacts +and derives the admitted image digest from that exact manifest. Changing either +artifact invalidates the admitted image. Retain the built image ID and artifact +manifest when reproducing an acceptance run. + +The guest firmware obtains DHCP configuration and an HTTP iPXE script, then +fetches the kernel and initrd from the guarded broker. Installer domain XML has +only network boot: no libvirt kernel/initrd or disk-boot shortcut. The guest +installer starts with an empty 2 GiB disk, partitions and formats it, +copies its Linux filesystem, installs GRUB, and writes the operation's random +receipt onto disk. A separate libvirt domain boot uses only that disk: no external +kernel, initrd or installer medium. Its one-shot init script checks that `/` is +`/dev/vda1` ext4, emits the retained receipt on serial, and powers off. Fleet +requires the exact serial line and domain disappearance. Installer exit alone, +QEMU running, an old receipt, or missing evidence never yields installed success. +There is no ongoing guest agent. The minimal guest deliberately powers off after +verification; this does not qualify a production distribution or workload. + +Reinstall creates a new blank disk and a new receipt under the same allocation. +Prior incarnation disks remain private until cleanup; they are never booted or +exposed to another consumer. Cleanup deletes only retained disks for that exact +binding after verifying no matching domain exists, and verifies absence before +returning the full request-bound clean result. This is disposable-file deletion, +not a claim of physical media sanitization. + +The harness crashes the process after verified provider completion, before the +controller receives its result, then starts a new process to recover the same +Installation. It repeats install and reinstall to verify retries, then releases +and allocates the slot to the waiting consumer. Pending effects without sufficient +evidence remain unknown and require inspection; the adapter does not blindly +restart an installer after an ambiguous libvirt start. + +## Local PXE admission and trust boundary + +The executable now selects `pxe` durably in the journal. Journals from the earlier +direct-kernel prototype cannot silently replay under PXE; there is no automatic +migration or runtime direct-boot option. The accelerator remains separately bound. +Tests retain private direct-mode fixtures for the existing lifecycle regressions. + +A random 256-bit bearer capability is retained with the exact admitted operation, +request digest, asset, allocation, epoch, fence and ten-minute expiry before effects. +The HTTP broker reads the atomic journal on every request and permits only the +current `installer-started` operation with an open, unexpired admission. It serves +only its derived iPXE script and the two manifest-bound artifacts. Artifact bytes +and the manifest are rechecked before delivery. Unknown identity, wrong capability, +stale allocation/fence, closed/revoked/expired admission, unsupported paths and +unguarded artifacts are denied. No general file server is exposed. + +The DHCP boot URL contains a short operation locator and scoped capability; the +locator is deliberately short enough for the legacy BOOTP filename field. MAC/IP +are routing information, not authentication. Delivery over HTTP and DHCP trusts the +single-guest isolated lab and container operator. A tenant or hostile peer on this +network could steal the capability: this is **not production attestation**, TLS +bootstrap, or qualified multi-tenant PXE. The listener is reachable in the disposable +container network but no host port is published. The capability cannot select an +image, asset, operation, URL or arbitrary file beyond its retained admission. + +Expiry/revocation prevents new HTTP retrieval, not execution of a downloaded +installer. The provider first observes domain disappearance and the exact installer +receipt, then closes admission durably. It removes the isolated network before the +separate NIC-free disk boot. Missing observations remain Unknown with capacity held; +no timeout triggers a second installer start. Cleanup still requires every retained +domain absent before deleting disks. Network teardown is local test plumbing, not +NSO/IPAM or production fencing evidence. + +Raw runtime state and failed-run directories are private: the journal and network +XML contain capabilities, and kubeconfigs contain Kubernetes credentials. Successful +exports remove these credentials, scan for retained boot capabilities, and retain +only artifact names, byte counts, DHCP leases and exact non-secret receipts. + +## Evidence and limitations + +Successful output includes DHCP leases, guarded HTTP delivery receipts, live +closed-admission HTTP denial probes, sanitized provider journal, both serial logs and +rendered domain definitions per installation, public Installation status, phase +log, image ID and the final domain inventory. The journal binds receipts to exact +requests including allocation, epoch, fence and image. Readiness assurance is +local trusted-executor evidence, not hardware attestation. The local operator and +container root remain trusted. No remote API or production authorization is added. + +See the separately maintained [adversarial validation report](local-vm-adversarial-validation.md). +Actual execution results must be reported separately; a successful Go build or +synthetic simulator test is not evidence of an OS installation. + +## Execution record (2026-11-14) + +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, +`hack/validate-doc-links.sh`, and `git diff --check` passed. The Linux executable +and installer image built. Two disposable runs reached real Kubernetes-backed +exclusive allocation and contention rejection. The first real KVM guest booted, +partitioned and formatted its blank disk, then failed during filesystem copying +because BusyBox selected its built-in tar. The installer now calls GNU tar by +absolute path, checks pipeline failures, enables ACPI, and disables automatic +libvirt restart on guest reboot/crash. + +The corrected second run was interrupted by the dedicated Colima VM rebooting +and Docker being gracefully stopped. Subsequent serial-console inspection found +that this reboot followed a nested-KVM host kernel panic, not merely an external +Docker stop. Its journal retained `installer-started` +with an `Unknown` result. The runtime contained only the four containers from +these two runs. One authorized Docker restart restored the internal daemon; +the workstation socket remained unavailable. Restarting the provider daemon +showed no libvirt domains. An attempt to recover the existing installation +exited 139. Subsequent inspection traced exit 139 to an executable truncated at +4,194,304 bytes, compared with the original 37,455,636-byte binary. Restoring that +exact original binary to a separate recovery path, verifying its SHA256, and +retrying the same Installation correctly returned Unknown. No operation was reset +and no disk was reformatted during recovery. +Both runs' resources and private state were retained for inspection. + +**The interrupted KVM attempts did not complete real OS disk boot, post-effect +crash recovery, reinstall, or cleanup/reuse.** The subsequent successful explicit +TCG acceptance is recorded below; it does not qualify this KVM environment. +The original local evidence directory is +`/tmp/fleet-local-evidence.ixHu29`; `summary.json`, `runtime-status.txt`, +`journal-sanitized.json`, `device.json`, and `SHA256SUMS` are safe diagnostic +artifacts. Its kubeconfig files and the raw container journals are private and +must not be published. The retained resource names are +`fleet-local-9c2ad625d67a` and `fleet-local-adcaca5a98e8`, each with a corresponding +`-control-plane` kind container. Inspect those exact resources before cleanup. + +### Follow-up runtime diagnosis + +The dedicated `fleet-e2e-x86` runtime is itself an x86 VM emulated by QEMU TCG on +an Apple Silicon host. A fresh diagnostic run, `fleet-local-9d76bd454637`, reproduced +the host Linux panic at 20:50 CST on November 14, 2026: +`Kernel panic - not syncing: corrupted stack end detected inside scheduler`, +with `Comm: CPU 0/KVM`. The earlier 20:35 CST reboot has the same signature. +The fresh operation also remains `installer-started`/Unknown; its container, +disk, kind cluster and private credentials are retained. No further KVM guest +boots should be attempted in this runtime until the nested virtualization issue +is resolved. The daemon was started only to collect retained diagnostics, without +restarting any provider container or replaying an installer. + +Sanitized panic excerpts and sanitized journals are under +`/tmp/fleet-acceptance-recovery` (`nested-kvm-panic.txt`, +`prior-nested-kvm-panic.txt`, `journal-sanitized.json`, +`first-journal-sanitized.json`, and `diagnostic-journal-sanitized.json`). This +directory also contains private recovery files: share only the named sanitized +files, not the directory. A separate task-owned native arm64 Colima VZ runtime, +`fleet-acceptance-tcg`, was created with no host mounts and without switching the +active Docker context, for explicit TCG acceptance using the updated provider. + +### Successful explicit TCG acceptance (2026-11-14) + +The following command exited zero on November 14, 2026 at approximately 21:03 CST +(November 15, 03:03 UTC), using the parent-updated provider with durable directory +sync, accelerator binding, and lifecycle regression tests: + +```sh +DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh +``` + +The runtime has no `/dev/kvm`. Its native arm64 QEMU executed the real amd64 Linux +guest from the built installer, not a simulator or a preinstalled cloud disk. +The run verified Kubernetes-backed exclusive allocation and contention rejection; +partitioning, ext4 formatting, payload copying and GRUB installation onto a blank +2 GiB disk; a separate disk-only boot with the exact installation receipt; exit 75 +after the provider's durable success and recovery by a new process; exact retries; +a second real installation with a distinct receipt and blank disk; and verified +cleanup followed by exclusive allocation to the waiting consumer. + +The fresh resource `fleet-local-00cf3dc540bb` and its kind cluster were removed +after successful cleanup/reuse. Its credentials were removed from the evidence +directory. The new task-owned Colima runtime remains available, with no containers; +none of the three unknown KVM operations was reset, cleaned, or declared ready. + +Sanitized acceptance evidence is in `/tmp/fleet-local-evidence.gz8QaY`: + +- `summary.json`, `phases.log`, `accelerator`, and `runtime-architecture` record + the result and execution mode. +- `provider/journal.json` contains two succeeded installation operations and one + succeeded cleanup operation, with fences redacted and the allocation closed. +- The operation directories contain both installer and disk serial logs and XML; + the two disk-only boot receipts match their retained operations and differ from + each other. Neither disk domain XML contains a kernel, initrd, or network NIC. +- `provider/installations.json` records both public Installation statuses as Ready. +- `domains-after.txt` is empty, and no `disk.raw` remains in the copied provider state. +- `SHA256SUMS`, `binary-SHA256SUMS`, `source-SHA256SUMS`, and `image-id` identify + the exact tested artifacts. The runner image ID is + `sha256:5047968ca9404706a83199f3808eaf23f94ca7d2fb165dda1f1cd3dfa97ea24b`. + +An independent readback checked these journal, receipt, XML, retry, cleanup and +credential-removal assertions after the harness passed. +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, ShellCheck on +`run.sh` and `start-libvirt`, documentation links, and `git diff --check` also passed. +The installer has an informational ShellCheck SC2013 diagnostic for intentionally +splitting `/proc/cmdline` into words. Docker reports an intentional fixed-platform +build warning because the installer must remain amd64 on an arm64 runner. + +**This is real OS-install/control-plane acceptance under explicit TCG, not KVM +qualification, production hardware attestation, or a production distribution +qualification.** KVM remains the default and must be qualified separately on a +reliable x86 virtualization host. + +### Successful firmware PXE acceptance (2026-11-14 CST / 2026-11-15 UTC) + +The same explicit TCG command above exited zero with the PXE implementation. +Sanitized evidence is `/tmp/fleet-local-evidence.A5KTID`; its `summary.json` was +produced by a separate readback of the exported artifacts. The runner image ID is +`sha256:2b2c1109b2e11068c03ef25239adec425108898a4299e06a50bce2414ed6e6c3`. +The native arm64 runtime executed amd64 SeaBIOS/e1000 iPXE firmware and Linux with +TCG. This is legacy BIOS PXE, not UEFI or KVM qualification. + +Both fresh blank-disk installations have DHCP leases and guarded requests for +`boot.ipxe`, the 8,234,944-byte kernel and 215,654,737-byte initrd. Readback verified +network-only installer XML with no direct kernel/initrd, real partition/format/ +payload-copy/GRUB logs, distinct exact receipts from separate NIC-free disk boots, +closed admissions, two succeeded installs, succeeded cleanup, no remaining disks +or domains, and allocation to the waiting consumer. The harness also exercised +exclusive contention, exit 75 after durable provider completion, new-process +recovery, repeated exact requests, and reinstall. Twelve live HTTP denials after +reinstall/cleanup cover closed predecessor scripts/artifacts, unknown identity, +unguarded paths and unsupported artifacts; the earlier post-install denial probe +also passed. Expired/revoked admission and cross-operation capabilities were tested +through HTTP against durable synthetic journals in `boot_test.go`, not by expiring +a real destructive guest mid-install. + +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax, ShellCheck on +`run.sh` and `start-libvirt`, documentation links, and whitespace validation passed. +The successful harness checks exported credentials, XML boot paths, DHCP evidence, +artifact receipts and disk deletion. Its resource `fleet-local-7ad959c9bb50` and +corresponding kind cluster were removed. No production changes or KVM starts were +made. Base image and artifact checksums are retained; apt package resolution still +is not reproducible. + +Two diagnostic attempts remain in the task-owned TCG runtime, each with its +corresponding `-control-plane` kind container and private credentials/state: + +- `fleet-local-d4e060978d40`: the first DHCP URL exceeded the legacy BOOTP filename + capacity. DHCP succeeded but no HTTP request followed. The guest was explicitly + destroyed and absence observed; the operation remains `installer-started`/Unknown. + Private failure directory: `/tmp/fleet-local-evidence.Hs5F4y`. +- `fleet-local-482c67269d19`: after shortening the locator, real PXE install, + disk-only boot, post-effect recovery and exact retries passed. The harness then + stopped because a newly added probe was unsupported by its already-built binary. + Its single installation is Succeeded, no guest domain remains, and its allocated + disk is retained. Private failure directory: `/tmp/fleet-local-evidence.3W7DIL`. + +Only sanitized diagnostic journals and empty domain inventories are exported in +`/tmp/fleet-pxe-diagnostics`. The earlier three unknown KVM resource sets remain +untouched. Neither those nor the failed PXE operation was inferred clean or ready. +The final complete acceptance used a freshly built executable and a fresh resource. diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile new file mode 100644 index 00000000..f86ddeda --- /dev/null +++ b/hack/local-vm/Containerfile @@ -0,0 +1,18 @@ +FROM --platform=linux/amd64 debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS guest +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends linux-image-amd64 initramfs-tools busybox-static grub-pc-bin grub2-common fdisk e2fsprogs cpio && rm -rf /var/lib/apt/lists/* +COPY init /init +COPY boot /fleet-boot +RUN chmod 755 /init /fleet-boot && mkdir -p /out && cp /boot/vmlinuz-* /out/kernel && find . \( -path ./out -o -path ./proc -o -path ./sys -o -path ./dev \) -prune -o -print | cpio -o -H newc | gzip -1 > /out/installer.gz && cd /out && sha256sum kernel installer.gz > SHA256SUMS +FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS tcg +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils libvirt-daemon-system libvirt-clients tini dnsmasq-base ipxe-qemu iptables && rm -rf /var/lib/apt/lists/* && printf '%s\n' 'user = "root"' 'group = "root"' 'security_driver = "none"' 'dynamic_ownership = 0' 'cgroup_controllers = []' >> /etc/libvirt/qemu.conf && rm -f /etc/libvirt/qemu/networks/autostart/default.xml +COPY start-libvirt /usr/local/bin/fleet-start-libvirt +RUN chmod 755 /usr/local/bin/fleet-start-libvirt +COPY --from=guest /out /opt/fleet-local/artifacts +ENV FLEET_LOCAL_VM=disposable-container LIBVIRT_DEFAULT_URI=qemu:///system + +FROM fleet-vm-local AS kvm +USER root +COPY start-libvirt /usr/local/bin/fleet-start-libvirt +RUN chmod 755 /usr/local/bin/fleet-start-libvirt +COPY --from=guest /out /opt/fleet-local/artifacts +ENV FLEET_LOCAL_VM=disposable-container diff --git a/hack/local-vm/boot b/hack/local-vm/boot new file mode 100644 index 00000000..b40c21ec --- /dev/null +++ b/hack/local-vm/boot @@ -0,0 +1,10 @@ +#!/bin/busybox sh +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +mount -t proc proc /proc 2>/dev/null || true +exec >/dev/ttyS0 2>&1 +# Only the disk-root boot emits completion; installer completion is insufficient. +if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then + printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" +fi +sync +/bin/busybox poweroff -f diff --git a/hack/local-vm/init b/hack/local-vm/init new file mode 100644 index 00000000..fce1814a --- /dev/null +++ b/hack/local-vm/init @@ -0,0 +1,37 @@ +#!/bin/busybox sh +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +mkdir -p /dev /proc /sys +mount -t devtmpfs devtmpfs /dev +mount -t proc proc /proc +mount -t sysfs sys /sys +exec >/dev/ttyS0 2>&1 +set -exo pipefail +modprobe virtio_pci +modprobe virtio_blk +modprobe ext4 +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; esac; done +[ ${#receipt} = 64 ] || /bin/busybox poweroff -f +printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda +mkfs.ext4 -F /dev/vda1 +mkdir -p /target +mount /dev/vda1 /target +# The payload is this pinned installer filesystem; exclude virtual mounts. +/bin/tar -cf - --exclude=./target --exclude=./proc --exclude=./sys --exclude=./dev --exclude=./out . | /bin/tar -xf - -C /target +mkdir -p /target/dev /target/proc /target/sys +mount --bind /dev /target/dev +mount --bind /proc /target/proc +mount --bind /sys /target/sys +printf '%s\n' "$receipt" > /target/fleet-receipt +chroot /target grub-install --target=i386-pc /dev/vda +kernel=$(basename /boot/vmlinuz-*) +initrd=$(basename /boot/initrd.img-*) +cat > /target/boot/grub/grub.cfg <&2; exit 1; } +export KIND_EXPERIMENTAL_PROVIDER=docker +accelerator=${FLEET_LOCAL_VM_ACCEL:-kvm} +case "$accelerator" in + kvm|tcg) ;; + *) echo 'FLEET_LOCAL_VM_ACCEL must be kvm or tcg' >&2; exit 1;; +esac +case $(docker context inspect --format '{{.Endpoints.docker.Host}}') in + unix://*) ;; + *) echo 'Local Unix Docker endpoint required; remote runtimes are not authorized' >&2; exit 1;; +esac +case $(docker info --format '{{.Architecture}}') in + x86_64|amd64) runtime_arch=amd64 ;; + aarch64|arm64) runtime_arch=arm64 ;; + *) echo 'Unsupported Docker runtime architecture' >&2; exit 1;; +esac +[[ $accelerator == tcg || $runtime_arch == amd64 ]] || { echo 'KVM requires an amd64 runtime for this guest' >&2; exit 1; } +run_id="fleet-local-$(python3 -c 'import uuid; print(uuid.uuid4().hex[:12])')" +evidence=$(mktemp -d /tmp/fleet-local-evidence.XXXXXX) +export KUBECONFIG="$evidence/kubeconfig" +printf '%s\n' "$run_id" > "$evidence/resource-name" +printf '%s\n' "$accelerator" > "$evidence/accelerator" +printf '%s\n' "$runtime_arch" > "$evidence/runtime-architecture" +printf 'Evidence: %s\n' "$evidence" +trap 'echo "Resources retained for inspection: $run_id; evidence: $evidence"' EXIT +python3 - "$evidence/source-SHA256SUMS" <<'PYHASH' +import hashlib,pathlib,sys +paths=[*pathlib.Path('internal/localvm').glob('*.go'),*pathlib.Path('cmd/fleet-local-vm').glob('*.go'),*pathlib.Path('hack/local-vm').glob('*')] +with open(sys.argv[1],'w') as out: + for p in sorted(paths): + if p.is_file(): out.write(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n') +PYHASH +CGO_ENABLED=0 GOOS=linux GOARCH="$runtime_arch" go build -o "$evidence/fleet-local-vm" ./cmd/fleet-local-vm +docker build --target "$accelerator" -t fleet-local-install -f hack/local-vm/Containerfile hack/local-vm +kind create cluster --name "$run_id" --kubeconfig "$KUBECONFIG" --image kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f --wait 120s +kubectl apply -f config/base/crd/metal.datumapis.com.yaml +kubectl wait --for=condition=Established crd --all --timeout=60s +for ns in fleet-system-private fleet-provider fleet-project-a fleet-project-b; do kubectl create namespace "$ns"; done +docker run -d --name "$run_id" --network kind --privileged --user root -e "FLEET_LOCAL_VM_ACCEL=$accelerator" --entrypoint /usr/local/bin/fleet-start-libvirt fleet-local-install +# No host filesystem mounts, host network, or host libvirt socket. +docker exec "$run_id" mkdir -p /run/fleet +binary_digest=$(python3 - "$evidence/fleet-local-vm" <<'PY' +import hashlib,sys +print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest()) +PY +) +printf '%s fleet-local-vm\n' "$binary_digest" > "$evidence/binary-SHA256SUMS" +docker cp "$evidence/fleet-local-vm" "$run_id:/usr/local/bin/fleet-local-vm.pending" +printf '%s /usr/local/bin/fleet-local-vm.pending\n' "$binary_digest" | docker exec -i "$run_id" sha256sum -c - +docker exec "$run_id" mv /usr/local/bin/fleet-local-vm.pending /usr/local/bin/fleet-local-vm +kind get kubeconfig --name "$run_id" --internal > "$evidence/internal-kubeconfig" +docker cp "$evidence/internal-kubeconfig" "$run_id:/run/fleet/kubeconfig" +docker exec -d "$run_id" fleet-local-vm boot-service +image=$(docker exec "$run_id" fleet-local-vm image) +docker cp "$run_id:/opt/fleet-local/artifacts/SHA256SUMS" "$evidence/SHA256SUMS" +python3 - "$image" > "$evidence/fixtures.yaml" <<'PY' +import sys +s=open('config/standalone/fixtures.yaml').read() +s=s.replace('cores: 24','cores: 2').replace('capacity: 128Gi','capacity: 2Gi') +s=s.replace('debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb',sys.argv[1]) +print(s) +PY +kubectl apply -f "$evidence/fixtures.yaml" +docker exec "$run_id" fleet-local-vm allocate | tee -a "$evidence/phases.log" +set +e +docker exec "$run_id" fleet-local-vm install-crash >> "$evidence/phases.log" 2>&1 +crash_status=$? +set -e +[[ $crash_status == 75 ]] || { echo "Expected post-effect crash 75; got $crash_status"; exit 1; } +printf "post-effect process crash verified (75)\n" >> "$evidence/phases.log" +for phase in install install boot-denials reinstall reinstall boot-denials release boot-denials evidence; do + docker exec "$run_id" fleet-local-vm "$phase" | tee -a "$evidence/phases.log" +done +docker cp "$run_id:/var/lib/fleet-local" "$evidence/provider" +docker exec "$run_id" virsh list --all --name > "$evidence/domains-after.txt" +docker image inspect fleet-local-install --format '{{.Id}}' > "$evidence/image-id" +# Retain receipts but omit fence tokens and all kubeconfigs from shareable evidence. +python3 - "$evidence/provider/journal.json" <<'PY' +import json,sys,pathlib +p=sys.argv[1];j=json.load(open(p));j.pop('fence',None) +tokens=[r.get('bootToken','') for r in j['operations'].values() if r.get('bootToken')] +for r in j['operations'].values(): + r['request'].pop('fenceToken',None) + r.pop('bootToken',None) +json.dump(j,open(p,'w'),indent=2) +root=pathlib.Path(p).parent +(root/'network-private.xml').unlink(missing_ok=True) +for file in root.rglob('*'): + if file.is_file() and any(token.encode() in file.read_bytes() for token in tokens): + raise SystemExit('credential found in exported evidence') +assert j['bootMode']=='pxe' +for r in j['operations'].values(): + if r['request']['kind']!='install': continue + import hashlib + d=root/hashlib.sha256(r['request']['id'].encode()).hexdigest() + installer=(d/'installer.xml').read_text(); disk=(d/'disk.xml').read_text() + assert '' not in installer and '' not in installer and "boot dev='network'" in installer + assert '' not in disk and '' not in disk + assert r['bootClosed'] + for name in ['boot.ipxe','kernel','installer.gz']: assert 'write-complete '+name+' bytes=' in (d/'boot-delivery.log').read_text() + assert '52:54:00:77:00:02' in (d/'dhcp-leases.txt').read_text() + assert 'FLEET-DISK-BOOT:'+r['receipt'] in (d/'disk.log').read_text() + assert not (d/'disk.raw').exists() +PY +rm -f "$evidence/provider/network-private.xml" +docker rm -f "$run_id" +kind delete cluster --name "$run_id" +rm -f "$evidence/kubeconfig" "$evidence/internal-kubeconfig" "$evidence/fleet-local-vm" +trap - EXIT +printf 'PASS: real local installation, retry, reinstall, cleanup and reuse; evidence %s\n' "$evidence" diff --git a/hack/local-vm/start-libvirt b/hack/local-vm/start-libvirt new file mode 100644 index 00000000..3875c759 --- /dev/null +++ b/hack/local-vm/start-libvirt @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +case "${FLEET_LOCAL_VM_ACCEL:-kvm}" in + kvm) + [ -c /dev/kvm ] && [ -r /dev/kvm ] && [ -w /dev/kvm ] || { + echo 'KVM device unavailable; no automatic software fallback' >&2 + exit 1 + } + ;; + tcg) ;; + *) echo 'Unsupported local VM accelerator' >&2; exit 1 ;; +esac +mkdir -p /run/libvirt /var/lib/libvirt/images /var/log/libvirt +virtlogd --daemon +virtlockd --daemon +exec /usr/bin/tini -- libvirtd diff --git a/internal/localvm/boot.go b/internal/localvm/boot.go new file mode 100644 index 00000000..4f6ab8af --- /dev/null +++ b/internal/localvm/boot.go @@ -0,0 +1,258 @@ +package localvm + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "io" + "net/http" + "os" + "strconv" + "strings" + "time" +) + +// defaultBootOrigin is the provisioning-bridge address used when the boot +// service shares the hypervisor network namespace (single-container mode). +const defaultBootOrigin = "http://192.168.77.1:8080" + +func (p *Provider) origin() string { + if p.bootOrigin == "" { + return defaultBootOrigin + } + return p.bootOrigin +} + +// prepareNetwork is the sole local network writer. DHCP stays on a bridge in the +// runtime namespace. NAT forwarding lets firmware reach a boot Service outside +// that namespace; the runtime restricts forwarded traffic to that origin. +func (p *Provider) prepareNetwork(ctx context.Context, r *record) error { + names, err := p.virsh(ctx, "net-list", "--name") + if err != nil { + return err + } + for _, n := range strings.Fields(names) { + if n == "fleet-pxe" { + if _, err = p.virsh(ctx, "net-destroy", n); err != nil { + return err + } + } + } + xml := fmt.Sprintf(`fleet-pxe%s`, p.forward(), p.origin(), key(r.Request.ID)[:16], r.BootToken) + path := p.stateRoot() + "/network-private.xml" + if err = os.WriteFile(path, []byte(xml), 0600); err != nil { + return err + } + _, err = p.virsh(ctx, "net-create", path) + return err +} + +// forward is empty when the boot service is on the bridge itself. +func (p *Provider) forward() string { + if p.origin() == defaultBootOrigin { + return "" + } + return "" +} + +// BootHandler never uses a file server or caller-selected filesystem path. +// Atomic journal replacement allows reads while the executor holds its flock. +func (p *Provider) BootHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(q.URL.Path, "/") + if q.Method != "GET" || q.URL.RawQuery != "" || len(parts) != 4 { + deny() + return + } + j, err := p.read() + if err != nil || p.checkMode(j) != nil || j.BootMode != "pxe" || j.Image != p.image || j.Closed { + deny() + return + } + var r *record + for _, candidate := range j.Operations { + if key(candidate.Request.ID)[:16] == parts[1] { + r = candidate + break + } + } + if r == nil || r.Request.Kind != "install" || r.Stage != "installer-started" || r.BootClosed || !time.Now().Before(r.BootExpires) || len(r.BootToken) != 64 || subtle.ConstantTimeCompare([]byte(parts[2]), []byte(r.BootToken)) != 1 || r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence || p.validate(r.Request) != nil { + deny() + return + } + name := parts[3] + var data []byte + var artifact *os.File + var size int64 + switch name { + case "boot.ipxe": + base := p.origin() + "/" + parts[1] + "/" + r.BootToken + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, base)) + size = int64(len(data)) + case "kernel", "installer.gz": + // Stream: hash the pinned artifact, then serve the same open file. + artifact, err = os.Open(artifacts + "/" + name) + if err != nil { + deny() + return + } + defer artifact.Close() + manifest, e := os.ReadFile(artifacts + "/SHA256SUMS") + sum := sha256.Sum256(manifest) + h := sha256.New() + size, err = io.Copy(h, artifact) + if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + default: + deny() + return + } + // No URLs, headers, credentials or bootstrap script in evidence. + if err := os.MkdirAll(p.bootDirectory(r), 0700); err != nil { + deny() + return + } + f, err := os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + deny() + return + } + _, err = fmt.Fprintf(f, "%s admitted %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, size) + if err == nil { + err = f.Sync() + } + f.Close() + if err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var n int64 + var writeErr error + if artifact != nil { + n, writeErr = io.Copy(w, artifact) + } else { + var written int + written, writeErr = w.Write(data) + n = int64(written) + } + if writeErr != nil || n != size { + return + } + // A completed server write is not proof of client receipt or guest boot. + f, err = os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return + } + _, err = fmt.Fprintf(f, "%s write-complete %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, n) + if err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil && closeErr == nil { + _ = p.syncDir(p.bootDirectory(r)) + } + }) +} + +func (p *Provider) ServeBoot() error { + // The write bound matches the boot admission window: through the site's + // NAT path an emulated firmware takes several minutes for the installer. + s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} + return s.ListenAndServe() +} + +func (p *Provider) verifyNetworkBoot(ctx context.Context, r *record) error { + b, err := os.ReadFile(p.bootDirectory(r) + "/boot-delivery.log") + if err != nil { + return err + } + completed := map[string]bool{} + for _, line := range strings.Split(string(b), "\n") { + fields := strings.Fields(line) + if len(fields) != 4 || fields[1] != "write-complete" || !strings.HasPrefix(fields[3], "bytes=") { + continue + } + n, err := strconv.Atoi(strings.TrimPrefix(fields[3], "bytes=")) + if err == nil && n > 0 { + completed[fields[2]] = true + } + } + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !completed[name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + leases, err := p.virsh(ctx, "net-dhcp-leases", "fleet-pxe") + if err != nil { + return err + } + if !strings.Contains(leases, "52:54:00:77:00:02") || !strings.Contains(leases, "192.168.77.2") { + return fmt.Errorf("missing firmware DHCP lease") + } + return os.WriteFile(p.directory(r)+"/dhcp-leases.txt", []byte(leases), 0600) +} + +func (p *Provider) stopNetwork(ctx context.Context) error { + names, err := p.virsh(ctx, "net-list", "--name") + if err != nil { + return err + } + for _, n := range strings.Fields(names) { + if n == "fleet-pxe" { + _, err = p.virsh(ctx, "net-destroy", n) + return err + } + } + return nil +} + +// CheckClosedBoot probes a live boot listener without printing capability URLs. +// origin is the listener under test, e.g. the boot Service seen by the runtime. +func (p *Provider) CheckClosedBoot(origin string) (string, error) { + origin, err := parseBootOrigin(origin) + if err != nil { + return "", err + } + j, err := p.read() + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + for _, r := range j.Operations { + if r.Request.Kind != "install" { + continue + } + if !r.BootClosed { + return "", fmt.Errorf("boot admission not closed") + } + base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { + resp, e := client.Get(url) + if e != nil { + return "", fmt.Errorf("boot denial probe unavailable") + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + return "", fmt.Errorf("closed/unknown boot access allowed") + } + count++ + } + } + if count == 0 { + return "", fmt.Errorf("no retained admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed predecessor scripts/artifacts, unsupported artifact, unguarded artifact, unknown identity", count), nil +} diff --git a/internal/localvm/boot_test.go b/internal/localvm/boot_test.go new file mode 100644 index 00000000..7376d142 --- /dev/null +++ b/internal/localvm/boot_test.go @@ -0,0 +1,123 @@ +package localvm + +import ( + "go.datum.net/fleet/internal/simulator" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +func TestBootAdmission(t *testing.T) { + f := newVMFixture(t) + p := f.p + p.bootMode = "pxe" + q := vmRequest("admitted-installation") + digest, _ := simulator.RequestDigest(q) + base := record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} + os.Mkdir(p.directory(&base), 0700) + for _, tc := range []struct { + name string + change func(*record, *journal) + path string + allowed bool + }{ + {name: "admitted", allowed: true}, + {name: "unknown identity", path: "/unknown/" + base.BootToken + "/boot.ipxe"}, + {name: "wrong operation credential", path: "/" + key(q.ID)[:16] + "/" + strings.Repeat("c", 64) + "/boot.ipxe"}, + {name: "expired", change: func(r *record, j *journal) { r.BootExpires = time.Now().Add(-time.Second) }}, + {name: "revoked", change: func(r *record, j *journal) { r.BootClosed = true }}, + {name: "not started", change: func(r *record, j *journal) { r.Stage = "admitted" }}, + {name: "stale epoch", change: func(r *record, j *journal) { j.Epoch++ }}, + {name: "wrong fence", change: func(r *record, j *journal) { j.Fence = "other" }}, + {name: "closed predecessor", change: func(r *record, j *journal) { r.Stage = "installer-verified"; r.BootClosed = true }}, + {name: "closed allocation", change: func(r *record, j *journal) { j.Closed = true }}, + {name: "unsupported artifact", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/disk.raw"}, + {name: "unguarded artifact", path: "/kernel"}, + {name: "traversal", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/../journal.json"}, + } { + t.Run(tc.name, func(t *testing.T) { + r := base + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: &r}} + if tc.change != nil { + tc.change(&r, &j) + } + if err := p.save(j); err != nil { + t.Fatal(err) + } + path := tc.path + if path == "" { + path = "/" + key(q.ID)[:16] + "/" + base.BootToken + "/boot.ipxe" + } + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + want := 403 + if tc.allowed { + want = 200 + } + if w.Code != want { + t.Fatalf("status %d want %d", w.Code, want) + } + }) + } +} +func TestFirmwarePXEAndModeBinding(t *testing.T) { + p := &Provider{bootMode: "pxe"} + r := &record{} + x := p.domainXML(r, "installer") + if strings.Contains(x, "") || strings.Contains(x, "") || strings.Contains(x, "boot dev='hd'") || !strings.Contains(x, "boot dev='network'") || !strings.Contains(x, "") { + t.Fatal(x) + } +} + +func TestCrossOperationCapabilityOverHTTP(t *testing.T) { + f := newVMFixture(t) + p := f.p + p.bootMode = "pxe" + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: 1, Binding: "allocation", Fence: "fence", Operations: map[string]*record{}} + for i, id := range []string{"predecessor", "successor"} { + q := vmRequest(id) + d, _ := simulator.RequestDigest(q) + r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: d, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat(string(rune('b'+i)), 64), BootExpires: time.Now().Add(time.Minute)} + j.Operations[id] = r + if err := os.Mkdir(p.directory(r), 0700); err != nil { + t.Fatal(err) + } + } + server := httptest.NewServer(p.BootHandler()) + defer server.Close() + check := func(op, token string, want int) { + t.Helper() + resp, err := server.Client().Get(server.URL + "/" + key(op)[:16] + "/" + token + "/boot.ipxe") + if err != nil { + t.Fatal("HTTP request failed") + } + resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("status %d want %d", resp.StatusCode, want) + } + } + save := func() { + t.Helper() + if err := p.save(j); err != nil { + t.Fatal(err) + } + } + save() + check("successor", j.Operations["predecessor"].BootToken, 403) + check("successor", j.Operations["successor"].BootToken, 200) + j.Operations["successor"].BootExpires = time.Now().Add(-time.Second) + save() + check("successor", j.Operations["successor"].BootToken, 403) + j.Operations["predecessor"].BootClosed = true + save() + check("predecessor", j.Operations["predecessor"].BootToken, 403) +} diff --git a/internal/localvm/lifecycle_test.go b/internal/localvm/lifecycle_test.go new file mode 100644 index 00000000..5f1b5767 --- /dev/null +++ b/internal/localvm/lifecycle_test.go @@ -0,0 +1,294 @@ +package localvm + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type vmFixture struct { + p *Provider + creates []string + failStart bool + present string +} + +func newVMFixture(t *testing.T) *vmFixture { + t.Helper() + f := &vmFixture{p: &Provider{root: t.TempDir(), image: "local@sha256:approved"}} + f.p.command = func(_ context.Context, name string, args ...string) (string, error) { + if name != "virsh" || len(args) < 3 || args[0] != "--connect" || args[1] != "qemu:///system" { + t.Fatalf("unexpected command %s %v", name, args) + } + switch args[2] { + case "list": + return f.present, nil + case "create": + f.creates = append(f.creates, args[3]) + if f.failStart { + return "", errors.New("lost start response") + } + j, err := f.p.read() + if err != nil { + return "", err + } + for _, r := range j.Operations { + stage := strings.TrimSuffix(filepath.Base(args[3]), ".xml") + if args[3] != filepath.Join(f.p.directory(r), stage+".xml") { + continue + } + if r.Stage != stage+"-started" { + t.Fatalf("command preceded durable uncertainty: %s", r.Stage) + } + marker := "FLEET-INSTALLED:" + if stage == "disk" { + marker = "FLEET-DISK-BOOT:" + } + return "", os.WriteFile(filepath.Join(f.p.directory(r), stage+".log"), []byte(marker+r.Receipt+"\n"), 0600) + } + return "", errors.New("command not bound to journal") + default: + t.Fatalf("unexpected virsh operation %v", args) + } + return "", nil + } + return f +} +func vmRequest(id string) simulator.Request { + return simulator.Request{ID: id, Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"local@sha256:approved"}`)} +} +func TestLocalReplayAndAuthorityTransitions(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("install") + result, err := f.p.Execute(ctx, q) + if err != nil { + t.Fatal(err) + } + if result.Result != "installed" || len(f.creates) != 2 { + t.Fatalf("unexpected install: %+v %v", result, f.creates) + } + // Reopen state through a fresh provider without changing the command fixture. + f.p = &Provider{root: f.p.root, image: f.p.image, command: f.p.command} + replay, err := f.p.Execute(ctx, q) + if err != nil || replay.InputDigest != result.InputDigest || len(f.creates) != 2 { + t.Fatalf("replay caused effects: %v", err) + } + for _, change := range []func(*simulator.Request){ + func(r *simulator.Request) { r.AssetID = "another" }, func(r *simulator.Request) { r.BindingID = "another" }, + func(r *simulator.Request) { r.Epoch++ }, func(r *simulator.Request) { r.FenceToken = "another" }, + func(r *simulator.Request) { r.Inputs = json.RawMessage(`{"image":"another"}`) }, + } { + altered := q + change(&altered) + if _, err = f.p.Execute(ctx, altered); err == nil { + t.Fatal("accepted substituted retained request") + } + } + next := vmRequest("next") + next.Epoch = 2 + next.BindingID = "next" + next.FenceToken = "next" + if _, err = f.p.Execute(ctx, next); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("advanced before cleanup: %v", err) + } + cleanup := q + cleanup.ID = "cleanup" + cleanup.Kind = "cleanup" + cleanup.Inputs = nil + f.present = domain(&record{Request: q}) + if _, err = f.p.Execute(ctx, cleanup); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("cleaned live domain: %v", err) + } + if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); err != nil { + t.Fatal("deleted live disk", err) + } + f.present = "decoy-domain" + decoy := filepath.Join(f.p.root, "decoy.raw") + if err = os.WriteFile(decoy, []byte("retain"), 0600); err != nil { + t.Fatal(err) + } + if _, err = f.p.Execute(ctx, cleanup); err != nil { + t.Fatal(err) + } + if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); !os.IsNotExist(err) { + t.Fatalf("disk survived cleanup: %v", err) + } + if b, err := os.ReadFile(decoy); err != nil || string(b) != "retain" { + t.Fatal("decoy changed") + } + stale := vmRequest("stale") + if _, err = f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("stale authority accepted: %v", err) + } + if _, err = f.p.Execute(ctx, next); err != nil { + t.Fatal(err) + } + count := len(f.creates) + if _, err = f.p.Execute(ctx, cleanup); err != nil || len(f.creates) != count { + t.Fatal("old cleanup replay changed current allocation") + } + if _, err = os.Stat(f.p.directory(&record{Request: next}) + "/disk.raw"); err != nil { + t.Fatal("old cleanup deleted new disk", err) + } +} +func TestLocalDiskDirectorySyncPrecedesPrepared(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("sync-failure") + injected := errors.New("directory sync failed") + f.p.syncDirectory = func(path string) error { + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Operations[q.ID].Stage != "admitted" { + t.Fatal("journal advanced before sync") + } + info, err := os.Stat(filepath.Join(path, "disk.raw")) + if err != nil || info.Size() != 2<<30 { + t.Fatal("disk not prepared before sync", err) + } + return injected + } + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("sync failure ignored: %v", err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Operations[q.ID].Stage != "admitted" || len(f.creates) != 0 { + t.Fatal("sync failure permitted boot") + } + path := f.p.directory(j.Operations[q.ID]) + "/disk.raw" + file, err := os.OpenFile(path, os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err = file.Write([]byte("do-not-overwrite")); err != nil { + t.Fatal(err) + } + file.Close() + f.p.syncDirectory = nil + if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("overwrote uncertain preparation: %v", err) + } + file, err = os.Open(path) + if err != nil { + t.Fatal(err) + } + defer file.Close() + b := make([]byte, len("do-not-overwrite")) + if _, err = file.Read(b); err != nil { + t.Fatal(err) + } + if string(b) != "do-not-overwrite" { + t.Fatalf("disk overwritten: %q", b) + } +} +func TestLocalUncertainStartRecoversReceiptWithoutReinstall(t *testing.T) { + for _, bad := range []string{"missing", "wrong-receipt", "wrong-stage"} { + t.Run(bad, func(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("interrupted") + f.failStart = true + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + r := j.Operations[q.ID] + if r.Stage != "installer-started" { + t.Fatal(r.Stage) + } + if _, _, err = f.p.Lookup(ctx, q.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal("lookup inferred completion") + } + log := f.p.directory(r) + "/installer.log" + content := "FLEET-INSTALLED:stale\n" + if bad == "wrong-stage" { + content = "FLEET-DISK-BOOT:" + r.Receipt + "\n" + } + if bad != "missing" { + if err = os.WriteFile(log, []byte(content), 0600); err != nil { + t.Fatal(err) + } + } + f.failStart = false + if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.creates) != 1 { + t.Fatalf("uncertain start retried or bad receipt accepted: %v", err) + } + if err = os.WriteFile(log, []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err = f.p.Execute(ctx, q); err != nil { + t.Fatal(err) + } + if len(f.creates) != 2 || !strings.HasSuffix(f.creates[1], "/disk.xml") { + t.Fatalf("installer repeated: %v", f.creates) + } + }) + } +} + +func TestExplicitAccelerationAndJournalBinding(t *testing.T) { + for _, value := range []string{"auto", "qemu", "TCG", " kvm"} { + if _, err := parseAccelerator(value); err == nil { + t.Fatalf("accepted unknown accelerator %q", value) + } + } + for _, mode := range []string{"kvm", "tcg"} { + t.Run(mode, func(t *testing.T) { + f := newVMFixture(t) + f.p.accelerator = mode + q := vmRequest("mode-bound") + expected := "kvm" + if mode == "tcg" { + expected = "qemu" + } + if !strings.Contains(f.p.domainXML(&record{Request: q}, "disk"), "") { + t.Fatal("incorrect domain accelerator") + } + if _, err := f.p.Execute(context.Background(), q); err != nil { + t.Fatal(err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Accelerator != mode { + t.Fatal("accelerator not retained") + } + other := "tcg" + if mode == "tcg" { + other = "kvm" + } + f.p.accelerator = other + if _, err = f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("mode changed on replay: %v", err) + } + if _, _, err = f.p.Lookup(context.Background(), q.ID); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("lookup ignored mode: %v", err) + } + }) + } + if mode, err := parseAccelerator(""); err != nil || mode != "kvm" { + t.Fatal("default changed") + } + f := newVMFixture(t) + f.p.accelerator = "tcg" + if err := f.p.checkMode(journal{Image: f.p.image}); !errors.Is(err, executor.ErrConflict) { + t.Fatal("legacy journal was not bound to KVM") + } +} diff --git a/internal/localvm/provider.go b/internal/localvm/provider.go new file mode 100644 index 00000000..ef35cbb0 --- /dev/null +++ b/internal/localvm/provider.go @@ -0,0 +1,715 @@ +// Package localvm implements a deliberately bounded local VM executor. +// It is not a remotely accessible provider or a production authorization boundary. +package localvm + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "golang.org/x/sys/unix" +) + +const Root = "/var/lib/fleet-local" +const artifacts = "/opt/fleet-local/artifacts" + +// bootWindow bounds one-time network boot admission after an install is retained. +const bootWindow = 10 * time.Minute + +const AssetID = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" + +type Provider struct { + bootMode string + image string + accelerator string + root string + // bootRoot holds boot-service delivery evidence. In the Kubernetes site it + // is a separate volume path so the boot service never writes the journal. + bootRoot string + // bootOrigin is the boot Service URL written into the DHCP boot filename. + bootOrigin string + // uri selects the libvirt daemon; the site shares only its socket. + uri string + // readOnly providers (boot service, observer) never take the journal lock, + // create inventory, or execute effects. + readOnly bool + command func(context.Context, string, ...string) (string, error) + syncDirectory func(string) error +} + +func parseAccelerator(value string) (string, error) { + switch value { + case "", "kvm": + return "kvm", nil + case "tcg": + return "tcg", nil + default: + return "", errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") + } +} +func (p *Provider) mode() string { + if p.accelerator == "" { + return "kvm" + } + return p.accelerator +} +func (p *Provider) checkMode(j journal) error { + mode, err := parseAccelerator(j.Accelerator) + if err != nil { + return err + } + if j.Image != "" && (mode != p.mode() || j.BootMode != p.bootMode) { + return executor.ErrConflict + } + return nil +} +func (p *Provider) stateRoot() string { + if p.root != "" { + return p.root + } + return Root +} +func syncDir(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + return f.Sync() +} +func (p *Provider) syncDir(path string) error { + if p.syncDirectory != nil { + return p.syncDirectory(path) + } + return syncDir(path) +} + +type record struct { + Request simulator.Request `json:"request"` + Result simulator.OperationResult `json:"result"` + Receipt string `json:"receipt"` + Stage string `json:"stage"` + BootToken string `json:"bootToken,omitempty"` + BootExpires time.Time `json:"bootExpires"` + BootClosed bool `json:"bootClosed"` +} +type journal struct { + BootMode string `json:"bootMode"` + Accelerator string `json:"accelerator"` + Image string `json:"image"` + Epoch int64 `json:"epoch"` + Binding string `json:"binding"` + Fence string `json:"fence"` + Closed bool `json:"closed"` + Operations map[string]*record `json:"operations"` +} + +// Open returns the effectful provider used only by per-operation workers. +func Open() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + if err := os.MkdirAll(Root, 0700); err != nil { + return nil, err + } + inventory := []byte(`{"kind":"Device","name":"synthetic-device-central-01","assetID":"` + AssetID + `","management":"LocalOwned","architecture":"amd64","vcpus":2,"memoryMiB":2048,"diskBytes":2147483648,"networkInterfaces":1}`) + guard, e := p.lock() + if e != nil { + return nil, e + } + defer guard.Close() + current, e := os.ReadFile(Root + "/device.json") + if os.IsNotExist(e) { + f, e := os.OpenFile(Root+"/device.json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if e != nil { + return nil, e + } + _, e = f.Write(inventory) + if e == nil { + e = f.Sync() + } + f.Close() + if e != nil { + return nil, e + } + } else if e != nil { + return nil, e + } else if string(current) != string(inventory) { + return nil, errors.New("local device inventory differs; adoption is not authorized") + } + return p, nil +} + +// OpenReadOnly verifies the same artifacts and configuration but cannot +// execute, lock, or create state. The boot service and observer use it with +// a read-only journal mount. +func OpenReadOnly() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + p.readOnly = true + return p, nil +} + +func open() (*Provider, error) { + if os.Getenv("FLEET_LOCAL_VM") != "disposable-container" { + return nil, errors.New("local VM provider requires its disposable container") + } + accelerator, err := parseAccelerator(os.Getenv("FLEET_LOCAL_VM_ACCEL")) + if err != nil { + return nil, err + } + if accelerator == "kvm" { + if _, err := os.Stat("/dev/kvm"); err != nil { + return nil, err + } + } + origin, err := parseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return nil, err + } + uri, err := parseLibvirtURI(os.Getenv("FLEET_LIBVIRT_URI")) + if err != nil { + return nil, err + } + bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") + if bootRoot != "" && (!filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot) { + return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + b, err := os.ReadFile(artifacts + "/SHA256SUMS") + if err != nil { + return nil, err + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + if len(lines) != 2 { + return nil, errors.New("artifact manifest requires exactly two artifacts") + } + seen := map[string]bool{} + for _, line := range lines { + fields := strings.Fields(line) + if len(fields) != 2 || (fields[1] != "kernel" && fields[1] != "installer.gz") { + return nil, errors.New("invalid artifact manifest") + } + if seen[fields[1]] { + return nil, errors.New("duplicate artifact") + } + seen[fields[1]] = true + f, e := os.Open(artifacts + "/" + fields[1]) + if e != nil { + return nil, e + } + h := sha256.New() + _, e = io.Copy(h, f) + f.Close() + if e != nil { + return nil, e + } + if hex.EncodeToString(h.Sum(nil)) != fields[0] { + return nil, errors.New("artifact digest mismatch") + } + } + sum := sha256.Sum256(b) + p := &Provider{accelerator: accelerator, bootMode: "pxe", bootOrigin: origin, bootRoot: bootRoot, uri: uri} + p.image = "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]) + return p, nil +} + +// parseBootOrigin accepts only a literal http://IPv4:port origin. The site +// derives it from the boot Service ClusterIP; no hostname is resolved. +func parseBootOrigin(value string) (string, error) { + if value == "" { + return defaultBootOrigin, nil + } + u, err := url.Parse(value) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + ip := net.ParseIP(u.Hostname()) + port, err := strconv.Atoi(u.Port()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// parseLibvirtURI allows only the system daemon, optionally through an +// explicit absolute socket path shared from the runtime Pod. +func parseLibvirtURI(value string) (string, error) { + if value == "" || value == "qemu:///system" { + return "qemu:///system", nil + } + const prefix = "qemu:///system?socket=" + socket := strings.TrimPrefix(value, prefix) + if !strings.HasPrefix(value, prefix) || !filepath.IsAbs(socket) || filepath.Clean(socket) != socket || strings.ContainsAny(socket, "&?#") { + return "", errors.New("FLEET_LIBVIRT_URI must be qemu:///system or qemu:///system?socket=/absolute/path") + } + return value, nil +} + +func (p *Provider) lock() (*os.File, error) { + f, e := os.OpenFile(p.stateRoot()+"/lock", os.O_CREATE|os.O_RDWR, 0600) + if e != nil { + return nil, e + } + if e = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); e != nil { + f.Close() + return nil, e + } + return f, nil +} +func (p *Provider) read() (journal, error) { + var j journal + b, e := os.ReadFile(p.stateRoot() + "/journal.json") + if os.IsNotExist(e) { + j.Operations = map[string]*record{} + return j, nil + } + if e != nil { + return j, e + } + e = json.Unmarshal(b, &j) + if e == nil { + for id, r := range j.Operations { + if r == nil { + return j, errors.New("invalid retained operation") + } + if _, err := hex.DecodeString(r.Receipt); err != nil { + return j, errors.New("invalid receipt") + } + switch r.Stage { + case "admitted", "prepared", "installer-started", "installer-verified", "disk-started", "disk-verified": + if r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { + return j, errors.New("invalid pending result") + } + case "done": + if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { + return j, errors.New("invalid terminal result") + } + default: + return j, errors.New("unknown journal stage") + } + d, de := simulator.RequestDigest(r.Request) + if de != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Request.AssetID != AssetID || len(r.Receipt) != 64 { + return j, errors.New("invalid retained request") + } + } + } + if e == nil && j.Operations == nil { + e = errors.New("invalid journal") + } + return j, e +} +func (p *Provider) save(j journal) error { + b, e := json.MarshalIndent(j, "", " ") + if e != nil { + return e + } + f, e := os.OpenFile(p.stateRoot()+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if e != nil { + return e + } + _, e = f.Write(b) + if e == nil { + e = f.Sync() + } + ce := f.Close() + if e != nil { + return e + } + if ce != nil { + return ce + } + if e = os.Rename(p.stateRoot()+"/journal.tmp", p.stateRoot()+"/journal.json"); e != nil { + return e + } + d, e := os.Open(p.stateRoot()) + if e != nil { + return e + } + defer d.Close() + return d.Sync() +} +func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } +func run(ctx context.Context, name string, args ...string) (string, error) { + c := exec.CommandContext(ctx, name, args...) + b, e := c.CombinedOutput() + if e != nil { + return "", fmt.Errorf("%s failed: %w: %s", name, e, b) + } + return strings.TrimSpace(string(b)), nil +} +func (p *Provider) virsh(ctx context.Context, args ...string) (string, error) { + command := p.command + if command == nil { + command = run + } + uri := p.uri + if uri == "" { + uri = "qemu:///system" + } + return command(ctx, "virsh", append([]string{"--connect", uri}, args...)...) +} + +// Lookup reports only terminal retained results. A read-only provider reads +// without the lock: atomic journal replacement makes each read consistent. +func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if !p.readOnly { + f, e := p.lock() + if e != nil { + return simulator.OperationResult{}, false, e + } + defer f.Close() + } + j, e := p.read() + if e != nil { + return simulator.OperationResult{}, false, e + } + if e = p.checkMode(j); e != nil { + return simulator.OperationResult{}, false, e + } + r := j.Operations[id] + if r == nil { + return simulator.OperationResult{}, false, nil + } + if r.Stage != "done" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return r.Result, true, nil +} +func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + if p.readOnly { + return simulator.OperationResult{}, executor.ErrInvalid + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) + defer cancel() + f, e := p.lock() + if e != nil { + return simulator.OperationResult{}, e + } + defer f.Close() + if e = p.validate(q); e != nil { + return simulator.OperationResult{}, e + } + digest, e := simulator.RequestDigest(q) + if e != nil { + return simulator.OperationResult{}, e + } + j, e := p.read() + if e != nil { + return simulator.OperationResult{}, e + } + if e = p.checkMode(j); e != nil { + return simulator.OperationResult{}, e + } + j.Accelerator = p.mode() + j.BootMode = p.bootMode + if j.Image != "" && j.Image != p.image { + return simulator.OperationResult{}, executor.ErrConflict + } + j.Image = p.image + r := j.Operations[q.ID] + if r != nil { + if r.Result.InputDigest != digest { + return simulator.OperationResult{}, executor.ErrConflict + } + if r.Stage == "done" { + return r.Result, nil + } + } else { + for _, old := range j.Operations { + if old.Stage != "done" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + } + if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { + return simulator.OperationResult{}, executor.ErrFenced + } + j.Epoch = q.Epoch + j.Binding = q.BindingID + j.Fence = q.FenceToken + j.Closed = false + nonce := make([]byte, 32) + if _, e = rand.Read(nonce); e != nil { + return simulator.OperationResult{}, e + } + r = &record{Request: q, Receipt: hex.EncodeToString(nonce), Stage: "admitted", Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now().UTC()}} + if p.bootMode == "pxe" && q.Kind == "install" { + token := make([]byte, 32) + if _, e = rand.Read(token); e != nil { + return simulator.OperationResult{}, e + } + r.BootToken = hex.EncodeToString(token) + r.BootExpires = time.Now().UTC().Add(bootWindow) + } + j.Operations[q.ID] = r + if e = p.save(j); e != nil { + return simulator.OperationResult{}, e + } + } + if q.Kind == "install" { + e = p.install(ctx, &j, r) + } else { + e = p.cleanup(ctx, &j, r) + } + if e != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) + } + now := time.Now().UTC() + r.Stage = "done" + r.Result.Phase = "Succeeded" + r.Result.CompletedAt = &now + r.Result.Result = "installed" + if q.Kind == "cleanup" { + r.Result.Result = "clean" + j.Closed = true + } + if e = p.save(j); e != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) + } + return r.Result, nil +} +func (p *Provider) directory(r *record) string { + return filepath.Join(p.stateRoot(), key(r.Request.ID)) +} + +// bootDirectory holds boot-service delivery evidence for one operation. +func (p *Provider) bootDirectory(r *record) string { + if p.bootRoot == "" { + return p.directory(r) + } + return filepath.Join(p.bootRoot, key(r.Request.ID)) +} +func domain(r *record) string { return "fleet-local-" + key(r.Request.ID)[:24] } +func (p *Provider) install(ctx context.Context, j *journal, r *record) error { + dir := p.directory(r) + if r.Stage == "admitted" { + if e := os.Mkdir(dir, 0700); e != nil && !os.IsExist(e) { + return e + } + // Exclusive creation prevents an interrupted preparation from overwriting a disk. + f, e := os.OpenFile(dir+"/disk.raw", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if e != nil { + return e + } + e = f.Truncate(2 << 30) + if e == nil { + e = f.Sync() + } + closeErr := f.Close() + if e != nil { + return e + } + if closeErr != nil { + return closeErr + } + if e = p.syncDir(dir); e != nil { + return e + } + r.Stage = "prepared" + if e = p.save(*j); e != nil { + return e + } + } + for _, stage := range []string{"installer", "disk"} { + before := "prepared" + if stage == "disk" { + before = "installer-verified" + } + if r.Stage == before { + if stage == "disk" && p.bootMode == "pxe" { + if !r.BootClosed { + return errors.New("boot admission still open") + } + if e := p.stopNetwork(ctx); e != nil { + return e + } + } + if stage == "installer" && p.bootMode == "pxe" { + if !time.Now().Before(r.BootExpires) || r.BootClosed { + return errors.New("boot admission expired or closed") + } + if e := p.prepareNetwork(ctx, r); e != nil { + return e + } + } + xml := p.domainXML(r, stage) + if e := os.WriteFile(dir+"/"+stage+".xml", []byte(xml), 0600); e != nil { + return e + } + // Retain start uncertainty before invoking libvirt. Recovery observes it; + // it never repeats a possibly executed installer boot. + r.Stage = stage + "-started" + if e := p.save(*j); e != nil { + return e + } + if _, e := p.virsh(ctx, "create", dir+"/"+stage+".xml"); e != nil { + return e + } + } + if r.Stage == stage+"-started" { + if e := p.waitReceipt(ctx, r, stage); e != nil { + return e + } + if stage == "installer" && p.bootMode == "pxe" { + if e := p.verifyNetworkBoot(ctx, r); e != nil { + return e + } + r.BootClosed = true + } + r.Stage = stage + "-verified" + if e := p.save(*j); e != nil { + return e + } + } + } + if r.Stage != "disk-verified" { + return errors.New("unexpected installation stage") + } + return nil +} +func (p *Provider) domainXML(r *record, stage string) string { + dir := p.directory(r) + boot := "" + nic := "" + if stage == "installer" { + boot = fmt.Sprintf("%s/kernel%s/installer.gzconsole=ttyS0 rdinit=/init fleet.receipt=%s", artifacts, artifacts, r.Receipt) + } + if stage == "installer" && p.bootMode == "pxe" { + boot = "" + nic = "" + } + domainType := "kvm" + if p.mode() == "tcg" { + domainType = "qemu" + } + return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(r), boot, nic, dir, dir, stage) +} +func (p *Provider) waitReceipt(ctx context.Context, r *record, stage string) error { + marker := "FLEET-INSTALLED:" + if stage == "disk" { + marker = "FLEET-DISK-BOOT:" + } + for { + names, e := p.virsh(ctx, "list", "--all", "--name") + if e != nil { + return e + } + present := false + for _, name := range strings.Fields(names) { + if name == domain(r) { + present = true + } + } + if !present { + b, e := os.ReadFile(p.directory(r) + "/" + stage + ".log") + if e != nil { + return e + } + for _, line := range strings.Split(string(b), "\n") { + if strings.TrimSpace(line) == marker+r.Receipt { + evidence, err := os.OpenFile(p.directory(r)+"/"+stage+".log", os.O_RDWR, 0) + if err != nil { + return err + } + err = evidence.Sync() + closeErr := evidence.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return p.syncDir(p.directory(r)) + } + } + return errors.New("guest stopped without exact boot receipt") + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } +} +func (p *Provider) cleanup(ctx context.Context, j *journal, r *record) error { + // Only retained operations in this allocation identify cleanup targets. + names, e := p.virsh(ctx, "list", "--all", "--name") + if e != nil { + return e + } + for _, old := range j.Operations { + if old.Request.Kind != "install" || old.Request.BindingID != r.Request.BindingID { + continue + } + for _, n := range strings.Fields(names) { + if n == domain(old) { + return errors.New("domain still exists; cleanup remains unknown") + } + } + path := p.directory(old) + "/disk.raw" + if e = os.Remove(path); e != nil && !os.IsNotExist(e) { + return e + } + dir, err := os.Open(p.directory(old)) + if err != nil { + return err + } + err = dir.Sync() + dir.Close() + if err != nil { + return err + } + if _, e = os.Lstat(path); !os.IsNotExist(e) { + return errors.New("disk deletion unverified") + } + } + d, e := os.Open(p.stateRoot()) + if e != nil { + return e + } + defer d.Close() + return d.Sync() +} + +func (p *Provider) validate(q simulator.Request) error { + if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { + return executor.ErrInvalid + } + if q.AssetID != AssetID || (q.Kind != "install" && q.Kind != "cleanup") { + return executor.ErrInvalid + } + if q.Kind == "install" { + var in struct { + Image string `json:"image"` + } + d := json.NewDecoder(strings.NewReader(string(q.Inputs))) + d.DisallowUnknownFields() + if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { + return executor.ErrInvalid + } + } + if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { + return executor.ErrInvalid + } + return nil +} + +// ImageReference is the locally verified artifact manifest identity. +func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/localvm/provider_test.go b/internal/localvm/provider_test.go new file mode 100644 index 00000000..b35f2c24 --- /dev/null +++ b/internal/localvm/provider_test.go @@ -0,0 +1,35 @@ +package localvm + +import ( + "encoding/json" + "go.datum.net/fleet/internal/simulator" + "strings" + "testing" +) + +func TestBoundedInputs(t *testing.T) { + p := &Provider{image: "approved@sha256:abc"} + base := simulator.Request{ID: "installation", Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"approved@sha256:abc"}`)} + if e := p.validate(base); e != nil { + t.Fatal(e) + } + for _, mutate := range []func(*simulator.Request){func(q *simulator.Request) { q.AssetID = "other" }, func(q *simulator.Request) { q.Epoch = 0 }, func(q *simulator.Request) { q.FenceToken = "" }, func(q *simulator.Request) { q.Inputs = json.RawMessage(`{"image":"unapproved"}`) }, func(q *simulator.Request) { + q.Inputs = json.RawMessage(`{"image":"approved@sha256:abc","path":"/host"}`) + }, func(q *simulator.Request) { q.Kind = "cleanup"; q.Inputs = json.RawMessage(`{"target":"/host"}`) }, func(q *simulator.Request) { q.Kind = "power" }} { + q := base + mutate(&q) + if p.validate(q) == nil { + t.Fatalf("accepted unsupported request: %#v", q) + } + } +} +func TestDiskBootHasNoInstallerAndNamesAreOpaque(t *testing.T) { + r := &record{Request: simulator.Request{ID: "../../host' "}, Receipt: strings.Repeat("a", 64)} + xml := (&Provider{}).domainXML(r, "disk") + if strings.Contains(xml, "") || strings.Contains(xml, "") || strings.Contains(xml, "") { + t.Fatal("missing disk boot") + } +} diff --git a/internal/localvm/pxe_review_adversarial_test.go b/internal/localvm/pxe_review_adversarial_test.go new file mode 100644 index 00000000..276f5af7 --- /dev/null +++ b/internal/localvm/pxe_review_adversarial_test.go @@ -0,0 +1,189 @@ +package localvm + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +func reviewBootRecord(t *testing.T) (*Provider, journal, *record) { + t.Helper() + p := newVMFixture(t).p + p.bootMode = "pxe" + q := vmRequest("independent-review") + digest, err := simulator.RequestDigest(q) + if err != nil { + t.Fatal(err) + } + r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: r}} + if err := os.Mkdir(p.directory(r), 0700); err != nil { + t.Fatal(err) + } + if err := p.save(j); err != nil { + t.Fatal(err) + } + return p, j, r +} + +type reviewFailedResponse struct { + header http.Header + writes int + short bool +} + +func (w *reviewFailedResponse) Header() http.Header { return w.header } +func (w *reviewFailedResponse) WriteHeader(int) {} +func (w *reviewFailedResponse) Write(data []byte) (int, error) { + w.writes++ + if w.short { + return len(data) - 1, nil + } + return 0, errors.New("client disconnected before body") +} + +func TestReviewIncompleteHTTPWriteCannotRecordCompletion(t *testing.T) { + for _, short := range []bool{false, true} { + p, _, r := reviewBootRecord(t) + w := &reviewFailedResponse{header: make(http.Header), short: short} + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) + if w.writes != 1 { + t.Fatal("did not exercise body write") + } + b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), "admitted boot.ipxe bytes=") || strings.Contains(string(b), "write-complete") { + t.Fatal("incomplete write counted as completion") + } + if err := p.verifyNetworkBoot(context.Background(), r); err == nil { + t.Fatal("attempt counted as network boot evidence") + } + } +} +func TestReviewCompleteHTTPWriteRecordsCompletion(t *testing.T) { + p, _, r := reviewBootRecord(t) + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) + b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") + if err != nil { + t.Fatal(err) + } + if w.Code != http.StatusOK || !strings.Contains(string(b), "write-complete boot.ipxe bytes=") { + t.Fatal("successful write not recorded") + } +} + +func TestReviewCorruptDigestAndHTTPPathVariantsDenied(t *testing.T) { + p, j, r := reviewBootRecord(t) + base := "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + for _, path := range []string{base + "/kernel/extra", base + "/%2e%2e", base + "/boot.ipxe?token=x", base + "/%2fkernel"} { + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("path variant allowed: status %d", w.Code) + } + } + r.Result.InputDigest = "substituted" + if err := p.save(j); err != nil { + t.Fatal(err) + } + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", base+"/boot.ipxe", nil)) + if w.Code != http.StatusForbidden { + t.Fatal("corrupt request digest admitted") + } +} + +func TestReviewClosedAdmissionDoesNotSettleLiveInstaller(t *testing.T) { + p, j, r := reviewBootRecord(t) + r.BootClosed = true + r.BootExpires = time.Now().Add(-time.Minute) + if err := p.save(j); err != nil { + t.Fatal(err) + } + // Even an exact receipt cannot settle a domain still present. + if err := os.WriteFile(p.directory(r)+"/installer.log", []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + p.command = func(_ context.Context, _ string, args ...string) (string, error) { + if args[2] != "list" { + t.Fatalf("unexpected effect %s", args[2]) + } + return domain(r), nil + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := p.Execute(ctx, r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("live expired installer settled: %v", err) + } + got, err := p.read() + if err != nil { + t.Fatal(err) + } + if got.Operations[r.Request.ID].Stage != "installer-started" { + t.Fatal("advanced live installer") + } +} + +func TestReviewNetworkTeardownFailureBlocksDiskBootAndRecovers(t *testing.T) { + p, j, r := reviewBootRecord(t) + r.Stage = "installer-verified" + r.BootClosed = true + if err := p.save(j); err != nil { + t.Fatal(err) + } + fail := true + creates := 0 + p.command = func(_ context.Context, _ string, args ...string) (string, error) { + switch args[2] { + case "net-list": + return "fleet-pxe", nil + case "net-destroy": + if fail { + return "", errors.New("uncertain teardown") + } + return "", nil + case "create": + creates++ + if !strings.HasSuffix(args[3], "/disk.xml") { + t.Fatal("installer replay") + } + return "", os.WriteFile(p.directory(r)+"/disk.log", []byte("FLEET-DISK-BOOT:"+r.Receipt+"\n"), 0600) + case "list": + return "", nil + default: + t.Fatalf("unexpected command %s", args[2]) + return "", nil + } + } + if _, err := p.Execute(context.Background(), r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("teardown failure not unknown: %v", err) + } + if creates != 0 { + t.Fatal("booted despite uncertain teardown") + } + got, err := p.read() + if err != nil { + t.Fatal(err) + } + if got.Operations[r.Request.ID].Stage != "installer-verified" { + t.Fatal("advanced after failure") + } + fail = false + if _, err := p.Execute(context.Background(), r.Request); err != nil { + t.Fatal(err) + } + if creates != 1 { + t.Fatal("unexpected disk boot count") + } +} diff --git a/internal/localvm/site_test.go b/internal/localvm/site_test.go new file mode 100644 index 00000000..1abcf9b0 --- /dev/null +++ b/internal/localvm/site_test.go @@ -0,0 +1,116 @@ +package localvm + +import ( + "context" + "errors" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +func TestSiteBootOriginAndLibvirtURIValidation(t *testing.T) { + for value, want := range map[string]string{"": defaultBootOrigin, "http://10.96.12.7:8080": "http://10.96.12.7:8080"} { + if got, err := parseBootOrigin(value); err != nil || got != want { + t.Fatalf("%q: %q %v", value, got, err) + } + } + for _, bad := range []string{"https://10.0.0.1:8080", "http://boot.local:8080", "http://10.0.0.1", "http://10.0.0.1:8080/x", "http://u@10.0.0.1:8080", "http://[::1]:8080", "http://10.0.0.1:0"} { + if _, err := parseBootOrigin(bad); err == nil { + t.Fatalf("accepted boot origin %q", bad) + } + } + for _, good := range []string{"", "qemu:///system", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} { + if _, err := parseLibvirtURI(good); err != nil { + t.Fatalf("%q: %v", good, err) + } + } + for _, bad := range []string{"qemu+tcp://runtime/system", "qemu:///session", "qemu:///system?socket=relative", "qemu:///system?socket=/run/x&no_verify=1", "qemu:///system?socket=/run/../etc"} { + if _, err := parseLibvirtURI(bad); err == nil { + t.Fatalf("accepted libvirt URI %q", bad) + } + } +} + +// The site network forwards only when the boot Service is outside the +// hypervisor namespace, and the DHCP boot file names that exact origin. +func TestSiteNetworkUsesBootServiceOrigin(t *testing.T) { + var defined string + p := &Provider{root: t.TempDir(), bootMode: "pxe", bootOrigin: "http://10.96.0.40:8080", uri: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + p.command = func(_ context.Context, name string, args ...string) (string, error) { + if args[1] != p.uri { + t.Fatalf("libvirt URI not used: %v", args) + } + if args[2] == "net-create" { + b, err := os.ReadFile(args[3]) + defined = string(b) + return "", err + } + return "", nil + } + r := &record{Request: vmRequest("site-net"), BootToken: strings.Repeat("b", 64)} + if err := p.prepareNetwork(context.Background(), r); err != nil { + t.Fatal(err) + } + if !strings.Contains(defined, "") || !strings.Contains(defined, "file='http://10.96.0.40:8080/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe'") { + t.Fatal(defined) + } + single := &Provider{root: t.TempDir(), bootMode: "pxe"} + single.command = func(_ context.Context, name string, args ...string) (string, error) { + if args[2] == "net-create" { + b, _ := os.ReadFile(args[3]) + defined = string(b) + } + return "", nil + } + if err := single.prepareNetwork(context.Background(), r); err != nil { + t.Fatal(err) + } + if strings.Contains(defined, " Date: Wed, 18 Nov 2026 13:33:08 -0600 Subject: [PATCH 09/12] feat(multiplane): local Milo, Karmada and kro acceptance with Flux-owned sites One command (task multiplane:acceptance) composes the local VM executor with native Milo project APIs, real Karmada delivery and reflection, and a Kubernetes-native site in a dedicated Colima profile: - internal/coordination defines the delivered handoff and journal-derived observation contract between management and a cell, with exact-request digests, epoch fencing and wrong-cell, stale and duplicate rejection. - internal/multiplane drives allocation, install, release and reuse through the shared lifecycle library; Coordinator.ClaimReleased lets it avoid restoring protection after verified release. - cmd/fleet-multiplane runs the management phases and the site roles. - config/site holds the Flux-owned shared site services and a kro graph that creates only per-handoff RBAC and bounded worker Jobs; config/multiplane holds per-cluster Flux sources for Milo, Karmada, kro and the site. - hack/multiplane runs the bounded phases, fault injection (worker Pod/Job interruption, delivery and reflection faults, wrong location, Flux drift, restart and fail-closed cases) and writes sanitized evidence. CI runs the harness's offline tests and shellcheck. Production authority, KVM and hardware remain unqualified. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +- .gitignore | 8 + Taskfile.yaml | 27 + cmd/fleet-multiplane/main.go | 211 ++++ config/README.md | 7 + .../cell-federation/federation.yaml | 47 + .../cell-federation/kustomization.yaml | 4 + .../clusters/cell-site/kustomization.yaml | 4 + .../multiplane/clusters/cell-site/site.yaml | 53 + config/multiplane/clusters/cell/cell.yaml | 88 ++ .../clusters/cell/kustomization.yaml | 4 + config/multiplane/clusters/hub/hub.yaml | 100 ++ .../clusters/hub/kustomization.yaml | 4 + .../clusters/platform/kustomization.yaml | 4 + config/multiplane/clusters/platform/milo.yaml | 37 + config/multiplane/coordination/crd.yaml | 42 + .../coordination/kustomization.yaml | 7 + config/multiplane/coordination/namespace.yaml | 8 + config/multiplane/flux/components.yaml | 55 + config/multiplane/host/custody.yaml | 32 + config/multiplane/host/kustomization.yaml | 4 + config/multiplane/karmada-api/hub-rbac.yaml | 19 + .../multiplane/karmada-api/interpreter.yaml | 31 + .../multiplane/karmada-api/kustomization.yaml | 8 + .../karmada-api/member-namespace.yaml | 8 + .../karmada-members/kustomization.yaml | 4 + .../multiplane/karmada-members/members.yaml | 34 + config/multiplane/karmada/karmada.yaml | 81 ++ config/multiplane/karmada/kustomization.yaml | 4 + config/multiplane/kro/kro.yaml | 72 ++ config/multiplane/kro/kustomization.yaml | 4 + .../multiplane/milo/base/kustomization.yaml | 4 + config/multiplane/milo/base/milo.yaml | 112 ++ .../milo/consumer-a/kustomization.yaml | 13 + .../multiplane/milo/consumer-a/namespace.yaml | 7 + .../milo/consumer-b/kustomization.yaml | 13 + .../multiplane/milo/consumer-b/namespace.yaml | 7 + .../milo/provider/kustomization.yaml | 13 + .../multiplane/milo/provider/namespace.yaml | 7 + config/site/base/kro.yaml | 178 +++ config/site/base/kustomization.yaml | 6 + config/site/base/reconcilers.yaml | 81 ++ config/site/base/site.yaml | 78 ++ config/site/graph/kustomization.yaml | 4 + config/site/graph/rgd.yaml | 223 ++++ config/site/instance/dispatcher.yaml | 19 + config/site/instance/kustomization.yaml | 4 + config/site/services/kustomization.yaml | 4 + config/site/services/services.yaml | 161 +++ docs/development/README.md | 8 + docs/enhancements/pxe-installation/README.md | 22 +- docs/operations/README.md | 1 + docs/operations/gitops.md | 304 +++++ docs/operations/local-vm.md | 4 +- docs/operations/multiplane.md | 965 ++++++++++++++ docs/operations/site-execution.md | 386 ++++++ hack/local-vm/Containerfile | 8 + hack/local-vm/site-runtime | 22 + hack/multiplane/acceptance.sh | 45 + hack/multiplane/evidence.py | 276 ++++ hack/multiplane/fault_guard.py | 64 + hack/multiplane/flux.py | 1114 +++++++++++++++++ hack/multiplane/harness.py | 424 +++++++ hack/multiplane/k8s_evidence.py | 291 +++++ hack/multiplane/milo.py | 83 ++ hack/multiplane/reflection-faults.py | 45 + hack/multiplane/roles.py | 49 + hack/multiplane/run.sh | 104 ++ hack/multiplane/site.sh | 58 + hack/multiplane/steps.sh | 309 +++++ hack/multiplane/stop.sh | 27 + hack/multiplane/sysctl.py | 30 + hack/multiplane/teardown.sh | 65 + hack/multiplane/test-flux.py | 288 +++++ hack/multiplane/test-harness.sh | 273 ++++ hack/multiplane/test-k8s-evidence.py | 183 +++ hack/multiplane/topology.sh | 81 ++ hack/multiplane/verify-rbac.py | 101 ++ internal/controller/lifecycle.go | 14 + internal/coordination/mapping.go | 71 ++ internal/coordination/mapping_test.go | 41 + .../coordination/recovery_adversarial_test.go | 159 +++ internal/coordination/run.go | 40 + internal/coordination/site_test.go | 127 ++ internal/coordination/transport.go | 301 +++++ internal/coordination/transport_test.go | 115 ++ .../multiplane_recovery_adversarial_test.go | 139 ++ .../multiplane/location_adversarial_test.go | 131 ++ internal/multiplane/runner.go | 488 ++++++++ internal/multiplane/runner_test.go | 105 ++ 90 files changed, 9302 insertions(+), 7 deletions(-) create mode 100644 cmd/fleet-multiplane/main.go create mode 100644 config/multiplane/cell-federation/federation.yaml create mode 100644 config/multiplane/cell-federation/kustomization.yaml create mode 100644 config/multiplane/clusters/cell-site/kustomization.yaml create mode 100644 config/multiplane/clusters/cell-site/site.yaml create mode 100644 config/multiplane/clusters/cell/cell.yaml create mode 100644 config/multiplane/clusters/cell/kustomization.yaml create mode 100644 config/multiplane/clusters/hub/hub.yaml create mode 100644 config/multiplane/clusters/hub/kustomization.yaml create mode 100644 config/multiplane/clusters/platform/kustomization.yaml create mode 100644 config/multiplane/clusters/platform/milo.yaml create mode 100644 config/multiplane/coordination/crd.yaml create mode 100644 config/multiplane/coordination/kustomization.yaml create mode 100644 config/multiplane/coordination/namespace.yaml create mode 100644 config/multiplane/flux/components.yaml create mode 100644 config/multiplane/host/custody.yaml create mode 100644 config/multiplane/host/kustomization.yaml create mode 100644 config/multiplane/karmada-api/hub-rbac.yaml create mode 100644 config/multiplane/karmada-api/interpreter.yaml create mode 100644 config/multiplane/karmada-api/kustomization.yaml create mode 100644 config/multiplane/karmada-api/member-namespace.yaml create mode 100644 config/multiplane/karmada-members/kustomization.yaml create mode 100644 config/multiplane/karmada-members/members.yaml create mode 100644 config/multiplane/karmada/karmada.yaml create mode 100644 config/multiplane/karmada/kustomization.yaml create mode 100644 config/multiplane/kro/kro.yaml create mode 100644 config/multiplane/kro/kustomization.yaml create mode 100644 config/multiplane/milo/base/kustomization.yaml create mode 100644 config/multiplane/milo/base/milo.yaml create mode 100644 config/multiplane/milo/consumer-a/kustomization.yaml create mode 100644 config/multiplane/milo/consumer-a/namespace.yaml create mode 100644 config/multiplane/milo/consumer-b/kustomization.yaml create mode 100644 config/multiplane/milo/consumer-b/namespace.yaml create mode 100644 config/multiplane/milo/provider/kustomization.yaml create mode 100644 config/multiplane/milo/provider/namespace.yaml create mode 100644 config/site/base/kro.yaml create mode 100644 config/site/base/kustomization.yaml create mode 100644 config/site/base/reconcilers.yaml create mode 100644 config/site/base/site.yaml create mode 100644 config/site/graph/kustomization.yaml create mode 100644 config/site/graph/rgd.yaml create mode 100644 config/site/instance/dispatcher.yaml create mode 100644 config/site/instance/kustomization.yaml create mode 100644 config/site/services/kustomization.yaml create mode 100644 config/site/services/services.yaml create mode 100644 docs/operations/gitops.md create mode 100644 docs/operations/multiplane.md create mode 100644 docs/operations/site-execution.md create mode 100755 hack/local-vm/site-runtime create mode 100755 hack/multiplane/acceptance.sh create mode 100755 hack/multiplane/evidence.py create mode 100644 hack/multiplane/fault_guard.py create mode 100644 hack/multiplane/flux.py create mode 100755 hack/multiplane/harness.py create mode 100644 hack/multiplane/k8s_evidence.py create mode 100755 hack/multiplane/milo.py create mode 100755 hack/multiplane/reflection-faults.py create mode 100755 hack/multiplane/roles.py create mode 100755 hack/multiplane/run.sh create mode 100755 hack/multiplane/site.sh create mode 100755 hack/multiplane/steps.sh create mode 100755 hack/multiplane/stop.sh create mode 100755 hack/multiplane/sysctl.py create mode 100755 hack/multiplane/teardown.sh create mode 100644 hack/multiplane/test-flux.py create mode 100755 hack/multiplane/test-harness.sh create mode 100644 hack/multiplane/test-k8s-evidence.py create mode 100644 hack/multiplane/topology.sh create mode 100755 hack/multiplane/verify-rbac.py create mode 100644 internal/coordination/mapping.go create mode 100644 internal/coordination/mapping_test.go create mode 100644 internal/coordination/recovery_adversarial_test.go create mode 100644 internal/coordination/run.go create mode 100644 internal/coordination/site_test.go create mode 100644 internal/coordination/transport.go create mode 100644 internal/coordination/transport_test.go create mode 100644 internal/localvm/multiplane_recovery_adversarial_test.go create mode 100644 internal/multiplane/location_adversarial_test.go create mode 100644 internal/multiplane/runner.go create mode 100644 internal/multiplane/runner_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9bc7d38..83fdfdb0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,8 @@ jobs: - run: ./hack/test-standalone-build-context.sh - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh - - run: shellcheck -S warning hack/local-vm/run.sh hack/local-vm/start-libvirt + - run: ./hack/multiplane/test-harness.sh + - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime standalone-smoke: runs-on: ubuntu-latest timeout-minutes: 35 diff --git a/.gitignore b/.gitignore index 1e2ab3f7..710fb1db 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,13 @@ .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-local-vm diff --git a/Taskfile.yaml b/Taskfile.yaml index 058efe55..6bda8974 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -6,6 +6,33 @@ tasks: cmds: - ./hack/run-standalone-smoke.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: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:test-harness: + desc: Offline tests for the multi-plane harness with fake runtime tools. + cmds: + - ./hack/multiplane/test-harness.sh + local-vm:acceptance: desc: Single-plane local VM PXE acceptance with explicit TCG in the task-owned Colima profile. env: diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go new file mode 100644 index 00000000..004b6208 --- /dev/null +++ b/cmd/fleet-multiplane/main.go @@ -0,0 +1,211 @@ +// fleet-multiplane is an opt-in local acceptance binary. Production managers do +// not import its synthetic admission, quota or hardware enrollment fixtures. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/localvm" + "go.datum.net/fleet/internal/multiplane" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" +) + +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 site-worker|site-observer|image|boot-service|boot-denials| [flags]") + } + fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) + once := fs.Bool("once", false, "one reconcile attempt for fault injection") + handoff := fs.String("handoff", "", "exact delivered handoff name (site-worker)") + origin := fs.String("origin", "", "boot listener origin to probe (boot-denials); default the configured origin") + interval := fs.Duration("interval", 10*time.Second, "observation refresh interval (site-observer)") + 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") + scoped := fs.String("scoped-asset", "", "exact retained provider-scoped Device ID") + if err := fs.Parse(os.Args[2:]); err != nil { + return err + } + switch os.Args[1] { + case "seed", "allocate", "install", "admit-install", "release", "release-b", "reuse", "asset": + config, err := multiplane.ReadConfig(*configPath) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + if os.Args[1] == "seed" { + return multiplane.Seed(ctx, config) + } + r, err := multiplane.New(ctx, config) + if err != nil { + return err + } + if os.Args[1] == "asset" { + fmt.Println(r.ScopedAsset()) + return nil + } + var action func(context.Context) error + switch os.Args[1] { + case "allocate": + action = r.Allocate + case "install", "admit-install": + action = r.Install + case "release": + action = r.Release + case "release-b": + action = r.ReleaseSecond + case "reuse": + action = r.Reuse + } + for { + err = action(ctx) + if os.Args[1] == "admit-install" { + if errors.Is(err, executor.ErrOutcomeUnknown) { + fmt.Println("Installation intent retained; execution result remains Unknown") + return nil + } + if err == nil { + return fmt.Errorf("admission probe unexpectedly completed; run before starting cell") + } + return err + } + if (*once || terminal(err)) && err != nil { + return err + } + if err == nil { + fmt.Println(os.Args[1] + ": verified local acceptance phase (synthetic authority)") + return nil + } + if ctx.Err() != nil { + return fmt.Errorf("%s did not converge; authority retained; last error: %w", os.Args[1], err) + } + time.Sleep(3 * time.Second) + } + } + switch os.Args[1] { + case "image", "boot-service", "boot-denials": + // Read-only: the boot service mounts the journal read-only. + p, err := localvm.OpenReadOnly() + if err != nil { + return err + } + switch os.Args[1] { + case "image": + fmt.Println(p.ImageReference()) + return nil + case "boot-service": + return p.ServeBoot() + } + summary, err := p.CheckClosedBoot(*origin) + if err != nil { + return err + } + fmt.Println(summary) + return nil + case "site-worker", "site-observer": + default: + return fmt.Errorf("unknown command") + } + if *cell == "" || *scoped == "" || (os.Args[1] == "site-worker" && *handoff == "") { + return fmt.Errorf("cell, scoped-asset 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() + if os.Args[1] == "site-observer" { + // The observer never executes: its provider is read-only. + p, err := localvm.OpenReadOnly() + if err != nil { + return err + } + mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} + observer := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} + return observer.Observe(ctx, *interval, func(name string, err error) { + fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) + }) + } + p, err := localvm.Open() + if err != nil { + return err + } + mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} + worker := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} + err = worker.Execute(ctx, *handoff) + fmt.Fprintf(os.Stderr, "site-worker: handoff %s: %s\n", *handoff, classify(err)) + if err != nil { + if terminal(err) { + os.Exit(exitRejected) + } + os.Exit(exitRetry) + } + return nil +} + +const coordinationNamespace = "fleet-coordination" + +// Worker exit codes are the Job podFailurePolicy contract: rejected authority +// fails the Job without retry; anything else is retried by the Job controller +// against the same retained operation. Exit 0 only follows a validated +// terminal journal result, and still does not publish or authorize readiness. +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 "terminal result verified in provider journal" + case errors.Is(err, executor.ErrFenced): + return "fenced: " + err.Error() + case errors.Is(err, executor.ErrConflict): + return "conflict: " + err.Error() + case errors.Is(err, executor.ErrInvalid): + return "invalid: " + err.Error() + case errors.Is(err, executor.ErrOutcomeUnknown): + return "outcome unknown: " + err.Error() + default: + return "pending: " + err.Error() + } +} + +// terminal errors are authority rejections; retrying cannot change them and +// Unknown (the only retained-uncertainty result) stays retryable. +func terminal(err error) bool { + for _, target := range []error{executor.ErrConflict, executor.ErrFenced, executor.ErrInvalid, multiplane.ErrLocationNotServed} { + if errors.Is(err, target) { + return true + } + } + return false +} diff --git a/config/README.md b/config/README.md index 953821e1..07e34cda 100644 --- a/config/README.md +++ b/config/README.md @@ -21,6 +21,13 @@ API servers and must be reconciled independently. `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 implementation, but substitutes synthetic admission and provider evidence. It diff --git a/config/multiplane/cell-federation/federation.yaml b/config/multiplane/cell-federation/federation.yaml new file mode 100644 index 00000000..f704aa17 --- /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] + 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] + 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..a31b21ce --- /dev/null +++ b/config/multiplane/clusters/hub/hub.yaml @@ -0,0 +1,100 @@ +# 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 +--- +# Private custody namespace and the custodian identity on the host API. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-host, 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/host +--- +# 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/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..bb4d4591 --- /dev/null +++ b/config/multiplane/coordination/crd.yaml @@ -0,0 +1,42 @@ +# Experimental handoff API: install on the Karmada API and participating cells. +# Never install in consumer project APIs. Payloads contain private authority. +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, requestJSON] + x-kubernetes-validations: + - rule: self == oldSelf + message: Retained handoff intent is immutable + properties: + cell: {type: string, minLength: 1, maxLength: 63} + requestJSON: + type: string + minLength: 1 + maxLength: 1048576 + status: + type: object + x-kubernetes-preserve-unknown-fields: true 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/host/custody.yaml b/config/multiplane/host/custody.yaml new file mode 100644 index 00000000..327eff17 --- /dev/null +++ b/config/multiplane/host/custody.yaml @@ -0,0 +1,32 @@ +# Private allocation custody on the management host API. Only the shared +# lifecycle coordinator's custodian identity may read or write these Secrets; +# its token is minted by bootstrap and never stored in the source. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-system-private + annotations: + # Holds retained allocation custody. Never garbage-collect it. Same name + # and policy as the production manager's private namespace. + kustomize.toolkit.fluxcd.io/prune: disabled + fleet.datumapis.com/shared-with-standalone: "true" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-custodian, namespace: fleet-system-private} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-custodian, namespace: fleet-system-private} +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch, create, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-custodian, namespace: fleet-system-private} +subjects: + - {kind: ServiceAccount, name: fleet-custodian, namespace: fleet-system-private} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-custodian} diff --git a/config/multiplane/host/kustomization.yaml b/config/multiplane/host/kustomization.yaml new file mode 100644 index 00000000..b838ac56 --- /dev/null +++ b/config/multiplane/host/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - custody.yaml diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml new file mode 100644 index 00000000..858908e6 --- /dev/null +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -0,0 +1,19 @@ +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] + verbs: [get, list, watch, create] +--- +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..c77d1ed1 --- /dev/null +++ b/config/multiplane/karmada-members/members.yaml @@ -0,0 +1,34 @@ +# 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}" + 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..0610c3e5 --- /dev/null +++ b/config/multiplane/milo/base/milo.yaml @@ -0,0 +1,112 @@ +# 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), native arm64 image. + image: ghcr.io/milo-os/milo@sha256:ec90618ecc723d6e175fbf49bc14292fd930be3e0251acb161c1166e6224279f + 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..64abfc8f --- /dev/null +++ b/config/multiplane/milo/provider/kustomization.yaml @@ -0,0 +1,13 @@ +# 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 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/site/base/kro.yaml b/config/site/base/kro.yaml new file mode 100644 index 00000000..a6d759d7 --- /dev/null +++ b/config/site/base/kro.yaml @@ -0,0 +1,178 @@ +# 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, kro itself must hold that get permission. +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] +--- +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 +--- +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) == 1 && + object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && + r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && + has(r.resourceNames) && r.resourceNames == [variables.handoff])) + message: a worker Role may grant only get on its own handoff + - 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] diff --git a/config/site/base/kustomization.yaml b/config/site/base/kustomization.yaml new file mode 100644 index 00000000..064bf927 --- /dev/null +++ b/config/site/base/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - site.yaml + - kro.yaml + - reconcilers.yaml 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/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..d7f6e080 --- /dev/null +++ b/config/site/graph/rgd.yaml @@ -0,0 +1,223 @@ +# kro ResourceGraphDefinition for one selected local cell. For each delivered +# MachineAllocationHandoff 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. Management trusts only Karmada-reflected, +# journal-derived handoff status. +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 + scopedAsset: 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 + 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 intent for this cell, watched by kro. The workers re-validate + # the cell, name and exact request; 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}"] + # Per-operation identity and policy: each worker may read exactly its own + # handoff 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] + - 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 operation. The Job controller retries and + # replaces Pods; every Pod replays the same retained operation from the + # journal. Job completion is not readiness: only the observer publishes, + # and only management validates 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 journal lock + # is the second guard. + podReplacementPolicy: Failed + podFailurePolicy: + rules: + # Exit 65: fenced, conflicting or invalid authority. Retrying + # cannot change it; fail without another attempt. + - 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}", --scoped-asset, "${schema.spec.scopedAsset}"] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {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..ae051632 --- /dev/null +++ b/config/site/instance/dispatcher.yaml @@ -0,0 +1,19 @@ +# 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}" + scopedAsset: "${FLEET_SCOPED_ASSET}" + dispatch: ${FLEET_SITE_DISPATCH} 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/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..2ec7f2cf --- /dev/null +++ b/config/site/services/services.yaml @@ -0,0 +1,161 @@ +# 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} +--- +# 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: tcg} + - {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: journal 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: tcg} + - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + 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, from the journal only. +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}", --scoped-asset, "${FLEET_SCOPED_ASSET}", --interval, 10s] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + 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} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} diff --git a/docs/development/README.md b/docs/development/README.md index eba7743f..66164926 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -23,6 +23,14 @@ An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. It uses a disposable Kubernetes API and explicit local authority fixtures; it is not wired into the production manager. +The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes +that executor with native Milo project APIs and actual Karmada delivery. On the +selected cell it runs as [Flux-owned site Deployments and kro-created per-operation 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. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index faabba4d..97a26a28 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -361,11 +361,23 @@ Location implementation may use: - a Deployment or facility-edge DaemonSet for boot scripts and callbacks; - a private execution CRD for the delivered handoff; - Jobs for bounded Redfish, power, verification, and fencing actions; and -- KRO to create and order those local resources. - -Jobs must recover a retained provider operation before retrying. Job completion -does not by itself prove a remote effect. A KRO instance is derived state and -cannot replace the hub handoff, operation journal, or provider fence. +- KRO to create and order the per-operation resources: one bounded Job and its + scoped identity and RBAC for each delivered handoff. + +Long-lived location services, their policies and RBAC, and durable provider state +have one configuration owner: the environment's GitOps writer (Flux), not an +operation graph. An operation graph references them and cannot create, change or +delete them, so its lifecycle cannot remove a shared service or a provider +journal. Jobs must recover a retained provider operation before retrying. Job +completion does not by itself prove a remote effect. A KRO instance is derived +state and cannot replace the hub handoff, operation journal, or provider fence. + +The local multi-plane acceptance implements this pattern for a disposable +libvirt cell with kro v0.9.4. Flux owns the VM runtime Deployment, the boot +Deployment and Service, the journal-only status observer and the retained +journal volume. kro creates only per-handoff RBAC and bounded Jobs. See +[Kubernetes-native site execution](../../operations/site-execution.md). That is +local evidence for the contract above, not hardware qualification. ![Shared installation workflow and mode-specific execution](diagrams/installation-workflows.svg) diff --git a/docs/operations/README.md b/docs/operations/README.md index 02f356ee..a21ad1f7 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -14,6 +14,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Build and test locally or run the simulator | [Implementation commands](../development/README.md#build-test-and-run) | Behavior of the implemented code and synthetic provider | | Exercise allocation, install recovery, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | +| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md new file mode 100644 index 00000000..d0c03849 --- /dev/null +++ b/docs/operations/gitops.md @@ -0,0 +1,304 @@ +# Flux-reconciled local environment + +The [multi-plane acceptance](multiplane.md) installs every long-running service +the way a real environment would: each cluster runs its own Flux, and Flux +reconciles Helm releases and Kustomizations from one OCI source artifact. +That artifact is built from the current checkout, including uncommitted +changes. The harness no longer runs `helm install`, `kind load`, or +`kubectl apply` for any service, and no Milo API runs as a bare Docker container. + +This is an **implemented local composition**. It shows that the manifests, +dependency ordering, ownership and retention policies work under real Flux +controllers. It does not qualify production deployment: the seams are listed +under [what is not production](#what-is-not-production). + +## Ownership + +```text + run registry (registry:3.0.0, plain HTTP on the kind network) + ├── fleet-gitops:local OCI artifact: config/multiplane + config/site + │ + generated environment/ + └── fleet-site@sha256:… site image + ┌───────────────────┬──────────────┴─────────────┐ + platform cluster hub cluster (host) cell cluster + Flux v2.9.6 Flux v2.9.6 Flux v2.9.6 + ├ milo-provider ├ karmada (HelmRelease) ├ fleet-coordination (CRD, ns) + ├ milo-consumer-a ├ fleet-host (custody RBAC) ├ fleet-federation (member identity) + └ milo-consumer-b └ karmada-system/… ├ kro (OCI chart HelmRelease) + ├ fleet-karmada-coordination├ fleet-site-base (ns, Retain PVC, identities, + ├ fleet-karmada-api │ RBAC, kro grants, admission) + └ fleet-karmada-members ├ fleet-site-services (runtime, boot, observer, + (applied to the Karmada API│ boot Service; scoped identity) + through karmada-kubeconfig)├ fleet-site-graph (RGD; scoped identity) + └ fleet-site-dispatch (HandoffDispatcher; scoped) + │ + ▼ + kro: per-operation ServiceAccount, Role, + RoleBinding and worker Job only +``` + +| Surface | Writer | Never written by | +| --- | --- | --- | +| Flux controllers and sync objects (`flux-system`) | Bootstrap once, then each cluster's own Flux (`fleet-cluster` reconciles `environment//flux-system`) | — | +| Milo project API Deployments, etcd StatefulSets, PVCs, Services | Platform Flux (`milo-`) | Harness (it suspends the Kustomization before fault injection) | +| Karmada chart | hub helm-controller (`HelmRelease karmada`) | Harness (suspended during reflection faults) | +| Handoff CRD, management role, interpreter, member `Cluster`, `PropagationPolicy` on the Karmada API | hub kustomize-controller through the chart's `karmada-kubeconfig` | — | +| Private custody namespace and custodian identity (host) | hub Flux (`fleet-host`) | — | +| kro controller | cell helm-controller (`HelmRelease kro`) | — | +| Site namespace, StorageClass, journal PVC, service identities, observer RBAC, kro grants and admission policies | cell Flux (`fleet-site-base`) | kro does not manage these; its delete grants still cover service identities and coordination RBAC (see trust model) | +| Shared runtime, boot and observer Deployments, boot Service, worker-policy parameter | cell Flux as `fleet-site-services-reconciler` | kro (read only; verified by label, inventory and RBAC), harness (drift is injected, repair is Flux's) | +| `ResourceGraphDefinition fleet-handoff-dispatcher` | cell Flux as `fleet-site-graph-reconciler` | — | +| `HandoffDispatcher/dispatcher`, including `dispatch` | cell Flux as `fleet-site-dispatch-reconciler`, from a source revision | Harness (dispatch is a pushed revision; the graph-lifecycle fault suspends the layer first) | +| Per-operation `w-` ServiceAccounts, Roles, RoleBindings and Jobs | kro only, admission-checked | Flux (verified absent from every inventory) | +| `MachineAllocationHandoff` objects and their status | Management/Karmada (intent), site observer (status) | Flux, kro | +| Allocation custody Secrets | Shared lifecycle coordinator | Flux | +| Credentials: Milo static tokens and serving keys, ServiceAccount tokens, Karmada member Secret | Bootstrap credential enrollment | Any source revision | + +Fleet and Karmada stay the operation authority and delivery path. Nothing per +allocation is written to the source: handoffs, Jobs and results never appear +in an artifact or a Flux inventory. + +## Bootstrap boundary + +`hack/multiplane/run.sh` performs only these imperative steps, each a bounded +phase: + +1. **`topology`** (`topology.sh`) creates the run registry and three kind + clusters with memory caps, the cell's registry mirror configuration and + the reversible inotify adjustment. It installs no service. +2. **`site-image-push`** pushes the built site image; the cell pulls it by digest. +3. **`flux-tools`** downloads the Flux v2.9.6 CLI and `install.yaml` and + verifies both against SHA-256 values pinned in `hack/multiplane/flux.py`. +4. **`flux-source`** stages revision 1 and pushes it with + `flux push artifact --reproducible`. +5. **`flux-bootstrap-`** applies that revision's Flux components, + waits for the CRDs, then applies the two sync objects (`OCIRepository + fleet-gitops`, `Kustomization fleet-cluster`). This is what + `flux bootstrap` commits as `gotk-components.yaml` and `gotk-sync.yaml`. The + apply uses kustomize-controller's field manager, so Flux takes these + objects over without a second owner. From then on each cluster's Flux + reconciles its own controllers from the source. +6. **Credential enrollment.** `milo.py` writes each Milo API's + `milo-apiserver-private` Secret into the namespace Flux created. `roles.py` + mints 24-hour tokens for the Flux-created management, custodian and + federation ServiceAccounts, and writes the Karmada member Secret. +7. **Tenant fixture bootstrap.** `milo.py` creates the Milo Projects, + static-token RBAC grants and metal CRDs inside each project API, and the + management CLI seeds catalog fixtures. These are data inside running + services, not service installation, and are labelled synthetic fixtures. + +Everything else is a Flux reconciliation of a pushed revision. + +## Source revisions + +`flux.py stage` copies `config/multiplane` and `config/site` from the +checkout into `/gitops/r`. It stages the verified `install.yaml` +with `config/multiplane/flux/components.yaml`, unchanged, as +`environment/flux-components`, and adds a generated `environment/` +per cluster. The environment holds the +sync objects and a non-secret `fleet-environment` ConfigMap: cell name, +member endpoint, scoped asset, digest-pinned site image, dispatch flag and a +revision marker. Before pushing, it refuses any file that contains a `Secret` +manifest, a private key, a token-shaped field, or any credential retained in +the run state. It also requires every environment to render with `kustomize`. +The per-file SHA-256 list is copied to `evidence/gitops-r.SHA256SUMS`. +`flux-revisions.json` records the digest, Git HEAD and dirty-checkout content +hash. + +| Revision | Purpose | +| --- | --- | +| r1 | Platform services: Milo, Karmada, host RBAC, Karmada API configuration, kro, site base and graph | +| r2 | Adds the shared site services and the `HandoffDispatcher` instance with `dispatch: false` once the scoped asset is known | +| r3 | `dispatch: true`, pushed while the hub is paused; the cell's Flux applies it from the registry | +| r4 | Fail-closed: kro chart pinned to a digest no registry serves | +| r5 | Recovery: pinned kro chart restored | +| r6 | Retention: the journal PVC removed from the source | +| r7 | Retention: the PVC restored to the source | + +## Versions and pins + +| Component | Pin | Why | +| --- | --- | --- | +| Flux | v2.9.6: `install.yaml` SHA-256 `9c1fda7e…4251c`; CLI `flux_2.9.6_darwin_arm64.tar.gz` SHA-256 `7008a758…c126`; controllers by digest in `config/multiplane/flux/components.yaml` (source v1.9.6, kustomize v1.9.6, helm v1.6.5, notification v1.9.4) | v2.10.0 (2026-10-26) requires Kubernetes ≥ 1.35.2, and the exercised kind node is v1.35.0. v2.9.6 (2026-10-01) is the newest patch of the newest compatible minor, and datum-cloud/infra staging runs v2.9.5. Image automation and source-watcher are removed; notification-controller is kept so controller events have a receiver. | +| Source | OCI artifact `fleet-gitops:local` in the run registry, `registry:3.0.0@sha256:6c5666b8…457e` | The Flux OCI pattern Datum uses for `*-kustomize` bundles, with no external publication of uncommitted changes | +| Karmada | chart v1.16.0 from `HelmRepository` `raw.githubusercontent.com/karmada-io/karmada/master/charts`; chart archive SHA-256 `773ab194…34fe` verified in Flux's HelmChart artifact | Same chart as the connected test-infra federation. The repository and release shape follow datum-cloud/infra `infrastructure/karmada`. The chart's floating `cfssl` and `kubectl` hook images are now pinned by index digest. | +| kro | `OCIRepository` `oci://registry.k8s.io/kro/charts/kro` at manifest digest `sha256:4e8de4d3…a67c` (chart layer `ceeb6307…`), image `v0.9.4@sha256:eaf9fbad…` | Unchanged from [site execution](site-execution.md#versions); `OCIRepository` as a chart source is the Flux-native way to pin an OCI chart by digest | +| Milo | `ghcr.io/milo-os/milo@sha256:ec90618e…` (v0.32.5, arm64); etcd `registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11c…` | Same Milo build as before, now as Flux-managed workloads | + +## Dependency, health and upgrade policy + +- **Dependencies.** Child Kustomizations use `dependsOn`, so a dependent is + applied only when its dependencies are Ready at their current generation. + The order is: Karmada → API coordination → Karmada API → members; and on + the cell: coordination → federation; coordination → site base → shared + services; kro and site base → graph; graph, services and federation → + dispatcher. Shared site infrastructure does not depend on kro. The only + controller tuning is `--requeue-dependency=10s` (default 30s) on + kustomize-controller and helm-controller, so a revision ripples through the + site chain faster. Flux manages that setting on its own + controllers like any other source change. The Helm + releases are wrapped in Kustomizations with `wait: true`, so a release and + its chart source must both be healthy before anything depends on them. +- **Health.** `wait: true` everywhere, with CEL `healthCheckExprs` for kinds + kstatus cannot judge: + - RGD `status.state == 'Active'`; + - HandoffDispatcher `status.state == 'ACTIVE'`, which kro reports only when + the Flux-owned runtime, boot and observer Deployments and boot Service it + references are ready; + - Karmada `Cluster` Ready; + - PVC `Pending` or `Bound`, because the class is `WaitForFirstConsumer`. + + The Milo Deployments, etcd StatefulSets, kro and the shared site Deployments + use kstatus. +- **CRDs.** The handoff CRD Kustomizations use `prune: false` and the CRD is + annotated `prune: disabled`, as datum-cloud/infra does for Karmada CRDs. + kro installs its CRDs on install and skips them on upgrade. +- **Helm upgrades.** kro: `driftDetection: enabled`, remediation retries with + rollback. Karmada: `driftDetection: warn`, as in datum-cloud/infra, because + its pre-upgrade hooks regenerate certificates. One upgrade retry, then + rollback. Both use `upgrade.crds: Skip`. +- **Scoped identities.** Three site layers impersonate ServiceAccounts with + narrow grants: + - `fleet-site-services`: Deployments, Services and ConfigMaps in `fleet-site`, + plus read access for health checks; + - `fleet-site-graph`: `ResourceGraphDefinitions` only; + - `fleet-site-dispatch`: `HandoffDispatchers` in `fleet-site` only. + + None of these identities can directly write Jobs, volumes, RBAC, admission policy or + handoffs. Source authors remain trusted. The services identity can create a + Deployment using the observer ServiceAccount and thereby obtain its status-write + authority, or create a privileged workload. The services layer chooses the + privileged runtime image. Graph authors choose the worker template within the + admission policy. The same source controls the admin-applied site base. This + is not a sandbox for untrusted site revisions; see the + [trust model](site-execution.md#ownership-and-trust-model). The other + Kustomizations use the controller identity, as in a standard single-tenant + bootstrap. + +## Retention and pruning + +Root and child Kustomizations prune. These objects are annotated +`kustomize.toolkit.fluxcd.io/prune: disabled`, so removing them from the +source, or deleting their Kustomization, never deletes them: + +- the site and coordination namespaces; +- the handoff CRD; +- `fleet-site-retain` and the journal PVC; +- the RGD and the `HandoffDispatcher`; +- the private custody namespace; +- the Karmada `HelmRelease` and member `Cluster`; +- each Milo namespace. + +The shared Deployments and boot Service are prunable by their own layer only: +removing one from the source deletes it, which stops new work and, for the runtime, +any running guest. That leaves operations Unknown rather than released. No graph +or instance lifecycle can delete them. + +The StorageClass and PVC are also `ssa: IfNotPresent`: Flux creates them once +and never updates them. A reconcile, a controller restart or a source change +therefore cannot replace the journal volume. A fresh journal would let replayed +handoffs be admitted as new operations; see the +[known limitations](multiplane.md#known-limitations-of-the-local-mvp). +Retiring a site or unjoining a member is an ordered manual procedure, as in +datum-cloud/infra's Karmada runbook. + +Pruning is still not cancellation. A source revision that changes `dispatch` +has the same effect as the +[documented kro pruning behavior](site-execution.md#lifecycle-and-retention). + +## Acceptance coverage + +These phases run in addition to the existing scenarios; see +[acceptance phases](multiplane.md#acceptance-phases). + +| Phase | Asserts | Evidence | +| --- | --- | --- | +| `flux-verify` | Each cluster's source is at the pushed digest. Every expected Kustomization and HelmRelease is Ready at the current generation and revision. The kro chart source is at the pinned digest, the Karmada chart artifact matches the pinned SHA-256, and controllers are digest-pinned. Ownership audit: the services, graph and dispatch inventories are exactly their objects. Each shared Deployment, Service, ConfigMap, ServiceAccount, Role, binding, policy and the PVC carries its one Flux layer label, is in that inventory, and has no kro label or owner reference. kro has written nothing before dispatch. No Job, Pod, handoff, Secret or `w-` object is in any Flux inventory. Shared layers do not depend on kro. Protected objects carry `prune: disabled`. | `flux-verify.json`, `flux-initial.json` | +| `rbac` | The revoked observer RoleBinding is restored by kustomize-controller under a new UID, not by the harness. As kro's identity, 8 worker-scoped verbs are allowed and 15 others denied, including Deployment, Service, PVC and ConfigMap writes, Jobs outside `fleet-site`, Secrets and handoff status. Server-side dry runs admit worker-shaped objects. They deny, by policy, a Job running as the observer, a privileged Job, another image, a hostPath volume and the host network; a broader Role; a RoleBinding to another Role; and a ServiceAccount outside the worker set. | `flux-rbac-restore.json`, `kro-rbac.json` | +| `flux-graph-lifecycle` | With the install terminal and its workers present, the ownership audit passes. The dispatcher's layer is suspended and the instance deleted. kro removes exactly that handoff's Job, ServiceAccount, Role and RoleBinding. Every shared object, the RGD and the StorageClass keep their UIDs, and the PVC/PV, journal and custody are unchanged. Resuming lets Flux recreate the instance under a new UID, and the recreated Job replays a verified no-op (exit 0). Orphaned terminal Pods are listed. | `flux-graph-lifecycle.json` | +| `partition`, `partition-readiness` | Consumer A is stopped by suspending its Kustomization and scaling it to zero. The suspension, UID, generation, zero replicas and no Pods survive the platform root reconciling r3. Resuming leaves Flux to restore it. | `flux-partition.json`, `flux-reconciles.json` | +| `dispatch` | Dispatch arrives as r3 through the cell's Flux while the hub is paused | `flux-revisions.json` | +| `heal` | Flux on every cluster acknowledges fresh requests and is Ready at the current revision after both node restarts | `flux-reconciles.json` | +| `flux-drift` | Five out-of-band changes are each corrected by Flux, with journal, Jobs, PVC/PV and custody unchanged. helm-controller restores the kro Deployment scaled to 0 (same UID). kustomize-controller recreates the Karmada interpreter deleted on the Karmada API, and reverts a widened `fleet-site-kro` grant. As `fleet-site-services-reconciler`, it recreates the deleted shared boot Service under a new UID with the same fixed ClusterIP, ports and selector, and no kro label. It also restores the shared observer Deployment scaled to 0 (same UID). The dispatcher returns to `ACTIVE` and the ownership audit passes. | `flux-drift.json` | +| `flux-restart` | Every Flux controller Pod on the three clusters is deleted. Each source, Kustomization and HelmRelease then acknowledges a request token issued after the restart. No Helm release revision, inventory, Job, journal or custody changes. | `flux-restart.json`, `flux-reconciles.json` | +| `flux-fail-closed` | r4 leaves the kro chart source and Kustomization not Ready. The graph and dispatcher report `DependencyNotReady` and their new revision is not applied (marker unchanged). The site base and shared services layers are Ready at r4, with every shared object UID and Deployment generation unchanged. The running kro Deployment and site are untouched. r5 converges. | `flux-fail-closed.json` | +| `flux-retention` | r6 drops the PVC from the inventory without deleting it (same PVC/PV UID, journal and custody). r7 re-adopts the same claim. | `flux-retention.json` | +| `flux-final` | All three clusters are at the final revision with nothing suspended, and the ownership audit passes with the cleanup workers present | `flux-final.json`, `flux-ownership-final.json` | + +## What is not production + +- **Source transport.** A plain-HTTP, unauthenticated, unsigned registry on the + disposable kind network (`OCIRepository.spec.insecure`). Production needs TLS, + registry credentials and `spec.verify` (cosign or notation). +- **Credentials.** Credentials are enrolled imperatively. They are never in + the source and are scanned for, but there is no SOPS, External Secrets or + workload identity, and tokens are not rotated. +- **Cluster and Milo topology.** Three kind clusters on one VM, not + independent failure domains. Milo project APIs are Flux-managed workloads on + one platform cluster, with static-token RBAC, self-signed serving keys and + fixture Projects. This is not Milo's project provisioning, IAM or HA + storage. +- **Flux lockdown.** The Karmada API is reconciled with the chart's admin + kubeconfig. datum-cloud/infra uses a dedicated, secretless Flux identity + there. Multi-tenancy lockdown flags, such as `--no-cross-namespace-refs` and a + default ServiceAccount, are not set; only the site layers impersonate scoped + ServiceAccounts. +- **Upstream sources.** Karmada's HelmRepository and the kro chart come from + upstream over the internet. No mirror or signature check is configured. + Pins are verified in evidence (Karmada) or enforced by digest (kro). +- **Acceptance driver.** The management phase CLI (`fleet-multiplane-host`) + remains an explicit acceptance driver run on the host. It is not a deployed + manager. + +The `summary.json` qualification keeps `productionAuthority` and +`productionEquivalence` false. + +## Review follow-up: suspension and reconcile evidence + +Fault injection patches `spec.suspend` with field manager +`fleet-fault-injection`, rather than a `kubectl`-prefixed manager whose fields +Flux may take over. Before resuming, the harness requires the same suspended +object UID and generation, zero Deployment replicas and no matching Pods. +`flux-partition.json` and `flux-reflection-suspension.json` retain those checks. +This prevents a source reconciliation silently ending the injected fault. +While consumer A is still suspended, `partition-readiness` also forces the +platform's source and root sync to reconcile the dispatch revision (r3) with +fresh request tokens. The guard then records the root's applied revision +(`rootReconciledDuringFault`) beside the unchanged suspension receipt. + +Convergence waits require the source and each requested Kustomization to report +`status.lastHandledReconcileAt` equal to its fresh request token, as well as +current readiness and revision. Restart checks additionally require those +receipts from both HelmReleases. `flux-reconciles.json` and `flux-restart.json` +record the acknowledgements. Old Ready status is insufficient. + +A parent Kustomization's server-side apply can remove a `kubectl annotate` +request from the child it manages before any reconcile handles it. A root sync +also applies its own object. In the first fresh run, the cell root lost its only +request this way and the wait timed out. When the request annotation is gone +and the object has not acknowledged it, the wait now issues a new token and +requires that exact token to be acknowledged. `lostRequestsReissued` counts +these per object. A reissue never accepts an older acknowledgement. + +**Bootstrap gating evidence.** The `flux-platform` wait samples the cell and +the hub on every poll (`flux.py wait --observe`), not only the cluster it is +waiting on. Observations are keyed by whether the dependent had already applied +the revision. `flux-verify` requires a `DependencyNotReady` observation on both +the cell and the hub with nothing applied: no applied revision and an empty +inventory. A dependent seen gated *after* applying r1 means a dependency +re-reconciled at the same revision on a fresh request. It is recorded as +`bootstrapRegatedAfterApply` and is neither evidence nor a fault. An inventory +with no applied revision, or another applied revision during bootstrap, fails. +The earlier check sampled the hub only after the cell converged. It treated any +gated observation with r1 applied as "applied before its dependency was Ready", +which it cannot show. The second fresh run of this change, +`/tmp/fleet-multiplane.XjeuF8`, failed on that false positive: its first hub +sample came after the hub had applied r1. That run had created no allocation, +handoff or effect, and was discarded with `teardown.sh --discard-unknown`. + +The [fresh acceptance run](multiplane.md#flux-acknowledgement-acceptance-2026-11-15) +established these stronger claims. They supersede the +[earlier run's](multiplane.md#flux-reconciled-acceptance-2026-11-15) weaker +suspension and restart assertions. That run established PXE results and final +convergence, but not that consumer suspension persisted or that every object +reconciled after the controller restart. diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 45d7e3b5..06ba44f7 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -16,7 +16,9 @@ For a local runtime without reliable x86 KVM, explicitly select software executi DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh ``` -`task local-vm:acceptance` runs the same TCG command. +`task local-vm:acceptance` runs the same TCG command. For the multi-plane composition +of this provider with Milo and Karmada, use the one-command +[multi-plane acceptance](multiplane.md) harness instead. The named Docker context must already identify your dedicated disposable runtime. TCG builds a native amd64 or arm64 Debian libvirt/QEMU runner and boots the same diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md new file mode 100644 index 00000000..bb097fff --- /dev/null +++ b/docs/operations/multiplane.md @@ -0,0 +1,965 @@ +# Local Milo, Karmada and PXE acceptance + +This opt-in harness runs native Milo project routing, actual Karmada delivery and +status reflection, and the local VM executor through the existing allocator and +installation lifecycle. On the selected cell, execution runs as Flux-owned +Kubernetes Deployments and kro-created per-operation Jobs; see [Kubernetes-native site execution](site-execution.md). +Every long-running service is installed by each cluster's own Flux from a source +artifact built from the checkout; see [Flux-reconciled local environment](gitops.md). It is not enabled by the production manager or any +production overlay. Production authority and deployment equivalence remain +**unqualified**. + +Read the [writer placement contract](../architecture/README.md#control-plane-placement-and-writers), +[pinned design sources](../architecture/design.md#source-proposals), and +[local VM contract](local-vm.md) first. New multi-plane files implement this +composition. The shared lifecycle adds only the read-only +`Coordinator.ClaimReleased` custody query, and the executor interface documents +exact-request replay and its narrow not-found-plus-Unknown lookup contract. + +## Topology and versions + +| Surface | Local implementation | Writer | +| --- | --- | --- | +| Provider project | Milo v0.32.5 native `/projects/provider/control-plane` route; dedicated API Deployment and etcd StatefulSet with its own PVC on the platform kind cluster, reconciled by Flux | Bootstrap fixture supplies definitions and observations; allocator retains exclusive custody | +| Consumer A / B | Two independently restartable Milo v0.32.5 Deployments and etcds, one Flux Kustomization each; native project routes; both use namespace `default` and Machine name `allocation` | Separate customer credentials create/watch requests; management writes public status | +| Private allocation custody | `fleet-system-private` Secrets on the management host Kubernetes API | Shared lifecycle coordinator, with its own scoped credential | +| Coordination intent | Karmada v1.16.0 API (hub Flux `HelmRelease`), separate from the host Kubernetes API | Management credential creates immutable handoffs; cannot write status | +| Selected cell | Separate kind Kubernetes API running its own Flux, the Flux-owned shared site services, kro v0.9.4 and the `HandoffDispatcher` graph | Karmada delivers intent; the site observer ServiceAccount is the only local status writer | +| Reflected results | Karmada interpreter aggregates each member's identity and observation | Karmada; management validates before projection | +| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG | One bounded kro-created worker Job per handoff invokes `executor.Client`; provider persists exact requests and boot evidence on a retained, Flux-owned PVC | + +The platform integration choices were discovered in these connected sources: + +- Fleet's `go.mod` pins Milo **v0.32.5**. The local Milo checkout reviewed was + `3c2a160d6d5614d6dc7bf119b8d022fc641c5d4f` (v0.32.5 plus later commits). + Its `pkg/server/filters/projects.go` implements project path routing and + `internal/apiserver/storage/project/mux.go` uses `/projects/` etcd + prefixes. The harness runs the released v0.32.5 image, not that dirty checkout. +- `datum-cloud/test-infra` federation checkout + `3619e71d4686c3d1ead01f08a1136f7d272b3344` pins the Karmada Helm chart to + **v1.16.0**. Its Taskfile and `components/karmada/values.yaml` supplied the + bootstrap model. This harness keeps fsync enabled; it does not adopt that + checkout's `unsafe-no-fsync` tuning or insecure TLS kubeconfig rewrites. +- The connected Compute federation interpreter supplied the supported Karmada + `statusReflection` / `statusAggregation` customization interface. Fleet's + interpreter preserves *all* reflected replicas and their Karmada cluster + names, rather than accepting the first result. +- kind nodes use **v1.35.0**, digest-pinned to the already exercised local VM + node image. Karmada's chart pins its own API/controller images to v1.34.1 and + its etcd to 3.6.0-0. Milo's local etcd uses 3.5.16-0. The Milo arm64 image is + digest-pinned in the launcher. Some upstream Helm hook images still use + floating tags; this is a remaining reproducibility seam. +- kro **v0.9.4** is installed on the cell by a Flux `HelmRelease` from its + official OCI Helm chart, pinned by manifest and image digest. The newer v0.10.0 was five days old and is + not used. See [versions](site-execution.md#versions). + +- Flux **v2.9.6** runs on each of the three kind clusters; see + [versions and pins](gitops.md#versions-and-pins) for why not v2.10.0. + +Independent local Milo roots make project process/storage failures independently +injectable without a hand-written proxy. Each is a Flux-managed Deployment with +its own etcd StatefulSet and volume on a dedicated platform kind cluster, not a +bare Docker container. **This is still a local placement seam:** it is not the +platform's complete root/ProjectControlPlane provisioning machinery, Kyverno +orchestration, shared root IAM, or project retirement path. Milo's +native project routing and project storage are real. Separate roots and etcds +prevent namespace-based isolation shortcuts. The management process runs on the +host, and its private storage shares host infrastructure with Karmada, while +using a distinct API endpoint, namespace and credential. + +## Run + +Prerequisites: Go from `go.mod`, Python 3.12+, OpenSSL, Docker, kind, kubectl, +kustomize, curl, Git, Colima, network access to GitHub releases, `ghcr.io`, +`registry.k8s.io` and Docker Hub, and the task-owned native arm64 VZ Colima profile `fleet-acceptance-tcg` +with 4 CPUs, 8 GiB memory, amd64 container emulation, and at least 12 GiB free in +its Docker data root. Never use `fleet-e2e-x86`. The harness never changes the +global Docker context, never creates a Colima profile, and never stops or deletes +another run's containers. Stopped diagnostics from earlier runs are left alone; +only *running* `fleet-local-*`/`fleet-mp-*` containers block a launch. + +One command runs preflight, a fresh topology, every acceptance phase, sanitized +evidence, and owned-resource teardown: + +```sh +task multiplane:acceptance +# equivalent: +FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh +``` + +`FLEET_MULTIPLANE_INOTIFY=1024` (set by the task) is the explicit opt-in for a +reversible, nonpersistent `fs.inotify.max_user_instances` adjustment inside the +task Colima VM only; the original value is restored at teardown or stop and both +values are recorded in `sysctl.json`. Options: + +| Option | Effect | +| --- | --- | +| `--preflight-only` (`task multiplane:preflight`) | Run every check below, create nothing, exit | +| `--bootstrap` | If the existing `fleet-acceptance-tcg` profile is stopped, start it with its saved configuration | +| `--keep` | After a pass, stop instead of delete this run's containers | +| `--leave-running` | After a failure, leave containers running for live diagnosis instead of stopping them | +| `--skip-readiness-tests` | Skip the implementation test gate (diagnosis only) | + +Preflight records `evidence/preflight.json`. Prerequisite checks cover tools, +the exact Docker context socket, reachability, architecture, memory, CPUs, free +disk, amd64 emulation, inotify, and concurrent Fleet runtimes. Readiness checks +require the CLI subcommands and location-denial error the harness drives, then +run `go test -race -count=1 ./internal/coordination ./internal/multiplane +./internal/localvm ./cmd/fleet-multiplane`. Failing either blocks before any +resource is created. + +Exit codes and `evidence/result.json` status: + +| Exit | Status | Meaning | Resources | +| --- | --- | --- | --- | +| 0 | `passed` | Every phase and evidence assertion passed | Owned containers, clusters and image tag deleted; private credentials removed | +| 1 | `failed` | A phase or assertion failed | Owned containers stopped, state retained, custody Unknown | +| 2 | `preflight-failed` | A local prerequisite is missing | None created | +| 3 | `blocked` | Implementation readiness gate failed | None created | +| 4 | `timeout` | A bounded phase expired; its process group was terminated | Stopped and retained as for 1 | +| 64 | `usage` | Invalid option | None created | + +The full run uses three kind nodes (platform, hub, cell), a registry, Flux on +each node, three small Milo/etcd pairs, Karmada and kro. Node caps are +2300 MiB (platform), 2600 MiB (hub), 4400 MiB (cell) and 128 MiB (registry). +They total about 9.2 GiB and deliberately overcommit the 8 GiB VM, because +actual usage is much lower. In a debug run the cgroup peaks were 1.99 GiB for +the platform node (under reclaim pressure at the earlier 1900 MiB cap), 2.06 GiB +for the hub and 1.6 GiB for the cell after its restart; VM usage was about 4 GiB +after the install. Re-measure with `docker stats` and each node's +`memory.peak` if you change workloads. The cell holds the cell API, Flux, kro and the site, including the +VM runtime Pod, whose limit is 3 GiB. Each Milo API has a 384 MiB cap. The VM +guest is configured with 2 GiB and 2 vCPUs, using TCG. A 2.5 GiB provider cap +caused an installer OOM in an earlier fresh run. Evidence fails on any OOM kill +in the runtime Pod, any kind node, or the site, kro, Flux, Karmada or Milo containers. Expect 20 to 60 minutes, +mostly bootstrap, image pulls and builds. Every phase has an explicit bound. +Do not run another full acceptance topology concurrently on an 8 GiB VM. + +### State and evidence layout + +All containers have one fresh `fleet-mp-` prefix. The command prints a +mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with +`FLEET_MULTIPLANE_STATE_ROOT`). Only its `evidence/` subdirectory is shareable: + +| File | Content | +| --- | --- | +| `result.json` | Final status, exit code, failed phase, every phase record, retained containers, custody statement | +| `phases.jsonl` | One record per bounded phase: name, status, exit code, bound, duration | +| `preflight.json` | Each prerequisite and readiness check | +| `summary.json` | Pass only: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags | +| `flux-verify.json`, `flux-initial.json`, `flux-rbac-restore.json`, `flux-drift.json`, `flux-graph-lifecycle.json`, `flux-restart.json`, `flux-fail-closed.json`, `flux-retention.json`, `flux-final.json`, `flux-ownership-final.json`, `flux-reconciles.json`, `flux-partition.json`, `flux-reflection-suspension.json`, `gitops-r.SHA256SUMS` | Flux source revisions and digests, Ready/generation/revision of every Kustomization and HelmRelease, inventories and single-writer ownership, and each GitOps scenario ([details](gitops.md#acceptance-coverage)) | +| `kro-rbac.json` | kro's allowed and denied verbs and each admission probe's outcome | +| `kubernetes-execution.json` | kro version, image and RGD/instance state; Flux-owned site Deployments; retained volume identity; every worker Job's UID, conditions, Pods, exit codes and policies; per-operation RBAC | +| `interrupt.json`, `lifecycle.json`, `delivery-faults.json`, `wrong-location.json` | Scenario-specific observations, no secrets | +| `source-SHA256SUMS`, `binary-SHA256SUMS`, `image-id`, `sysctl.json`, `teardown.json` | Tested inputs and teardown record | + +Before reporting, the harness scans `evidence/` for every retained static token, +ServiceAccount token (including the short-lived observer and worker probe +tokens), kubeconfig client key, fence and boot capability, and +redacts and fails on any match. Outside `evidence/`, `logs/.log` keeps +each phase's full output and the kubeconfigs, tokens, journals and binaries +remain private. Never publish the state directory itself. + +### Acceptance phases + +`hack/multiplane/acceptance.sh` lists the ordered phases; `steps.sh` implements +the harness-side ones and `k8s_evidence.py` records the Kubernetes facts. Before +acceptance starts, the run does the following: + +- builds the current source and the site image, and verifies its binary checksum; +- verifies the pinned Flux CLI and install manifest; +- creates the run registry and the platform, hub and cell kind clusters, and + pushes the site image (the cell pulls it by digest); +- publishes source revision 1 and bootstraps Flux on each cluster (the + [bootstrap boundary](gitops.md#bootstrap-boundary)). Flux then installs + Milo, Karmada, host RBAC, the Karmada API configuration, kro, the site base + and the graph in dependency order; +- enrolls credentials and seeds fixtures; +- publishes revision 2, which adds the shared site services and the + `HandoffDispatcher` with dispatch disabled. `site.sh check` requires the + following: + - the runtime, boot and observer Deployments Available from the published + digest, each labelled as owned by the Flux `fleet-site-services` layer; + - the boot Service at its fixed ClusterIP; + - the dispatcher reporting the same worker image; + - the volume `Retain`; + - no worker Job; +- runs `flux-verify`. + +The phases are then: + +1. **Native Milo routing and RBAC.** Customer create/watch, with equal namespace and request + names in separate project APIs. Exact Project and namespace UIDs distinguish + lifetimes. `rbac` verifies against real API servers that the site observer + ServiceAccount cannot create objects, write handoff specs, delete intent, read + Secrets or create Jobs. It also checks forbidden project and hub writes, and + that revoking the observer RoleBinding denies its reads. The cell's Flux, + not the harness, then restores the binding. Finally, as kro's own identity, + it proves the narrowed grant and the admission policies on kro's writes + ([trust model](site-execution.md#ownership-and-trust-model)). +2. **Contention.** Two consumers request one provider capacity. One binding + succeeds; `verify-contention` independently reads Bound for A and + Pending/InsufficientCapacity for B. +3. **Retained admission before effects.** Installation admission retains core + authority and inputs, then immutable hub intent, before any effect. + `await-delivery` requires the following: + - exactly one Karmada-delivered handoff; + - kro reporting that handoff in `HandoffDispatcher.status.deliveredHandoffs`; + - no cell status and no worker Job. +4. **Partition.** Suspend consumer A's Flux Kustomization, stop its API and pause + the hub. `dispatch` then publishes revision 3, which sets `dispatch: true`. + The cell's own Flux reconciles it from the registry with no hub access. kro + creates the per-operation ServiceAccount, Role, RoleBinding and Job from its + local replica. +5. **Pod interruption.** `interrupt-pod` waits until the provider journal shows + the install `installer-started` *and* its libvirt domain running. It then + force-deletes the worker Pod with no grace period. It requires: + - no local result; + - the Job controller to record the lost Pod and start a replacement in the + same Job; + - the same unfinished operation. +6. **Job interruption.** `interrupt-job` deletes the whole worker Job as soon as + the replacement exists, still mid-install. kro must recreate the Job under + a new UID for the same operation. +7. **Exact resume.** `resume` requires the recreated Job to be `Complete` with + one succeeded Pod, and the observer to publish `Succeeded` from the journal. + The journal must hold exactly one install. Evidence later proves exactly one + firmware-network installer start followed by exactly one disk-only start. + It uses libvirt's append-only QEMU log, plus one `sfdisk`, one installer + receipt and one disk-boot receipt in the guest serial logs. `worker-rbac` + then proves the worker token can read only its own handoff: no list, no + other names, no status or spec writes, no Secrets, no site writes. +8. **Readiness under partition.** The platform's root sync first reconciles r3 + while consumer A stays suspended at the same UID and generation, with no + Pods (`flux-partition.json`). Consumer A's Kustomization is then resumed and + Flux restores its API. The install Job is + `Complete` but public Ready must still be False while the hub is + disconnected. Job completion is not readiness. +9. **Heal and project.** Restart the hub and the cell node; the cell restart + recreates every site Pod from the retained volume. Flux on every cluster + must return to Ready at the current revision. Karmada reflects the + result, and management validates the following before public projection: + - the exact selected cell, request and operation; + - allocation, asset, epoch and fence; + - input digest and observation freshness. + + Installation is repeated to confirm idempotent recovery. +10. **Pod and Job lifecycle.** `lifecycle` recreates the runtime, boot and + observer Pods and deletes the completed install Job; kro recreates the Job, + which replays a verified no-op. The following must be unchanged: + - journal bytes; + - QEMU start count; + - PVC/PV identity and `Retain` policy; + - domains; + - consumer A's Ready/Bound allocation. + + The restarted observer must republish. + + The GitOps phases follow: + - `flux-graph-lifecycle`: deleting the dispatcher removes only kro's + per-operation objects, and shared services and storage are untouched; + - `flux-drift`: Flux corrects drift, including the shared boot Service and + observer; + - `flux-restart`: controllers restart without duplicate effects; + - `flux-fail-closed`: a broken kro release blocks only the dispatcher + layers; + - `flux-retention`: the journal volume is retained when its claim is + removed from the source. + + See [acceptance coverage](gitops.md#acceptance-coverage). +11. **Invalid and stale results.** With the Karmada `HelmRelease` suspended and its controller stopped, bootstrap + credentials substitute one attribute of the real reflected result at a time: + wrong cell, stale, future, duplicate replicas, wrong intent digest, wrong input + digest, wrong operation ID, incomplete phase, and missing reflection. Management + must reject each. This is fault injection, not a replacement status relay. +12. **Cleanup and reuse.** Cleanup goes through the same federation path and + kro-created Jobs, with synthetic quota settlement. `release-status-a` + requires consumer A's Machine to be Released with Ready False, no + `currentInstallationRef`, and no Fleet finalizer. Consumer B then reuses the + capacity in epoch 2 and must show Bound. +13. **Delivery faults.** `delivery-faults` creates three cell-local handoffs + with cell bootstrap credentials: + - the epoch-1 install under a second name; + - a wrong-cell intent; + - a stale epoch-1 replay. + + Each kro-created Job must fail once with exit 65 by `podFailurePolicy`. + The journal must be unchanged, no status may appear, consumer B must stay + Bound, and kro must prune them once deleted. After B's release, + `release-status-b` repeats the released checks for B. +14. **Wrong location.** With capacity free, the consumer A customer recreates its + request with `locationRef: remote-elsewhere`. Allocation must fail with the + location-not-served error. Private custody Secret names/UIDs/resourceVersions, + the provider journal bytes, and the Machine's finalizers and status must be + unchanged. Free capacity rules out contention as the reason for denial. +15. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the + boot Service are denied after closure. Evidence requires all of: + - PXE mode, one install and two cleanups, epochs 1 and 2; + - completed broker writes and a DHCP lease for the installer NIC; + - network-only installer XML, and disk XML with no NIC or direct kernel; + - closed boot admission, no remaining domain or disk; + - kro-created, `Complete` worker Jobs for exactly the one install and two + cleanups, each with one successful Pod; + - zero OOM kills. +16. **Final convergence and teardown.** `flux-final` requires all three + clusters at the last revision with nothing suspended, and repeats the + single-writer ownership audit. After a pass, only exact-prefix resources are deleted, the + inotify value is restored, and private credentials are removed. + +### Failed or interrupted runs + +Failures stop this run's exact containers (never delete them) and retain the full +private state; execution and custody are **Unknown**. `result.json` names the +failed phase and the retained containers. Stopping is not release evidence: + +```sh +hack/multiplane/stop.sh /tmp/fleet-multiplane.REPLACE # stop only; idempotent +hack/multiplane/teardown.sh /tmp/fleet-multiplane.REPLACE --discard-unknown +``` + +`teardown.sh` without `--discard-unknown` refuses unless `summary.json` records +a pass. `--discard-unknown` is an explicit human decision after inspection: it +deletes the same exact-prefix resources, keeps every private file, and records +in `teardown.json` that it is not release evidence. Neither script touches other +prefixes. The original limit of 128 inotify instances was insufficient for this +API count: the real Karmada webhook exited with `too many open files`. The bounded +value 1024 resolves that local prerequisite. + +Offline harness tests run in CI and locally with `task multiplane:test-harness`. +They use fake runtime tools to cover preflight outcomes, Flux source staging +(credential refusal, revision variants, rendering), push records, reconcile waits +(stale acknowledgements rejected, stripped requests reissued), fault-guard +suspension and root-revision receipts, bounded phase timeouts +that kill the process group, sanitized journal observation, secret detection, +result mapping, and effect-free teardown refusal. + +## Implementation and trust boundaries + +`internal/coordination.Hub` implements `executor.Client`. It creates an immutable +`MachineAllocationHandoff` under `coordination.fleet.datumapis.com/v1alpha1` and +returns Unknown until a valid reflected observation exists. The request is stored +as a JSON string so API-server normalization cannot reorder opaque input fields +and change the retained executor digest. `spec` is immutable through CRD CEL. +Names derive from the operation ID; a changed request under the same ID conflicts. + +`internal/coordination.Cell` is split into two least-privilege roles. Both +validate that the delivered handoff names this cell, that its name is derived +from the operation ID, and that the intent is valid before anything else. + +- **`Cell.Execute`** runs in the per-operation worker Job (`fleet-multiplane + site-worker`). It looks up the provider journal first, and a terminal + result is not re-executed. When lookup reports the operation not found and + Unknown, the worker re-sends the identical retained request under the same + operation ID. The local provider reports exactly this for a retained but + unfinished operation. The provider replays it against its digest-checked + journal and resumes observing an already-started installer instead of + starting another. Conflict, fencing, transport errors and a found-but-errored + lookup stop before any effect. `Execute` never writes status. +- **`Cell.Publish`/`Cell.Observe`** run in the observer Deployment + (`fleet-multiplane site-observer`), which uses a read-only provider. Every 10 + seconds it lists this cell's handoffs and publishes an observation only for + a terminal journal result that passes `ValidateResult`. Unknown is never + published, and periodic refresh keeps observation timestamps fresh. + +Retries, Pod replacement and dependency ordering belong to the Job controller +and kro. Neither role holds a hub, consumer, provider-project or +private-custody credential. This proves recoverable operation completion, not +ongoing guest health or live production hardware attestation. + +Allocation serves exactly one location, `local`, bound to the configured cell. +`Runner.request` rejects any other Machine `locationRef`, an empty `Config.Cell`, +or a hub client with a different cell. It returns `ErrLocationNotServed` before +claim custody, authority records, finalizers or allocation. The CLI treats this +rejection, conflicts, fencing and invalid requests as terminal instead of +retrying until timeout. + +Release projection runs only after verified cleanup made finalizer removal safe. +Each step is retry-safe. The referenced Installation is retired first (`Released`, +Ready False), then `currentInstallationRef` is cleared and the Machine is +published `Released` with Bound and Ready False. The Fleet finalizer is removed +last, from the server's fresh copy, so the removal is not reverted. Later requests +read terminal custody through `Coordinator.ClaimReleased` and never restore the +finalizer on a released claim. Reuse writes consumer B's Bound status only from +the coordinator's committed binding. The CRD types Installation `status.phase` as +a free-form string with no enum or CEL rule, so `Released` is schema-valid. +`release-status-a` reads it back from the real Milo API. + +`LocalAssetMapping` maps exactly one configured provider-scoped Device identity +to `localvm.AssetID`. It obtains the original retained request from the cell API, +validates the translated provider digest, and returns the original digest. +It never aliases by suffix or moves custody into the cell. This explicit +synthetic hardware enrollment is necessary because the local VM provider accepts +one fixed physical asset ID. No Device/capacity/allocation/Installation identity +is substituted for another. + +Cell site identities are as follows: + +- **Observer** (static Role): get/list/watch handoffs and update handoff + status only. +- **Workers** (one kro-created Role each): `get` on exactly one handoff by + `resourceNames`, with an automounted short-lived projected token. +- **kro** (aggregated read-only ClusterRole plus two namespaced Roles): reads + handoffs, the Flux-owned shared services and the PVC cluster-wide. It writes + only Jobs and ServiceAccounts in `fleet-site`, and Roles and RoleBindings in + `fleet-coordination`. Two admission policies pin those writes to the + per-operation shape. It has no Deployment, Service, volume, Secret or + handoff spec/status write. + +Management's hub Role grants intent create/get/list/watch but no status writes. +Karmada uses a separate member ServiceAccount with namespace-scoped intent +writes. It also has cluster-wide read/watch for handoffs, because its member +informer lists that resource across namespaces, and it can read +nodes/pods/namespaces and discovery/health endpoints. It has no Secret-reading +permission or local status-writing grant. Management and Karmada tokens are +24-hour local ServiceAccount tokens; the harness does not refresh them for +long-running deployments. Bootstrap administrator credentials remain on the +host. No cell credential leaves the cell: the cell kubeconfig export from the +previous design was removed. + +Milo static-token RBAC grants live in the native root RBAC store, where its RBAC +authorizer reads them. Customer tokens cannot write status or read Secrets. +Management uses separate project read/status roles. Tests also delete the cell +RoleBinding, verify denial, and restore that exact binding. These tests establish +Kubernetes RBAC behavior, not caller-preserving production Milo IAM. + +The local runner's catalog, publication, hardware observations, source-use +admission, quota holds and settlement are explicit synthetic fixtures. Concrete +synthetic contract records and the existing lifecycle custody are durable before +effects. Networking is deliberately empty; no NSO/IPAM/routing implementation is +substituted. Adoption and production service readiness are never enabled. + +## Verification and remaining gaps + +### Flux-owned shared site acceptance (2026-11-16) + +This run verifies the current ownership split: the cell's Flux owns the shared +site services and storage, and kro owns only per-operation workers (see the +[trust model](site-execution.md#ownership-and-trust-model)). It supersedes the +ownership claims of the runs below, which verified kro-owned shared +Deployments. It re-establishes every other scenario of the +[acknowledgement run](#flux-acknowledgement-acceptance-2026-11-15). + +`task multiplane:acceptance` exited 0 at 00:07 UTC on November 16, 2026, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.WkV4ul`, prefix `fleet-mp-ed5636ae`; +- all 54 bounded phases passed (one more than before: `flux-graph-lifecycle`), + in 25.6 minutes from build to teardown with cached base images; +- SHA-256 of `source-SHA256SUMS` (155 entries): + `7faa0832c7b543d2504398b462b117ff1bd00cbea721f550b56d23778a17d31e`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4`, unchanged, because + no Go code changed; +- site image `sha256:66cdc9d8c6cd010825de447f8aa3b108d35bcf93531e6e255e13c5a56dee48ad`, + pulled by the cell by that registry digest; +- seven source revisions from the dirty checkout at HEAD `d7ff793b`, 58 files + each: r1 `4d743778…`, r2 `8e4b05f8…` (shared services and dispatcher), r3 + `84ff7ff0…`, r4 `939fae00…` (bad kro chart), r5 `7f319b98…`, r6 `1afccbf1…` + (claim removed), r7 `cc786e40…`. All three clusters ended at r7. + +New claims, from the sanitized evidence: + +- **Single writer per object** (`flux-verify.json`, `flux-ownership-final.json`). + Before dispatch, 20 shared site objects each carried exactly one Flux layer + label, were in that layer's inventory, and had no kro label or owner + reference. The services, graph and dispatch inventories held exactly their 5, + 1 and 1 objects, and kro had written nothing. At the end, the same 20 objects + passed again. kro had written exactly 12 objects: the Job, ServiceAccount, + Role and RoleBinding for the install and both cleanups. Every shared + Deployment was labelled `fleet-site-services` with no kro label + (`kubernetes-execution.json`). +- **kro's narrowed authority** (`kro-rbac.json`). As kro's identity, 8 worker + verbs were allowed and 15 others denied. Three worker shapes were admitted by + server-side dry run, and 8 violations were each denied by a + ValidatingAdmissionPolicy. Every real worker Job and its RBAC, including the + three delivery-fault Jobs, passed the policies. The chart grants kro keeps + are recorded: CRD create/delete and Leases. +- **Graph lifecycle does not touch shared infrastructure or storage** + (`flux-graph-lifecycle.json`). Deleting `HandoffDispatcher/dispatcher` + (UID `e4c7eb92…`) removed exactly the install's four `w-op-1325c74…` + objects. All 22 tracked identities kept their UIDs: the shared objects, the RGD + and the StorageClass. PVC `bb97aa91…`, the journal (`92ad2c9e…` before and + after) and custody were unchanged, and the handoff stayed `Succeeded`. Flux + recreated the instance (UID `65d41287…`), kro recreated the four objects, + and the Job replayed a verified no-op with exit 0. One orphaned, `Succeeded` + Pod from the deleted Job is recorded. +- **Flux drift repair of shared services** (`flux-drift.json`). The deleted + boot Service was recreated by the services layer under a new UID + (`ace32e5d…` → `26767a93…`), at the same ClusterIP `10.96.0.80` and with an + unchanged spec. The closed-boot probes later ran through it. The observer + Deployment scaled to 0 was restored with the same UID (generation 1 → 3). The + earlier three cases, kro, the Karmada interpreter and the widened kro grant, + were corrected as before. +- **kro failure does not gate shared infrastructure** (`flux-fail-closed.json`). + With r4, the kro chart source and Kustomization failed and the graph and + dispatcher reported `DependencyNotReady`; the dispatcher marker stayed r3. + The base and services layers applied r4 with every shared UID and Deployment + generation unchanged. r5 converged. +- **Bootstrap gating observed before apply** (`flux-verify.json`). Gating was + observed on the hub (Karmada coordination, API and members) and on the cell + (federation, site base, graph), each with nothing applied. + +Re-established, as in the earlier run: + +- **PXE.** Worker Pod force-deleted at `installer-started` with its domain + running and replaced in the same Job. Job deleted mid-install and recreated + by kro. One install operation recorded one network-installer start and one + disk-only start. +- **Recovery.** Partition kept public Ready False with the Job Complete. + Suspension receipts, heal, the idempotent install, lifecycle recreation and + retention all passed (PVC `bb97aa91…`, PV `27b3cd4d…`, `Retain`). +- **Acknowledgement and restart.** All 21 convergence waits required fresh + acknowledgements; 12 stripped requests were reissued. All 12 controller Pods + were replaced, every object acknowledged a post-restart token, and both Helm + releases stayed at version 1. +- **Rejections and denials.** Nine reflection faults were rejected, and release + and reuse passed across epochs 1 and 2 with two cleanups. Three delivery + faults failed by `PodFailurePolicy` at exit 65 and were pruned by kro. Wrong + location was denied with free capacity, and the closed-boot denials passed. +- **Memory, secrets and teardown.** Zero OOM kills; the cell node recorded 89 + `memory.max` events, more than the 17 of the earlier run. 33 evidence files + were clean against 23 retained secrets. Teardown removed every + `fleet-mp-ed5636ae` resource and private credential, and inotify was + restored from 1024 to 128. + +Three earlier fresh attempts of this change failed before any allocation or +effect. Each was inspected and then discarded with `teardown.sh +--discard-unknown`, which is not release evidence: + +1. `/tmp/fleet-multiplane.LpvtO5` (`fleet-mp-a84271ad`) failed in + `flux-platform`. kro rejected the RGD because `runtime` is a reserved + resource ID in kro v0.9.4. The ID is now `hypervisor`, and `test-harness.sh` + checks every ID against kro's reserved list. +2. `/tmp/fleet-multiplane.XjeuF8` (`fleet-mp-39f70830`) failed in `flux-verify`, + on a false positive in the bootstrap ordering check. Its ownership audit had + passed. See + [bootstrap gating evidence](gitops.md#review-follow-up-suspension-and-reconcile-evidence). +3. `/tmp/fleet-multiplane.jnCCQ9` (`fleet-mp-0e269a33`) failed in `rbac`. The + live probe found that the kro chart grants cluster-wide ConfigMap writes, + which kro does not use. The HelmRelease now removes them. + +Before the live runs, the admission policies, the narrowed grants and the +scoped Flux identities were also exercised against a disposable envtest +kube-apiserver v1.36.2 with the kro v0.9.4 controller built from its tag +(`4ba0e410`). Valid worker objects were admitted and violations denied. The +RGD became `Active`, with readiness gating on the referenced Deployments. +Deleting the instance removed only worker objects. This was a manual +pre-check, not a repository test. + +The run has not yet been independently reviewed. + +### Flux acknowledgement acceptance (2026-11-15) + +This run supersedes the partition and restart claims of the +[earlier Flux-reconciled run](#flux-reconciled-acceptance-2026-11-15). It +re-establishes every other scenario of that run. + +`task multiplane:acceptance` exited 0 on November 15, 2026 at 21:40 UTC, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.Ufjnxs`, prefix `fleet-mp-677f3c68`; +- all 53 bounded phases passed, in 25.6 minutes from build to teardown with + cached base images; +- SHA-256 of `source-SHA256SUMS` (152 entries, now including + `config/base/crd`): `a1a33d8944ba82f9fbd014c13092aca8151e2730210939cb2c6fb59fdf12f2f3`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4`, unchanged from + the earlier run; +- site image `sha256:efacf7ac9c17d83dab387683a3dc74561d5efce70447975e45b07cb72b31e2f3`, + pulled by the cell by that registry digest; +- seven source revisions from the dirty checkout at HEAD `d7ff793b`, 55 files + each: r1 `497fc276…`, r2 `31f19f68…`, r3 `63d46be3…`, r4 `8ee7a6b1…` (bad + kro chart), r5 `79855353…`, r6 `8bfa826c…` (claim removed), r7 `8cdc7270…`. + All three clusters ended at r7. + +The sanitized evidence records the following new claims. + +- **Partition suspension held** (`flux-partition.json`). Consumer A's + Kustomization kept UID `c58c9f19…` at generation 2, suspended, with zero + Deployment replicas and no Pods, from `partition` through + `partition-readiness`. In between, the platform source and root sync + acknowledged fresh requests and applied r3 (`rootReconciledDuringFault`). + Flux made no concurrent repair. The harness then resumed it and Flux, not the + harness, restored the API. +- **Reflection-fault suspension held** (`flux-reflection-suspension.json`). + The Karmada HelmRelease kept UID `41638898…` at generation 2, suspended, with + the controller at zero replicas and no Pods. That was checked before each of + the nine injected faults and again before resuming. +- **Acknowledged convergence** (`flux-reconciles.json`). All 20 convergence + waits, across bootstrap, revisions, heal, restart and final, required each + source and Kustomization to report `lastHandledReconcileAt` equal to a fresh + token, Ready at the current generation and revision. Fifteen requests were + removed by a parent apply before being handled, and were reissued: the cell + root six times, cell `kro` four, hub `karmada` three, platform root two. Every + final acknowledgement matched the latest token. +- **Restart re-reconciled every object** (`flux-restart.json`). All 12 + controller Pods on the three clusters were replaced (no UID kept). Every + source and Kustomization then acknowledged a post-restart token, and both + HelmReleases acknowledged theirs with no reissue. Helm release versions + stayed at 1; inventories, Jobs, the journal, PVC/PV and custody were + unchanged. + +The other scenarios passed as in the earlier run: + +- **PXE.** The worker Pod was force-deleted at `installer-started` with its + domain running, and replaced in the same Job. The Job was then deleted and + kro recreated it under a new UID. One install operation recorded one + network-installer start and one disk-only start. +- **Lifecycle and recovery.** Partition kept public Ready False with the Job + Complete. Heal, the idempotent install and lifecycle recreation kept the + journal and volume unchanged. +- **Flux.** Drift was corrected by Flux (kro same UID at release v1, Karmada + interpreter recreated, kro grant reverted). The observer RoleBinding was + restored under a new UID. r4 failed closed with `OCIArtifactPullFailed` and + `DependencyNotReady`, and the FleetSite stayed at r3. r6 and r7 retained PVC + `2c18ea7a…` and PV `45670d5d…` (`Retain`). +- **Rejections and denials.** All nine reflection faults were rejected. Release + and reuse passed in epochs 1 and 2, with two cleanups. Three delivery faults + failed by `PodFailurePolicy` at exit 65. Wrong location was denied with free + capacity, and six closed-boot denials were recorded. +- **Memory.** There were zero OOM kills. The cell node recorded 17 + `memory.max` events. +- **Secret scan and teardown.** 30 evidence files were clean against 23 + retained secrets. Teardown removed every `fleet-mp-677f3c68` container, + cluster, image tag and private credential. inotify was restored from 1024 to + 128. + +The first fresh attempt, `/tmp/fleet-multiplane.Xk3Nc9` (`fleet-mp-34c74885`), +failed in `flux-platform` after 11 phases, before any credential, fixture or +effect. The cell root sync was Ready at r1, but its `lastHandledReconcileAt` +stayed null for the 1500-second bound. Inspection showed the request annotation +and its `kubectl-annotate` field manager were gone five seconds after the +request: the root's own apply had removed them. The harness fix is described +under [suspension and reconcile evidence](gitops.md#review-follow-up-suspension-and-reconcile-evidence), +and `test-flux.py` covers it. That topology was discarded with +`teardown.sh --discard-unknown`, which is not release evidence. + +### Flux-reconciled acceptance (2026-11-15) + +Superseded for the partition and restart claims by the +[acknowledgement run](#flux-acknowledgement-acceptance-2026-11-15). Its harness +suspended Kustomizations with a `kubectl`-prefixed field manager and accepted +existing Ready status after the restart. The record below is kept as it was +observed. + +`task multiplane:acceptance` exited 0 on November 15, 2026 at 20:16 UTC, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.POC1nn`, prefix `fleet-mp-cff2f712`; +- all 53 bounded phases passed, in 22.4 minutes from build to teardown with + cached base images; +- SHA-256 of `source-SHA256SUMS` (149 entries): `f9cbb463949580c1b08216c3b7730a83a8a8faf63a6eff25f904672d08a4c2d2`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4` (`binary-SHA256SUMS`); +- site image `sha256:cf6871facaefb2d577d5ece8cb7f94b7f6e3b43f3589eb8d22b16890f20b8112`, + pulled by the cell by that registry digest. + +The 39 scenarios of the earlier run are preserved, as the same phases or +documented equivalents: + +| Earlier phase | Now | +| --- | --- | +| `milo-bootstrap` (Docker Milo/etcd) | `milo-bootstrap` (credential enrollment and fixtures) plus `flux-milo`, against Flux-managed Milo workloads | +| `federation-bootstrap` (`helm install` Karmada) | `topology`, `flux-bootstrap-*`, `flux-platform`, `federation-enrollment` | +| `site-image-load` (`kind load`) | `site-image-push` (registry, pulled by digest) | +| `kro-install` (`helm install`) | `flux-platform` (cell `HelmRelease kro`) | +| `site-install` (`kubectl apply`) | `flux-site` (revision 2) and `site-install` (checks only) | + +The 14 new phases are `flux-tools`, `topology`, `flux-source`, three +`flux-bootstrap-*`, `flux-milo`, `flux-verify`, `flux-drift`, `flux-restart`, +`flux-fail-closed`, `flux-retention`, `flux-final` and +`federation-enrollment`. The sanitized evidence records the following. + +- **Source.** Seven revisions were pushed from the dirty checkout at HEAD + `d7ff793b`, each with its per-file SHA-256 list (55 files): + - r1 `38e1c0b6…`, r2 `470cae7a…`, r3 `d26bf3d5…`; + - r4 `a3931e63…` (bad kro chart), r5 `123ccb2c…`; + - r6 `b826eb5b…` (claim removed), r7 `d3a9fdf8…`. + + All three clusters ended at `local@sha256:d3a9fdf8…3122dff82`. +- **Flux.** Flux v2.9.6 ran with the CLI and `install.yaml` digests verified, + and the four controllers digest-pinned on each cluster. + - Every Kustomization and HelmRelease was Ready at the current generation + and revision. + - The Karmada chart artifact digest was `773ab194…34fe`, release v1. The kro + release recorded chart `0.9.4+4e8de4d34b7e`, release v1. + - `DependencyNotReady` was observed for 13 Kustomization states across the + cell and hub chains. Six bootstrap observations had no applied revision or + inventory; seven during r2 retained their r1 revision and inventories. +- **Ownership.** The `fleet-site` inventory was exactly the FleetSite. The six + generated site objects carried kro node labels and no Flux label or + inventory entry. No Job, Pod, handoff or Secret appeared in any Flux + inventory. +- **Drift.** These changes were corrected by Flux, not by the harness: + - the revoked observer RoleBinding was restored under a new UID; + - the kro Deployment scaled to 0 was restored by helm-controller, with the + same UID, still release v1, and a drift event recorded; + - the deleted Karmada interpreter was recreated over the remote kubeconfig; + - a widened `fleet-site-kro` grant was reverted. + + The journal, Jobs, PVC/PV and custody did not change. +- **Restart.** Every Flux controller Pod on the three clusters was replaced + and managed objects were observed Ready. That historical run did not check + acknowledgement of each new reconcile request, so it does not prove every + object re-reconciled after restart. Helm release versions stayed at 1; + inventories, Jobs, the journal and custody were unchanged. +- **Fail-closed.** With r4, the kro chart source failed with + `OCIArtifactPullFailed` and the kro Kustomization with `HealthCheckFailed`. + The graph and FleetSite were `DependencyNotReady`. The FleetSite stayed at + r3 with marker `r3`, and the kro Deployment and site were unchanged. r5 + converged. +- **Retention.** r6 removed the claim from the inventory without deleting it. + The PVC `05b3b322…` and PV `37468f59…` (`Retain`), the journal and custody + were unchanged, and r7 re-adopted the same claim. +- **PXE.** The worker Pod was force-deleted at `installer-started` with its + domain running, and the Job controller replaced it in the same Job. The Job + was then deleted and kro recreated it. The run recorded one install + operation, with one network-installer QEMU start followed by one disk-only + start. Contention, partition (public Ready False with the Job Complete), heal, + idempotent install, lifecycle, nine reflection faults, release and reuse, + three delivery faults, wrong-location denial and six closed-boot denials all + passed as before. +- **Memory.** There were zero OOM kills. The cell node recorded 172 + `memory.max` reclaim events and no OOM. +- **Secret scan.** 27 evidence files were clean against 23 retained secrets. + Teardown removed every `fleet-mp-cff2f712` container, including the registry, + all three kind clusters, the image tags and private credentials. inotify was + restored from 1024 to 128. + +Two earlier attempts with this design never reached a pass: + +- `/tmp/fleet-multiplane.SQ5zAp` (`fleet-mp-bfe2f43e`) failed in + `flux-bootstrap-platform`: the sync objects were applied in the same batch + as the Flux CRDs. +- `/tmp/fleet-multiplane.SSCrNg` (`fleet-mp-8f36be4c`) was a diagnostic run + left running after a `flux-verify` check rejected Flux's digest-suffixed OCI + chart version. Its remaining phases were then driven piecewise to find two + more harness defects: a restart check that compared Deployment rather than + Pod UIDs, and a reworded log marker. It also showed the platform node under + reclaim pressure at a 1900 MiB cap. + +Both were stopped or discarded with `teardown.sh --discard-unknown`, which is +not release evidence. The fixes are in the recorded run. + +### Kubernetes and kro execution acceptance (2026-11-15, superseded installation path) + +This run installed kro, Karmada and the site imperatively, and ran Milo as +Docker containers. Its execution findings are re-established by the +Flux-reconciled run above. + +`FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh` (the command behind +`task multiplane:acceptance`) exited 0 on November 15, 2026 at 18:08 UTC. Run +details: + +- state `/tmp/fleet-multiplane.3TSkFC`, prefix `fleet-mp-b6b817c8`; +- all 39 bounded phases in `evidence/phases.jsonl` passed, in about 8.5 + minutes from build to teardown with cached base images; +- SHA-256 of `source-SHA256SUMS` itself: `20ce9da37d883eb223604c6a46e325dadba90a13dab8d1694a95c63b52feb9aa`; +- site image ID `sha256:ab24def82ee40395698845b9e491c31a9012371c0d914d7da1a0324600024cb0`. + +The sanitized evidence records the following. + +**kro and the site** (`kubernetes-execution.json`): + +- kro v0.9.4 ran image `registry.k8s.io/kro/kro@sha256:eaf9fbad…`, chart + archive `ceeb6307…`, in RBAC `aggregation` mode. +- RGD `fleet-site` was `Active`. `FleetSite/site` was `ACTIVE`, with runtime, + boot and observer Available, boot origin a ClusterIP, and three delivered + handoffs. +- The site volume was `fleet-site-retain`/`Retain` and not managed by kro. +- Exactly three kro-created worker Jobs remained: one install (epoch 1) and + two cleanups (epochs 1 and 2). Each was `Complete` with one succeeded Pod at + exit 0. + +**Interruption** (`interrupt.json`): + +- With the install `installer-started` and its domain running, the worker Pod + was force-deleted. The Job controller recorded `failed: 1` and started a + replacement Pod in the same Job UID. +- The Job was then deleted, still `installer-started`. kro recreated it under + a new UID, and its worker completed the same operation. +- The journal holds one install. libvirt's QEMU log shows exactly one + firmware-network installer start followed by one disk-only start. The guest + logs show one partition, one installer receipt and one disk-boot receipt. + +**Worker RBAC:** the per-operation token could read its own handoff only. +`get` on another name, list, status and spec patches, Secrets, ConfigMap +creation and Job reads were forbidden. + +**Partition:** the install Job was `Complete` while consumer A's public Ready +stayed False. Heal, the repeated install and all nine reflected-result faults +were then rejected as before. + +**Lifecycle** (`lifecycle.json`): the runtime, boot and observer Pods were +recreated, and the completed Job was recreated with a verified no-op replay +(one Pod, exit 0). Unchanged throughout: + +- journal bytes; +- QEMU starts (2); +- PVC/PV UIDs and the Retain policy; +- domains (none); +- consumer A Ready/Bound. + +The observer republished afterwards. + +**Delivery faults** (`delivery-faults.json`): the duplicate, wrong-cell and +stale-epoch handoffs each produced one Pod at exit 65 and a Job `Failed` with +reason `PodFailurePolicy`. They wrote no status, left the journal unchanged and +left consumer B Bound. kro pruned them after deletion. + +**Release, reuse and location:** + +- Released projection for A and B, and reuse Bound for B in epoch 2. +- Wrong-location denial with free capacity: six custody records and the + journal were unchanged. +- Six live closed-boot HTTP denials through the boot Service from the runtime + Pod. No domains or disks remained. +- Zero OOM events in the runtime Pod cgroup, the cell node cgroup, and the + site and kro containers. + +The secret scan checked 12 evidence files against 22 retained secrets. +Teardown removed every `fleet-mp-b6b817c8` container, both kind clusters, the +site image tag and private credentials, and restored inotify from 1024 to 128. +This is local TCG and legacy-BIOS PXE evidence only. KVM, UEFI, production +authority and production equivalence remain false in `summary.json`. + +The first attempt with this design, `/tmp/fleet-multiplane.e7atDk` +(`fleet-mp-ffab61d0`), passed every phase through `install-repeat`, including +both interruptions and exact resume. It then failed at `lifecycle` on a harness +defect: `k8s_evidence.get` rejected a `config` argument. The failure handler +stopped only that run's containers. Its stopped topology was then explicitly +discarded with `teardown.sh --discard-unknown`, which is not release evidence. +The defect is fixed, and `hack/multiplane/test-k8s-evidence.py` now runs every +helper command against a fake `kubectl` in the offline harness tests. + +### Earlier runs (superseded execution model) + +Runs before this change executed the cell as a `fleet-multiplane cell` process +started by `docker exec` in a privileged provider container. One passed on +2026-11-15 as `/tmp/fleet-multiplane.HkE6e5` (`fleet-mp-a6f50082`, 31 phases). +Others, `/tmp/fleet-multiplane.67Z4yk` and `/tmp/fleet-multiplane.CubymM`, +either passed or completed with manual bootstrap recovery. Their findings +(Milo routing, Karmada delivery and reflection, firmware PXE, disk boot, +reflection-fault rejection, and cleanup and reuse) are re-established by the +run above. Their process-launch and SIGKILL evidence no longer describes how +the cell executes and is not current evidence. + +Two earlier failures inform the current bounds. In +`/tmp/fleet-multiplane.4vyisu`, a 2.5 GiB provider cap caused an installer OOM; +the runtime limit is now 3 GiB and OOM is checked. In +`/tmp/fleet-multiplane.omuBXA`, a shell builtin was executed through +`docker exec`; that path no longer exists. Both retained Unknown custody and +were never treated as release evidence. + +### Offline checks + +```sh +go test -race -count=1 ./... +go vet ./... +task multiplane:test-harness # includes hack/multiplane/test-k8s-evidence.py +shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime +git diff --check +``` + +Deterministic Go tests cover these result faults: wrong-cell, stale/future, +duplicate, missing, wrong operation/digest/allocation/epoch/fence, and Unknown. +They also cover: + +- the worker/observer split: the worker never writes status, and the + observer never executes and never publishes Unknown, absent or mismatched + journal results; +- delivery faults fencing before effects, and cell-label selection; +- restart recovery and exact local asset mapping; +- boot-origin and libvirt-URI validation, and read-only providers; +- boot evidence kept outside the journal directory; +- NAT forwarding only for a remote boot Service; +- project identity collisions, concurrent allocation, and unknown cleanup + preventing capacity reuse. + +They do not pretend to implement Karmada, kro or the Job controller in memory. +Only the live command establishes federation, kro, Job and PXE acceptance. + +A known shared-lifecycle diagnostic edge remains: contenders with identical +Machine UIDs in different projects can receive `ErrRecordInvalid` rather than +`InsufficientCapacity`. Tests accept either fail-closed outcome and require one +exclusive winner and no reuse after Unknown cleanup. This harness does not edit +shared core lifecycle code to change that behavior. + +### Known limitations of the local MVP + +Independent review on 2026-11-15 found no blocking safety issue for this +disposable local MVP. It recorded these limits, which the harness does not hide: + +- **The provider journal is the sole fence.** The local provider's + `/var/lib/fleet-local/journal.json` alone binds operation IDs, allocation epoch, + fence and receipts to the physical asset. If provider state is deleted or + replaced and old handoffs are replayed, the provider admits them as new and can + re-image the disk. That is acceptable only because every site volume here is + disposable and created fresh per run. The volume uses `Retain` and is not + managed by kro, but nothing prevents an operator from deleting the PV. Never + reset, delete or replace a journal for a provider whose device or disk is + retained. +- **Location validation is local to this runner.** `ErrLocationNotServed` is + enforced by `internal/multiplane.Runner.request` for its single `local` + location and configured cell. The shared allocator, the standalone runner and + the production manager do not implement location binding. +- **Some crash windows remain Unknown indefinitely.** These include an ambiguous + `virsh create` after `installer-started` or `disk-started` was retained, a crash + after disk creation but before `prepared` (exclusive creation then refuses to + overwrite), and a lost PXE network, lease or broker delivery. The provider will + not restart a possibly executed installer. Custody, capacity and diagnostics stay + retained. Do not reset the journal or retry under new authority to "unstick" it. + No automated operator resolution exists. Resolving such a run means discarding + the whole disposable topology after inspection (`teardown.sh --discard-unknown`). +- **Test coverage seams.** Deterministic tests use identical scoped and physical + asset IDs in places and exercise recovery through the non-PXE provider path. + The live run is therefore the evidence for real firmware PXE with in-flight + worker Pod and Job interruption, exact resume and a single installer start. +- **Single-node site.** The runtime, boot service, observer and workers share + one kind node and one `ReadWriteOnce` local-path volume; the journal lock + depends on that. Losing the runtime Pod stops any running guest; the + operation then stays Unknown. Multi-node or HA execution is not designed. +- **kro is a broad reader, and graph authors are trusted.** kro must read + delivered handoffs, including the fence token in `requestJSON`, to enumerate + them. Its informers need cluster-wide get/list/watch on every referenced + kind. Its writes are namespaced and admission-checked, but an admitted worker + still reaches root libvirtd and the journal; see the + [trust model](site-execution.md#ownership-and-trust-model). Disabling + `dispatch` or deleting a handoff prunes worker Jobs without cancelling + effects. See [site execution](site-execution.md#lifecycle-and-retention). +- **Shared-service revisions roll the runtime.** A services-layer change, such + as a new site image, recreates the runtime Pod and stops any running guest. + The operation then stays Unknown. No migration from the earlier kro-owned + composition is implemented. Retained historical Jobs also have immutable pod + templates: changing the runtime-derived worker image may block kro dispatch. + This upgrade risk has not been exercised; image upgrades require a fresh + disposable topology until a tested upgrade lifecycle exists. See + [site lifecycle limitations](site-execution.md#lifecycle-and-retention). +- **Interrupt timing.** An emulated install takes about a minute. The Job + deletion is issued as soon as the replacement Pod exists; a much faster + guest could finish first, and the phase would then fail rather than pass + vacuously. +- **GitOps seams.** The Flux source is a plain-HTTP, unsigned registry on the + kind network. Credentials are enrolled imperatively, not with SOPS or + External Secrets. The Karmada API is reconciled with its admin kubeconfig, + and the three clusters share one VM. Revisions are staged from the checkout; + nothing is published. See [what is not production](gitops.md#what-is-not-production). + The journal volume's Flux policy (`prune: disabled`, `ssa: IfNotPresent`) + protects it from reconciliation, but not from an operator deleting the PV. +- **Qualification scope.** A non-disposable provider, KVM, UEFI, real hardware/BMC, + production Milo IAM, quota and networking remain out of scope. + +The production gaps include caller-preserving admission, source-use IAM, +service-owned quota recovery/settlement, source publication custody, true project +provisioning/deletion, cell enrollment and revocation at the hardware effect +boundary, live hardware/network attestation, token rotation, sustained outage +behavior beyond configured freshness, and independent durable/HA failure domains. +There is no production-equivalence or production-readiness flag to enable. + +### Automation notes + +Source fingerprints include all internal Go packages, `config/multiplane`, +`config/site`, the harness, and module manifests, and exclude Python caches. +Each Flux source revision also has its own per-file SHA-256 list in evidence. Phase deadlines are +enforced even with partial output or closed stdout. Image-tag removal is +reported separately from container cleanup. Teardown does not verify that +every Docker volume is absent. Scenario booleans in the summary derive from +successful bounded phases and checked log markers. The partition check runs +with the host publisher stopped, as described above. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md new file mode 100644 index 00000000..0bf57f76 --- /dev/null +++ b/docs/operations/site-execution.md @@ -0,0 +1,386 @@ +# Kubernetes-native site execution + +The [multi-plane acceptance](multiplane.md) runs selected-cell execution as +ordinary Kubernetes workloads. The cell's Flux owns the long-lived site services +directly, and an installed [kro](https://kro.run) controller creates only the +per-operation worker Jobs and their RBAC. Before Kubernetes execution, a hand-written cell +process was started with `docker exec` inside a privileged libvirt container. +That process listed and watched handoffs, executed them, retried them, and +wrote status. Now Kubernetes controllers own scheduling, retries, Pod +replacement and dependency ordering. Fleet code is left with only the parts +that carry authority: + +- exact-request replay against the provider journal; +- fencing; +- journal-derived observation. + +This is an **implemented local acceptance composition**, not a production +deployment. The [PXE installation proposal](../enhancements/pxe-installation/README.md#location-execution) +still defines the target contract. Physical Redfish, KVM, UEFI, production +IAM and HA remain out of scope. + +## Versions + +| Component | Pin | Why | +| --- | --- | --- | +| kro | v0.9.4, chart `oci://registry.k8s.io/kro/charts/kro` manifest digest `sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c` (archive layer SHA-256 `ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd`), image `registry.k8s.io/kro/kro:v0.9.4@sha256:eaf9fbaddd9d7f6cf400a8d47ab066b14cbef22b92a79be7bbdc7b3673376fb9`, installed by the cell's Flux `HelmRelease kro` | Newest patch of the newest minor with a settled release. v0.10.0 was published on 2026-11-10, five days before this work, and is deliberately not used. | +| Kubernetes | kind node v1.35.0 (digest-pinned in `topology.sh`) | Job `podFailurePolicy` and `podReplacementPolicy: Failed` are both available. | +| Site image | Built per run from `hack/local-vm/Containerfile` target `site`; the binary comes from a named build context that holds only the checksum-verified `fleet-multiplane`. Pushed to the run registry and referenced by digest in the source. | One image for runtime, boot service, observer and workers | + +Version sources were read at the pinned tag: the kro installation, schema, +external reference, collection and readiness documentation; the kro Helm chart +values; and kro's `aggregation` RBAC mode. Flux pulls the chart by manifest +digest, and `flux-verify` checks the release history records that digest. See +[Flux-reconciled local environment](gitops.md) for the installation path. + +## Topology on the selected cell + +```text + cell Flux (one source revision, scoped identity per layer) + ┌──────────────────┬───────────────────────┬──────────────────────────┐ + ▼ ▼ ▼ ▼ +fleet-site-base fleet-site-services fleet-site-graph fleet-site-dispatch +ns, Retain PVC, runtime, boot and ResourceGraphDefinition HandoffDispatcher/dispatcher +identities, RBAC, observer Deployments; fleet-handoff-dispatcher (cell, scoped asset, dispatch) +kro grants, boot Service (fixed │ +admission policy ClusterIP); policy param │ kro + ▲ externalRef (read only, readiness-gated) ▼ + └──────────────────────────────────── per delivered handoff (forEach): +Karmada ──delivers──▶ MachineAllocationHandoff ─ external collection ─▶ ServiceAccount, Role + (fleet-coordination, label-selected by cell) (resourceNames: that handoff, + get), RoleBinding, bounded Job + +VM runtime (libvirtd, privileged) ◀─ libvirt socket ─ worker Job ── replays one operation + └─ firmware DHCP/iPXE ─NAT─▶ boot Service ─▶ boot Deployment (journal read-only) +observer Deployment (journal read-only; only handoff status writer) + ╲_____________ fleet-site-state PVC (Retain), Flux-owned __________╱ +``` + +| Resource | Owner (single writer) | Privileges | Volume subpaths | Role | +| --- | --- | --- | --- | --- | +| `fleet-site` namespace, `fleet-site-retain` StorageClass, `fleet-site-state` PVC | Flux `fleet-site-base` (`config/site/base`; never pruned; class and claim created once) | — | — | Durable journal, disks, boot evidence, libvirt socket and QEMU logs. Never in any graph. | +| `fleet-site-runtime`, `fleet-site-boot`, `fleet-site-observer` ServiceAccounts; observer Role and RoleBinding | Flux `fleet-site-base` | Observer: get/list/watch handoffs; update handoff status | — | The observer is the only cell identity that writes handoff status | +| `fleet-site-kro` ClusterRole, `fleet-site-kro-workers` and `fleet-site-kro-worker-rbac` Roles and bindings, two `ValidatingAdmissionPolicies` | Flux `fleet-site-base` | — | — | kro's narrowed grant and the shape of its writes ([trust model](#ownership-and-trust-model)) | +| `fleet-site-runtime` Deployment | Flux `fleet-site-services` | **privileged** (bridge, dnsmasq, tap, iptables) | `journal` rw, `libvirt-socket` rw, `libvirt-log` rw, `boot-evidence` ro | libvirtd and QEMU only. No API token, no TCP listener. | +| `fleet-site-boot` Service and Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem, no API token | `journal` **ro**, `boot-evidence` rw | Boot decision point and artifact delivery. The Service has a fixed ClusterIP (`10.96.0.80`). | +| `fleet-site-observer` Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem | `journal` **ro** | Publishes validated terminal journal results every 10 seconds | +| `fleet-site-worker-policy` ConfigMap | Flux `fleet-site-services` | — | — | Admission parameter: the image worker Jobs must run | +| `fleet-handoff-dispatcher` ResourceGraphDefinition, `HandoffDispatcher/dispatcher` | Flux `fleet-site-graph`, `fleet-site-dispatch` (each a scoped identity; never pruned) | — | — | Orders per-operation work and projects non-authoritative status | +| `w-` ServiceAccount, Role, RoleBinding, Job | kro `forEach` over delivered handoffs | get on exactly one handoff; uid 0 with all capabilities dropped; read-only root filesystem | `journal` rw, `libvirt-socket` rw, `boot-evidence` ro | Executes or resumes that one retained operation | + +## Ownership and trust model + +This split is **implemented**, and is exercised by the acceptance phases named +below; see [verification](multiplane.md#verification-and-remaining-gaps) for +the run record. It supersedes the earlier composition, in which the graph +also created the three shared Deployments, the boot Service and their +ServiceAccounts. + +**One writer per object.** Each shared site object carries exactly one Flux +`kustomize.toolkit.fluxcd.io/name` label, appears in exactly that layer's +inventory, and carries no kro label or owner reference. Every object kro writes +is a `w-` Job, ServiceAccount, Role or RoleBinding, has a kro node +label, and is in no Flux inventory. `flux-verify` (before dispatch), +`flux-graph-lifecycle` (with workers present), `flux-drift` and `flux-final` +each run this audit (`flux.py ownership`). This audit uses labels, owner +references, RBAC and inventories, not server-recorded `managedFields`. Shared +inventory membership is matched by namespace/name prefix rather than kind, so +same-named resources can satisfy each other; the base inventory is not checked +for exactness. Independent review confirmed the expected kinds in the saved +live inventory. These checks are evidence of the intended ownership split, not +a complete proof that no other field manager has written an object. + +**Dependency and health ordering.** + +1. `fleet-site-base` depends only on the handoff CRD (`fleet-coordination`). +2. `fleet-site-services` depends on the base. It waits for all three + Deployments to be Available; the runtime's readiness probe requires libvirtd. +3. `fleet-site-graph` depends on the kro release and the base, and is healthy + when the RGD is `Active`. +4. `fleet-site-dispatch` depends on the graph, the services and the federation + member identity. It is healthy only when kro reports the instance `ACTIVE`. + +Inside the graph, every worker template references the runtime, boot and +observer Deployments and the boot Service through `externalRef` with +`readyWhen`. kro v0.9.4 treats a missing or unready reference as pending data. +It then creates no new worker object and **disables pruning** for that +reconcile, so a shared-service outage never deletes an existing Job. Shared +infrastructure does not depend on kro: in `flux-fail-closed`, a broken kro +release blocks only the graph and the dispatcher, while the base and services +layers apply the same revision without restarting any service. + +**kro's narrowed authority.** kro v0.9.4 watches every kind it manages or +references with cluster-wide metadata informers, so its aggregated +`fleet-site-kro` ClusterRole keeps cluster-wide get/list/watch. That covers +Deployments, Services, PVCs, ServiceAccounts, Jobs, Roles, RoleBindings and +handoffs. Its only cluster-wide write is to its own `HandoffDispatcher` +instances. Writes are namespaced: + +- Jobs and ServiceAccounts in `fleet-site`; +- Roles and RoleBindings in `fleet-coordination`. + +kro has no Deployment, Service, PVC, ConfigMap or Secret write, and no handoff +spec or status write. The kro chart's own static role also granted +cluster-wide ConfigMap read/write, which kro v0.9.4 never uses. A live `rbac` +probe found it, and the `HelmRelease` now removes it with a post-renderer +patch. A JSON-patch `test` guards that patch, so a changed chart fails the +release rather than removing another rule. The chart grants kro keeps are +cluster-wide CustomResourceDefinition management, which it needs to create +each graph's kind, plus Leases and Events. `kro-rbac.json` records them as +remaining authority. 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. Two `ValidatingAdmissionPolicies` apply only to +kro's own requests and pin those writes to the worker shape: + +- a `w-` name matching the Job's handoff label; +- the Job's own ServiceAccount; +- one container from the image the shared services run (a parameter written + by the services layer); +- no privilege or added capability; +- no host namespaces; +- only the journal claim and `emptyDir` volumes. + +A Role may grant only `get` on its own handoff, and a RoleBinding may bind only +its own Role to its own ServiceAccount. The `rbac` phase proves this with real +`auth can-i` checks as kro's identity and server-side dry runs. Valid worker +shapes are admitted, and eight violations are each denied by policy +(`kro-rbac.json`). The policies cover CREATE and UPDATE, not DELETE. kro +can still delete any ServiceAccount in `fleet-site` and any Role or RoleBinding +in `fleet-coordination`, including Flux-owned identities and observer or +federation RBAC. Normal pruning targets only tracked worker objects, and the +policies prevent adopting these shared objects, but a controller bug or +compromise could interrupt delivery or status until Flux repairs them. Delete +denials are not covered by the current probes. + +**What graph authors are still trusted with.** This is not a sandbox for +untrusted graph revisions: + +- A worker mounts the journal read-write and reaches root libvirtd through + its socket. A graph author who changes the worker command, within the + admitted image, can therefore drive the hypervisor and rewrite the journal. +- kro must read every delivered handoff, including the fence token in + `requestJSON`, to enumerate them. +- kro keeps cluster-wide CRD create/update/delete from its chart, so a + compromised kro controller could alter or remove CRDs it does not own. +- The services layer chooses the privileged runtime image and its + configuration. +- The same source owns the admin-applied base, including these policies. + +Source review remains the control for all layers. The admission policies remove +the paths a graph revision would otherwise have to the observer's +status-writing token, to a privileged Pod, to another image or volume, and to +other namespaces. Production still needs a narrower action broker in place of +the libvirt socket; see [practical separation decisions](#practical-separation-decisions). + +**Migration from the earlier composition** is not implemented. Every acceptance +run creates a fresh cell. An existing site with kro-owned shared Deployments +would need these steps: + +1. Quiesce: no unfinished operation, and dispatch disabled. +2. Publish a graph revision without the shared resources, and confirm kro + removed them. A gap stops new boots, which is safe but not cancellation. +3. Publish the services layer. + +Doing it in one revision would leave two writers contending for the same +objects. This sequence is proposed only. + +### Practical separation decisions + +- **Only the VM runtime sets `privileged: true`.** Guests run under libvirtd in + that Pod, not under a worker. Losing a worker Pod or Job therefore loses only + an observer process; the installer continues. Losing the runtime Pod stops + any guest. The operation then stays Unknown and capacity stays occupied. +- **Workers reach libvirt through a Unix socket on the site volume** + (`qemu:///system?socket=/run/fleet-libvirt/libvirt-sock`). They hold no + network credential, and nothing listens on TCP. The provider accepts only + that URI shape. This socket still grants broad control over root libvirtd, + including domain definitions backed by paths in the runtime filesystem. + Dropped Linux capabilities do not isolate workers from the runtime's power. + The fixed worker image and graph are trusted in this disposable proof; + production requires a narrower action broker. +- **The boot service is a separate Deployment behind a ClusterIP Service.** The + provisioning bridge uses libvirt NAT forwarding. DHCP hands firmware an + `http://:8080/...` boot file. The Service's ClusterIP is fixed + (`10.96.0.80`, in the static band of kind's default `10.96.0.0/16` Service + range) and comes from the environment's `FLEET_BOOT_SERVICE_IP`. Flux + substitutes it into the runtime and boot Deployments, and kro reads it from + the Service for the workers. A recreated Service therefore keeps the boot + origin that running Pods were configured with; `flux-drift` deletes it and + proves this. The runtime + entrypoint adds a `mangle` chain: traffic from the bridge may reach only + local addresses (DHCP), broadcast, and the boot Service port. Everything + else is dropped. The boot service reads the journal read-only and writes + only its own delivery evidence in a separate subpath. Workers read that + evidence when they verify network boot. +- **One shared volume, separate subpaths and mount modes.** All site Pods run + on the single kind node, so one `ReadWriteOnce` local-path volume serves + them. The journal `flock` is effective because every writer shares one + kernel and inode. +- **The observer is a Deployment, not part of the Job.** Management requires + reflected observations to be fresher than one minute. Refreshing them is a + persistent site service, so freshness does not depend on any Job's + lifetime. It also keeps one status writer per cell. + +## Authority and failure contract + +- **Exact operation before effect.** A worker reads only its handoff. It + checks the cell, checks that the name is derived from the operation ID, and + validates the intent. `LocalAssetMapping` re-reads the same handoff and + compares digests. The provider then replays the journal under the exact + operation ID. A digest conflict, fence mismatch, stale epoch, or an + unfinished prior operation stops before any effect. +- **Worker exit codes are the Job contract.** + - `0`: a terminal result was validated against the journal. + - `65`: fenced, conflicting or invalid authority. `podFailurePolicy` fails + the Job with no retry. + - `75`: Unknown or transport error. The Job controller retries, up to + `backoffLimit: 6` and `activeDeadlineSeconds: 3600`. + + Disruption-target Pod conditions are ignored, not counted. +- **The journal lock serializes effects.** `podReplacementPolicy: Failed` + delays ordinary replacement until the old Pod is terminal. Force deletion + can remove its API object while the old process still runs, and Job recreation + can also overlap workers. The provider's non-blocking journal lock is the + actual execution guard in these cases; a contender exits 75. A recreated + worker replays the same retained operation. +- **Job Complete and kro Ready grant nothing.** The worker never writes + status. The observer publishes only a terminal journal result that passes + `ValidateResult`. Management accepts only the Karmada-reflected observation + that passes `ValidateReflection`, which checks: + - exact cell, operation and intent/input digests; + - freshness; + - a single replica. + + The acceptance shows this directly: during the hub partition the install Job + is `Complete` while public Machine `Ready` stays `False`. A failed Job leaves + the operation Unknown; it never releases capacity. +- **Delivery faults fail closed.** kro selects handoffs by cell label only for + convenience. A duplicate under another name, a wrong-cell intent and a + stale-epoch replay each get a Job. The acceptance injects these faults with + no pending operation: each fails once by policy without touching the journal. + While another operation is unfinished, the provider may reject a stale + request as Unknown before checking its fence. That worker exits 75 and may + exhaust its retry budget instead of failing once with exit 65; no effect is + authorized in either case. + +## Lifecycle and retention + +- `fleet-site-state` uses a StorageClass with `reclaimPolicy: Retain`. Only + `fleet-site-base` declares it. The services mount it and the RGD references + it through `externalRef`, so neither the services layer nor the dispatcher + instance or graph can delete it. kro v0.9.4 skips external references when it + deletes an instance. +- **Operation graph lifecycle cannot remove shared infrastructure.** + `flux-graph-lifecycle` suspends the dispatcher's Flux layer and deletes the + `HandoffDispatcher` instance. kro removes only that handoff's Job, + ServiceAccount, Role and RoleBinding. Every shared object keeps its UID, + including the Deployments, Service, ServiceAccounts, RBAC, admission policies, + PVC and StorageClass. The journal, PV, guests and custody are unchanged, and + the handoff keeps its terminal observation. Resuming lets Flux recreate the + instance; kro recreates the workers and the Job replays a verified no-op. + kro deletes Jobs without a propagation policy, so batch/v1 orphans their + terminal Pods; the evidence lists them. +- **Never delete or replace the journal** of a provider whose disk or device + is retained. A fresh journal would admit replayed handoffs as new + operations; see [known limitations](multiplane.md#known-limitations-of-the-local-mvp). +- After the installation is terminal, recreating the Flux-owned runtime, boot or + observer Pods does not change journal bytes, guest starts, volume identity or + public allocation. Neither does + recreating a completed Job, which only replays a verified no-op. The + `lifecycle` phase asserts all of this. +- **Pruning is not cancellation.** Setting `spec.dispatch` false, deleting a + handoff, or deleting the `HandoffDispatcher` can prune worker Jobs. kro v0.9.4 does not + specify cascading deletion for pruned Jobs, so dependent worker Pods may be + orphaned and continue to completion, as may their guests. The observer can + still publish a completed result if its handoff exists. Re-enabling dispatch + can create a competing worker that exits 75 on the journal lock. The harness + does not exercise pruning an active Job; its explicit Job deletion uses + background propagation. Neither dispatch nor object deletion is an authorized + cancellation or fencing protocol. +- **Shared-service changes are reviewed source revisions.** Changing the + services layer, such as a new site image, rolls the Deployments. The runtime + uses `Recreate`, so a rollout stops any running guest. The operation then stays + Unknown and capacity occupied; schedule such revisions with no operation in + flight. Dispatch changes are also source revisions, and kro remains the + only writer of the per-operation objects. Flux's `fleet-site-dispatch` + inventory is exactly the `HandoffDispatcher`; see [ownership](gitops.md#ownership). + **Image upgrades are not qualified:** historical Jobs are retained, and the + graph derives their image from the runtime Deployment. A changed image can + therefore cause kro to update an immutable Job pod template and block later + dispatch. This is a review-identified risk, not an exercised upgrade failure. + Instance recreation has verified no-op replay with the same image; it does + not qualify upgrades. Use a fresh disposable topology for image changes until + an upgrade lifecycle is implemented and tested. +- kro's controller is not in the authority path. If kro is down, no new + worker is created, existing Jobs continue, and the Flux-owned shared services + keep running and reconciling. Recovery is kro reconciliation followed by + journal replay. + +## Secrets + +The fence token remains inside the handoff's `requestJSON`; this is the existing +federation contract. Cell readers of handoffs are: + +- each worker, for its one handoff only; +- the observer; +- Karmada's member identity; +- kro, which must read handoffs to enumerate them. + +Job specs, Pod arguments, kro instance status and labels carry only handoff +names, the cell name and the scoped asset ID. Worker and observer logs print an +outcome class, never request bodies. The harness creates short-lived tokens for +RBAC probes with names ending in `.token`. It scans every evidence file against +all retained tokens, fences and boot capabilities. + +## What replaced what + +| Removed | Replaced by | +| --- | --- | +| `fleet-multiplane cell` process launched with `docker exec`, its PID file and `kill` signalling | kro-created Jobs and the Job controller | +| `coordination.Cell.Run` list/watch loop and `Reconcile` (execute plus publish) | `Cell.Execute` (worker; no status writes) and `Cell.Publish`/`Cell.Observe` (observer; lookup only) | +| `config/multiplane/cell-rbac.yaml` and an exported cell kubeconfig | Static observer RBAC and kro per-operation RBAC; no cell credential leaves the cell | +| Dedicated privileged provider container and `docker exec` probes | Runtime, boot and observer Deployments; probes through the cell API | +| kro-created runtime, boot and observer Deployments, boot Service and their ServiceAccounts (`FleetSite` graph), with a cluster-wide kro write grant | Flux layer `fleet-site-services` (scoped identity) and identities in `fleet-site-base`; the `HandoffDispatcher` graph references them; kro writes are namespaced and admission-checked | +| `helm install` of kro, `kubectl apply` of the site base and RGD, a `kubectl patch` of `dispatch`, and `kind load` of the image | Cell Flux `HelmRelease`/Kustomizations from a pushed source revision; the image pulled by digest from the run registry ([details](gitops.md)) | + +The single-plane [local VM harness](local-vm.md) still uses its own disposable +container and is unchanged. + +## Implemented versus proposed + +| Behavior | Status | +| --- | --- | +| Flux-owned shared site services and storage; kro-created per-operation RBAC and bounded worker Jobs on a real cell API | Implemented and exercised by `task multiplane:acceptance` | +| Single-writer ownership audit, shared Service drift repair by Flux, graph lifecycle leaving shared services and storage untouched | Implemented and exercised (`flux-verify`, `flux-drift`, `flux-graph-lifecycle`, `flux-final`) | +| Narrowed kro RBAC and admission policies on kro's writes | Implemented and exercised (`rbac`, `kro-rbac.json`); every dispatched Job and its RBAC passed them | +| In-place migration of an existing site from kro-owned shared services | Proposed only ([trust model](#ownership-and-trust-model)) | +| Pod loss and Job deletion mid-install resuming the same operation with one installer start | Implemented and exercised | +| Duplicate, wrong-cell and stale-epoch delivery failing by `podFailurePolicy` before effects | Implemented and exercised | +| Pod/Job lifecycle not changing journal, guest or allocation | Implemented and exercised | +| Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | +| Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | +| Redfish/BMC execution Jobs | Not implemented | + +## Independent review of the recorded run + +This review covered the run before Flux installation. The +[Flux-reconciled run](multiplane.md#flux-reconciled-acceptance-2026-11-15) +re-established the same execution findings and has not yet been independently +reviewed. + +The reviewer reproduced both binaries byte for byte, verified all 113 source +fingerprint entries and all 39 phase results, and passed the full Go race suite, +vet, offline harness tests and ShellCheck. An adversarial concurrency probe +confirmed that a second worker cannot act while the first holds the journal lock. +No blocker was found for the disposable single-node proof. + +The Job-deletion phase establishes that installation was still at +`installer-started` and that a replacement Job resumed that exact operation. It +does not establish that the replacement worker Pod was already Running or held +the journal lock at the instant its predecessor Job was deleted. Pod interruption +and Job recreation evidence should not be read as a stronger timing guarantee. +That review found that RGD and instance authors remained trusted, because kro's +grant could create workloads using any namespace ServiceAccount, including the +observer's. The current composition closes that path with namespaced kro writes +and admission policies; the remaining trust is listed under +[ownership and trust model](#ownership-and-trust-model). diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile index f86ddeda..14e4afe6 100644 --- a/hack/local-vm/Containerfile +++ b/hack/local-vm/Containerfile @@ -10,6 +10,14 @@ RUN chmod 755 /usr/local/bin/fleet-start-libvirt COPY --from=guest /out /opt/fleet-local/artifacts ENV FLEET_LOCAL_VM=disposable-container LIBVIRT_DEFAULT_URI=qemu:///system +# Kubernetes site image: the same pinned artifacts plus the checksum-verified +# fleet-multiplane binary from the named build context "fleetbin". Runtime, +# boot service, observer and per-operation worker Jobs all use this image. +FROM tcg AS site +COPY site-runtime /usr/local/bin/fleet-site-runtime +COPY --from=fleetbin fleet-multiplane /usr/local/bin/fleet-multiplane +RUN chmod 755 /usr/local/bin/fleet-site-runtime /usr/local/bin/fleet-multiplane && printf '%s\n' 'unix_sock_dir = "/run/fleet-libvirt"' >> /etc/libvirt/libvirtd.conf + FROM fleet-vm-local AS kvm USER root COPY start-libvirt /usr/local/bin/fleet-start-libvirt diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime new file mode 100755 index 00000000..2d71dd70 --- /dev/null +++ b/hack/local-vm/site-runtime @@ -0,0 +1,22 @@ +#!/bin/sh +# VM runtime for the Kubernetes site: libvirtd only. Workers reach it through +# the socket directory shared on the site volume; nothing listens on TCP. +set -eu +[ "${FLEET_LOCAL_VM_ACCEL:-}" = tcg ] || { echo 'site runtime requires FLEET_LOCAL_VM_ACCEL=tcg' >&2; exit 1; } +boot_ip=${FLEET_BOOT_IP:?boot Service ClusterIP required} +case "$boot_ip" in *[!0-9.]*|'') echo 'invalid boot Service IP' >&2; exit 1 ;; esac +sock=/run/fleet-libvirt +mkdir -p "$sock" /run/libvirt /var/lib/libvirt/images /var/log/libvirt/qemu +# A previous runtime Pod's socket is stale; libvirtd recreates it. +rm -f "$sock"/libvirt-sock "$sock"/libvirt-sock-ro "$sock"/libvirt-admin-sock +# Firmware on the provisioning bridge may reach this namespace (DHCP) and the +# boot Service only. Anything else forwarded from the bridge is dropped. +iptables -t mangle -N FLEET-PXE 2>/dev/null || iptables -t mangle -F FLEET-PXE +iptables -t mangle -A FLEET-PXE -m addrtype --dst-type LOCAL -j RETURN +iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN +iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN +iptables -t mangle -A FLEET-PXE -j DROP +iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE +virtlogd --daemon +virtlockd --daemon +exec /usr/bin/tini -- libvirtd diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh new file mode 100755 index 00000000..54d3c27a --- /dev/null +++ b/hack/multiplane/acceptance.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Ordered acceptance phases over an already bootstrapped topology. Each phase is +# bounded and recorded in evidence/phases.jsonl; the first failure stops the run. +set -euo pipefail +umask 077 +state=${1:?private state directory} +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +host="$state/fleet-multiplane-host" +ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } +flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } + +ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +ph allocate 900 "$host" allocate --config "$state/acceptance.json" +step verify-contention 120 +ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" +step await-delivery 300 +step partition 300 +step dispatch 900 +step interrupt-pod 1200 +step interrupt-job 600 +step resume 1800 +step worker-rbac 120 +step partition-readiness 900 +step heal 1200 +ph install 900 "$host" install --config "$state/acceptance.json" +ph install-repeat 900 "$host" install --config "$state/acceptance.json" +step lifecycle 900 +flux graph-lifecycle 1200 +flux drift 900 +flux restart 1200 +flux fail-closed 1500 +flux retention 1500 +ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" +ph release 1200 "$host" release --config "$state/acceptance.json" +step release-status-a 120 +ph reuse 900 "$host" reuse --config "$state/acceptance.json" +step reuse-status 120 +step delivery-faults 900 +ph release-b 1200 "$host" release-b --config "$state/acceptance.json" +step release-status-b 120 +step wrong-location 300 +step boot-denials 300 +step flux-final 900 +ph evidence 300 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py new file mode 100755 index 00000000..95c96ee5 --- /dev/null +++ b/hack/multiplane/evidence.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Capture private diagnostics and emit an explicit allowlist-only summary. + +Private copies stay in /provider-private. Only evidence/ is shareable, +and run.sh scans it against every retained credential before reporting. +""" +import datetime +import hashlib +import json +import os +import pathlib +import re +import subprocess +import sys +import tarfile + +s = pathlib.Path(sys.argv[1]) +prefix = (s / 'prefix').read_text().strip() +ev = s / 'evidence' +os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' + + +def out(*args): + return subprocess.check_output(args, text=True, timeout=60) + + +def fail(message): + raise SystemExit(message + '; retain diagnostics and Unknown custody') + + +def kubectl(*args): + return out('kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '--request-timeout=30s', *args) + + +def kget(*args): + return json.loads(kubectl(*args, '-o', 'json')) + + +def runtime(*command): + return kubectl('-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command) + + +def copy_out(source, destination): + """Stream a runtime Pod directory into private state through the cell API.""" + destination.mkdir(mode=0o700, parents=True, exist_ok=True) + p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', + '--', 'tar', '-C', source, '-cf', '-', '.'], stdout=subprocess.PIPE) + with tarfile.open(fileobj=p.stdout, mode='r|') as archive: + archive.extractall(destination, filter='data') + if p.wait(timeout=120): + fail('could not copy ' + source + ' from the runtime Pod') + + +memory_events = dict(line.split() for line in runtime('cat', '/sys/fs/cgroup/memory.events').splitlines()) +node_events = {node: dict(line.split() for line in out('docker', 'exec', prefix + '-' + node + '-control-plane', 'cat', '/sys/fs/cgroup/memory.events').splitlines()) + for node in ('cell', 'hub', 'platform')} +node_memory_events = node_events['cell'] +if int(memory_events.get('oom_kill', '0')) or any(int(e.get('oom_kill', '0')) for e in node_events.values()): + fail('runtime Pod or kind node OOM kill recorded; inspect memory.events') +for config, namespace in (('cell-admin.yaml', 'fleet-site'), ('cell-admin.yaml', 'kro-system'), ('cell-admin.yaml', 'flux-system'), ('host.yaml', 'flux-system'), + ('host.yaml', 'karmada-system'), ('platform-admin.yaml', 'flux-system'), ('platform-admin.yaml', 'milo-provider'), + ('platform-admin.yaml', 'milo-consumer-a'), ('platform-admin.yaml', 'milo-consumer-b')): + for pod in json.loads(out('kubectl', '--kubeconfig', str(s / config), '--request-timeout=30s', '-n', namespace, 'get', 'pods', '-o', 'json'))['items']: + for c in pod['status'].get('containerStatuses', []): + if any(state.get('reason') == 'OOMKilled' for state in (c.get('lastState', {}).get('terminated') or {}, c.get('state', {}).get('terminated') or {})): + fail('OOMKilled container in ' + namespace + '/' + pod['metadata']['name']) +routing = json.loads((s / 'routing.json').read_text()) +if len(routing) != 2 or any(x['namespace'] != 'default' or x['watch'] != 'Added exact UID' for x in routing) or routing[0]['namespaceUID'] == routing[1]['namespaceUID'] or routing[0]['projectUID'] == routing[1]['projectUID']: + fail('missing independent native project create/watch evidence') + +phases = (s / 'phases.log').read_text() +markers = ('Verified forbidden observer/project/hub writes', 'allocate: verified', 'contention: consumer-a Bound', 'delivery: Karmada delivered exactly one', + 'kro created the worker Job and per-operation RBAC', 'worker-rbac: per-operation ServiceAccount', 'interrupt-pod: worker Pod force-deleted', + 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', + 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', + 'delivery-faults: duplicate, wrong-cell and stale-epoch', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine Released', + 'wrong-location: denied before allocation', 'Flux restored the binding', 'flux-verify: 3 clusters Ready', 'cell Flux applied the dispatch revision', + 'Flux restored consumer-a', 'Flux on every cluster Ready at the current revision', 'flux-drift: helm-controller restored kro', + 'recreated the shared boot Service at its fixed ClusterIP and restored the observer', 'flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects', + 'kro RBAC and admission confine it to per-operation objects', + 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', + 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in ( + 'wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing')) +for marker in markers: + if marker not in phases: + fail('missing acceptance phase: ' + marker) + +def libvirt_provider(): + raw = s / 'provider-private' + raw.mkdir(mode=0o700, exist_ok=True) + copy_out('/var/lib/fleet-local', raw) + copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') + copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') + j = json.loads((raw / 'journal.json').read_text()) + ops = list(j['operations'].values()) + installs = [o for o in ops if o['request']['kind'] == 'install'] + cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] + if j.get('bootMode') != 'pxe' or len(installs) != 1 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): + fail('expected PXE mode, exactly one install and two verified cleanups') + if not j.get('closed'): + fail('allocation epoch is not closed after final cleanup') + epochs = sorted({o['request']['epoch'] for o in ops}) + if epochs != [1, 2]: + fail('expected allocation epochs 1 and 2, got %s' % epochs) + + interrupt = json.loads((ev / 'interrupt.json').read_text()) + if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: + fail('interrupt evidence does not identify the retained install operation mid-installer') + + logs = list(raw.rglob('boot-delivery.log')) + written = '\n'.join(p.read_text() for p in logs) + for name in ('boot.ipxe', 'kernel', 'installer.gz'): + if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): + fail('missing completed broker write for ' + name) + + receipts, starts = [], {} + for o in installs: + op_id = o['request']['id'] + directory = raw / hashlib.sha256(op_id.encode()).hexdigest() + for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): + p = directory / filename + lines = [line.strip() for line in p.read_text(errors='replace').splitlines()] if p.exists() else [] + if lines.count(marker + o['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: + fail('expected exactly one exact guest receipt in ' + filename) + receipts.append({'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) + if sum(1 for l in (directory / 'installer.log').read_text(errors='replace').splitlines() if re.match(r'^\+ sfdisk /dev/vda', l.strip())) != 1: + fail('installer partitioned the disk other than exactly once') + installer, disk = (directory / 'installer.xml').read_text(), (directory / 'disk.xml').read_text() + if "boot dev='network'" not in installer or '' in installer or '' in installer: + fail('installer domain is not firmware network boot only') + if '' in disk or '' in disk or "boot dev='hd'" not in disk: + fail('disk-only boot has a NIC or direct kernel') + if '52:54:00:77:00:02' not in (directory / 'dhcp-leases.txt').read_text(): + fail('missing DHCP lease for the installer NIC') + if not o.get('bootClosed'): + fail('boot admission not closed') + if (directory / 'disk.raw').exists(): + fail('cleaned allocation still has a guest disk') + # libvirt appends one 'starting up' block per QEMU start. Independent of the + # journal, this proves one firmware-network installer start and one disk start. + qemu = (raw / 'libvirt-qemu' / ('fleet-local-' + hashlib.sha256(op_id.encode()).hexdigest()[:24] + '.log')).read_text(errors='replace') + blocks = [b for b in re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:]] + network = [b for b in blocks if '-netdev' in b and '52:54:00:77:00:02' in b] + disk_only = [b for b in blocks if '-netdev' not in b and 'virtio-disk0' in b] + starts[op_id] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} + if len(blocks) != 2 or len(network) != 1 or len(disk_only) != 1 or blocks.index(network[0]) != 0: + fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[op_id]) + + domains = runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--all', '--name').strip() + if domains: + fail('provider domain remains after cleanup') + denials = (s / 'boot-denials.txt').read_text().strip() if (s / 'boot-denials.txt').exists() else '' + if not denials.startswith('PASS'): + fail('missing live closed-boot HTTP denial evidence') + return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + + +ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = libvirt_provider() + +# Kubernetes execution: what actually ran, as names, UIDs, phases and conditions. +kro = kget('-n', 'kro-system', 'get', 'deployment')['items'] +kro_pods = kget('-n', 'kro-system', 'get', 'pods')['items'] +rgd = kget('get', 'resourcegraphdefinition', 'fleet-handoff-dispatcher') +instance = kget('-n', 'fleet-site', 'get', 'handoffdispatcher', 'dispatcher') +if rgd['status'].get('state') != 'Active' or instance['status'].get('state') != 'ACTIVE': + fail('kro RGD or HandoffDispatcher instance not active') +jobs = kget('-n', 'fleet-site', 'get', 'jobs', '-l', 'app.kubernetes.io/name=fleet-site-worker')['items'] +handoffs = {h['metadata']['name']: json.loads(h['spec']['requestJSON']) for h in kget('-n', 'fleet-coordination', 'get', 'machineallocationhandoffs')['items']} +worker_jobs = [] +for job in jobs: + handoff = job['metadata']['labels']['fleet.datumapis.com/handoff'] + conditions = sorted([c['type'], c['status'], c.get('reason', '')] for c in job['status'].get('conditions', [])) + if ['Complete', 'True', 'CompletionsReached'] not in conditions: + fail('worker Job not Complete: ' + job['metadata']['name']) + job_pods = kget('-n', 'fleet-site', 'get', 'pods', '-l', 'batch.kubernetes.io/controller-uid=' + job['metadata']['uid'])['items'] + exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in job_pods] + if exits.count(0) != 1: + fail('worker Job without exactly one successful Pod: ' + job['metadata']['name']) + worker_jobs.append({'job': job['metadata']['name'], 'uid': job['metadata']['uid'], 'operationID': handoffs[handoff]['id'], 'kind': handoffs[handoff]['kind'], + 'epoch': handoffs[handoff]['epoch'], 'conditions': conditions, 'succeeded': job['status'].get('succeeded', 0), 'failed': job['status'].get('failed', 0), + 'pods': [{'uid': p['metadata']['uid'], 'phase': p['status'].get('phase'), 'exitCode': e} for p, e in zip(job_pods, exits)], + 'serviceAccount': job['spec']['template']['spec']['serviceAccountName'], 'podReplacementPolicy': job['spec'].get('podReplacementPolicy'), + 'podFailurePolicy': job['spec'].get('podFailurePolicy'), 'backoffLimit': job['spec'].get('backoffLimit'), + 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id')}) +if sorted(j['kind'] for j in worker_jobs) != ['cleanup', 'cleanup', 'install'] or any(j['createdBy'] != 'workers' for j in worker_jobs): + fail('expected kro-created worker Jobs for exactly one install and two cleanups, got %s' % [(j['kind'], j['createdBy']) for j in worker_jobs]) +pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') +pv = kget('get', 'pv', pvc['spec']['volumeName']) +deployments = {d['metadata']['name']: {'uid': d['metadata']['uid'], 'availableReplicas': d['status'].get('availableReplicas', 0), + 'fluxLayer': d['metadata'].get('labels', {}).get('kustomize.toolkit.fluxcd.io/name'), + 'kroLabels': sorted(k for k in d['metadata'].get('labels', {}) if k.startswith('kro.run/') or k.startswith('applyset.kubernetes.io/'))} + for d in kget('-n', 'fleet-site', 'get', 'deployments')['items']} +execution = { + 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'kro': {'version': 'v0.9.4', 'chart': 'oci://registry.k8s.io/kro/charts/kro@sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c', + 'chartArchiveSHA256': 'ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd', 'installedBy': 'Flux HelmRelease flux-system/kro', + 'image': kro[0]['spec']['template']['spec']['containers'][0]['image'], 'imageID': kro_pods[0]['status']['containerStatuses'][0]['imageID'], 'rbacMode': 'aggregation', + 'helmReleaseOwner': kro[0]['metadata'].get('labels', {}).get('helm.toolkit.fluxcd.io/name')}, + 'resourceGraphDefinition': {'name': 'fleet-handoff-dispatcher', 'state': rgd['status']['state'], 'conditions': sorted([c['type'], c['status']] for c in rgd['status'].get('conditions', []))}, + 'handoffDispatcher': {k: v for k, v in instance['status'].items() if k != 'conditions'}, + 'siteDeployments': deployments, + 'ownership': 'Flux Kustomization fleet-site-services owns the shared Deployments and boot Service; kro owns only per-operation worker Jobs, ServiceAccounts, Roles and RoleBindings', + 'siteVolume': {'pvc': pvc['metadata']['name'], 'pvcUID': pvc['metadata']['uid'], 'pv': pv['metadata']['name'], 'pvUID': pv['metadata']['uid'], + 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'storageClass': pvc['spec']['storageClassName'], 'managedByKro': False}, + 'workerJobs': worker_jobs, + 'dispatch': json.loads((s / 'k8s-dispatch-job.json').read_text()), + 'workerRBAC': json.loads((s / 'k8s-worker-rbac.json').read_text()), + 'interruptions': json.loads((ev / 'interrupt.json').read_text()), + 'lifecycle': json.loads((ev / 'lifecycle.json').read_text()), + 'deliveryFaults': json.loads((ev / 'delivery-faults.json').read_text()), + 'authority': 'Job Complete, Flux Ready and kro Ready are execution facts only; management validated Karmada-reflected, journal-derived observations before any projection', +} +if execution['kro']['helmReleaseOwner'] != 'kro': + fail('kro controller is not owned by the Flux HelmRelease') +if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime']) or any( + d['availableReplicas'] != 1 or d['fluxLayer'] != 'fleet-site-services' or d['kroLabels'] for d in deployments.values()): + fail('site volume or Flux-owned shared Deployments not as expected') +(ev / 'kubernetes-execution.json').write_text(json.dumps(execution, indent=2, sort_keys=True) + '\n') +arch = out('docker', 'info', '--format', '{{.Architecture}}').strip() +flux_files = ('flux-verify.json', 'flux-initial.json', 'flux-rbac-restore.json', 'flux-drift.json', 'flux-restart.json', 'flux-fail-closed.json', 'flux-retention.json', 'flux-final.json', + 'flux-graph-lifecycle.json', 'flux-ownership-final.json', 'kro-rbac.json') +for name in flux_files: + if not (ev / name).exists(): + fail('missing Flux evidence ' + name) +flux_revisions = json.loads((s / 'flux-revisions.json').read_text()) +final = json.loads((ev / 'flux-final.json').read_text()) +for cluster, snap in final.items(): + if snap['sources']['flux-system/fleet-gitops']['artifactRevision'] != flux_revisions[-1]['fluxRevision']: + fail('%s did not end on the final source revision' % cluster) + if any(k['lastAppliedRevision'] != flux_revisions[-1]['fluxRevision'] or k['suspend'] for n, k in snap['kustomizations'].items()): + fail('%s has a Kustomization not at the final revision' % cluster) +write_env = json.loads((s / 'gitops-environment.json').read_text()) + +summary = { + 'schemaVersion': 2, 'acceptance': 'passed', + 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'prefix': prefix, + 'qualification': {'nativeMiloProjectAPIs': True, 'actualKarmadaDeliveryAndReflection': True, 'realLocalPXE': True, + 'kubernetesJobExecution': True, 'actualKroController': True, 'fluxReconciledServices': True, + 'kvm': False, 'uefi': False, 'productionAuthority': False, 'productionEquivalence': False}, + 'versions': {'milo': 'v0.32.5', 'karmada': 'v1.16.0', 'kro': 'v0.9.4', 'flux': 'v2.9.6', 'kindNode': 'v1.35.0', 'architecture': arch, 'guestArchitecture': 'amd64', 'accelerator': 'tcg', 'firmware': 'SeaBIOS/iPXE (legacy BIOS)'}, + 'scenarios': { + 'exclusiveContention': True, + 'partitionPublicReadyStayedFalse': True, + 'interruptedWorkerResumedExactOperation': interrupt, + 'kubernetesExecution': 'kubernetes-execution.json', + 'gitops': {'sourceRevisions': [{k: r[k] for k in ('revision', 'digest', 'purpose', 'gitHead', 'contentSumsSHA256', 'files')} for r in flux_revisions], + 'evidence': list(flux_files), 'siteImage': write_env['siteImage']}, + 'installerStarts': starts, + 'reflectionRejections': ['wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing'], + 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), + 'releasedProjection': {'consumerA': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer', 'installation': 'Released, Ready False'}, + 'consumerB': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer'}}, + 'cleanupAndReuse': {'epochs': epochs, 'cleanups': len(cleanups), 'domainsAfterCleanup': [], 'disksAfterCleanup': 0}, + 'closedBootDenials': denials, + }, + 'operations': [{'id': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], 'phase': o['result']['phase'], 'result': o['result']['result'], 'inputDigest': o['result']['inputDigest']} for o in ops], + 'projectRouting': routing, 'brokerWriteCompletion': True, 'guestEvidence': receipts, + 'runtimePodMemoryEvents': {key: int(value) for key, value in memory_events.items()}, + 'cellNodeMemoryEvents': {key: int(value) for key, value in node_memory_events.items()}, + 'nodeMemoryEvents': {node: {key: int(value) for key, value in e.items()} for node, e in node_events.items()}, + 'seams': ['static-token root RBAC', 'independent local Milo roots on one platform kind cluster (Flux-managed workloads, bootstrap-enrolled credentials, fixture project bootstrap)', + 'plain-HTTP unsigned local OCI registry as the Flux source', 'bootstrap-minted 24h ServiceAccount tokens and member Secret', 'synthetic source-use admission and publication', + 'synthetic quota and settlement', 'synthetic hardware enrollment mapping', 'networkless workload', + 'privileged disposable VM runtime Pod on a single kind node', 'kro reads delivered handoffs (it must, to enumerate them)', + 'trusted graph and services authors: worker Jobs reach root libvirtd through its socket', + 'reflection faults injected with bootstrap credentials while the Karmada controller is stopped'], + 'privateArtifacts': 'state directory outside evidence/ contains authority; do not publish', +} +(ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') +for name in ('source-SHA256SUMS', 'sysctl.json'): + if (s / name).exists(): + (ev / name).write_text((s / name).read_text()) +paths = [s / 'site-bin' / 'fleet-multiplane', s / 'fleet-multiplane-host'] +(ev / 'binary-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest() + ' ' + p.name + '\n' for p in paths)) +(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n') +print('evidence: sanitized summary ' + str(ev / 'summary.json')) diff --git a/hack/multiplane/fault_guard.py b/hack/multiplane/fault_guard.py new file mode 100644 index 00000000..4c6408ad --- /dev/null +++ b/hack/multiplane/fault_guard.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Record and verify that a Flux suspension survived a fault interval.""" +import datetime +import json +import pathlib +import subprocess +import sys + + +def validate(obj, deployment, pods, baseline=None): + metadata = obj['metadata'] + receipt = {'uid': metadata['uid'], 'generation': metadata['generation'], + 'suspended': obj.get('spec', {}).get('suspend') is True, + 'replicas': deployment.get('spec', {}).get('replicas'), + 'activePods': len(pods['items'])} + if not receipt['suspended'] or receipt['replicas'] != 0 or receipt['activePods'] != 0: + raise ValueError('fault isolation lost: suspension, zero replicas and no Pods required') + if baseline is not None and receipt != baseline: + raise ValueError('fault isolation changed during suspension') + return receipt + + +def root_receipt(root, revision): + """The cluster's root sync applied the given source revision while the fault held.""" + status = root.get('status', {}) + ready = any(c.get('type') == 'Ready' and c.get('status') == 'True' for c in status.get('conditions', [])) + if status.get('lastAppliedRevision') != revision or not ready or status.get('observedGeneration') != root['metadata']['generation']: + raise ValueError('root sync did not apply %s during the fault' % revision) + return {'revision': revision, 'lastHandledReconcileAt': status.get('lastHandledReconcileAt')} + + +def main(): + mode, state, config, kind, name, namespace, deployment, evidence = sys.argv[1:9] + # Optional: the source revision the root sync must have applied during the fault. + revision = sys.argv[9] if len(sys.argv) > 9 else None + if mode not in ('record', 'check'): + raise ValueError('expected record or check') + state = pathlib.Path(state) + + def get(*args): + return json.loads(subprocess.check_output( + ['kubectl', '--kubeconfig', str(state / config), '--request-timeout=20s', + *args, '-o', 'json'], text=True)) + + obj = get('-n', 'flux-system', 'get', kind, name) + dep = get('-n', namespace, 'get', 'deployment', deployment) + labels = dep['spec']['selector']['matchLabels'] + pods = get('-n', namespace, 'get', 'pods', '-l', ','.join(k + '=' + v for k, v in sorted(labels.items()))) + path = state / 'evidence' / (evidence + '.json') + previous = json.loads(path.read_text()) if mode == 'check' else None + receipt = validate(obj, dep, pods, previous['before'] if previous else None) + record = previous or {'kind': kind, 'name': name, 'fieldManager': 'fleet-fault-injection', 'before': receipt} + record['checkedAt'] = datetime.datetime.now(datetime.timezone.utc).isoformat() + if mode == 'check': + record['after'] = receipt + record['unchanged'] = True + if revision: + root = get('-n', 'flux-system', 'get', 'kustomizations.kustomize.toolkit.fluxcd.io', 'fleet-cluster') + record['rootReconciledDuringFault'] = root_receipt(root, revision) + path.write_text(json.dumps(record, indent=2) + '\n') + + +if __name__ == '__main__': + main() diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py new file mode 100644 index 00000000..30bac12f --- /dev/null +++ b/hack/multiplane/flux.py @@ -0,0 +1,1114 @@ +#!/usr/bin/env python3 +"""Flux source, bootstrap and reconciliation evidence for the local acceptance. + +The acceptance reconciles every long-running service from one OCI artifact, +staged from the current checkout and pushed to this run's local registry. +This module owns only: + + tools download and verify the pinned Flux CLI and install manifest + stage build one source revision (checkout config + generated environment) + push push a staged revision and record its digest + bootstrap apply one cluster's Flux components and sync objects, once + publish stage + push + request reconcile + wait for the given clusters + wait wait until a cluster's Flux objects are Ready at the pushed revision + record write a sanitized snapshot of a cluster's Flux objects + verify, drift, restart, fail-closed, retention, graph-lifecycle + acceptance scenarios; ownership audits who writes each site object + +Every Kubernetes write it makes is either the documented bootstrap boundary +(Flux components and sync objects, applied once), a reconcile request +annotation, or explicit fault injection whose repair is left to Flux. +Nothing here stores credentials in a source revision. +""" +import argparse +import datetime +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tarfile +import time +import urllib.request + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (secret discovery and exit codes) + +FLUX_VERSION = '2.9.6' +RELEASE = 'https://github.com/fluxcd/flux2/releases/download/v%s/' % FLUX_VERSION +# From flux_2.9.6_checksums.txt of the v2.9.6 GitHub release. +INSTALL_SHA256 = '9c1fda7e401429531ed1478f67ba06b3edff6513b75da7ee47bde9f1c4d4251c' +CLI = {('darwin', 'arm64'): ('flux_2.9.6_darwin_arm64.tar.gz', '7008a758da4b8d57c5845aad6552f256d4d23630c2b2de2ca8da362f9a48c126'), + ('darwin', 'x86_64'): ('flux_2.9.6_darwin_amd64.tar.gz', 'c3c3532c8c6cf689ef7b93125b33dc170df84a9d5d036f578568bfdf88a2d7e6'), + ('linux', 'x86_64'): ('flux_2.9.6_linux_amd64.tar.gz', 'b4d22673e9246cbd628881f1a9ef3b090085dced291e42d804555cee8e8d42c5'), + ('linux', 'aarch64'): ('flux_2.9.6_linux_arm64.tar.gz', '6663c154755b732f43dc993d72321f71c2fc1ff0bcb94b2696e0a8638fa562b4')} +REGISTRY_IMAGE = 'registry:3.0.0@sha256:6c5666b861f3505b116bb9aa9b25175e71210414bd010d92035ff64018f9457e' +KRO_CHART_DIGEST = 'sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c' +KRO_CHART_LAYER_SHA256 = 'ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd' +KARMADA_CHART_SHA256 = '773ab194cb92dad81d479d2199b968a2c6b0b8366306ba47961afd67616834fe' +# A well-formed digest that no registry serves: the fail-closed revision. +MISSING_DIGEST = 'sha256:' + hashlib.sha256(b'fleet: deliberately absent chart').hexdigest() +TAG = 'local' +CLUSTERS = ('platform', 'hub', 'cell') +KUBECONFIG = {'platform': 'platform-admin.yaml', 'hub': 'host.yaml', 'cell': 'cell-admin.yaml'} +SOURCE_DIRS = ('config/multiplane', 'config/site') +# Expected Flux Kustomizations per cluster (namespace/name), besides the root. +EXPECTED = { + 'platform': ['flux-system/milo-provider', 'flux-system/milo-consumer-a', 'flux-system/milo-consumer-b'], + 'hub': ['flux-system/karmada', 'flux-system/fleet-host', 'karmada-system/fleet-karmada-coordination', + 'karmada-system/fleet-karmada-api', 'karmada-system/fleet-karmada-members'], + 'cell': ['flux-system/fleet-coordination', 'flux-system/fleet-federation', 'flux-system/kro', + 'flux-system/fleet-site-base', 'flux-system/fleet-site-graph'], +} +HELMRELEASES = {'hub': ['flux-system/karmada'], 'cell': ['flux-system/kro']} +# Cell site layers present once the scoped asset is known (revision 2 onwards). +SITE_LAYERS = ['flux-system/fleet-site-services', 'flux-system/fleet-site-dispatch'] +# A fixed ClusterIP in the static band (first 256 addresses) of kind's default +# 10.96.0.0/16 Service range, so a recreated boot Service keeps its origin. +BOOT_SERVICE_IP = '10.96.0.80' +SITE, COORD = 'fleet-site', 'fleet-coordination' +DISPATCHER = ('handoffdispatchers.site.fleet.datumapis.com', 'dispatcher') +RGD = 'fleet-handoff-dispatcher' +# Flux-owned shared site objects and the layer (Kustomization) that writes each. +SHARED = {('deployments', SITE, 'fleet-site-runtime'): 'fleet-site-services', ('deployments', SITE, 'fleet-site-boot'): 'fleet-site-services', + ('deployments', SITE, 'fleet-site-observer'): 'fleet-site-services', ('services', SITE, 'fleet-site-boot'): 'fleet-site-services', + ('configmaps', SITE, 'fleet-site-worker-policy'): 'fleet-site-services', + ('serviceaccounts', SITE, 'fleet-site-runtime'): 'fleet-site-base', ('serviceaccounts', SITE, 'fleet-site-boot'): 'fleet-site-base', + ('serviceaccounts', SITE, 'fleet-site-observer'): 'fleet-site-base', ('persistentvolumeclaims', SITE, 'fleet-site-state'): 'fleet-site-base', + ('roles', COORD, 'fleet-site-observer'): 'fleet-site-base', ('rolebindings', COORD, 'fleet-site-observer'): 'fleet-site-base', + ('roles', SITE, 'fleet-site-kro-workers'): 'fleet-site-base', ('rolebindings', SITE, 'fleet-site-kro-workers'): 'fleet-site-base', + ('roles', COORD, 'fleet-site-kro-worker-rbac'): 'fleet-site-base', ('rolebindings', COORD, 'fleet-site-kro-worker-rbac'): 'fleet-site-base', + ('clusterroles', None, 'fleet-site-kro'): 'fleet-site-base', + ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-jobs'): 'fleet-site-base', + ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-jobs'): 'fleet-site-base', + ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base', + ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base'} +# Exact inventories of the layers that must hold nothing else. +SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') +LAYER_INVENTORY = { + 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', + 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', + 'fleet-site_fleet-site-observer_apps_Deployment']), + 'flux-system/fleet-site-graph': ['_fleet-handoff-dispatcher_kro.run_ResourceGraphDefinition'], + 'flux-system/fleet-site-dispatch': ['fleet-site_dispatcher_site.fleet.datumapis.com_HandoffDispatcher'], +} +# kro writes only these per-operation kinds, all named w-. +WORKER_KINDS = (('jobs', SITE), ('serviceaccounts', SITE), ('roles', COORD), ('rolebindings', COORD)) +FORBIDDEN = (re.compile(r'^kind:\s*Secret\s*$', re.M), re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----'), + re.compile(r'''^\s*(token|client-key-data|password)\s*:\s*\S{16,}''', re.M)) + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def die(message, code=harness.EXIT_FAILED): + print(message, file=sys.stderr) + raise SystemExit(code) + + +def kubectl(state, cluster, *args, input=None, check=True, timeout=60, config=None): + path = pathlib.Path(state) / (config or KUBECONFIG[cluster]) + try: + r = subprocess.run(['kubectl', '--kubeconfig', str(path), '--request-timeout=20s', *args], input=input, + text=True, capture_output=True, timeout=timeout) + except subprocess.TimeoutExpired: + die('kubectl %s on %s timed out' % (' '.join(args[:3]), cluster), harness.EXIT_TIMEOUT) + if check and r.returncode: + die('kubectl %s on %s failed: %s' % (' '.join(args[:4]), cluster, r.stderr.strip()[:400])) + return r + + +def kget(state, cluster, *args, config=None): + return json.loads(kubectl(state, cluster, *args, '-o', 'json', config=config).stdout) + + +def sha256(path): + return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest() + + +def write(path, value): + path = pathlib.Path(path) + path.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + path.chmod(0o600) + + +def flux_bin(state): + return str(pathlib.Path(state) / 'flux-tools' / 'flux') + + +# ---------------------------------------------------------------- tools + +def fetch(url, dest, digest): + if not dest.exists() or sha256(dest) != digest: + tmp = dest.with_suffix('.part') + with urllib.request.urlopen(url, timeout=120) as r, open(tmp, 'wb') as f: + shutil.copyfileobj(r, f) + tmp.replace(dest) + if sha256(dest) != digest: + die('%s digest mismatch: %s' % (dest.name, sha256(dest))) + + +def tools(args): + d = pathlib.Path(args.state) / 'flux-tools' + d.mkdir(mode=0o700, exist_ok=True) + key = (os.uname().sysname.lower(), os.uname().machine) + if key not in CLI: + die('no pinned Flux CLI for %s/%s' % key, harness.EXIT_PREFLIGHT) + archive, digest = CLI[key] + fetch(RELEASE + archive, d / archive, digest) + fetch(RELEASE + 'install.yaml', d / 'install.yaml', INSTALL_SHA256) + with tarfile.open(d / archive) as t: + t.extract('flux', d, filter='data') + version = subprocess.run([str(d / 'flux'), 'version', '--client'], text=True, capture_output=True).stdout.strip() + if version != 'flux: v' + FLUX_VERSION: + die('unexpected Flux CLI version: ' + version) + record = {'version': 'v' + FLUX_VERSION, 'cli': {'archive': archive, 'sha256': digest, 'binarySHA256': sha256(d / 'flux')}, + 'installManifest': {'url': RELEASE + 'install.yaml', 'sha256': INSTALL_SHA256}} + write(d / 'tools.json', record) + print('flux-tools: Flux CLI v%s and install manifest verified (install.yaml sha256 %s)' % (FLUX_VERSION, INSTALL_SHA256)) + return 0 + + +# ---------------------------------------------------------------- source + +def environment(state): + s = pathlib.Path(state) + env = json.loads((s / 'gitops-environment.json').read_text()) + if (s / 'scoped-asset').exists(): + env['scopedAsset'] = (s / 'scoped-asset').read_text().strip() + return env + + +def sync_objects(cluster, url): + """The per-cluster sync objects that flux bootstrap would commit as gotk-sync.yaml.""" + return '''# Generated per environment: the OCI source and the root sync for %(c)s. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: + name: fleet-gitops + namespace: flux-system +spec: + interval: 1m + url: %(url)s + ref: + tag: %(tag)s + # Local seam: a plain-HTTP registry on the disposable kind network. A real + # environment uses TLS and verifies signatures (spec.verify). + insecure: true +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: + name: fleet-cluster + namespace: flux-system +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: false + sourceRef: + kind: OCIRepository + name: fleet-gitops + path: ./environment/%(c)s +''' % {'c': cluster, 'url': url, 'tag': TAG} + + +def config_map(name, namespace, data): + lines = ['apiVersion: v1', 'kind: ConfigMap', 'metadata:', ' name: ' + name, ' namespace: ' + namespace, 'data:'] + lines += [' %s: %s' % (k, json.dumps(str(v))) for k, v in sorted(data.items())] + return '\n'.join(lines) + '\n' + + +def stage(args): + s = pathlib.Path(args.state).resolve() + root = pathlib.Path(args.root).resolve() + env = environment(s) + out = s / 'gitops' / ('r%d' % args.revision) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True, mode=0o700) + for name in SOURCE_DIRS: + shutil.copytree(root / name, out / name, ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '.*')) + tools_dir = s / 'flux-tools' + if sha256(tools_dir / 'install.yaml') != INSTALL_SHA256: + die('install manifest changed after verification') + components = out / 'environment' / 'flux-components' + components.mkdir(parents=True) + shutil.copy(tools_dir / 'install.yaml', components / 'gotk-components.yaml') + shutil.copy(root / 'config/multiplane/flux/components.yaml', components / 'kustomization.yaml') + url = 'oci://%s:5000/fleet-gitops' % env['registryHost'] + marker = 'r%d' % args.revision + for cluster in CLUSTERS: + d = out / 'environment' / cluster + (d / 'flux-system').mkdir(parents=True) + (d / 'flux-system' / 'gotk-sync.yaml').write_text(sync_objects(cluster, url)) + (d / 'flux-system' / 'kustomization.yaml').write_text( + 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - ../../flux-components\n - gotk-sync.yaml\n') + resources = ['flux-system', '../../config/multiplane/clusters/' + cluster, 'environment.yaml'] + data = {'FLEET_CELL': env['cell'], 'FLEET_CELL_ENDPOINT': env['cellEndpoint'], 'FLEET_SOURCE_MARKER': marker} + maps = [] + patches = [] + if cluster == 'hub': + # Karmada-API Kustomizations live beside their kubeconfig Secret. + maps.append(config_map('fleet-environment', 'karmada-system', data)) + if cluster == 'cell': + if args.site != 'absent': + resources.insert(2, '../../config/multiplane/clusters/cell-site') + data.update(FLEET_SCOPED_ASSET=env['scopedAsset'], FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, + FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false') + if args.bad_kro_chart: + patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, + 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}])) + if args.drop_site_volume: + patches.append(child_patch('fleet-site-base', [{'patch': '$patch: delete\napiVersion: v1\nkind: PersistentVolumeClaim\n' + 'metadata:\n name: fleet-site-state\n namespace: fleet-site\n'}])) + maps.insert(0, config_map('fleet-environment', 'flux-system', data)) + (d / 'environment.yaml').write_text('# Generated, non-secret environment values for revision %s.\n' % marker + '---\n'.join(maps)) + k = 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n' + ''.join(' - %s\n' % r for r in resources) + if patches: + k += 'patches:\n' + ''.join(patches) + (d / 'kustomization.yaml').write_text(k) + files = sorted(p for p in out.rglob('*') if p.is_file()) + secrets = harness.secrets(s) + for p in files: + text = p.read_text(errors='ignore') + if any(f.search(text) for f in FORBIDDEN) or any(v in text for v in secrets): + die('refusing to stage credential-like content: ' + str(p.relative_to(out))) + # Every environment must render before it is published. + for cluster in CLUSTERS: + r = subprocess.run(['kustomize', 'build', str(out / 'environment' / cluster)], capture_output=True, text=True) + if r.returncode: + die('environment %s does not render: %s' % (cluster, r.stderr[-400:])) + sums = ''.join('%s %s\n' % (sha256(p), p.relative_to(out)) for p in files) + (s / 'gitops' / ('r%d.SHA256SUMS' % args.revision)).write_text(sums) + print('stage: revision %s with %d files (%s); no credential content' % (marker, len(files), ', '.join( + k for k, v in (('site', args.site != 'absent'), ('dispatch', args.site == 'dispatch'), ('bad-kro-chart', args.bad_kro_chart), + ('site-volume-removed', args.drop_site_volume)) if v) or 'platform only')) + return 0 + + +def child_patch(name, patches): + """Patch a child Kustomization's spec.patches: the effect of a source commit.""" + return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: add\n path: /spec/patches\n value: %s\n' % ( + name, json.dumps(patches)) + + +def revisions(state): + p = pathlib.Path(state) / 'flux-revisions.json' + return json.loads(p.read_text()) if p.exists() else [] + + +def push(args): + s = pathlib.Path(args.state).resolve() + env = environment(s) + root = pathlib.Path(args.root).resolve() + out = s / 'gitops' / ('r%d' % args.revision) + head = subprocess.run(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True, capture_output=True).stdout.strip() + branch = subprocess.run(['git', '-C', str(root), 'branch', '--show-current'], text=True, capture_output=True).stdout.strip() or 'detached' + sums = s / 'gitops' / ('r%d.SHA256SUMS' % args.revision) + content = hashlib.sha256(sums.read_bytes()).hexdigest() + r = subprocess.run([flux_bin(s), 'push', 'artifact', 'oci://127.0.0.1:%s/fleet-gitops:%s' % (env['registryPort'], TAG), '--path', str(out), + '--source', 'file://fleet-checkout/' + branch, '--revision', '%s@sha1:%s' % (branch, head), '--reproducible', '--insecure-registry', + '--annotations', 'org.opencontainers.image.description=fleet local acceptance r%d; uncommitted checkout content sha256 %s' % (args.revision, content), + '--output', 'json'], text=True, capture_output=True, timeout=180) + if r.returncode: + die('flux push artifact failed: ' + r.stderr[-400:]) + pushed = json.loads(r.stdout) + digest = pushed['digest'] + record = {'revision': args.revision, 'marker': 'r%d' % args.revision, 'digest': digest, 'fluxRevision': '%s@%s' % (TAG, digest), + 'pushedAt': now(), 'gitHead': head, 'gitBranch': branch, 'checkoutDirty': True, 'contentSumsSHA256': content, + 'files': len(sums.read_text().splitlines()), 'purpose': args.purpose} + all_revs = [x for x in revisions(s) if x['revision'] != args.revision] + [record] + write(s / 'flux-revisions.json', all_revs) + shutil.copy(sums, s / 'evidence' / ('gitops-r%d.SHA256SUMS' % args.revision)) + print('push: r%d %s (%s)' % (args.revision, digest, args.purpose)) + return 0 + + +def current(state): + revs = revisions(state) + if not revs: + die('no source revision has been pushed') + return revs[-1] + + +# ---------------------------------------------------------------- reconcile and wait + +def request(state, cluster, kind, ref): + namespace, name = ref.split('/') + token = now() + kubectl(state, cluster, '-n', namespace, 'annotate', '--overwrite', kind, name, REQUEST + '=' + token) + return token + + +REQUEST = 'reconcile.fluxcd.io/requestedAt' + + +def acknowledged(obj, token): + return obj.get('status', {}).get('lastHandledReconcileAt') == token + + +def lost(obj, token): + """A parent Flux apply can strip a kubectl-managed request before any reconcile handles it.""" + return not acknowledged(obj, token) and (obj['metadata'].get('annotations') or {}).get(REQUEST) != token + + +def conditions(obj): + return {c['type']: c for c in obj.get('status', {}).get('conditions', [])} + + +def ready(obj): + c = conditions(obj).get('Ready', {}) + return c.get('status') == 'True' and obj.get('status', {}).get('observedGeneration') == obj['metadata']['generation'] + + +def kustomizations(state, cluster): + return {i['metadata']['namespace'] + '/' + i['metadata']['name']: i for i in kget(state, cluster, 'get', 'kustomizations.kustomize.toolkit.fluxcd.io', '-A')['items']} + + +def wait_cluster(state, cluster, timeout, names=None, revision=None, skip=(), observe_also=()): + """All named (default: every) Kustomizations Ready, current generation, at the pushed revision. + + observe_also samples other clusters' gating while waiting (bootstrap only: + later waits run while a cluster is deliberately paused).""" + revision = revision or current(state)['fluxRevision'] + deadline = time.monotonic() + timeout + source_token = request(state, cluster, 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + tokens = {} + reissued = {} + last = {} + while time.monotonic() < deadline: + source = kget(state, cluster, '-n', 'flux-system', 'get', 'ocirepositories.source.toolkit.fluxcd.io', 'fleet-gitops') + if lost(source, source_token): + # Only a fresh request counts; the acknowledgement must still match it exactly. + source_token = request(state, cluster, 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + reissued['flux-system/fleet-gitops'] = reissued.get('flux-system/fleet-gitops', 0) + 1 + ks = kustomizations(state, cluster) + want = [n for n in names or ['flux-system/fleet-cluster'] + EXPECTED[cluster] + ([n for n in SITE_LAYERS if n in ks] if cluster == 'cell' else []) + if n not in skip and not ks.get(n, {}).get('spec', {}).get('suspend')] + for n in want: + if n in ks and (n not in tokens or lost(ks[n], tokens[n])): + if n in tokens: + reissued[n] = reissued.get(n, 0) + 1 + tokens[n] = request(state, cluster, 'kustomizations.kustomize.toolkit.fluxcd.io', n) + last = {n: {'requestedAt': tokens.get(n), 'lastHandledReconcileAt': ks.get(n, {}).get('status', {}).get('lastHandledReconcileAt'), 'ready': ready(ks[n]) if n in ks else False, 'revision': ks.get(n, {}).get('status', {}).get('lastAppliedRevision'), + 'reason': conditions(ks.get(n, {})).get('Ready', {}).get('reason')} for n in want} + observe(state, cluster, revision, ks) + for other in observe_also: + if other != cluster: + try: + observe(state, other, revision, kustomizations(state, other)) + except SystemExit: + pass # an unreachable cluster is sampled on the next poll + if ready(source) and source.get('status', {}).get('lastHandledReconcileAt') == source_token and source.get('status', {}).get('artifact', {}).get('revision') == revision and all( + v['ready'] and v['revision'] == revision and v['requestedAt'] is not None and v['lastHandledReconcileAt'] == v['requestedAt'] for v in last.values()): + path = pathlib.Path(state) / 'evidence' / 'flux-reconciles.json' + records = json.loads(path.read_text()) if path.exists() else [] + records.append({'cluster': cluster, 'revision': revision, 'observedAt': now(), 'sourceRequestedAt': source_token, 'sourceLastHandledReconcileAt': source['status']['lastHandledReconcileAt'], 'kustomizations': last, + 'lostRequestsReissued': reissued}) + write(path, records) + return last + time.sleep(3) + die('%s did not converge on %s: %s' % (cluster, revision, json.dumps(last)), harness.EXIT_TIMEOUT) + + +def observe(state, cluster, revision, ks): + """Record each distinct non-Ready reason seen while waiting, e.g. dependency gating.""" + path = pathlib.Path(state) / 'flux-wait-observations.json' + seen = json.loads(path.read_text()) if path.exists() else [] + # Keyed by whether the revision was already applied, so a dependent seen + # gated after applying (a dependency re-reconciling) never masks the + # gated-before-apply observation, or the reverse. + keys = {(o['cluster'], o['kustomization'], o['revision'], o['reason'], o['lastAppliedRevision'] == o['revision']) for o in seen} + for n, o in ks.items(): + c = conditions(o).get('Ready', {}) + key = (cluster, n, revision, c.get('reason'), o.get('status', {}).get('lastAppliedRevision') == revision) + if c.get('status') != 'True' and key not in keys: + keys.add(key) + seen.append({'cluster': cluster, 'kustomization': n, 'revision': revision, 'reason': c.get('reason'), + 'message': c.get('message', '')[:160], 'lastAppliedRevision': o.get('status', {}).get('lastAppliedRevision'), + 'inventoryEntries': len(inventory(o)), 'observedAt': now()}) + write(path, seen) + + +def wait_cmd(args): + for cluster in args.cluster: + wait_cluster(args.state, cluster, args.timeout, skip=args.skip, observe_also=args.observe) + print('wait: %s Kustomizations Ready at %s' % (cluster, current(args.state)['fluxRevision'])) + return 0 + + +def bootstrap(args): + """The documented bootstrap boundary: Flux components and sync objects, once.""" + s = pathlib.Path(args.state).resolve() + first = s / 'gitops' / 'r1' + components = subprocess.run(['kustomize', 'build', str(first / 'environment/flux-components')], capture_output=True, text=True, check=True).stdout + path = s / ('flux-bootstrap-%s.yaml' % args.cluster) + path.write_text(components) + sync = first / 'environment' / args.cluster / 'flux-system' / 'gotk-sync.yaml' + # Components (with CRDs) first, then the sync objects once the CRDs serve. + # The bootstrap applies under kustomize-controller's own field manager, so + # when Flux reconciles the same objects it takes them over with no residual + # second manager (and no second writer) left behind. + kubectl(s, args.cluster, 'apply', '--server-side', '--field-manager=kustomize-controller', '-f', str(path), timeout=180) + kubectl(s, args.cluster, 'wait', '--for=condition=Established', 'crd/kustomizations.kustomize.toolkit.fluxcd.io', + 'crd/ocirepositories.source.toolkit.fluxcd.io', 'crd/helmreleases.helm.toolkit.fluxcd.io', '--timeout=120s', timeout=140) + kubectl(s, args.cluster, '-n', 'flux-system', 'wait', '--for=condition=Available', 'deployment', '--all', '--timeout=300s', timeout=320) + kubectl(s, args.cluster, 'apply', '--server-side', '--field-manager=kustomize-controller', '-f', str(sync), timeout=60) + record = {'cluster': args.cluster, 'appliedAt': now(), 'componentsSHA256': sha256(path), 'syncSHA256': sha256(sync), 'fieldManager': 'kustomize-controller', + 'objects': len([d for d in components.split('\n---\n') if d.strip()]) + 2} + write(s / ('flux-bootstrap-%s.json' % args.cluster), record) + print('bootstrap: %s Flux v%s controllers Available; sync objects applied once (%d objects)' % (args.cluster, FLUX_VERSION, record['objects'])) + return 0 + + +def publish(args): + a = argparse.Namespace(**vars(args)) + stage(a) + push(a) + for cluster in args.cluster: + wait_cluster(args.state, cluster, args.timeout) + print('publish: r%d reconciled on %s' % (args.revision, ', '.join(args.cluster) or 'no cluster (waited later)')) + return 0 + + +# ---------------------------------------------------------------- evidence + +def inventory(obj): + return sorted(e['id'] for e in obj.get('status', {}).get('inventory', {}).get('entries', [])) + + +def snapshot(state, cluster): + ks = kustomizations(state, cluster) + oci = kget(state, cluster, 'get', 'ocirepositories.source.toolkit.fluxcd.io', '-A')['items'] + hr = kget(state, cluster, 'get', 'helmreleases.helm.toolkit.fluxcd.io', '-A')['items'] + hrepo = kget(state, cluster, 'get', 'helmrepositories.source.toolkit.fluxcd.io', '-A')['items'] + charts = kget(state, cluster, 'get', 'helmcharts.source.toolkit.fluxcd.io', '-A')['items'] + deploys = kget(state, cluster, '-n', 'flux-system', 'get', 'deployments')['items'] + + def cond(o): + return sorted([c['type'], c['status'], c.get('reason', '')] for c in o.get('status', {}).get('conditions', [])) + return { + 'cluster': cluster, 'observedAt': now(), + 'controllers': {d['metadata']['name']: {'image': d['spec']['template']['spec']['containers'][0]['image'], 'uid': d['metadata']['uid'], + 'availableReplicas': d['status'].get('availableReplicas', 0)} for d in deploys}, + 'sources': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'url': o['spec']['url'], 'ref': o['spec'].get('ref'), 'artifactRevision': o.get('status', {}).get('artifact', {}).get('revision'), + 'artifactDigest': o.get('status', {}).get('artifact', {}).get('digest'), 'generation': o['metadata']['generation'], + 'observedGeneration': o.get('status', {}).get('observedGeneration'), 'conditions': cond(o)} for o in oci + hrepo}, + 'helmCharts': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'chart': o['spec'].get('chart'), 'version': o['spec'].get('version'), 'artifactRevision': o.get('status', {}).get('artifact', {}).get('revision'), + 'artifactDigest': o.get('status', {}).get('artifact', {}).get('digest'), 'conditions': cond(o)} for o in charts}, + 'kustomizations': {n: {'path': o['spec']['path'], 'prune': o['spec'].get('prune'), 'wait': o['spec'].get('wait'), + 'dependsOn': o['spec'].get('dependsOn', []), 'serviceAccountName': o['spec'].get('serviceAccountName'), + 'remote': bool(o['spec'].get('kubeConfig')), 'suspend': o['spec'].get('suspend', False), + 'generation': o['metadata']['generation'], 'observedGeneration': o.get('status', {}).get('observedGeneration'), + 'lastAppliedRevision': o.get('status', {}).get('lastAppliedRevision'), + 'lastAttemptedRevision': o.get('status', {}).get('lastAttemptedRevision'), + 'conditions': cond(o), 'inventory': inventory(o)} for n, o in ks.items()}, + 'helmReleases': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'generation': o['metadata']['generation'], 'observedGeneration': o.get('status', {}).get('observedGeneration'), + 'conditions': cond(o), 'driftDetection': o['spec'].get('driftDetection'), + 'history': [{k: h.get(k) for k in ('name', 'namespace', 'version', 'chartName', 'chartVersion', 'appVersion', 'digest', 'status', 'configDigest')} + for h in o.get('status', {}).get('history', [])], + 'lastAttemptedRevision': o.get('status', {}).get('lastAttemptedRevision'), + 'lastAttemptedRevisionDigest': o.get('status', {}).get('lastAttemptedRevisionDigest')} for o in hr}, + } + + +def record(args): + snap = {c: snapshot(args.state, c) for c in args.cluster} + write(pathlib.Path(args.state) / 'evidence' / ('flux-%s.json' % args.name), snap) + print('record: Flux snapshot %s for %s' % (args.name, ', '.join(args.cluster))) + return 0 + + +def labels(obj): + return obj['metadata'].get('labels', {}) or {} + + +def flux_owned(obj): + return 'kustomize.toolkit.fluxcd.io/name' in labels(obj) + + +def kro_marked(obj): + l = labels(obj) + return any(k.startswith('kro.run/') for k in l) or 'applyset.kubernetes.io/part-of' in l or l.get('app.kubernetes.io/managed-by') == 'kro' + + +def ownership(state, snaps): + """One writer per site object: a named Flux layer for shared infrastructure, + kro only for per-operation worker objects. Returns (record, problems).""" + s = pathlib.Path(state) + problems = [] + cell_ks = snaps['cell']['kustomizations'] + every = sorted({e for c in snaps.values() for k in c['kustomizations'].values() for e in k['inventory']}) + layers = {} + for layer, expected in LAYER_INVENTORY.items(): + layers[layer] = cell_ks.get(layer, {}).get('inventory') + if layers[layer] != expected: + problems.append('%s inventory is not exactly %s: %s' % (layer, expected, layers[layer])) + shared = [] + for (kind, ns, name), layer in sorted(SHARED.items(), key=str): + r = kubectl(s, 'cell', *(['-n', ns] if ns else []), 'get', kind, name, '-o', 'json', check=False) + if r.returncode: + problems.append('shared %s %s/%s is missing' % (kind, ns, name)) + continue + o = json.loads(r.stdout) + rec = {'kind': kind, 'namespace': ns, 'name': name, 'uid': o['metadata']['uid'], 'fluxLayer': labels(o).get('kustomize.toolkit.fluxcd.io/name'), + 'kroMarked': kro_marked(o), 'ownerReferences': sorted(x.get('kind', '') for x in o['metadata'].get('ownerReferences', [])), + 'inLayerInventory': any(e.startswith('%s_%s_' % (ns or '', name)) for e in cell_ks.get('flux-system/' + layer, {}).get('inventory', []))} + shared.append(rec) + if rec['fluxLayer'] != layer or rec['kroMarked'] or rec['ownerReferences'] or not rec['inLayerInventory']: + problems.append('shared object not solely owned by Flux %s: %s' % (layer, rec)) + kro_written = [] + for kind, ns in WORKER_KINDS + (('deployments', SITE), ('services', SITE), ('configmaps', SITE), ('persistentvolumeclaims', SITE)): + for o in kget(s, 'cell', '-n', ns, 'get', kind)['items']: + name = o['metadata']['name'] + worker = name.startswith('w-op-') + if kind == 'jobs' and not worker: + problems.append('Job outside the per-operation set: %s' % name) + if not worker and not kro_marked(o): + continue + rec = {'kind': kind, 'namespace': ns, 'name': name, 'uid': o['metadata']['uid'], 'kroNode': labels(o).get('kro.run/node-id'), + 'fluxOwned': flux_owned(o), 'inFluxInventory': any(e.startswith('%s_%s_' % (ns, name)) for e in every)} + kro_written.append(rec) + if (kind, ns) not in WORKER_KINDS or not worker or not rec['kroNode'] or rec['fluxOwned'] or rec['inFluxInventory']: + problems.append('kro wrote outside the per-operation set, or a worker object is not solely kro-owned: %s' % rec) + for forbidden in ('batch_Job', '_Pod', '_MachineAllocationHandoff', '_Secret'): + hits = [e for e in every if e.endswith(forbidden)] + if hits: + problems.append('Flux inventory contains %s: %s' % (forbidden, hits[:4])) + if [e for e in every if '_w-op-' in e]: + problems.append('a per-operation worker object is in a Flux inventory') + deps = {n: sorted(d['name'] for d in cell_ks.get(n, {}).get('dependsOn', [])) for n in ['flux-system/fleet-site-base'] + SITE_LAYERS + ['flux-system/fleet-site-graph']} + if 'kro' in deps['flux-system/fleet-site-base'] + deps['flux-system/fleet-site-services']: + problems.append('shared site infrastructure depends on kro: %s' % deps) + if not {'fleet-site-graph', 'fleet-site-services'} <= set(deps['flux-system/fleet-site-dispatch']): + problems.append('the dispatcher does not depend on the graph and the shared services: %s' % deps) + record = {'observedAt': now(), 'layerInventories': layers, 'sharedObjects': shared, 'kroWrittenObjects': kro_written, + 'siteDependsOn': deps, 'problems': problems} + return record, problems + + +def ownership_cmd(args): + snaps = {c: snapshot(args.state, c) for c in CLUSTERS} + record, problems = ownership(args.state, snaps) + write(pathlib.Path(args.state) / 'evidence' / ('flux-ownership-%s.json' % args.name), record) + if problems: + die('ownership audit failed:\n ' + '\n '.join(problems)) + print('ownership: %d shared site objects each owned by one Flux layer; kro wrote only %d per-operation worker objects' + % (len(record['sharedObjects']), len(record['kroWrittenObjects']))) + return 0 + + +def verify(args): + """Source identity, readiness, ownership and inventory on every cluster.""" + s = pathlib.Path(args.state) + rev = current(s) + problems = [] + snaps = {} + for cluster in CLUSTERS: + snap = snapshot(s, cluster) + snaps[cluster] = snap + src = snap['sources'].get('flux-system/fleet-gitops', {}) + if src.get('artifactRevision') != rev['fluxRevision']: + problems.append('%s source at %s, pushed %s' % (cluster, src.get('artifactRevision'), rev['fluxRevision'])) + for n in ['flux-system/fleet-cluster'] + EXPECTED[cluster] + (SITE_LAYERS if cluster == 'cell' else []): + k = snap['kustomizations'].get(n) + if not k or ['Ready', 'True', 'ReconciliationSucceeded'] not in k['conditions'] or k['generation'] != k['observedGeneration'] or k['lastAppliedRevision'] != rev['fluxRevision']: + problems.append('%s %s not Ready at the pushed revision: %s' % (cluster, n, k and (k['conditions'], k['lastAppliedRevision']))) + for n in HELMRELEASES.get(cluster, []): + h = snap['helmReleases'].get(n) + if not h or ['Ready', 'True', 'InstallSucceeded'] not in h['conditions'] and ['Ready', 'True', 'UpgradeSucceeded'] not in h['conditions'] or h['generation'] != h['observedGeneration']: + problems.append('%s HelmRelease %s not Ready: %s' % (cluster, n, h and h['conditions'])) + if set(snap['controllers']) != {'source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller'} or any( + '@sha256:' not in c['image'] or c['availableReplicas'] != 1 for c in snap['controllers'].values()): + problems.append('%s Flux controllers not the pinned set: %s' % (cluster, snap['controllers'])) + cell = snaps['cell'] + hub = snaps['hub'] + kro_src = cell['sources'].get('flux-system/kro-chart', {}) + if (kro_src.get('ref') or {}).get('digest') != KRO_CHART_DIGEST or not str(kro_src.get('artifactRevision', '')).endswith(KRO_CHART_DIGEST): + problems.append('kro chart source not at pinned digest: %s' % kro_src) + kro_hist = (cell['helmReleases'].get('flux-system/kro', {}).get('history') or [{}])[0] + # helm-controller suffixes an OCI chart's version with its manifest digest. + if kro_hist.get('chartVersion') != '0.9.4+' + KRO_CHART_DIGEST[7:19] or kro_hist.get('status') != 'deployed': + problems.append('kro release history: %s' % kro_hist) + karmada_chart = next((c for c in hub['helmCharts'].values() if c['chart'] == 'karmada'), {}) + if karmada_chart.get('artifactDigest') != 'sha256:' + KARMADA_CHART_SHA256: + problems.append('Karmada chart artifact digest %s, expected sha256:%s' % (karmada_chart.get('artifactDigest'), KARMADA_CHART_SHA256)) + karmada_hist = (hub['helmReleases'].get('flux-system/karmada', {}).get('history') or [{}])[0] + if karmada_hist.get('chartVersion') != 'v1.16.0' or karmada_hist.get('status') != 'deployed': + problems.append('karmada release history: %s' % karmada_hist) + # Ownership: Flux layers own the shared site; kro alone owns per-operation workers. + owners, owner_problems = ownership(s, snaps) + problems += owner_problems + if owners['kroWrittenObjects']: + problems.append('kro wrote objects before dispatch: %s' % owners['kroWrittenObjects']) + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + pvc_ann = pvc['metadata'].get('annotations', {}) + if pvc_ann.get('kustomize.toolkit.fluxcd.io/prune') != 'disabled' or pvc_ann.get('kustomize.toolkit.fluxcd.io/ssa') != 'IfNotPresent': + problems.append('site volume claim is not retained by Flux policy: %s' % pvc_ann) + protected = {} + for cluster, kind, ns, name in (('cell', 'namespace', None, 'fleet-site'), ('cell', 'namespace', None, 'fleet-coordination'), + ('cell', 'crd', None, 'machineallocationhandoffs.coordination.fleet.datumapis.com'), + ('cell', 'resourcegraphdefinition', None, RGD), ('cell', DISPATCHER[0], SITE, DISPATCHER[1]), + ('cell', 'storageclass', None, 'fleet-site-retain'), ('hub', 'namespace', None, 'fleet-system-private')): + o = kget(s, cluster, *(['-n', ns] if ns else []), 'get', kind, name) + value = o['metadata'].get('annotations', {}).get('kustomize.toolkit.fluxcd.io/prune') + protected['%s/%s/%s' % (cluster, kind, name)] = value + if value != 'disabled': + problems.append('%s %s %s is prunable' % (cluster, kind, name)) + handoffs = kget(s, 'cell', '-n', 'fleet-coordination', 'get', 'machineallocationhandoffs')['items'] + if any(flux_owned(h) for h in handoffs): + problems.append('a handoff carries Flux ownership labels') + # Bootstrap dependency ordering, as Flux recorded it while every cluster was sampled. + seen = json.loads((s / 'flux-wait-observations.json').read_text()) if (s / 'flux-wait-observations.json').exists() else [] + first = revisions(s)[0]['fluxRevision'] + events = [o for o in seen if o['reason'] == 'DependencyNotReady'] + # Gating before apply: the dependent had applied nothing of r1. Gating after + # apply is a dependency re-reconciling at the same revision (for example on + # a fresh request) and is recorded, not counted as either evidence or fault. + gated = [o for o in events if o['revision'] == first and not o['lastAppliedRevision'] and not o['inventoryEntries']] + regated = [o for o in events if o['revision'] == first and o['lastAppliedRevision'] == first] + for o in events: + if o['revision'] == first and o['lastAppliedRevision'] not in (None, first): + problems.append('dependent applied another revision during bootstrap: %s' % o) + elif o['revision'] == first and not o['lastAppliedRevision'] and o['inventoryEntries']: + problems.append('dependent has an inventory before applying while its dependency is not Ready: %s' % o) + for cluster in ('cell', 'hub'): + if not [o for o in gated if o['cluster'] == cluster]: + problems.append('no dependency gating before apply was observed on %s during bootstrap' % cluster) + result = {'observedAt': now(), 'revision': rev, 'revisions': revisions(s), 'tools': json.loads((s / 'flux-tools' / 'tools.json').read_text()), + 'bootstrap': [json.loads((s / ('flux-bootstrap-%s.json' % c)).read_text()) for c in CLUSTERS], + 'pins': {'kroChartManifestDigest': KRO_CHART_DIGEST, 'kroChartLayerSHA256': KRO_CHART_LAYER_SHA256, + 'karmadaChartSHA256': KARMADA_CHART_SHA256, 'registryImage': REGISTRY_IMAGE}, + 'ownership': owners, 'pruneProtected': protected, 'siteVolumeAnnotations': {k: v for k, v in pvc_ann.items() if 'fluxcd' in k}, + 'handoffsFluxOwned': False, 'bootstrapDependencyEvents': events, 'bootstrapGatedBeforeApply': gated, + 'bootstrapRegatedAfterApply': regated, 'problems': problems} + write(s / 'evidence' / 'flux-verify.json', result) + write(s / 'evidence' / 'flux-initial.json', snaps) + if problems: + die('flux verification failed:\n ' + '\n '.join(problems)) + print('flux-verify: 3 clusters Ready at %s; pinned charts and controllers; Flux layers own %d shared site objects; kro owns %d per-operation objects; volume, CRD, graph and instance prune-protected' + % (rev['fluxRevision'], len(owners['sharedObjects']), len(owners['kroWrittenObjects']))) + return 0 + + +# ---------------------------------------------------------------- scenarios + +def site_facts(state): + """Effect and custody facts that no GitOps action may change.""" + s = pathlib.Path(state) + jobs = sorted((j['metadata']['name'], j['metadata']['uid']) for j in kget(s, 'cell', '-n', 'fleet-site', 'get', 'jobs')['items']) + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + pv = kget(s, 'cell', 'get', 'pv', pvc['spec']['volumeName']) + journal = kubectl(s, 'cell', '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/lib/fleet-local/journal.json').stdout + secrets = kget(s, 'hub', '-n', 'fleet-system-private', 'get', 'secrets')['items'] + custody = hashlib.sha256(json.dumps(sorted((i['metadata']['name'], i['metadata']['uid'], i['metadata']['resourceVersion']) for i in secrets)).encode()).hexdigest() + return {'jobs': jobs, 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvPhase': pv['status'].get('phase'), + 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'journalSHA256': hashlib.sha256(journal.encode()).hexdigest(), + 'custodyRecords': len(secrets), 'custodyDigest': custody} + + +def same_facts(before, after, what): + if before != after: + die('%s changed effect or custody facts: before %s after %s' % (what, before, after)) + + +def wait_for(fn, timeout, what, interval=2): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = fn() + if value: + return value + time.sleep(interval) + die(what + ' not observed before deadline', harness.EXIT_TIMEOUT) + + +def drift(args): + """Out-of-band changes corrected by Flux, not by the harness.""" + s = pathlib.Path(args.state) + before = site_facts(s) + out = {'observedAt': now(), 'cases': []} + # 1. helm-controller drift correction of the kro release. + d = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + kubectl(s, 'cell', '-n', 'kro-system', 'scale', 'deployment/kro', '--replicas=0') + request(s, 'cell', 'helmreleases.helm.toolkit.fluxcd.io', 'flux-system/kro') + + def kro_back(): + x = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + return x if x['spec']['replicas'] == 1 and x['status'].get('availableReplicas') == 1 else None + restored = wait_for(kro_back, 300, 'helm-controller correction of kro replicas') + hr = kget(s, 'cell', '-n', 'flux-system', 'get', 'helmreleases.helm.toolkit.fluxcd.io', 'kro') + events = [e.get('message', '')[:200] for e in kget(s, 'cell', '-n', 'flux-system', 'get', 'events', '--field-selector', 'involvedObject.name=kro')['items'] + if 'drift' in e.get('message', '').lower()] + out['cases'].append({'case': 'kro Deployment scaled to 0 out of band', 'correctedBy': 'helm-controller driftDetection=enabled', + 'deploymentUID': d['metadata']['uid'], 'sameDeployment': restored['metadata']['uid'] == d['metadata']['uid'], + 'releaseVersion': [h.get('version') for h in hr['status'].get('history', [])][:1], 'events': events[:3]}) + # 2. kustomize-controller recreates a deleted Karmada-API object over the remote kubeconfig. + old = kget(s, 'hub', 'get', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', config='hub-admin.yaml') + kubectl(s, 'hub', 'delete', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', config='hub-admin.yaml') + request(s, 'hub', 'kustomizations.kustomize.toolkit.fluxcd.io', 'karmada-system/fleet-karmada-api') + + def interp_back(): + r = kubectl(s, 'hub', 'get', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', '-o', 'json', check=False, config='hub-admin.yaml') + return json.loads(r.stdout) if r.returncode == 0 else None + new = wait_for(interp_back, 300, 'Flux recreation of the Karmada interpreter') + if new['metadata']['uid'] == old['metadata']['uid'] or new['spec'] != old['spec']: + die('interpreter was not recreated from the source') + out['cases'].append({'case': 'Karmada interpreter deleted on the Karmada API', 'correctedBy': 'kustomize-controller (remote kubeConfig)', + 'oldUID': old['metadata']['uid'], 'newUID': new['metadata']['uid'], 'specFromSource': True}) + # 3. kustomize-controller reverts an in-place edit of a site policy object. + kubectl(s, 'cell', 'patch', 'clusterrole', 'fleet-site-kro', '--type=json', '-p', + '[{"op":"add","path":"/rules/-","value":{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}}]') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-base') + + def role_back(): + rules = kget(s, 'cell', 'get', 'clusterrole', 'fleet-site-kro').get('rules', []) + return not any('secrets' in r.get('resources', []) for r in rules) + wait_for(role_back, 300, 'Flux reversion of the widened kro grant') + out['cases'].append({'case': 'fleet-site-kro ClusterRole widened to read Secrets', 'correctedBy': 'kustomize-controller server-side apply', 'secretReadRemoved': True}) + # 4. kustomize-controller recreates the deleted shared boot Service, with the + # same fixed ClusterIP, as the scoped services identity. kro must not write it. + svc = kget(s, 'cell', '-n', SITE, 'get', 'service', 'fleet-site-boot') + kubectl(s, 'cell', '-n', SITE, 'delete', 'service', 'fleet-site-boot', '--wait=true') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-services') + + def svc_back(): + r = kubectl(s, 'cell', '-n', SITE, 'get', 'service', 'fleet-site-boot', '-o', 'json', check=False) + o = json.loads(r.stdout) if r.returncode == 0 else None + return o if o and o['metadata']['uid'] != svc['metadata']['uid'] else None + new_svc = wait_for(svc_back, 300, 'Flux recreation of the boot Service') + same = {k: new_svc['spec'].get(k) == svc['spec'].get(k) for k in ('clusterIP', 'clusterIPs', 'ports', 'selector', 'type')} + if not all(same.values()) or new_svc['spec']['clusterIP'] != BOOT_SERVICE_IP or labels(new_svc).get('kustomize.toolkit.fluxcd.io/name') != 'fleet-site-services' or kro_marked(new_svc): + die('boot Service was not recreated by Flux with the same fixed ClusterIP and spec: %s' % same) + out['cases'].append({'case': 'shared boot Service deleted', 'correctedBy': 'kustomize-controller as fleet-site-services-reconciler', 'oldUID': svc['metadata']['uid'], + 'newUID': new_svc['metadata']['uid'], 'clusterIP': new_svc['spec']['clusterIP'], 'specUnchanged': same, 'fluxLayer': 'fleet-site-services', 'kroMarked': False}) + # 5. kustomize-controller restores the shared observer Deployment scaled to 0. + obs = kget(s, 'cell', '-n', SITE, 'get', 'deployment', 'fleet-site-observer') + kubectl(s, 'cell', '-n', SITE, 'scale', 'deployment/fleet-site-observer', '--replicas=0') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-services') + + def obs_back(): + x = kget(s, 'cell', '-n', SITE, 'get', 'deployment', 'fleet-site-observer') + return x if x['spec']['replicas'] == 1 and x['status'].get('availableReplicas') == 1 and x['metadata']['generation'] > obs['metadata']['generation'] else None + restored_obs = wait_for(obs_back, 300, 'Flux restoration of the observer Deployment') + if restored_obs['metadata']['uid'] != obs['metadata']['uid']: + die('observer Deployment was replaced instead of restored') + out['cases'].append({'case': 'shared observer Deployment scaled to 0', 'correctedBy': 'kustomize-controller as fleet-site-services-reconciler', + 'deploymentUID': obs['metadata']['uid'], 'sameDeployment': True, 'generationBefore': obs['metadata']['generation'], + 'generationAfter': restored_obs['metadata']['generation']}) + # The dispatcher must return to ACTIVE against the repaired references. + wait_for(lambda: kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]).get('status', {}).get('state') == 'ACTIVE', 300, 'dispatcher ACTIVE after repair') + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners, problems = ownership(s, snaps) + if problems: + die('ownership after drift repair:\n ' + '\n '.join(problems)) + out['ownershipAfterRepair'] = owners + after = site_facts(s) + same_facts(before, after, 'drift correction') + out['siteFacts'] = after + write(s / 'evidence' / 'flux-drift.json', out) + print('flux-drift: helm-controller restored kro, kustomize-controller recreated the Karmada interpreter, reverted a widened grant, recreated the shared boot Service at its fixed ClusterIP and restored the observer; journal, Jobs, volume and custody unchanged') + return 0 + + +def suspend(state, cluster, ref, value): + namespace, name = ref.split('/') + kubectl(state, cluster, '-n', namespace, 'patch', 'kustomizations.kustomize.toolkit.fluxcd.io', name, '--field-manager=fleet-fault-injection', + '--type=merge', '-p', json.dumps({'spec': {'suspend': value}})) + + +def shared_uids(state): + """Identity of every Flux-owned shared site object, the PV and the dispatcher graph.""" + s = pathlib.Path(state) + out = {} + for kind, ns, name in sorted(SHARED, key=str): + out['%s/%s/%s' % (kind, ns, name)] = kget(s, 'cell', *(['-n', ns] if ns else []), 'get', kind, name)['metadata']['uid'] + out['rgd'] = kget(s, 'cell', 'get', 'resourcegraphdefinition', RGD)['metadata']['uid'] + out['storageclass'] = kget(s, 'cell', 'get', 'storageclass', 'fleet-site-retain')['metadata']['uid'] + return out + + +def worker_objects(state): + s = pathlib.Path(state) + return sorted((kind, o['metadata']['name'], o['metadata']['uid']) for kind, ns in WORKER_KINDS + for o in kget(s, 'cell', '-n', ns, 'get', kind)['items'] if o['metadata']['name'].startswith('w-op-')) + + +def graph_lifecycle(args): + """Deleting the dispatcher instance removes only kro's per-operation objects. + + Flux then recreates the instance from the source and kro recreates the + workers, which replay a verified no-op. Shared services, the journal + volume, the journal, guests and custody are untouched throughout. + """ + s = pathlib.Path(args.state) + handoff = (s / 'install-handoff').read_text().strip() + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners, problems = ownership(s, snaps) + if problems: + die('ownership with workers present:\n ' + '\n '.join(problems)) + want = sorted(['jobs', 'serviceaccounts', 'roles', 'rolebindings']) + if sorted(k for k, n, _ in worker_objects(s) if n == 'w-' + handoff) != want: + die('expected one kro-written Job, ServiceAccount, Role and RoleBinding for the install handoff: %s' % worker_objects(s)) + before, uids, workers = site_facts(s), shared_uids(s), worker_objects(s) + status = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + if status != 'Succeeded': + die('install handoff is not terminal before the graph lifecycle: %s' % status) + old = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + # Explicit ownership transfer for the fault: suspend the instance's Flux + # layer so the harness is never a second concurrent writer, then delete the + # instance out of band. + suspend(s, 'cell', 'flux-system/fleet-site-dispatch', True) + kubectl(s, 'cell', '-n', SITE, 'delete', DISPATCHER[0], DISPATCHER[1], '--wait=true', timeout=300) + wait_for(lambda: not worker_objects(s), 300, 'kro removal of per-operation objects') + during_uids, during = shared_uids(s), site_facts(s) + if during_uids != uids: + die('instance deletion changed shared site objects: %s -> %s' % (uids, during_uids)) + same_facts(dict(before, jobs=[]), during, 'dispatcher instance deletion') + for d in SITE_DEPLOYMENTS: + if kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['status'].get('availableReplicas') != 1: + die(d + ' became unavailable when the dispatcher was deleted') + # Resuming hands ownership back: Flux, not the harness, restores the instance. + suspend(s, 'cell', 'flux-system/fleet-site-dispatch', False) + wait_cluster(s, 'cell', 600) + new = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + if new['metadata']['uid'] == old['metadata']['uid'] or labels(new).get('kustomize.toolkit.fluxcd.io/name') != 'fleet-site-dispatch': + die('dispatcher was not recreated by Flux') + + def replayed(): + j = kget(s, 'cell', '-n', SITE, 'get', 'jobs')['items'] + done = [x for x in j if x['metadata']['name'] == 'w-' + handoff and any(c['type'] == 'Complete' and c['status'] == 'True' for c in x['status'].get('conditions', []))] + return done[0] if done else None + job = wait_for(replayed, 600, 'recreated worker Job completing its verified no-op replay', interval=3) + pods = [p for p in kget(s, 'cell', '-n', SITE, 'get', 'pods', '-l', 'batch.kubernetes.io/controller-uid=' + job['metadata']['uid'])['items']] + exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in pods] + if exits != [0]: + die('recreated worker Job did not finish with one verified no-op replay: %s' % exits) + after_uids, after = shared_uids(s), site_facts(s) + if after_uids != uids: + die('instance recreation changed shared site objects') + same_facts(dict(before, jobs=[]), dict(after, jobs=[]), 'dispatcher instance recreation') + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners_after, problems = ownership(s, snaps) + if problems: + die('ownership after the graph lifecycle:\n ' + '\n '.join(problems)) + status_after = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + if status_after != 'Succeeded': + die('install handoff lost its terminal observation across the graph lifecycle: %s' % status_after) + # kro deletes Jobs without a propagation policy, so batch/v1 orphans their + # (already terminal) Pods. Recorded, not hidden; see site-execution.md. + live_jobs = {j['metadata']['uid'] for j in kget(s, 'cell', '-n', SITE, 'get', 'jobs')['items']} + orphans = [{'pod': p['metadata']['name'], 'phase': p['status'].get('phase')} for p in kget(s, 'cell', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] + if labels(p).get('batch.kubernetes.io/controller-uid') not in live_jobs] + if any(o['phase'] not in ('Succeeded', 'Failed') for o in orphans): + die('a non-terminal worker Pod outlived its Job: %s' % orphans) + write(s / 'evidence' / 'flux-graph-lifecycle.json', { + 'observedAt': now(), 'handoff': handoff, 'deletedInstanceUID': old['metadata']['uid'], 'recreatedInstanceUID': new['metadata']['uid'], + 'recreatedBy': 'kustomize-controller (Kustomization fleet-site-dispatch)', 'workerObjectsBefore': workers, 'workerObjectsAfter': worker_objects(s), + 'workerObjectsRemovedByKro': True, 'sharedObjectUIDs': uids, 'sharedObjectsUnchanged': True, 'replayJobUID': job['metadata']['uid'], 'replayExitCodes': exits, + 'handoffResultPhase': [status, status_after], 'orphanedTerminalWorkerPods': orphans, 'ownershipWithWorkers': owners, 'ownershipAfter': owners_after, 'siteFactsBefore': before, 'siteFactsAfter': after}) + print('flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects; shared services, volume, journal and custody unchanged; Flux recreated it and the replayed Job was a verified no-op') + return 0 + + +def restart(args): + """Restart every Flux controller; reconcile must not re-execute or upgrade anything.""" + s = pathlib.Path(args.state) + before = site_facts(s) + snap_before = {c: snapshot(s, c) for c in CLUSTERS} + + def pod_uids(cluster): + return sorted(p['metadata']['uid'] for p in kget(s, cluster, '-n', 'flux-system', 'get', 'pods')['items'] if not p['metadata'].get('deletionTimestamp')) + pods_before = {c: pod_uids(c) for c in CLUSTERS} + release_tokens = {} + for cluster in CLUSTERS: + kubectl(s, cluster, '-n', 'flux-system', 'delete', 'pod', '--all', '--wait=true', timeout=180) + for cluster in CLUSTERS: + kubectl(s, cluster, '-n', 'flux-system', 'wait', '--for=condition=Available', 'deployment', '--all', '--timeout=300s', timeout=320) + for kind, ref in [('kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-cluster')] + [ + ('kustomizations.kustomize.toolkit.fluxcd.io', n) for n in EXPECTED[cluster]] + [('helmreleases.helm.toolkit.fluxcd.io', n) for n in HELMRELEASES.get(cluster, [])]: + token = request(s, cluster, kind, ref) + if kind == 'helmreleases.helm.toolkit.fluxcd.io': + release_tokens[(cluster, ref)] = token + for cluster in CLUSTERS: + wait_cluster(s, cluster, 600) + release_receipts = [] + for (cluster, ref), token in release_tokens.items(): + namespace, name = ref.split('/') + pending = {'token': token, 'reissued': 0} + + def reconciled_release(): + obj = kget(s, cluster, '-n', namespace, 'get', 'helmreleases.helm.toolkit.fluxcd.io', name) + if lost(obj, pending['token']): + pending['token'] = request(s, cluster, 'helmreleases.helm.toolkit.fluxcd.io', ref) + pending['reissued'] += 1 + return None + return obj if ready(obj) and acknowledged(obj, pending['token']) else None + obj = wait_for(reconciled_release, 600, 'post-restart HelmRelease reconcile') + release_receipts.append({'cluster': cluster, 'release': ref, 'requestedAt': pending['token'], 'lastHandledReconcileAt': obj['status']['lastHandledReconcileAt'], + 'lostRequestsReissued': pending['reissued']}) + time.sleep(10) + snap_after = {c: snapshot(s, c) for c in CLUSTERS} + changes = [] + for c in CLUSTERS: + for n, h in snap_before[c]['helmReleases'].items(): + if [x['version'] for x in h['history']] != [x['version'] for x in snap_after[c]['helmReleases'][n]['history']]: + changes.append('%s %s Helm release revision changed' % (c, n)) + for n, k in snap_before[c]['kustomizations'].items(): + if k['inventory'] != snap_after[c]['kustomizations'][n]['inventory']: + changes.append('%s %s inventory changed' % (c, n)) + if set(pods_before[c]) & set(pod_uids(c)) or len(pod_uids(c)) != len(pods_before[c]): + changes.append('%s controller Pods were not all replaced' % c) + if changes: + die('controller restart changed managed state: ' + '; '.join(changes)) + after = site_facts(s) + same_facts(before, after, 'Flux controller restart') + write(s / 'evidence' / 'flux-restart.json', {'observedAt': now(), 'restartedControllers': {c: sorted(snap_after[c]['controllers']) for c in CLUSTERS}, + 'controllerPodsBefore': pods_before, 'controllerPodsAfter': {c: pod_uids(c) for c in CLUSTERS}, + 'helmReleaseVersions': {c: {n: [x['version'] for x in h['history']] for n, h in snap_after[c]['helmReleases'].items()} for c in CLUSTERS}, + 'inventoriesUnchanged': True, 'helmReconcileReceipts': release_receipts, 'siteFacts': after}) + print('flux-restart: every Flux controller on 3 clusters restarted and re-reconciled; no Helm upgrade, inventory change, new Job, journal or custody change') + return 0 + + +def fail_closed(args): + """A bad dependency revision blocks dependents; nothing running is disturbed.""" + s = pathlib.Path(args.state) + before = site_facts(s) + kro_before = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + site_before = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + shared_before = shared_uids(s) + services_before = {d: kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['metadata']['generation'] for d in SITE_DEPLOYMENTS} + good = current(s) + bad = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 1, site='dispatch', bad_kro_chart=True, drop_site_volume=False, + purpose='fail-closed: kro chart pinned to an absent digest', cluster=[], timeout=0) + stage(bad) + push(bad) + rev = current(s)['fluxRevision'] + request(s, 'cell', 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + + def blocked(): + ks = kustomizations(s, 'cell') + kro, site = ks['flux-system/kro'], ks['flux-system/fleet-site-dispatch'] + oci = kget(s, 'cell', '-n', 'flux-system', 'get', 'ocirepositories.source.toolkit.fluxcd.io', 'kro-chart') + kro_failed = conditions(kro).get('Ready', {}).get('status') == 'False' and kro['status'].get('lastAttemptedRevision') == rev + dep = conditions(site).get('Ready', {}).get('reason') == 'DependencyNotReady' + # Shared site infrastructure does not depend on kro: it applies the new revision. + shared_applied = all(ready(ks[n]) and ks[n]['status'].get('lastAppliedRevision') == rev for n in ('flux-system/fleet-site-base', 'flux-system/fleet-site-services')) + return (kro, site, oci) if kro_failed and dep and shared_applied and conditions(oci).get('Ready', {}).get('status') == 'False' else None + for n in ('flux-system/fleet-site-base', 'flux-system/fleet-site-services', 'flux-system/fleet-site-graph', 'flux-system/fleet-site-dispatch'): + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', n) + kro, site, oci = wait_for(blocked, 600, 'kro failure blocking only the dispatcher layers', interval=5) + graph = kustomizations(s, 'cell')['flux-system/fleet-site-graph'] + site_obj = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + marker = site_obj['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') + if marker != site_before['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') or site.get('status', {}).get('lastAppliedRevision') == rev: + die('the dependent dispatcher revision applied while kro was not Ready') + services_during = {d: kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['metadata']['generation'] for d in services_before} + if shared_uids(s) != shared_before or services_during != services_before: + die('the failed kro revision disturbed shared site services: %s -> %s' % (services_before, services_during)) + kro_now = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + if kro_now['metadata']['uid'] != kro_before['metadata']['uid'] or kro_now['status'].get('availableReplicas') != 1: + die('the running kro controller was disturbed by the failed revision') + during = site_facts(s) + same_facts(before, during, 'failed dependency revision') + blocked_record = {'revision': rev, 'kroKustomization': sorted([c['type'], c['status'], c.get('reason', '')] for c in kro['status']['conditions']), + 'kroChartSource': sorted([c['type'], c['status'], c.get('reason', '')] for c in oci['status']['conditions']), + 'graphReady': conditions(graph).get('Ready', {}).get('reason'), 'siteReady': conditions(site).get('Ready', {}).get('reason'), + 'siteLastAppliedRevision': site['status'].get('lastAppliedRevision'), 'siteMarkerUnchanged': marker, + 'kroDeploymentUnchanged': True, 'siteFactsUnchanged': True, 'sharedLayersAppliedBadRevision': True, + 'sharedServiceGenerationsUnchanged': services_during, 'sharedObjectUIDsUnchanged': True} + fixed = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, + purpose='fail-closed recovery: pinned kro chart restored', cluster=['cell'], timeout=600) + publish(fixed) + site_obj = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + if site_obj['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') != 'r%d' % fixed.revision: + die('recovered revision did not reach the dispatcher') + after = site_facts(s) + same_facts(before, after, 'fail-closed recovery') + write(s / 'evidence' / 'flux-fail-closed.json', {'observedAt': now(), 'blocked': blocked_record, 'recoveredRevision': current(s), 'siteFacts': after, + 'missingDigest': MISSING_DIGEST}) + print('flux-fail-closed: absent kro chart digest left kro not Ready; graph and dispatcher reported DependencyNotReady and were not applied; shared site layers applied it with services untouched; running kro and site untouched; restored revision converged') + return 0 + + +def retention(args): + """Removing the journal volume from the source must not delete or replace it.""" + s = pathlib.Path(args.state) + before = site_facts(s) + base = current(s)['revision'] + drop = argparse.Namespace(state=str(s), root=args.root, revision=base + 1, site='dispatch', bad_kro_chart=False, drop_site_volume=True, + purpose='retention: site volume claim removed from the source', cluster=['cell'], timeout=600) + publish(drop) + inv = kustomizations(s, 'cell')['flux-system/fleet-site-base'] + if any('PersistentVolumeClaim' in e for e in inventory(inv)): + die('volume claim still in the Flux inventory after its removal from the source') + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + if pvc['metadata'].get('deletionTimestamp'): + die('Flux garbage-collected the journal volume claim') + removed = site_facts(s) + same_facts(before, removed, 'source removal of the volume claim') + restore = argparse.Namespace(state=str(s), root=args.root, revision=base + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, + purpose='retention: site volume claim restored to the source (create-once policy)', cluster=['cell'], timeout=600) + publish(restore) + inv = kustomizations(s, 'cell')['flux-system/fleet-site-base'] + if not any(e == 'fleet-site_fleet-site-state__PersistentVolumeClaim' for e in inventory(inv)): + die('restored claim not back in the Flux inventory') + after = site_facts(s) + same_facts(before, after, 'restoring the volume claim to the source') + write(s / 'evidence' / 'flux-retention.json', {'observedAt': now(), 'removedAt': drop.revision, 'restoredAt': restore.revision, + 'pvcUID': after['pvcUID'], 'pvUID': after['pvUID'], 'reclaimPolicy': after['reclaimPolicy'], + 'inventoryWithoutClaim': True, 'claimNotDeleted': True, 'siteFacts': after}) + print('flux-retention: removing the volume claim from the source left it, its PV, journal and custody unchanged; restoring it re-adopted the same claim') + return 0 + + +def main(): + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest='cmd', required=True) + + def add(name, *extra): + s = sub.add_parser(name) + s.add_argument('state') + s.add_argument('--root', default='.') + for e in extra: + e(s) + return s + + def staging(s): + s.add_argument('--revision', type=int, required=True) + s.add_argument('--site', choices=('absent', 'off', 'dispatch'), default='absent') + s.add_argument('--bad-kro-chart', action='store_true') + s.add_argument('--drop-site-volume', action='store_true') + s.add_argument('--purpose', default='') + + def clusters(s): + s.add_argument('--cluster', action='append', default=[], choices=CLUSTERS) + s.add_argument('--timeout', type=int, default=900) + add('tools') + add('stage', staging) + add('push', staging) + add('publish', staging, clusters) + add('bootstrap', lambda s: s.add_argument('--cluster', required=True, choices=CLUSTERS)) + add('wait', clusters, lambda s: s.add_argument('--except', dest='skip', action='append', default=[]), + lambda s: s.add_argument('--observe', action='append', default=[], choices=CLUSTERS)) + add('record', clusters, lambda s: s.add_argument('--name', required=True)) + for name in ('verify', 'drift', 'restart', 'fail-closed', 'retention', 'graph-lifecycle'): + add(name) + add('ownership', lambda s: s.add_argument('--name', required=True)) + a = p.parse_args() + return {'tools': tools, 'stage': stage, 'push': push, 'publish': publish, 'bootstrap': bootstrap, 'wait': wait_cmd, 'record': record, + 'verify': verify, 'drift': drift, 'restart': restart, 'fail-closed': fail_closed, 'retention': retention, + 'graph-lifecycle': graph_lifecycle, 'ownership': ownership_cmd}[a.cmd](a) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py new file mode 100755 index 00000000..9127cd17 --- /dev/null +++ b/hack/multiplane/harness.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Shared local acceptance helpers: preflight, bounded phases, sanitized results. + +Exit codes are part of the harness contract (see docs/operations/multiplane.md): +0 passed, 1 failed, 2 preflight failed, 3 blocked by implementation readiness, +4 bounded wait expired, 64 usage. Nothing here deletes resources. +""" +import argparse +import datetime +import hashlib +import json +import os +import pathlib +import re +import shutil +import signal +import subprocess +import sys +import time + +PROFILE = os.environ.get('FLEET_MULTIPLANE_PROFILE', 'fleet-acceptance-tcg') +CONTEXT = 'colima-' + PROFILE +EXIT_PASSED, EXIT_FAILED, EXIT_PREFLIGHT, EXIT_BLOCKED, EXIT_TIMEOUT, EXIT_USAGE = 0, 1, 2, 3, 4, 64 +STATUS_BY_EXIT = {EXIT_PASSED: 'passed', EXIT_FAILED: 'failed', EXIT_PREFLIGHT: 'preflight-failed', + EXIT_BLOCKED: 'blocked', EXIT_TIMEOUT: 'timeout', EXIT_USAGE: 'usage'} +DEBIAN = 'debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc' +# Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. +REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', + 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) +READINESS_PACKAGES = ('./internal/coordination', './internal/multiplane', './internal/localvm', './cmd/fleet-multiplane') + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def env(): + e = dict(os.environ) + e['DOCKER_CONTEXT'] = CONTEXT + return e + + +def capture(args, timeout=60, **kw): + """Bounded command; returns (code, stdout, stderr). Missing tools return 127.""" + try: + r = subprocess.run(args, text=True, capture_output=True, timeout=timeout, env=kw.pop('env', env()), **kw) + return r.returncode, r.stdout, r.stderr + except FileNotFoundError: + return 127, '', args[0] + ' not found' + except subprocess.TimeoutExpired: + return 124, '', 'timed out after %ss' % timeout + + +def evidence_dir(state): + d = pathlib.Path(state) / 'evidence' + d.mkdir(mode=0o700, parents=True, exist_ok=True) + return d + + +def write_json(path, value): + path = pathlib.Path(path) + tmp = path.with_suffix(path.suffix + '.tmp') + tmp.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + tmp.chmod(0o600) + tmp.replace(path) + + +# ---------------------------------------------------------------- preflight + +def preflight(args): + checks = [] + + def check(name, ok, detail='', kind='preflight'): + checks.append({'name': name, 'ok': bool(ok), 'detail': detail, 'kind': kind}) + return ok + + for tool in ('go', 'python3', 'openssl', 'docker', 'kind', 'kubectl', 'kustomize', 'curl', 'git'): + check('tool:' + tool, shutil.which(tool), 'required on PATH') + check('python>=3.12', sys.version_info >= (3, 12), sys.version.split()[0] + ' (evidence extraction uses the tarfile data filter)') + + code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) + endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + if not endpoint_ok and args.bootstrap and shutil.which('colima'): + # Only start an existing task-owned profile with its saved configuration. + code, out, err = capture(['colima', 'list', '--json'], 30, cwd='/') + known = any(json.loads(line).get('name') == PROFILE for line in out.splitlines() if line.strip().startswith('{')) if code == 0 else False + if known: + code, _, err = capture(['colima', 'start', '--profile', PROFILE], 600, cwd='/') + check('bootstrap:colima-start', code == 0, 'started existing profile ' + PROFILE if code == 0 else err.strip()[-300:]) + code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) + endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + check('docker-context', endpoint_ok, CONTEXT + ' must point at the task-owned Colima profile socket; never fleet-e2e-x86') + + info = {} + if endpoint_ok: + code, out, err = capture(['docker', 'info', '--format', '{{json .}}'], 30) + if check('docker-reachable', code == 0, 'start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if code else 'reachable'): + info = json.loads(out) + if info: + check('runtime-architecture', info.get('Architecture') in ('aarch64', 'arm64'), '%s (the Milo image pin is native arm64)' % info.get('Architecture')) + check('runtime-memory', int(info.get('MemTotal', 0)) >= 7_800_000_000, '%.2f GiB; 8 GiB required' % (int(info.get('MemTotal', 0)) / 2**30)) + check('runtime-cpus', int(info.get('NCPU', 0)) >= 4, '%s CPUs; 4 required' % info.get('NCPU')) + code, out, _ = capture(['docker', 'ps', '--format', '{{.Names}}'], 30) + active = sorted(n for n in out.split() if re.match(r'^fleet-(local|mp)-', n)) + check('no-concurrent-fleet-runtime', code == 0 and not active, ('running: ' + ', '.join(active[:6])) if active else 'none running; stopped diagnostics are left untouched') + code, out, err = capture(['docker', 'run', '--rm', '--platform', 'linux/amd64', '--entrypoint', 'uname', DEBIAN, '-m'], 300) + check('amd64-emulation', code == 0 and out.strip() == 'x86_64', 'installer image build needs amd64 container execution' + ('' if code == 0 else ': ' + err.strip()[-200:])) + free = vm_free_bytes() + check('runtime-disk', free is not None and free >= 12 * 2**30, ('%.1f GiB free in docker data root; 12 GiB required' % (free / 2**30)) if free is not None else 'unable to read docker data-root free space') + limit = vm_inotify() + opted = os.environ.get('FLEET_MULTIPLANE_INOTIFY') == '1024' + check('inotify-instances', limit is not None and (limit >= 1024 or opted), 'current %s; requires >=1024 or FLEET_MULTIPLANE_INOTIFY=1024 (reversible task-VM adjustment)' % limit) + + root = pathlib.Path(args.root) + main = (root / 'cmd/fleet-multiplane/main.go') + source = main.read_text() if main.exists() else '' + missing = [c for c in REQUIRED_SOURCE_MARKERS if c not in source] + check('implementation:subcommands', not missing, ('missing: ' + ', '.join(missing)) if missing else 'all harness subcommands and denial errors present', 'readiness') + if args.skip_tests: + check('implementation:tests', True, 'skipped by caller', 'readiness') + else: + code, out, err = capture(['go', 'test', '-race', '-count=1', *READINESS_PACKAGES], 900, cwd=str(root), env=dict(os.environ)) + failing = sorted(set(re.findall(r'--- FAIL: (\S+)', out + err))) + check('implementation:tests', code == 0, 'passed' if code == 0 else 'failing: ' + (', '.join(failing[:8]) or (out + err).strip()[-300:]), 'readiness') + + pre = [c for c in checks if c['kind'] == 'preflight' and not c['ok']] + ready = [c for c in checks if c['kind'] == 'readiness' and not c['ok']] + code = EXIT_PREFLIGHT if pre else EXIT_BLOCKED if ready else EXIT_PASSED + write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks}) + for c in checks: + print('%-4s %-34s %s' % ('ok' if c['ok'] else 'FAIL', c['name'], c['detail'])) + return code + + +def vm_exec(command, timeout=30): + if not shutil.which('colima'): + return None + code, out, _ = capture(['colima', 'ssh', '--profile', PROFILE, '--', 'sh', '-c', command], timeout, cwd='/') + return out.strip() if code == 0 else None + + +def vm_free_bytes(): + out = vm_exec('df -Pk /var/lib/docker | tail -1') + try: + return int(out.split()[3]) * 1024 + except (AttributeError, IndexError, ValueError): + return None + + +def vm_inotify(): + out = vm_exec('cat /proc/sys/fs/inotify/max_user_instances') + try: + return int(out) + except (TypeError, ValueError): + return None + + +# ---------------------------------------------------------------- phases + +def phase(args): + """Run one bounded phase, keep its full output private, record a sanitized entry.""" + state = pathlib.Path(args.state) + logs = state / 'logs' + logs.mkdir(mode=0o700, exist_ok=True) + log = logs / (args.name + '.log') + started = time.monotonic() + record = {'name': args.name, 'startedAt': now(), 'timeoutSeconds': args.timeout} + print('==> %s (bound %ss)' % (args.name, args.timeout), flush=True) + with open(log, 'ab') as out, open(state / 'phases.log', 'ab') as markers: + p = subprocess.Popen(args.command, stdout=subprocess.PIPE, stderr=out, start_new_session=True) + deadline = started + args.timeout + timed_out = False + import selectors + sel = selectors.DefaultSelector() + os.set_blocking(p.stdout.fileno(), False) + sel.register(p.stdout, selectors.EVENT_READ) + eof = False + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + timed_out = True + break + if eof: + try: + p.wait(timeout=remaining) + except subprocess.TimeoutExpired: + timed_out = True + break + if sel.select(timeout=min(remaining, 1.0)): + line = os.read(p.stdout.fileno(), 65536) + if not line: + sel.unregister(p.stdout) + eof = True + continue + out.write(line) + markers.write(line) + out.flush() + markers.flush() + if args.echo: + sys.stdout.write(''.join(' ' + l for l in line.decode(errors='replace').splitlines(True))) + sys.stdout.flush() + sel.close() + p.stdout.close() + if timed_out: + terminate(p) + code = p.wait(timeout=5) + record['durationSeconds'] = round(time.monotonic() - started, 1) + record['finishedAt'] = now() + if timed_out: + record.update(status='timeout', exitCode=EXIT_TIMEOUT) + else: + record.update(status='passed' if code == 0 else 'blocked' if code == EXIT_BLOCKED else 'failed', exitCode=code) + with open(evidence_dir(state) / 'phases.jsonl', 'a') as f: + f.write(json.dumps(record, sort_keys=True) + '\n') + if record['status'] != 'passed': + print('<== %s %s (exit %s); private log: %s' % (args.name, record['status'], record['exitCode'], log), flush=True) + tail = log.read_bytes()[-1500:].decode(errors='replace') + print('\n'.join(' ' + l for l in tail.splitlines()[-15:]), flush=True) + return EXIT_TIMEOUT if timed_out else (0 if code == 0 else EXIT_BLOCKED if code == EXIT_BLOCKED else EXIT_FAILED) + + +def terminate(p): + for sig, wait in ((signal.SIGTERM, 15), (signal.SIGKILL, 5)): + try: + os.killpg(p.pid, sig) + except ProcessLookupError: + return + try: + p.wait(wait) + # The group may still contain children after its leader exits. + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + return + except subprocess.TimeoutExpired: + continue + + +# ---------------------------------------------------------------- provider observation + +LIBVIRT_URI = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' + + +def runtime_exec(state, *command, timeout=20): + """Run a read-only command in the site VM runtime Pod through the cell API.""" + kubeconfig = str(pathlib.Path(state) / 'cell-admin.yaml') + return capture(['kubectl', '--kubeconfig', kubeconfig, '--request-timeout=15s', '-n', 'fleet-site', 'exec', + 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command], timeout) + + +def journal(state): + code, out, err = runtime_exec(state, 'cat', '/var/lib/fleet-local/journal.json') + if code != 0: + return None + return json.loads(out) + + +def domains(state): + # Running domains only. + code, out, _ = runtime_exec(state, 'virsh', '--connect', LIBVIRT_URI, 'list', '--name') + return out.split() if code == 0 else None + + +def domain_name(operation_id): + return 'fleet-local-' + hashlib.sha256(operation_id.encode()).hexdigest()[:24] + + +def sanitized_operations(j): + """Only non-secret fields: no fence, boot capability or receipt.""" + ops = [] + for r in (j or {}).get('operations', {}).values(): + ops.append({'id': r['request']['id'], 'kind': r['request']['kind'], 'epoch': r['request']['epoch'], + 'stage': r.get('stage'), 'phase': r.get('result', {}).get('phase'), 'bootClosed': r.get('bootClosed', False), + 'domain': domain_name(r['request']['id'])}) + return ops + + +def wait_stage(args): + """Wait until exactly one install is in args.stage with its domain running.""" + deadline = time.monotonic() + args.timeout + last = None + while time.monotonic() < deadline: + ops = sanitized_operations(journal(args.state)) + installs = [o for o in ops if o['kind'] == 'install'] + running = domains(args.state) or [] + last = {'installs': installs, 'runningDomains': len(running)} + if len(installs) > 1: + print(json.dumps({'error': 'more than one install operation', **last})) + return EXIT_FAILED + if installs and installs[0]['stage'] in ('installer-verified', 'disk-armed', 'disk-requested', 'disk-started', 'disk-verified', 'done'): + print(json.dumps({'error': 'installer completed before the interrupt window', **last})) + return EXIT_FAILED + if installs and installs[0]['stage'] == args.stage and installs[0]['domain'] in running: + print(json.dumps({'observedAt': now(), 'operation': installs[0], 'domainRunning': True})) + return 0 + time.sleep(args.interval) + print(json.dumps({'error': 'stage not observed before deadline', **(last or {})})) + return EXIT_TIMEOUT + + +def journal_cmd(args): + print(json.dumps(sanitized_operations(journal(args.state)), sort_keys=True)) + return 0 + + +# ---------------------------------------------------------------- secrets and result + +TOKEN = re.compile(r'''["']?\b(?:token|client-key-data)["']?\s*:\s*["']?([A-Za-z0-9+/=._-]{16,})''') + + +def secrets(state): + state = pathlib.Path(state) + found = set() + for p in state.rglob('*'): + if not p.is_file() or 'evidence' in p.relative_to(state).parts or p.stat().st_size > 4 << 20: + continue + try: + text = p.read_text(errors='ignore') + except OSError: + continue + if p.suffix == '.token': + found.add(text.strip()) + if p.name == 'tokens.csv': + found.update(line.split(',')[0] for line in text.splitlines() if line.count(',') >= 2) + for m in TOKEN.finditer(text): + found.add(m.group(1)) + if p.name == 'journal.json': + try: + j = json.loads(text) + except ValueError: + continue + if j.get('fence'): + found.add(j['fence']) + for r in j.get('operations', {}).values(): + for value in (r.get('bootToken'), r.get('request', {}).get('fenceToken')): + if value: + found.add(value) + for m in re.finditer(r'-----BEGIN [A-Z ]*PRIVATE KEY-----[^-]+', text): + found.add(m.group(0)[40:100]) + return {s for s in found if s and len(s) >= 16} + + +def scan(args): + values = secrets(args.state) | set(args.extra or []) + leaked = [] + for p in evidence_dir(args.state).rglob('*'): + if p.is_file(): + data = p.read_bytes() + if any(v.encode() in data for v in values): + leaked.append(p.name) + if leaked: + for name in leaked: + (evidence_dir(args.state) / name).write_text('{"redacted":"secret scan matched; see private state"}\n') + print('secret scan matched and redacted: ' + ', '.join(sorted(leaked)), file=sys.stderr) + return EXIT_FAILED + print('secret scan: %d evidence files clean against %d retained secrets' % (sum(1 for p in evidence_dir(args.state).rglob('*') if p.is_file()), len(values))) + return 0 + + +def result(args): + state = pathlib.Path(args.state) + ev = evidence_dir(state) + phases = [] + if (ev / 'phases.jsonl').exists(): + phases = [json.loads(l) for l in (ev / 'phases.jsonl').read_text().splitlines() if l.strip()] + prefix = (state / 'prefix').read_text().strip() if (state / 'prefix').exists() else None + retained = [] + if prefix: + code, out, _ = capture(['docker', 'ps', '-a', '--filter', 'name=^' + prefix + '-', '--format', '{{.Names}}\t{{.State}}'], 30) + retained = [dict(zip(('name', 'state'), l.split('\t'))) for l in out.splitlines() if code == 0 and l.strip()] + failed = next((p for p in phases if p['status'] != 'passed'), None) + status = STATUS_BY_EXIT.get(args.exit_code, 'failed') + summary = ev / 'summary.json' + value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': args.exit_code, 'prefix': prefix, + 'failedPhase': failed['name'] if failed else None, 'phases': phases, 'retainedContainers': retained, + 'stateDirectory': str(state), 'evidenceDirectory': str(ev), + 'summary': 'summary.json' if summary.exists() and status == 'passed' else None, + 'custody': 'released and verified' if status == 'passed' else 'Unknown: inspect private state before any cleanup', + 'productionAuthority': False} + write_json(ev / 'result.json', value) + print('RESULT %s exit=%s evidence=%s' % (status, args.exit_code, ev / 'result.json')) + return 0 + + +def main(): + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest='cmd', required=True) + s = sub.add_parser('preflight') + s.add_argument('--state', required=True) + s.add_argument('--root', default='.') + s.add_argument('--bootstrap', action='store_true') + s.add_argument('--skip-tests', action='store_true') + s = sub.add_parser('phase') + s.add_argument('--state', required=True) + s.add_argument('--name', required=True) + s.add_argument('--timeout', type=int, required=True) + s.add_argument('--echo', action='store_true') + s.add_argument('command', nargs=argparse.REMAINDER) + s = sub.add_parser('wait-stage') + s.add_argument('--state', required=True) + s.add_argument('--stage', required=True) + s.add_argument('--timeout', type=int, default=900) + s.add_argument('--interval', type=float, default=1.0) + s = sub.add_parser('journal') + s.add_argument('--state', required=True) + s = sub.add_parser('scan') + s.add_argument('--state', required=True) + s.add_argument('--extra', nargs='*') + s = sub.add_parser('result') + s.add_argument('--state', required=True) + s.add_argument('--exit-code', type=int, required=True) + a = p.parse_args() + if a.cmd == 'phase': + if a.command[:1] == ['--']: + a.command = a.command[1:] + if not a.command or not re.match(r'^[a-z0-9-]+$', a.name): + return EXIT_USAGE + return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, + 'scan': scan, 'result': result}[a.cmd](a) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py new file mode 100644 index 00000000..17f7daef --- /dev/null +++ b/hack/multiplane/k8s_evidence.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Kubernetes site observation, fault injection and sanitized execution records. + +Every call goes through the selected cell's API with its bootstrap kubeconfig. +Records keep names, UIDs, phases, exit codes and conditions only: never handoff +specs, journal records, fences, boot capabilities or tokens. +""" +import datetime +import hashlib +import json +import pathlib +import subprocess +import sys + +NS, SITE = 'fleet-coordination', 'fleet-site' +LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def kubectl(state, *args, input=None, check=True, config='cell-admin.yaml'): + r = subprocess.run(['kubectl', '--kubeconfig', str(pathlib.Path(state) / config), '--request-timeout=20s', *args], + input=input, text=True, capture_output=True) + if check and r.returncode: + raise SystemExit('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[:300])) + return r + + +def get(state, *args, config='cell-admin.yaml'): + return json.loads(kubectl(state, *args, '-o', 'json', config=config).stdout) + + +def job(state, name): + j = get(state, '-n', SITE, 'get', 'job', 'w-' + name) + st = j.get('status', {}) + return {'job': j['metadata']['name'], 'uid': j['metadata']['uid'], 'active': st.get('active', 0), 'failed': st.get('failed', 0), + 'succeeded': st.get('succeeded', 0), 'conditions': sorted([c['type'], c['status'], c.get('reason', '')] for c in st.get('conditions', [])), + 'backoffLimit': j['spec'].get('backoffLimit'), 'podReplacementPolicy': j['spec'].get('podReplacementPolicy'), + 'serviceAccount': j['spec']['template']['spec'].get('serviceAccountName'), + 'kroNodeID': j['metadata'].get('labels', {}).get('kro.run/node-id')} + + +def pods(state, name): + out = [] + for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items']: + exit_code = next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) + out.append({'pod': p['metadata']['name'], 'uid': p['metadata']['uid'], 'phase': p['status'].get('phase'), 'exitCode': exit_code, + 'deleting': bool(p['metadata'].get('deletionTimestamp')), 'jobUID': p['metadata'].get('labels', {}).get('batch.kubernetes.io/controller-uid'), + 'node': p['spec'].get('nodeName')}) + return sorted(out, key=lambda p: p['pod']) + + +def running_pod(state, name, phases=('Running',)): + running = [p for p in pods(state, name) if p['phase'] in phases and not p['deleting']] + return running[0]['uid'] if len(running) == 1 else '' + + +def runtime(state, *command): + return kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command).stdout + + +def evidence(state): + return pathlib.Path(state) / 'evidence' + + +def interrupt_record(state): + return json.loads((evidence(state) / 'interrupt.json').read_text()) + + +def write(path, value): + pathlib.Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + + +def installs(path): + return [o for o in json.loads(pathlib.Path(path).read_text()) if o['kind'] == 'install'] + + +def worker_rbac(state, name): + s = pathlib.Path(state) + cfg = json.loads(kubectl(state, 'config', 'view', '--raw', '--minify', '-o', 'json').stdout) + cfg['users'] = [{'name': 'worker', 'user': {'token': (s / 'worker.token').read_text().strip()}}] + cfg['contexts'][0]['context']['user'] = 'worker' + path = s / 'worker-kubeconfig.json' + path.write_text(json.dumps(cfg)) + path.chmod(0o600) + own = kubectl(state, '-n', NS, 'get', 'machineallocationhandoff', name, '-o', 'name', check=False, config='worker-kubeconfig.json') + if own.returncode: + raise SystemExit('worker cannot read its own handoff: ' + own.stderr[:200]) + denied = [] + for args in (('-n', NS, 'get', 'machineallocationhandoff', 'op-other-operation'), ('-n', NS, 'get', 'machineallocationhandoffs'), + ('-n', NS, 'patch', 'machineallocationhandoff', name, '--subresource=status', '--type=merge', '-p', '{"status":{}}'), + ('-n', NS, 'patch', 'machineallocationhandoff', name, '--type=merge', '-p', '{"spec":{"cell":"other"}}'), + ('-n', NS, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs')): + r = kubectl(state, *args, check=False, config='worker-kubeconfig.json') + if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): + raise SystemExit('worker credential allowed: ' + ' '.join(args[:4]) + ' ' + r.stderr[:200]) + denied.append(' '.join(args[2:4]) + (' (status)' if '--subresource=status' in args else '')) + role = get(state, '-n', NS, 'get', 'role', 'w-' + name) + write(s / 'k8s-worker-rbac.json', {'observedAt': now(), 'serviceAccount': 'w-' + name, 'roleRules': role['rules'], + 'ownHandoffReadable': True, 'forbidden': denied, 'roleCreatedBy': role['metadata'].get('labels', {}).get('kro.run/node-id')}) + print('worker-rbac: per-operation ServiceAccount reads only its own handoff; list, other names, status, spec, Secrets and site writes forbidden') + + +def record_pod_interrupt(state, before, after): + s = pathlib.Path(state) + seen = json.loads((s / 'interrupt-observed.json').read_text()) + after_ops = installs(s / 'interrupt-after.json') + jb = json.loads((s / 'interrupt-job-before-pod.json').read_text()) + ja = json.loads((s / 'interrupt-job-after-pod.json').read_text()) + if len(after_ops) != 1 or after_ops[0]['id'] != seen['operation']['id'] or after_ops[0]['stage'] == 'done': + raise SystemExit('interrupted operation is not the same unfinished operation') + if jb['uid'] != ja['uid'] or ja['failed'] < 1: + raise SystemExit('Job controller did not account and replace the lost Pod in the same Job: %s' % ja) + write(evidence(state) / 'interrupt.json', { + 'observedAt': now(), 'operationID': seen['operation']['id'], 'domain': seen['operation']['domain'], + 'stageAtInterrupt': seen['operation']['stage'], 'domainRunningAtInterrupt': seen['domainRunning'], + 'podInterruption': {'method': 'worker Pod force-deleted with grace period 0', 'deletedPodUID': before, 'replacementPodUID': after, + 'jobUID': jb['uid'], 'jobFailedPodsBefore': jb['failed'], 'jobFailedPodsAfter': ja['failed'], 'replacedBy': 'Job controller'}, + 'localObservationAtInterrupt': None, 'stageAfterInterrupt': after_ops[0]['stage'], 'resultPhaseAfterInterrupt': after_ops[0]['phase']}) + + +def record_job_interrupt(state, old, new, pod_before, pod_after): + s = pathlib.Path(state) + i = interrupt_record(state) + before, after = installs(s / 'interrupt-job-before.json'), installs(s / 'interrupt-job-after.json') + if len(before) != 1 or before[0]['stage'] == 'done': + raise SystemExit('install finished before the Job could be deleted mid-operation') + if len(after) != 1 or after[0]['id'] != i['operationID']: + raise SystemExit('Job recreation created another install operation') + i['jobRecreation'] = {'deletedJobUID': old, 'recreatedJobUID': new, 'recreatedBy': 'kro collection reconciliation', + 'podBeforeUID': pod_before, 'podAfterUID': pod_after, 'stageAtDeletion': before[0]['stage'], 'stageAfterRecreation': after[0]['stage']} + write(evidence(state) / 'interrupt.json', i) + + +def record_resume(state, name): + s = pathlib.Path(state) + i = interrupt_record(state) + done = installs(s / 'resume-after.json') + if len(done) != 1 or done[0]['id'] != i['operationID'] or done[0]['stage'] != 'done' or done[0]['phase'] != 'Succeeded': + raise SystemExit('replacement workers did not complete the exact interrupted operation') + j, ps = job(state, name), pods(state, name) + if j['uid'] != i['jobRecreation']['recreatedJobUID'] or ['Complete', 'True', 'CompletionsReached'] not in j['conditions']: + raise SystemExit('recreated Job did not complete: %s' % j) + if [p['exitCode'] for p in ps if p['phase'] == 'Succeeded'] != [0]: + raise SystemExit('expected exactly one succeeded worker Pod in the recreated Job: %s' % ps) + i.update(resumedStage=done[0]['stage'], resumedPhase=done[0]['phase'], installOperations=len(done), completedJob=j, completedJobPods=ps) + write(evidence(state) / 'interrupt.json', i) + + +def qemu_starts(state, operation): + domain = 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] + r = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/log/libvirt/qemu/' + domain + '.log', check=False) + return r.stdout.count(': starting up ') if r.returncode == 0 else None + + +def lifecycle_snapshot(state, name): + s = pathlib.Path(state) + op = interrupt_record(state)['operationID'] + pvc = get(state, '-n', SITE, 'get', 'pvc', 'fleet-site-state') + pv = get(state, 'get', 'pv', pvc['spec']['volumeName']) + machine = get(state, '-n', 'default', 'get', 'machine', 'allocation', config='consumer-a/management-project.json') + conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} + site_pods = {d: [p['metadata']['uid'] for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=' + d)['items']] + for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')} + print(json.dumps({'observedAt': now(), 'journalSHA256': hashlib.sha256(runtime(state, 'cat', '/var/lib/fleet-local/journal.json').encode()).hexdigest(), + 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', '--all').split(), + 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvReclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], + 'machineA': {'phase': machine.get('status', {}).get('phase'), 'bound': conds.get('Bound'), 'ready': conds.get('Ready')}, + 'sitePods': site_pods, 'job': job(state, name)}, sort_keys=True)) + + +def record_lifecycle(state, old, new): + s = pathlib.Path(state) + a, b = json.loads((s / 'lifecycle-before.json').read_text()), json.loads((s / 'lifecycle-after.json').read_text()) + for key in ('journalSHA256', 'qemuStarts', 'pvcUID', 'pvUID', 'pvReclaimPolicy', 'domains', 'machineA'): + if a[key] != b[key]: + raise SystemExit('%s changed across Pod/Job lifecycle: %s -> %s' % (key, a[key], b[key])) + if a['machineA'] != {'phase': 'Ready', 'bound': 'True', 'ready': 'True'} or a['qemuStarts'] != 2 or a['domains'] or a['pvReclaimPolicy'] != 'Retain': + raise SystemExit('unexpected lifecycle baseline: %s' % a) + for d, uids in a['sitePods'].items(): + if set(uids) & set(b['sitePods'][d]) or len(b['sitePods'][d]) != 1: + raise SystemExit(d + ' Pod was not replaced exactly once') + name = (s / 'install-handoff').read_text().strip() + replay = [p for p in pods(state, name) if p['jobUID'] == new] + if [p['exitCode'] for p in replay] != [0]: + raise SystemExit('recreated completed Job did not finish with one verified no-op replay: %s' % replay) + write(evidence(state) / 'lifecycle.json', {'observedAt': now(), 'recreated': ['fleet-site-runtime Pod', 'fleet-site-boot Pod', 'fleet-site-observer Pod', 'completed install Job'], + 'completedJobUIDBefore': old, 'completedJobUIDAfter': new, 'replayPods': replay, + 'unchanged': ['provider journal bytes', 'QEMU starts (2)', 'PVC/PV identity', 'Retain reclaim policy', 'no domains', 'consumer-a Machine Ready/Bound'], + 'journalSHA256': a['journalSHA256'], 'observerRepublished': True, 'before': a, 'after': b}) + + +FAULTS = ('duplicate', 'wrong-cell', 'stale-epoch') + + +def delivery_faults(state, action): + s = pathlib.Path(state) + cell = (s / 'prefix').read_text().strip() + '-cell' + if action == 'create': + handoffs = get(state, '-n', NS, 'get', 'machineallocationhandoffs', '-l', 'coordination.fleet.datumapis.com/cell=' + cell)['items'] + source = [h for h in handoffs if json.loads(h['spec']['requestJSON'])['kind'] == 'install' and json.loads(h['spec']['requestJSON'])['epoch'] == 1] + if len(source) != 1: + raise SystemExit('expected exactly one epoch-1 install handoff to derive faults from') + spec = source[0]['spec'] + request = json.loads(spec['requestJSON']) + objects = {} + # Same retained intent under a second name: name/operation binding fails. + objects['duplicate'] = ('op-fault-duplicate-' + hashlib.sha256(spec['requestJSON'].encode()).hexdigest()[:12], dict(spec)) + # Selected by the cell label, but the intent names another cell. + wrong = dict(request, id=request['id'] + '-fault-wrong-cell') + objects['wrong-cell'] = ('op-' + hashlib.sha256(wrong['id'].encode()).hexdigest()[:40], {'cell': 'remote-elsewhere-cell', 'requestJSON': json.dumps(wrong, separators=(',', ':'))}) + # Well-formed for this cell, but replays the superseded epoch-1 fence. + stale = dict(request, id=request['id'] + '-fault-stale-epoch') + objects['stale-epoch'] = ('op-' + hashlib.sha256(stale['id'].encode()).hexdigest()[:40], {'cell': cell, 'requestJSON': json.dumps(stale, separators=(',', ':'))}) + if request['epoch'] != 1: + raise SystemExit('stale-epoch fault requires the epoch-1 install handoff') + for fault in FAULTS: + name, body = objects[fault] + obj = {'apiVersion': 'coordination.fleet.datumapis.com/v1alpha1', 'kind': 'MachineAllocationHandoff', + 'metadata': {'name': name, 'namespace': NS, 'labels': {'coordination.fleet.datumapis.com/cell': cell, 'fleet.datumapis.com/fault': fault}}, 'spec': body} + kubectl(state, 'create', '-f', '-', input=json.dumps(obj)) + (s / ('fault-%s-job' % fault)).write_text('w-' + name + '\n') + (s / ('fault-%s-handoff' % fault)).write_text(name + '\n') + return + names = {f: (s / ('fault-%s-handoff' % f)).read_text().strip() for f in FAULTS} + if action == 'verify': + record = {'observedAt': now(), 'faults': {}} + for fault, name in names.items(): + j, ps = job(state, name), pods(state, name) + if ['Failed', 'True', 'PodFailurePolicy'] not in j['conditions'] or j['succeeded'] or [p['exitCode'] for p in ps] != [65]: + raise SystemExit('%s fault Job did not fail once by podFailurePolicy exit 65: %s %s' % (fault, j, ps)) + h = get(state, '-n', NS, 'get', 'machineallocationhandoff', name) + if h.get('status'): + raise SystemExit(fault + ' fault handoff gained a status observation') + record['faults'][fault] = {'handoff': name, 'job': j, 'pods': ps, 'status': None} + machine = get(state, '-n', 'default', 'get', 'machine', 'allocation', config='consumer-b/management-project.json') + conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} + if machine.get('status', {}).get('phase') != 'Bound' or conds.get('Bound') != 'True': + raise SystemExit('failed fault Jobs changed consumer-b allocation: %s' % machine.get('status')) + record['providerJournalUnchanged'] = True + record['consumerBStillBound'] = True + write(evidence(state) / 'delivery-faults.json', record) + return + for name in names.values(): + kubectl(state, '-n', NS, 'delete', 'machineallocationhandoff', name, '--wait=true') + for _ in range(120): + left = [n for n in names.values() if kubectl(state, '-n', SITE, 'get', 'job', 'w-' + n, check=False).returncode == 0] + if not left: + break + subprocess.run(['sleep', '1']) + else: + raise SystemExit('kro did not prune fault Jobs: %s' % left) + record = json.loads((evidence(state) / 'delivery-faults.json').read_text()) + record['prunedByKro'] = True + write(evidence(state) / 'delivery-faults.json', record) + + +def main(): + cmd, state, *rest = sys.argv[1:] + if cmd == 'running-pod': + print(running_pod(state, rest[0])) + elif cmd == 'job-pod': + # Any Pod (any phase) created by one exact Job UID. + print(next((p['uid'] for p in pods(state, rest[0]) if p['jobUID'] == rest[1]), '')) + elif cmd == 'live-pod': + # A scheduled or running replacement; used to interrupt as early as possible. + print(running_pod(state, rest[0], ('Pending', 'Running'))) + elif cmd == 'job': + print(json.dumps(job(state, rest[0]), sort_keys=True)) + elif cmd == 'worker-rbac': + worker_rbac(state, rest[0]) + elif cmd == 'record-pod-interrupt': + record_pod_interrupt(state, *rest) + elif cmd == 'record-job-interrupt': + record_job_interrupt(state, *rest) + elif cmd == 'record-resume': + record_resume(state, rest[0]) + elif cmd == 'lifecycle-snapshot': + lifecycle_snapshot(state, rest[0]) + elif cmd == 'record-lifecycle': + record_lifecycle(state, *rest) + elif cmd == 'delivery-faults': + delivery_faults(state, rest[0]) + else: + raise SystemExit('unknown command ' + cmd) + + +if __name__ == '__main__': + main() diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py new file mode 100755 index 00000000..0e3dc5e6 --- /dev/null +++ b/hack/multiplane/milo.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Enroll credentials for, then seed, the Flux-managed Milo v0.32.5 project APIs. + +Flux on the platform cluster owns each Milo API's Deployment, etcd StatefulSet, +volume and Service (config/multiplane/milo). This script does only what a +source revision must never hold: + +- credential enrollment: per-API static tokens and a self-signed serving key, + written as the milo-apiserver-private Secret (local credential seam); +- tenant fixture bootstrap through each API: the Project, static-token RBAC + grants and the metal CRDs inside the project. Production uses Milo's own + project provisioning, service catalog and IAM; this is not that machinery. +""" +import argparse, base64, json, os, pathlib, secrets, subprocess, time +p=argparse.ArgumentParser();p.add_argument('state');p.add_argument('prefix');a=p.parse_args() +root=pathlib.Path(a.state).resolve();root.mkdir(mode=0o700,parents=True,exist_ok=True) +if not a.prefix.startswith('fleet-mp-'):raise SystemExit('task-owned fleet-mp- prefix required') +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +platform=root/'platform-admin.yaml' +ports=json.loads((root/'platform-ports.json').read_text()) +def run(*args,**kw):return subprocess.run(args,check=True,text=True,**kw) +def kubectl(config,*args,**kw):return run('kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args,**kw) +def apply(config,obj):kubectl(config,'apply','-f','-',input=json.dumps(obj),stdout=subprocess.DEVNULL) +def kube(path,server,token,ca): + path.write_text(json.dumps({'apiVersion':'v1','kind':'Config','clusters':[{'name':'local','cluster':{'server':server,'certificate-authority-data':base64.b64encode(ca).decode()}}],'users':[{'name':'role','user':{'token':token}}],'contexts':[{'name':'role','context':{'cluster':'local','user':'role'}}],'current-context':'role'}));path.chmod(0o600) +def wait(fn,seconds,what): + for _ in range(seconds//2): + if fn():return + time.sleep(2) + raise SystemExit(what) +roles=('provider','consumer-a','consumer-b') +# 1. Credential enrollment into the Flux-created namespaces. +for role in roles: + d=root/role;ns='milo-'+role + if not d.exists(): + d.mkdir(mode=0o700) + tokens={r:secrets.token_hex(32) for r in ('bootstrap','management','customer')} + (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k=='bootstrap' else 'fleet-local') for k,v in tokens.items())+'\n') + run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + for f in ('tokens.csv','tls.key','tls.crt'):(d/f).chmod(0o600) + wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(platform),'get','namespace',ns],capture_output=True).returncode==0,300,f'Flux did not create namespace {ns}') + secret=kubectl(platform,'-n',ns,'create','secret','generic','milo-apiserver-private',f'--from-file=tokens.csv={d/"tokens.csv"}',f'--from-file=tls.crt={d/"tls.crt"}',f'--from-file=tls.key={d/"tls.key"}','--dry-run=client','-o','json',capture_output=True).stdout + kubectl(platform,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=secret,stdout=subprocess.DEVNULL) + print(role+': credential Secret enrolled (not in the source)',flush=True) +# 2. Flux must report each Milo Kustomization Ready (Deployment and etcd healthy). +for role in roles: + kubectl(platform,'-n','flux-system','annotate','--overwrite','kustomization','milo-'+role,'reconcile.fluxcd.io/requestedAt='+str(time.time()),stdout=subprocess.DEVNULL) +for role in roles: + kubectl(platform,'-n','flux-system','wait','--for=condition=Ready','kustomization/milo-'+role,'--timeout=600s',stdout=subprocess.DEVNULL) +# 3. Tenant fixture bootstrap through each project API. +for role in roles: + d=root/role + tokens={line.split(',')[1]:line.split(',')[0] for line in (d/'tokens.csv').read_text().splitlines()} + server=f'https://127.0.0.1:{ports[role]}';ca=(d/'tls.crt').read_bytes() + kube(d/'bootstrap.json',server,tokens['bootstrap'],ca) + for attempt in range(90): + result=subprocess.run(['kubectl','--kubeconfig',str(d/'bootstrap.json'),'--request-timeout=2s','get','--raw','/readyz'],capture_output=True) + if result.returncode==0: + discovery=subprocess.run(['kubectl','--kubeconfig',str(d/'bootstrap.json'),'get','crd','projects.resourcemanager.miloapis.com'],capture_output=True) + if discovery.returncode==0:break + time.sleep(2) + else:raise SystemExit(f'{role} Milo API did not become ready. Inspect namespace milo-{role} on the platform cluster; private state: {d}') + kubectl(d/'bootstrap.json','wait','--for=condition=Established','crd/projects.resourcemanager.miloapis.com','--timeout=90s',stdout=subprocess.DEVNULL) + apply(d/'bootstrap.json',{'apiVersion':'resourcemanager.miloapis.com/v1alpha1','kind':'Project','metadata':{'name':role},'spec':{'ownerRef':{'kind':'Organization','name':'local-fixture'}}}) + route=server+'/apis/resourcemanager.miloapis.com/v1alpha1/projects/'+role+'/control-plane' + for who in tokens:kube(d/(who+'-project.json'),route,tokens[who],ca) + kube(d/'management-root.json',server,tokens['management'],ca) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-project-reader'},'rules':[{'apiGroups':['resourcemanager.miloapis.com'],'resources':['projects'],'verbs':['get']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-project-reader'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-project-reader'},'subjects':[{'kind':'User','name':'management'}]}) + config=d/'bootstrap-project.json' + kubectl(config,'apply','-f','config/base/crd/metal.datumapis.com.yaml',stdout=subprocess.DEVNULL) + kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) + ns='fleet-provider' if role=='provider' else 'default' + apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) + rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations'],'verbs':['get','list','watch']}] + if role!='provider':rules += [{'apiGroups':['metal.datumapis.com'],'resources':['machines'],'verbs':['update']},{'apiGroups':['metal.datumapis.com'],'resources':['machines/status','installations/status'],'verbs':['update','patch']}] + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-management'},'rules':rules}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) + if role!='provider': + apply(d/'bootstrap.json',{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'default'}}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'customer','namespace':'default'},'rules':[{'apiGroups':['metal.datumapis.com'],'resources':['machines','installations'],'verbs':['get','list','watch','create','delete']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':'customer','namespace':'default'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'customer'},'subjects':[{'kind':'User','name':'customer'}]}) + print(role+': Flux-managed Milo project API ready (static-token RBAC test seam)',flush=True) diff --git a/hack/multiplane/reflection-faults.py b/hack/multiplane/reflection-faults.py new file mode 100755 index 00000000..48873a2f --- /dev/null +++ b/hack/multiplane/reflection-faults.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Explicit test-only hub status fault injection; no simulated federation relay.""" +import copy,json,pathlib,subprocess,sys +s=pathlib.Path(sys.argv[1]);hub=s/'hub-admin.yaml';host=s/'host.yaml' +def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=20s',*args],input=input,text=True,capture_output=True,check=True).stdout +items=json.loads(k(hub,'-n','fleet-coordination','get','machineallocationhandoffs','-o','json'))['items'] +if len(items)!=1:raise SystemExit('run reflection faults after install and before cleanup') +obj=items[0];original=obj.get('status');name=obj['metadata']['name'] +if len((original or {}).get('reflected',[]))!=1:raise SystemExit('no real reflected result to test') +# Explicit ownership transfer: suspend the Flux HelmRelease before stopping the +# controller, so Flux and the harness are never concurrent writers. +k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":true}}') +k(host,'-n','karmada-system','scale','deployment/karmada-controller-manager','--replicas=0') +k(host,'-n','karmada-system','wait','--for=delete','pod','-l','app=karmada-controller-manager','--timeout=90s') +def guard(mode): + subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('fault_guard.py')),mode,str(s),'host.yaml','helmrelease','karmada','karmada-system','karmada-controller-manager','flux-reflection-suspension'],check=True) +guard('record') +def patch(status): + p=s/'status-fault.json';p.write_text(json.dumps({'status':status}));p.chmod(0o600) + k(hub,'-n','fleet-coordination','patch','machineallocationhandoff',name,'--subresource=status','--type=merge','--patch-file',str(p)) +try: + # Each mode changes exactly one attribute of the real reflected result. + for mode in ('wrong-cell','stale','duplicate','future','wrong-intent','wrong-digest','wrong-operation','incomplete','missing'): + status=copy.deepcopy(original);o=status['reflected'][0]['observation'] + if mode=='wrong-cell':status['reflected'][0]['clusterName']='wrong-cell' + elif mode=='stale':o['observedAt']='2000-01-01T00:00:00Z' + elif mode=='duplicate':status['reflected'].append(copy.deepcopy(status['reflected'][0])) + elif mode=='future':o['observedAt']='2999-01-01T00:00:00Z' + elif mode=='wrong-intent':o['intentDigest']='0'*64 + elif mode=='wrong-digest':o['result']['inputDigest']='0'*64 + elif mode=='wrong-operation':o['result']['id']=o['result']['id']+'-other' + elif mode=='incomplete':o['result']['phase']='Unknown' + else:status={'reflected':[]} + guard('check') + patch(status) + result=subprocess.run([str(s/'fleet-multiplane-host'),'install','--once','--config',str(s/'acceptance.json')],text=True,capture_output=True) + if result.returncode==0:raise SystemExit(mode+' incorrectly accepted') + if 'unknown' not in result.stderr.lower():raise SystemExit(mode+' did not reach result validation: '+result.stderr[:200]) + print(mode+': management rejected reflected evidence') +finally: + guard('check') + patch(original) + k(host,'-n','karmada-system','scale','deployment/karmada-controller-manager','--replicas=1') + k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":false}}') + k(host,'-n','karmada-system','wait','--for=condition=Available','deployment/karmada-controller-manager','--timeout=180s') diff --git a/hack/multiplane/roles.py b/hack/multiplane/roles.py new file mode 100755 index 00000000..65141651 --- /dev/null +++ b/hack/multiplane/roles.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Credential enrollment for Flux-created identities; installs nothing. + +Flux owns every ServiceAccount, Role, CRD, namespace, interpreter, member +Cluster and PropagationPolicy referenced here (config/multiplane). This script +only mints the short-lived tokens a source must never hold, writes private +mode-0600 kubeconfigs, and enrolls the cell's push-mode member Secret on the +Karmada API. No cell credential can access hub/project/private APIs. +""" +import base64,json,os,pathlib,subprocess,sys,time +state=pathlib.Path(sys.argv[1]).resolve();prefix=(state/'prefix').read_text().strip() +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +env=json.loads((state/'gitops-environment.json').read_text()) +def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=30s',*args],input=input,text=True,capture_output=True,check=True).stdout +def exists(config,*args):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s','get',*args],capture_output=True).returncode==0 +def wait(config,*args): + for _ in range(150): + if exists(config,*args):return + time.sleep(2) + raise SystemExit('Flux did not create '+' '.join(args)) +def credentials(config,ns,name,dest,internal=None,server=None): + wait(config,'-n',ns,'serviceaccount',name) + token=k(config,'-n',ns,'create','token',name,'--duration=24h').strip() + obj=json.loads(k(config,'config','view','--raw','--minify','-o','json')) + obj['users']=[{'name':name,'user':{'token':token}}];obj['contexts'][0]['context']['user']=name + if server or internal:obj['clusters'][0]['cluster']['server']=server or internal + dest.write_text(json.dumps(obj));dest.chmod(0o600) + return token,base64.b64decode(obj['clusters'][0]['cluster']['certificate-authority-data']) +host=state/'host.yaml';hub=state/'hub-admin.yaml';cell=state/'cell-admin.yaml';ns='fleet-coordination' +# Karmada's admin kubeconfig (chart-generated Secret) rewritten to the host port. +wait(host,'-n','karmada-system','secret','karmada-kubeconfig') +raw=base64.b64decode(json.loads(k(host,'-n','karmada-system','get','secret','karmada-kubeconfig','-o','json'))['data']['kubeconfig']) +hub.write_bytes(raw);hub.chmod(0o600) +entry=k(hub,'config','view','-o','jsonpath={.clusters[0].name}') +k(hub,'config','set-cluster',entry,'--server=https://127.0.0.1:%d'%env['karmadaPort']) +# CA verification is retained; the chart includes localhost in its serving SANs. +credentials(hub,ns,'fleet-management',state/'management-hub.json') +credentials(host,'fleet-system-private','fleet-custodian',state/'private.json') +# Cell execution credentials are Kubernetes ServiceAccounts inside the cell +# site; no cell credential is exported to the host. +token,ca=credentials(cell,ns,'fleet-federation',state/'federation-cell.json',env['cellEndpoint']) +wait(hub,'namespace','karmada-cluster') +secret={'apiVersion':'v1','kind':'Secret','metadata':{'name':env['cell'],'namespace':'karmada-cluster'},'data':{'token':base64.b64encode(token.encode()).decode(),'caBundle':base64.b64encode(ca).decode()}} +k(hub,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=json.dumps(secret)) +k(host,'-n','karmada-system','annotate','--overwrite','kustomization','fleet-karmada-members','reconcile.fluxcd.io/requestedAt=%f'%time.time()) +wait(hub,'cluster/'+env['cell']) +k(hub,'wait','--for=condition=Ready','cluster/'+env['cell'],'--timeout=300s') +k(host,'-n','karmada-system','wait','--for=condition=Ready','kustomization/fleet-karmada-members','--timeout=300s') +print('Karmada member enrolled; separate management/custodian/cell credentials minted for Flux-created identities') diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh new file mode 100755 index 00000000..3fe58150 --- /dev/null +++ b/hack/multiplane/run.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# One-command local Milo/Karmada/PXE acceptance. Creates only fresh resources with +# one fleet-mp- prefix. Failures stop (never delete) this run's containers +# and retain exact state as Unknown custody. See docs/operations/multiplane.md. +# +# Exit codes: 0 passed, 1 failed, 2 preflight failed, 3 blocked by implementation +# readiness, 4 bounded wait expired, 64 usage. +set -euo pipefail +cd "$(dirname "$0")/../.." +umask 077 +usage() { echo 'usage: hack/multiplane/run.sh [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() +for arg in "$@"; do + case "$arg" in + --preflight-only) preflight_only=1 ;; + --bootstrap) bootstrap=(--bootstrap) ;; + --keep) keep=1 ;; + --leave-running) leave=1 ;; + --skip-readiness-tests) skip_tests=(--skip-tests) ;; + *) usage ;; + esac +done +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +harness=(python3 hack/multiplane/harness.py) +state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") +mkdir -m 0700 "$state/evidence" +printf 'Private run state: %s\nShareable evidence: %s/evidence\n' "$state" "$state" + +finish() { + code=$1 + trap - EXIT + if [[ $code -ne 0 && -f $state/prefix ]]; then + if [[ $leave == 1 ]]; then + echo "Leaving this run's containers running for diagnosis. Stop only them with: hack/multiplane/stop.sh $state" + else + bash hack/multiplane/stop.sh "$state" || echo "stop.sh failed; inspect $(cat "$state/prefix")-* containers" >&2 + fi + echo "Execution and custody are Unknown. Retained private state: $state. Discard only after inspection: hack/multiplane/teardown.sh $state --discard-unknown" + fi + [[ $code -eq 0 ]] || "${harness[@]}" scan --state "$state" >/dev/null 2>&1 || true + "${harness[@]}" result --state "$state" --exit-code "$code" + exit "$code" +} +trap 'finish $?' EXIT +ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}"; } + +"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" +[[ $preflight_only == 0 ]] || exit 0 + +prefix="fleet-mp-$(openssl rand -hex 4)" +printf '%s\n' "$prefix" > "$state/prefix" +# Source identity covers uncommitted files as well as tracked files. +python3 - "$state" <<'PY' +import hashlib,pathlib,sys +paths=[] +for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','config/multiplane','config/site','config/base/crd'): + paths += [p for p in pathlib.Path(name).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')] +paths += [pathlib.Path(name) for name in ('go.mod', 'go.sum')] +(pathlib.Path(sys.argv[1])/'source-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n' for p in sorted(paths))) +PY +flux=(python3 hack/multiplane/flux.py) +# The site binary is built into its own directory: it is the only build context +# input besides hack/local-vm, so no private state can enter the image. +ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" +ph site-image 2400 docker build --target site --build-context "fleetbin=$state/site-bin" -t "$prefix-site-image" -f hack/local-vm/Containerfile hack/local-vm +ph site-image-verify 120 sh -c ' + sum=$(shasum -a 256 "$2/site-bin/fleet-multiplane" | cut -d" " -f1) + printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null + docker run --rm -e FLEET_LOCAL_VM_ACCEL=tcg --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" + echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" +ph flux-tools 300 "${flux[@]}" tools "$state" +docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null +# Disposable infrastructure only: registry and three kind clusters, no services. +ph topology 900 bash hack/multiplane/topology.sh "$state" +ph site-image-push 600 bash hack/multiplane/site.sh push "$state" +# Revision 1: platform services only. The bootstrap boundary applies each +# cluster's Flux components and sync objects once; Flux then owns them too. +ph flux-source 300 "${flux[@]}" publish "$state" --revision 1 --purpose 'platform services' +for c in platform hub cell; do ph "flux-bootstrap-$c" 600 "${flux[@]}" bootstrap "$state" --cluster "$c"; done +# Waiting from the moment of bootstrap records dependency gating as it happens. +# The member registration becomes Ready only after credential enrollment. +ph flux-platform 1800 "${flux[@]}" wait "$state" --cluster cell --cluster hub --observe hub --observe cell --except karmada-system/fleet-karmada-members --timeout 1500 +ph milo-bootstrap 1200 python3 hack/multiplane/milo.py "$state" "$prefix" +ph flux-milo 900 "${flux[@]}" wait "$state" --cluster platform --timeout 600 +ph federation-enrollment 600 python3 hack/multiplane/roles.py "$state" +python3 - "$state" <<'PY' +import json,pathlib,sys +s=pathlib.Path(sys.argv[1]).resolve();c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'PrivateKubeconfig':str(s/'private.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip()};(s/'acceptance.json').write_text(json.dumps(c)) +PY +ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" +ph scoped-asset 120 sh -c '"$1/fleet-multiplane-host" asset --config "$1/acceptance.json" > "$1/scoped-asset" && echo "scoped asset recorded"' sh "$state" +# Revision 2: the Flux-owned shared site services and the HandoffDispatcher +# instance, dispatch disabled. +ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 +ph site-install 900 bash hack/multiplane/site.sh check "$state" +ph flux-verify 300 "${flux[@]}" verify "$state" +bash hack/multiplane/acceptance.sh "$state" +ph secret-scan 120 "${harness[@]}" scan --state "$state" +if [[ $keep == 1 ]]; then + ph stop 300 bash hack/multiplane/stop.sh "$state" +else + ph teardown 900 bash hack/multiplane/teardown.sh "$state" +fi +printf 'Local topology/PXE acceptance passed. Production authority and physical hardware remain unqualified.\n' diff --git a/hack/multiplane/site.sh b/hack/multiplane/site.sh new file mode 100755 index 00000000..d7c35536 --- /dev/null +++ b/hack/multiplane/site.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Site image publication and post-reconcile checks for the selected cell. +# site.sh push STATE push the built site image to the run registry; record its digest +# site.sh check STATE after Flux applied the site layers: shared services Available +# and Flux-owned, dispatcher ready, volume Retain, no Job +# Installs nothing: kro, the site base, the shared services, the RGD and the +# HandoffDispatcher are reconciled by the cell's Flux (config/multiplane/clusters). +set -euo pipefail +umask 077 +step=${1:?step required} +state=${2:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +cell="$state/cell-admin.yaml" +deployments=(fleet-site-runtime fleet-site-boot fleet-site-observer) +k() { kubectl --kubeconfig "$cell" --request-timeout=30s "$@"; } + +case "$step" in + push) + port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") + docker tag "$prefix-site-image" "127.0.0.1:$port/fleet-site:$prefix" >/dev/null + docker push "127.0.0.1:$port/fleet-site:$prefix" >/dev/null + digest=$(docker image inspect "127.0.0.1:$port/fleet-site:$prefix" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^127.0.0.1:$port/fleet-site@" | cut -d@ -f2) + [[ $digest =~ ^sha256:[a-f0-9]{64}$ ]] || { echo "no registry digest for the site image" >&2; exit 1; } + python3 - "$state" "$prefix" "$digest" <<'PY' +import json, pathlib, sys +s, prefix, digest = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3] +env = json.loads((s / 'gitops-environment.json').read_text()) +env['siteImage'] = '%s-registry:5000/fleet-site@%s' % (prefix, digest) +env['siteImageDigest'] = digest +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY + printf 'site image: pushed to the run registry as fleet-site@%s; the cell pulls it by digest\n' "$digest" + ;; + check) + for d in "${deployments[@]}"; do + for _ in $(seq 1 120); do k -n fleet-site get deployment "$d" >/dev/null 2>&1 && break; sleep 2; done + k -n fleet-site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null + done + k -n fleet-site wait --for=jsonpath='{.status.runtimeAvailable}'=1 handoffdispatcher/dispatcher --timeout=120s >/dev/null + [[ -z $(k -n fleet-site get jobs -o name) ]] || { echo 'worker Jobs exist before dispatch' >&2; exit 1; } + pv=$(k -n fleet-site get pvc fleet-site-state -o jsonpath='{.spec.volumeName}') + policy=$(k get pv "$pv" -o jsonpath='{.spec.persistentVolumeReclaimPolicy}') + [[ $policy == Retain ]] || { echo "site volume reclaim policy $policy" >&2; exit 1; } + want=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["siteImage"])' "$state/gitops-environment.json") + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do + image=$(k -n fleet-site get deployment "$d" -o jsonpath='{.spec.template.spec.containers[0].image}') + [[ $image == "$want" ]] || { echo "$d runs $image, not the published digest" >&2; exit 1; } + owner=$(k -n fleet-site get deployment "$d" -o jsonpath='{.metadata.labels.kustomize\.toolkit\.fluxcd\.io/name}') + [[ $owner == fleet-site-services ]] || { echo "$d is not owned by the Flux services layer" >&2; exit 1; } + done + [[ $(k -n fleet-site get handoffdispatcher dispatcher -o jsonpath='{.status.workerImage}') == "$want" ]] || { echo 'dispatcher worker image is not the services image' >&2; exit 1; } + [[ $(k -n fleet-site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}') == "$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import flux; print(flux.BOOT_SERVICE_IP)')" ]] || { echo 'boot Service is not at its fixed ClusterIP' >&2; exit 1; } + printf 'site: Flux-owned runtime, boot service and observer Available from the digest-pinned image; boot Service at its fixed ClusterIP; dispatcher ready; volume Retain; dispatch disabled\n' + ;; + *) echo "unknown step: $step" >&2; exit 64 ;; +esac diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh new file mode 100755 index 00000000..81ee78ee --- /dev/null +++ b/hack/multiplane/steps.sh @@ -0,0 +1,309 @@ +#!/usr/bin/env bash +# Individual acceptance steps. Each runs inside a bounded harness phase, prints +# only non-secret marker lines on stdout, and exits nonzero on any violation. +# Site execution is observed and disturbed only through the cell Kubernetes API. +set -euo pipefail +umask 077 +step=${1:?step required} +state=${2:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +harness=(python3 hack/multiplane/harness.py) +host="$state/fleet-multiplane-host" +ns=fleet-coordination +helpers=hack/multiplane/k8s_evidence.py + +k() { kubectl --kubeconfig "$1" --request-timeout=20s "${@:2}"; } +cell() { k "$state/cell-admin.yaml" "$@"; } +platform() { k "$state/platform-admin.yaml" "$@"; } +flux() { python3 hack/multiplane/flux.py "$@"; } +# Explicit, recorded ownership transfer for fault injection: suspend the Flux +# object first so the harness is never a second concurrent writer. +suspend() { platform -n flux-system patch "kustomization/$1" --field-manager=fleet-fault-injection --type=merge -p "{\"spec\":{\"suspend\":$2}}" >/dev/null; } +site() { cell -n fleet-site "$@"; } +runtime() { site exec deploy/fleet-site-runtime -c libvirt -- "$@"; } +py() { python3 "$helpers" "$@"; } +wait_api() { + for _ in $(seq 1 120); do + if k "$1" get --raw /readyz >/dev/null 2>&1; then return; fi + sleep 1 + done + echo "API did not recover: $(basename "$1")" >&2; return 1 +} +local_phase() { cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].status.observation.result.phase}'; } +# Private custody digest: names, UIDs and resourceVersions only; data never leaves memory. +custody_digest() { + k "$state/host.yaml" -n fleet-system-private get secrets -o json | python3 -c ' +import hashlib,json,sys +items=sorted((i["metadata"]["name"],i["metadata"]["uid"],i["metadata"]["resourceVersion"]) for i in json.load(sys.stdin)["items"]) +print(len(items), hashlib.sha256(json.dumps(items).encode()).hexdigest())' +} +journal_digest() { + runtime cat /var/lib/fleet-local/journal.json | python3 -c ' +import hashlib,sys +print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' +} +wait_running_pod() { + for _ in $(seq 1 "${2:-120}"); do + uid=$(py running-pod "$state" "$1") + [[ -z $uid ]] || { printf '%s\n' "$uid"; return; } + sleep 1 + done + echo "no single running worker Pod for $1" >&2; return 1 +} + +case "$step" in + verify-contention) + # Independently read public status: one Bound winner, one Pending loser. + a=$(k "$state/consumer-a/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].reason}') + b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].reason}') + [[ $a == Bound/* && $b == Pending/InsufficientCapacity ]] || { echo "unexpected contention status: A=$a B=$b" >&2; exit 1; } + printf 'contention: consumer-a %s; consumer-b %s\n' "$a" "$b" + ;; + await-delivery) + for _ in $(seq 1 120); do + names=$(cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].metadata.name}') + [[ -z $names ]] || break + sleep 1 + done + [[ -n $names ]] || { echo 'Karmada did not deliver retained intent' >&2; exit 1; } + [[ $(wc -w <<<"$names") -eq 1 ]] || { echo 'more than one delivered handoff' >&2; exit 1; } + printf '%s\n' "$names" > "$state/install-handoff" + [[ -z $(local_phase) ]] || { echo 'cell status existed before any worker started' >&2; exit 1; } + site wait --for=jsonpath='{.status.deliveredHandoffs}'=1 handoffdispatcher/dispatcher --timeout=120s >/dev/null + [[ -z $(site get jobs -o name) ]] || { echo 'worker Job exists before dispatch' >&2; exit 1; } + printf 'delivery: Karmada delivered exactly one retained handoff; kro observed it; no worker Job before dispatch\n' + ;; + partition) + # Consumer A's API is Flux-managed: suspend its Kustomization, then stop it. + suspend milo-consumer-a true + platform -n milo-consumer-a scale deployment/milo-apiserver --replicas=0 >/dev/null + platform -n milo-consumer-a wait --for=delete pod -l app.kubernetes.io/name=milo-apiserver --timeout=120s >/dev/null + python3 hack/multiplane/fault_guard.py record "$state" platform-admin.yaml kustomization milo-consumer-a milo-consumer-a milo-apiserver flux-partition + docker pause "$prefix-hub-control-plane" >/dev/null + printf 'partition: consumer-a API stopped (its Flux Kustomization suspended) and hub paused before any worker Job exists\n' + ;; + dispatch) + # Dispatch is a source revision, reconciled by the cell's own Flux from the + # registry while the hub is paused; kro then creates per-operation RBAC and the Job. + flux publish "$state" --revision 3 --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 >/dev/null + [[ $(site get handoffdispatcher dispatcher -o jsonpath='{.spec.dispatch}') == true ]] || { echo 'dispatch revision not applied' >&2; exit 1; } + name=$(cat "$state/install-handoff") + for _ in $(seq 1 120); do site get job "w-$name" >/dev/null 2>&1 && break; sleep 1; done + py job "$state" "$name" > "$state/k8s-dispatch-job.json" + printf 'dispatch: cell Flux applied the dispatch revision; kro created the worker Job and per-operation RBAC from the delivered handoff with no hub access\n' + ;; + worker-rbac) + name=$(cat "$state/install-handoff") + site create token "w-$name" --duration=10m > "$state/worker.token" + py worker-rbac "$state" "$name" + rm -f "$state/worker-kubeconfig.json" + ;; + interrupt-pod) + name=$(cat "$state/install-handoff") + "${harness[@]}" wait-stage --state "$state" --stage installer-started --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" + before=$(wait_running_pod "$name" 30) + py job "$state" "$name" > "$state/interrupt-job-before-pod.json" + # Abrupt Pod loss with no grace period. The guest runs under the runtime Pod, + # so the in-flight installer continues; only its worker process is lost. + site delete pod -l "fleet.datumapis.com/handoff=$name" --grace-period=0 --force >/dev/null 2>&1 + [[ -z $(local_phase) ]] || { echo 'local result published for an interrupted operation' >&2; exit 1; } + after= + for _ in $(seq 1 180); do + after=$(py live-pod "$state" "$name") + [[ -z $after || $after == "$before" ]] || break + sleep 1 + done + [[ -n $after && $after != "$before" ]] || { echo 'no replacement worker Pod' >&2; exit 1; } + py job "$state" "$name" > "$state/interrupt-job-after-pod.json" + "${harness[@]}" journal --state "$state" > "$state/interrupt-after.json" + py record-pod-interrupt "$state" "$before" "$after" + printf 'interrupt-pod: worker Pod force-deleted while installer-started with its domain running; Job controller replaced it; no local result\n' + ;; + interrupt-job) + name=$(cat "$state/install-handoff") + old_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}') + # The whole emulated install takes about a minute: delete the Job as soon as + # its replacement worker exists, while the operation is still unfinished. + py live-pod "$state" "$name" > "$state/interrupt-job-pod-before" + [[ -s $state/interrupt-job-pod-before ]] || { echo 'no live worker Pod to interrupt' >&2; exit 1; } + "${harness[@]}" journal --state "$state" > "$state/interrupt-job-before.json" + site delete job "w-$name" --wait=false >/dev/null + new_job= + for _ in $(seq 1 120); do + new_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}' 2>/dev/null || true) + [[ -z $new_job || $new_job == "$old_job" ]] || break + sleep 1 + done + [[ -n $new_job && $new_job != "$old_job" ]] || { echo 'kro did not recreate the deleted Job' >&2; exit 1; } + pod= + for _ in $(seq 1 240); do pod=$(py job-pod "$state" "$name" "$new_job"); [[ -z $pod ]] || break; sleep 1; done + [[ -n $pod ]] || { echo 'recreated Job created no worker Pod' >&2; exit 1; } + "${harness[@]}" journal --state "$state" > "$state/interrupt-job-after.json" + py record-job-interrupt "$state" "$old_job" "$new_job" "$(cat "$state/interrupt-job-pod-before")" "$pod" + printf 'interrupt-job: running worker Job deleted mid-install; kro recreated it under a new UID for the same operation\n' + ;; + resume) + name=$(cat "$state/install-handoff") + site wait --for=condition=Complete "job/w-$name" --timeout=20m >/dev/null + cell -n "$ns" wait --for=jsonpath='{.status.observation.result.phase}'=Succeeded machineallocationhandoff "$name" --timeout=5m >/dev/null + "${harness[@]}" journal --state "$state" > "$state/resume-after.json" + py record-resume "$state" "$name" + printf 'resume: replacement worker completed the exact interrupted operation; one install operation; observer published from the journal\n' + ;; + partition-readiness) + # The platform's root sync must apply r3 (pushed during the partition) with + # consumer A still suspended, and the suspension must survive it unchanged. + flux wait "$state" --cluster platform --timeout 300 >/dev/null + rev=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))[-1]["fluxRevision"])' "$state/flux-revisions.json") + python3 hack/multiplane/fault_guard.py check "$state" platform-admin.yaml kustomization milo-consumer-a milo-consumer-a milo-apiserver flux-partition "$rev" + # Resuming hands ownership back: Flux, not the harness, restores replicas. + suspend milo-consumer-a false + platform -n flux-system annotate --overwrite kustomization/milo-consumer-a "reconcile.fluxcd.io/requestedAt=$(date +%s)" >/dev/null + platform -n milo-consumer-a wait --for=jsonpath='{.status.availableReplicas}'=1 deployment/milo-apiserver --timeout=240s >/dev/null + wait_api "$state/consumer-a/bootstrap.json" + ready=$(k "$state/consumer-a/management-project.json" -n default get machine allocation -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}') + [[ $ready == False ]] || { echo 'Public readiness advanced during partition' >&2; exit 1; } + name=$(cat "$state/install-handoff") + [[ $(site get job "w-$name" -o jsonpath='{.status.conditions[?(@.type=="Complete")].status}') == True ]] || { echo 'install Job not Complete' >&2; exit 1; } + printf 'PXE succeeded cell-locally and the worker Job is Complete while hub/consumer disconnected; public Ready stayed False; Flux restored consumer-a\n' + ;; + heal) + docker unpause "$prefix-hub-control-plane" >/dev/null + docker restart --timeout 30 "$prefix-hub-control-plane" >/dev/null + docker restart --timeout 30 "$prefix-cell-control-plane" >/dev/null + wait_api "$state/host.yaml" + wait_api "$state/cell-admin.yaml" + k "$state/host.yaml" -n karmada-system wait --for=condition=Available deployment --all --timeout=300s >/dev/null + # The cell node restart recreated every site Pod; the Flux-owned Deployments + # and the retained volume must bring the site back with the same journal. + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null; done + cell -n kro-system wait --for=condition=Available deployment --all --timeout=300s >/dev/null + # Restarted Flux on both nodes; the hub catches up with the dispatch revision. + flux wait "$state" --cluster hub --cluster cell --cluster platform --timeout 600 >/dev/null + printf 'heal: hub and cell APIs restarted; Karmada, kro and site Deployments available; Flux on every cluster Ready at the current revision\n' + ;; + lifecycle) + # Pod and Job lifecycle are not effects: recreating site Pods or a completed + # Job must not change the journal, start a guest, or release capacity. + name=$(cat "$state/install-handoff") + py lifecycle-snapshot "$state" "$name" > "$state/lifecycle-before.json" + started=$(date -u +%Y-%m-%dT%H:%M:%SZ) + old_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}') + site delete pod -l app.kubernetes.io/name=fleet-site-runtime --wait=true >/dev/null + site delete pod -l app.kubernetes.io/name=fleet-site-boot --wait=true >/dev/null + site delete pod -l app.kubernetes.io/name=fleet-site-observer --wait=true >/dev/null + site delete job "w-$name" --wait=true >/dev/null + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do + site rollout status "deployment/$d" --timeout=300s >/dev/null + site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null + done + for _ in $(seq 1 120); do + new_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}' 2>/dev/null || true) + [[ -z $new_job || $new_job == "$old_job" ]] || break + sleep 1 + done + [[ -n $new_job && $new_job != "$old_job" ]] || { echo 'kro did not recreate the completed Job' >&2; exit 1; } + site wait --for=condition=Complete "job/w-$name" --timeout=300s >/dev/null + # The restarted observer must republish from the unchanged journal. + for _ in $(seq 1 60); do + at=$(cell -n "$ns" get machineallocationhandoff "$name" -o jsonpath='{.status.observation.observedAt}') + [[ $at > $started ]] && break + sleep 2 + done + [[ $at > $started ]] || { echo 'observer did not republish after restart' >&2; exit 1; } + py lifecycle-snapshot "$state" "$name" > "$state/lifecycle-after.json" + py record-lifecycle "$state" "$old_job" "$new_job" + printf 'lifecycle: runtime, boot and observer Pods and the completed Job recreated; journal, guest starts and volume unchanged; capacity still occupied\n' + ;; + delivery-faults) + # Cell-local delivery faults injected with cell bootstrap credentials: a + # duplicate under another name, a wrong-cell intent, and a stale-epoch replay. + before=$(journal_digest) + py delivery-faults "$state" create + for fault in duplicate wrong-cell stale-epoch; do + job=$(cat "$state/fault-$fault-job") + for _ in $(seq 1 120); do site get job "$job" >/dev/null 2>&1 && break; sleep 1; done + site wait --for=condition=Failed "job/$job" --timeout=300s >/dev/null + done + after=$(journal_digest) + [[ $before == "$after" ]] || { echo 'provider journal changed during delivery faults' >&2; exit 1; } + py delivery-faults "$state" verify + py delivery-faults "$state" delete + printf 'delivery-faults: duplicate, wrong-cell and stale-epoch deliveries failed their Jobs by podFailurePolicy before effects; journal unchanged; kro pruned them\n' + ;; + release-status-a|release-status-b) + # Released claims must not keep public readiness or an installation reference. + project=consumer-a; [[ $step == release-status-a ]] || project=consumer-b + v=$(k "$state/$project/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}/{.status.conditions[?(@.type=="Ready")].status}/{.status.currentInstallationRef.name}/{.metadata.finalizers}') + [[ $v == Released/False/False// ]] || { echo "released $project Machine phase/Bound/Ready/currentInstallationRef/finalizers: $v" >&2; exit 1; } + if [[ $step == release-status-a ]]; then + # The referenced Installation is retired through the real Milo API status subresource. + i=$(k "$state/$project/management-project.json" -n default get installation debian-pxe -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Ready")].status}') + [[ $i == Released/False ]] || { echo "released $project Installation phase/Ready: $i" >&2; exit 1; } + fi + printf '%s: %s Machine Released, Bound False, Ready False, no current installation, no finalizer%s\n' "$step" "$project" "$([[ $step == release-status-a ]] && echo '; Installation Released, Ready False')" + ;; + reuse-status) + b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}') + [[ $b == Bound/True ]] || { echo "reused consumer-b status: $b" >&2; exit 1; } + printf 'reuse-status: consumer-b Bound after verified cleanup\n' + ;; + wrong-location) + # Runs after both verified cleanups, so capacity is free: denial cannot be + # explained by contention. The customer recreates its request elsewhere. + before_custody=$(custody_digest); before_journal=$(journal_digest) + customer="$state/consumer-a/customer-project.json" + k "$customer" -n default delete machine allocation --wait --timeout=60s >/dev/null + k "$customer" -n default create -f - >/dev/null <<'JSON' +{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"remote-elsewhere"},"powerState":"Off"}} +JSON + set +e + "$host" allocate --config "$state/acceptance.json" > "$state/wrong-location.out" 2> "$state/wrong-location.err" + code=$? + set -e + [[ $code -ne 0 ]] || { echo 'wrong-location Machine was allocated' >&2; exit 1; } + grep -q 'not served by the configured cell' "$state/wrong-location.err" || { echo "allocation failed for another reason: $(tail -c 300 "$state/wrong-location.err")" >&2; exit 1; } + after_custody=$(custody_digest); after_journal=$(journal_digest) + [[ $before_custody == "$after_custody" ]] || { echo 'private custody changed during wrong-location attempt' >&2; exit 1; } + [[ $before_journal == "$after_journal" ]] || { echo 'provider journal changed during wrong-location attempt' >&2; exit 1; } + k "$state/consumer-a/management-project.json" -n default get machine allocation -o json > "$state/wrong-location-machine.json" + python3 - "$state" "$code" "$before_custody" <<'PY' +import json,sys,pathlib,datetime +m=json.loads((pathlib.Path(sys.argv[1])/'wrong-location-machine.json').read_text()) +if m['metadata'].get('finalizers') or m.get('status'): raise SystemExit('wrong-location Machine gained finalizers or status') +record={'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'requestedLocation':m['spec']['locationRef']['name'],'servedLocation':'local', + 'capacityFree':True,'exitCode':int(sys.argv[2]),'error':'ErrLocationNotServed','privateCustodyUnchanged':True,'privateCustodyRecords':int(sys.argv[3].split()[0]), + 'providerJournalUnchanged':True,'machineFinalizers':[],'machineStatus':None} +(pathlib.Path(sys.argv[1])/'evidence'/'wrong-location.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') +PY + printf 'wrong-location: denied before allocation with free capacity; private custody and provider journal unchanged\n' + ;; + boot-denials) + # Probe the boot Service from the runtime Pod: the same path firmware uses. + # The origin comes from the Flux-owned Service, which drift repair recreated. + origin="http://$(site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}'):8080" + [[ $origin == "$(site get handoffdispatcher dispatcher -o jsonpath='{.status.bootOrigin}')" ]] || { echo 'dispatcher boot origin differs from the boot Service' >&2; exit 1; } + runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + grep -q '^PASS ' "$state/boot-denials.txt" || { echo 'closed-boot probe failed' >&2; exit 1; } + printf 'boot-denials: %s through the boot Service\n' "$(cat "$state/boot-denials.txt")" + ;; + flux-final) + # Every cluster converged on the last revision with nothing suspended. + flux wait "$state" --cluster platform --cluster hub --cluster cell --timeout 600 >/dev/null + python3 - "$state" <<'PY' +import json, pathlib, subprocess, sys +s = pathlib.Path(sys.argv[1]) +for c, cfg in (('platform', 'platform-admin.yaml'), ('hub', 'host.yaml'), ('cell', 'cell-admin.yaml')): + items = json.loads(subprocess.check_output(['kubectl', '--kubeconfig', str(s / cfg), 'get', 'kustomizations,helmreleases', '-A', '-o', 'json']))['items'] + held = [i['metadata']['name'] for i in items if i['spec'].get('suspend')] + if held: + raise SystemExit('%s still suspended: %s' % (c, held)) +PY + flux record "$state" --cluster platform --cluster hub --cluster cell --name final >/dev/null + flux ownership "$state" --name final >/dev/null + printf 'flux-final: platform, hub and cell Ready at the final revision with nothing suspended; one writer per site object\n' + ;; + *) echo "unknown step: $step" >&2; exit 64 ;; +esac diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh new file mode 100755 index 00000000..f0fe3677 --- /dev/null +++ b/hack/multiplane/stop.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Stop only this run's exact containers. Preserve volumes and Unknown custody. +set -euo pipefail +state=${1:?private run state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || exit 1 +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +# The cell node holds the site runtime, journal volume, kro and worker Jobs; the +# platform node holds the Milo APIs and their etcd volumes; the registry holds +# the source revisions. Earlier-layout container names are kept for old runs. +for suffix in vm consumer-a consumer-b provider consumer-a-etcd consumer-b-etcd provider-etcd cell-control-plane platform-control-plane registry; do + name="$prefix-$suffix" + if docker inspect "$name" >/dev/null 2>&1; then + if [[ $(docker inspect -f '{{.State.Paused}}' "$name") == true ]]; then docker unpause "$name" >/dev/null; fi + docker stop --timeout 30 "$name" >/dev/null + fi +done +if docker inspect "$prefix-hub-control-plane" >/dev/null 2>&1; then + if [[ $(docker inspect -f '{{.State.Running}}' "$prefix-hub-control-plane") == true ]]; then + if [[ $(docker inspect -f '{{.State.Paused}}' "$prefix-hub-control-plane") == true ]]; then docker unpause "$prefix-hub-control-plane" >/dev/null; fi + if [[ -f "$state/sysctl.json" ]]; then python3 hack/multiplane/sysctl.py "$state" restore; fi + docker stop --timeout 30 "$prefix-hub-control-plane" >/dev/null + else + echo 'Hub already stopped; inspect sysctl.json for prior restoration evidence.' + fi +fi +printf 'Stopped %s; disks, journals and custody retained. Stopping does not prove release.\n' "$prefix" diff --git a/hack/multiplane/sysctl.py b/hack/multiplane/sysctl.py new file mode 100755 index 00000000..2f2b3658 --- /dev/null +++ b/hack/multiplane/sysctl.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Reversible, explicitly opted-in inotify adjustment in the task Colima VM.""" +import json,os,pathlib,subprocess,sys +s=pathlib.Path(sys.argv[1]);action=sys.argv[2];prefix=(s/'prefix').read_text().strip() +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +def run(*args):return subprocess.check_output(args,text=True).strip() +endpoint=run('docker','context','inspect','colima-fleet-acceptance-tcg','--format','{{.Endpoints.docker.Host}}') +if not endpoint.endswith('/.colima/fleet-acceptance-tcg/docker.sock'):raise SystemExit('unexpected Colima profile') +node=prefix+'-hub-control-plane';current=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) +if action=='set': + if (s/'sysctl.json').exists():raise SystemExit('sysctl evidence already exists; do not overwrite original value') + if current<1024 and os.environ.get('FLEET_MULTIPLANE_INOTIFY')!='1024':raise SystemExit('Requires fs.inotify.max_user_instances>=1024. Opt into reversible task-VM adjustment with FLEET_MULTIPLANE_INOTIFY=1024') + record={'context':'colima-fleet-acceptance-tcg','setting':'fs.inotify.max_user_instances','original':current,'effective':max(current,1024)} + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if current<1024:run('docker','exec',node,'sysctl','-w','fs.inotify.max_user_instances=1024') + record['observedEffective']=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if record['observedEffective']!=record['effective']:raise SystemExit('inotify adjustment readback mismatch; inspect sysctl.json') +elif action=='restore': + record=json.loads((s/'sysctl.json').read_text()) + record.pop('restored',None);record.pop('restoreSkipped',None) + if current==record['effective'] and current!=record['original']: + run('docker','exec',node,'sysctl','-w','fs.inotify.max_user_instances='+str(record['original']));record['restored']=True + elif current!=record['effective']:record['restoreSkipped']='value changed by another owner' + else:record['restored']=True + record['observedAfterRestore']=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if record.get('restored') and record['observedAfterRestore']!=record['original']:raise SystemExit('inotify restoration readback mismatch; inspect sysctl.json') +else:raise SystemExit('expected set or restore') +print(json.dumps(record)) diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh new file mode 100755 index 00000000..299898a5 --- /dev/null +++ b/hack/multiplane/teardown.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Delete only this run's exact containers, kind clusters and provider image tag. +# Default: only after evidence/summary.json records passed acceptance (verified +# cleanup and release), then remove private credentials and keep evidence. +# --discard-unknown is an explicit human decision to abandon an Unknown run; it +# deletes the same exact resources, keeps all private state, and never claims release. +set -euo pipefail +cd "$(dirname "$0")/../.." +umask 077 +state=${1:?private run state directory required} +mode=${2:-passed} +[[ $mode == passed || $mode == --discard-unknown ]] || { echo 'usage: teardown.sh STATE [--discard-unknown]' >&2; exit 64; } +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo 'unexpected prefix' >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +if [[ $mode == passed ]]; then + python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="passed")' "$state/evidence/summary.json" 2>/dev/null || { + echo 'No passed acceptance summary; refusing teardown. Use --discard-unknown only after inspection.' >&2; exit 1; } +fi +hub="$prefix-hub-control-plane" +if docker inspect "$hub" >/dev/null 2>&1; then + [[ $(docker inspect -f '{{.State.Paused}}' "$hub") != true ]] || docker unpause "$hub" >/dev/null + if [[ $(docker inspect -f '{{.State.Running}}' "$hub") == true && -f $state/sysctl.json ]] && ! grep -q '"restored": true' "$state/sysctl.json"; then + python3 hack/multiplane/sysctl.py "$state" restore + fi +fi +for cluster in hub cell platform; do + if docker inspect "$prefix-$cluster-control-plane" >/dev/null 2>&1; then + # A private throwaway kubeconfig keeps kind from editing any user kubeconfig. + kind delete cluster --name "$prefix-$cluster" --kubeconfig "$state/kind-delete.kubeconfig" + fi +done +for suffix in registry vm consumer-a consumer-b provider consumer-a-etcd consumer-b-etcd provider-etcd; do + if docker inspect "$prefix-$suffix" >/dev/null 2>&1; then docker rm -f -v "$prefix-$suffix" >/dev/null; fi +done +image_tag_removed=true +pushed=() +if [[ -f $state/gitops-environment.json ]]; then + port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") + pushed=("127.0.0.1:$port/fleet-site:$prefix") +fi +for image in "$prefix-site-image" "$prefix-provider-image" ${pushed[@]+"${pushed[@]}"}; do + docker image rm "$image" >/dev/null 2>&1 || true + if docker image inspect "$image" >/dev/null 2>&1; then image_tag_removed=false; fi +done +remaining=$(docker ps -a --filter "name=^$prefix-" --format '{{.Names}}') +[[ -z $remaining ]] || { echo "owned containers remain: $remaining" >&2; exit 1; } +rm -f "$state/kind-delete.kubeconfig" +if [[ $mode == passed ]]; then + # Credentials and raw journals are no longer needed once the run has passed. + rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" + rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/private.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ + "$state"/status-fault.json "$state"/acceptance.json "$state"/fleet-multiplane "$state"/fleet-multiplane-host + rm -rf "$state/site-bin" "$state/kro-chart" "$state/flux-tools/flux" "$state"/flux-tools/*.tar.gz +fi +[[ ! -f $state/sysctl.json ]] || cp "$state/sysctl.json" "$state/evidence/sysctl.json" +python3 - "$state" "$prefix" "$mode" "$image_tag_removed" <<'PY' +import datetime,json,pathlib,sys +s,prefix,mode=pathlib.Path(sys.argv[1]),sys.argv[2],sys.argv[3] +record={'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'prefix':prefix,'deleted':'exact prefix containers (including the run registry) and platform, hub and cell kind clusters', 'providerImageTagRemoved':sys.argv[4]=='true', 'volumesVerifiedAbsent':False, + 'mode':'after passed acceptance' if mode=='passed' else 'discarded Unknown run by explicit request; not release evidence', + 'privateCredentialsRemoved':mode=='passed','remainingContainers':[]} +(s/'evidence'/'teardown.json').write_text(json.dumps(record,indent=2)+'\n') +PY +printf 'teardown: removed %s resources (%s)\n' "$prefix" "$mode" diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py new file mode 100644 index 00000000..c9fcd115 --- /dev/null +++ b/hack/multiplane/test-flux.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Offline tests for hack/multiplane/flux.py: source staging, push records and +reconcile waits, with fake flux and kubectl executables. Needs kustomize.""" +import argparse +import importlib.util +import json +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]).resolve() +spec = importlib.util.spec_from_file_location('flux', root / 'hack/multiplane/flux.py') +flux = importlib.util.module_from_spec(spec) +sys.path.insert(0, str(root / 'hack/multiplane')) +spec.loader.exec_module(flux) +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +def expect_exit(name, fn, code): + try: + fn() + except SystemExit as e: + check(name, e.code == code, 'exit %s' % e.code) + return + check(name, False, 'no exit') + + +FAKE_KUBECTL = r'''#!/usr/bin/env python3 +import json, os, sys +a = sys.argv[1:] +open(os.environ['FAKE_TRACE'], 'a').write(json.dumps(a) + '\n') +rev = os.environ.get('FAKE_REVISION', '') +ready = os.environ.get('FAKE_READY', 'True') +if 'annotate' in a: sys.exit(0) +def requested(name): + calls = [json.loads(l) for l in open(os.environ['FAKE_TRACE'])] + matches = [c[-1].split('=', 1)[1] for c in calls if 'annotate' in c and name in c] + # FAKE_STRIP: a parent apply removed the first request before it was handled. + if name == os.environ.get('FAKE_STRIP') and len(matches) < 2: return None + return matches[-1] if matches else None +def handled(name): + if os.environ.get('FAKE_STALE') == '1': return 'old-request' + return requested(name) +def meta(name, **kw): + r = requested(name) + return dict(kw, name=name, annotations={'reconcile.fluxcd.io/requestedAt': r} if r else {}) +if 'ocirepositories.source.toolkit.fluxcd.io' in a and 'fleet-gitops' in a: + print(json.dumps({'metadata': meta('fleet-gitops', generation=1), 'status': {'observedGeneration': 1, 'conditions': [{'type': 'Ready', 'status': ready}], 'lastHandledReconcileAt': handled('fleet-gitops'), 'artifact': {'revision': rev}}})); sys.exit(0) +if 'kustomizations.kustomize.toolkit.fluxcd.io' in a: + names = ['flux-system/fleet-cluster', 'flux-system/fleet-coordination', 'flux-system/fleet-federation', 'flux-system/kro', + 'flux-system/fleet-site-base', 'flux-system/fleet-site-graph', 'flux-system/fleet-site-services', 'flux-system/fleet-site-dispatch'] + items = [{'metadata': meta(n.split('/')[1], namespace=n.split('/')[0], generation=2), 'spec': {}, + 'status': {'lastHandledReconcileAt': handled(n.split('/')[1]), 'observedGeneration': 2, 'lastAppliedRevision': rev, 'conditions': [{'type': 'Ready', 'status': ready, 'reason': 'ReconciliationSucceeded'}]}} + for n in names] + print(json.dumps({'items': items})); sys.exit(0) +sys.exit(1) +''' +FAKE_FLUX = r'''#!/usr/bin/env python3 +import json, os, sys +open(os.environ['FAKE_TRACE'], 'a').write(json.dumps(['flux'] + sys.argv[1:]) + '\n') +print(json.dumps({'repository': 'x', 'digest': 'sha256:' + 'd' * 64})) +''' + +if not shutil.which('kustomize'): + print('FAIL flux tests: kustomize is required') + sys.exit(1) +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bin_dir = tmp / 'bin' + bin_dir.mkdir() + (bin_dir / 'kubectl').write_text(FAKE_KUBECTL.replace('#!/usr/bin/env python3', '#!' + sys.executable)) + (bin_dir / 'kubectl').chmod(0o755) + trace = tmp / 'trace' + os.environ.update(PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_TRACE=str(trace)) + s = tmp / 'state' + (s / 'flux-tools').mkdir(parents=True) + (s / 'evidence').mkdir() + (s / 'prefix').write_text('fleet-mp-0000abcd\n') + # A tiny stand-in for the release install.yaml, accepted by overriding its pin. + fake_install = 'apiVersion: v1\nkind: Namespace\nmetadata: {name: flux-system}\n' + for name in ('source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller', 'image-automation-controller', + 'image-reflector-controller', 'source-watcher'): + fake_install += '---\napiVersion: apps/v1\nkind: Deployment\nmetadata: {name: %s, namespace: flux-system}\nspec:\n template:\n spec:\n containers:\n - {name: manager, image: ghcr.io/fluxcd/%s:v0, args: []}\n' % (name, name) + fake_install += '---\napiVersion: v1\nkind: Service\nmetadata: {name: source-watcher, namespace: flux-system}\n' + (s / 'flux-tools' / 'install.yaml').write_text(fake_install) + flux.INSTALL_SHA256 = flux.sha256(s / 'flux-tools' / 'install.yaml') + (s / 'flux-tools' / 'flux').write_text(FAKE_FLUX.replace('#!/usr/bin/env python3', '#!' + sys.executable)) + (s / 'flux-tools' / 'flux').chmod(0o755) + env = {'registryHost': 'fleet-mp-0000abcd-registry', 'registryPort': 5555, 'karmadaPort': 1, 'cell': 'fleet-mp-0000abcd-cell', + 'cellEndpoint': 'https://fleet-mp-0000abcd-cell-control-plane:6443', 'siteImage': 'fleet-mp-0000abcd-registry:5000/fleet-site@sha256:' + 'a' * 64, + 'siteImageDigest': 'sha256:' + 'a' * 64} + (s / 'gitops-environment.json').write_text(json.dumps(env)) + (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') + + def ns(**kw): + base = dict(state=str(s), root=str(root), revision=1, site='absent', bad_kro_chart=False, drop_site_volume=False, purpose='test', cluster=[], timeout=5) + base.update(kw) + return argparse.Namespace(**base) + + def render(rev, cluster): + out = subprocess.run(['kustomize', 'build', str(s / 'gitops' / ('r%d' % rev) / 'environment' / cluster)], text=True, capture_output=True, check=True).stdout + return out + + check('stage platform revision', flux.stage(ns(revision=1)) == 0) + cell1 = render(1, 'cell') + check('r1 has no site layers', 'name: fleet-site-services' not in cell1 and 'name: fleet-site-dispatch' not in cell1 and 'name: fleet-site-base' in cell1) + check('sync source is the run registry', 'url: oci://fleet-mp-0000abcd-registry:5000/fleet-gitops' in cell1 and 'tag: local' in cell1) + check('controllers pinned by digest', 'ghcr.io/fluxcd/source-controller@sha256:' in cell1) + check('unused controllers removed', 'image-automation-controller' not in cell1 and 'source-watcher' not in cell1) + hub1 = render(1, 'hub') + check('hub environment beside the Karmada kubeconfig', 'name: fleet-environment\n namespace: karmada-system' in hub1 and 'name: fleet-environment\n namespace: flux-system' in hub1) + check('stage dispatch revision', flux.stage(ns(revision=3, site='dispatch')) == 0) + cell3 = render(3, 'cell') + check('dispatch revision carries the site', 'FLEET_SITE_DISPATCH: "true"' in cell3 and 'path: ./config/site/instance' in cell3 and 'FLEET_SCOPED_ASSET' in cell3 + and 'path: ./config/site/services' in cell3 and ('FLEET_BOOT_SERVICE_IP: %s\n' % flux.BOOT_SERVICE_IP) in cell3.replace('"', '')) + # Flux replaces an undefined variable with an empty string, which would give + # the boot Service a random ClusterIP: every substituted variable must be defined. + import re + env_keys = set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell3, re.M)) + used = set() + for layer in ('config/site/services', 'config/site/instance'): + for f in (root / layer).glob('*.yaml'): + used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) + check('substituted variables defined', used and used <= env_keys, str(sorted(used - env_keys))) + check('graph uses no Flux variables', not re.findall(r'\$\{FLEET_', (root / 'config/site/graph/rgd.yaml').read_text())) + check('stage off revision', flux.stage(ns(revision=2, site='off')) == 0 and 'FLEET_SITE_DISPATCH: "false"' in render(2, 'cell')) + flux.stage(ns(revision=4, site='dispatch', bad_kro_chart=True)) + check('bad chart revision patches only kro', flux.MISSING_DIGEST in render(4, 'cell') and flux.KRO_CHART_DIGEST not in render(4, 'cell')) + flux.stage(ns(revision=6, site='dispatch', drop_site_volume=True)) + check('volume removal revision', '$patch: delete' in render(6, 'cell') and 'fleet-site-state' in render(6, 'cell')) + sums = (s / 'gitops' / 'r3.SHA256SUMS').read_text() + check('content sums cover checkout config', 'config/site/graph/rgd.yaml' in sums and 'environment/cell/environment.yaml' in sums) + check('no credentials or Secrets staged', 'kind: Secret' not in cell3 + hub1) + + # A retained credential anywhere in the source refuses the revision. + (s / 'provider').mkdir() + secret = 'z' * 64 + (s / 'provider' / 'tokens.csv').write_text(secret + ',bootstrap,bootstrap,system:masters\n') + leaky = tmp / 'leaky' + shutil.copytree(root / 'config', leaky / 'config') + (leaky / 'config/site/instance/leak.yaml').write_text('# ' + secret + '\n') + expect_exit('stage refuses a retained token', lambda: flux.stage(ns(revision=9, root=str(leaky))), 1) + (leaky / 'config/site/instance/leak.yaml').write_text('apiVersion: v1\nkind: Secret\nmetadata: {name: x}\n') + expect_exit('stage refuses a Secret manifest', lambda: flux.stage(ns(revision=9, root=str(leaky))), 1) + os.environ['FLUX_FAKE'] = '1' + tampered = s / 'flux-tools' / 'install.yaml' + tampered.write_text(fake_install + '# changed\n') + expect_exit('stage refuses a changed install manifest', lambda: flux.stage(ns(revision=9)), 1) + tampered.write_text(fake_install) + + # Push records the digest, revision and checkout identity. + check('push', flux.push(ns(revision=3)) == 0) + rec = flux.current(s) + check('push record', rec['digest'] == 'sha256:' + 'd' * 64 and rec['fluxRevision'] == 'local@sha256:' + 'd' * 64 and rec['checkoutDirty'] is True) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + pushc = next(c for c in calls if c[:3] == ['flux', 'push', 'artifact']) + check('push is reproducible and insecure-local only', '--reproducible' in pushc and '--insecure-registry' in pushc and 'oci://127.0.0.1:5555/fleet-gitops:local' in pushc) + + # Waits require Ready, the current generation and the pushed revision. + (s / 'cell-admin.yaml').write_text('') + os.environ['FAKE_REVISION'] = rec['fluxRevision'] + os.environ['FAKE_READY'] = 'True' + check('wait converged', isinstance(flux.wait_cluster(s, 'cell', 10), dict)) + check('wait requested a source reconcile', any('annotate' in c and 'flux-system/fleet-gitops'.split('/')[1] in c for c in + [json.loads(l) for l in trace.read_text().splitlines()])) + trace.write_text('') + os.environ['FAKE_STRIP'] = 'fleet-cluster' + stripped = flux.wait_cluster(s, 'cell', 20) + receipts = json.loads((s / 'evidence' / 'flux-reconciles.json').read_text()) + check('stripped request reissued and acknowledged', stripped['flux-system/fleet-cluster']['lastHandledReconcileAt'] == stripped['flux-system/fleet-cluster']['requestedAt'] + and receipts[-1]['lostRequestsReissued'] == {'flux-system/fleet-cluster': 1}, json.dumps(receipts[-1].get('lostRequestsReissued'))) + os.environ.pop('FAKE_STRIP') + os.environ['FAKE_STALE'] = '1' + expect_exit('Ready old status cannot satisfy new reconcile', lambda: flux.wait_cluster(s, 'cell', 4), 4) + os.environ.pop('FAKE_STALE') + os.environ['FAKE_READY'] = 'False' + expect_exit('wait not Ready times out', lambda: flux.wait_cluster(s, 'cell', 4), 4) + os.environ['FAKE_READY'] = 'True' + os.environ['FAKE_REVISION'] = 'local@sha256:' + 'e' * 64 + expect_exit('wait on another revision times out', lambda: flux.wait_cluster(s, 'cell', 4), 4) + check('wait at an explicit revision', isinstance(flux.wait_cluster(s, 'cell', 10, revision='local@sha256:' + 'e' * 64), dict)) + +# Fault guards reject root reconciliation undoing suspension or changing generation. +import fault_guard +obj = {'metadata': {'uid': 'same', 'generation': 2}, 'spec': {'suspend': True}} +dep = {'spec': {'replicas': 0}} +pods = {'items': []} +receipt = fault_guard.validate(obj, dep, pods) +check('fault guard retains identity', fault_guard.validate(obj, dep, pods, receipt) == receipt) +for changed in ( + {'metadata': {'uid': 'same', 'generation': 3}, 'spec': {'suspend': True}}, + {'metadata': {'uid': 'same', 'generation': 2}, 'spec': {'suspend': False}}, +): + try: + fault_guard.validate(changed, dep, pods, receipt) + check('fault guard rejects drift', False) + except ValueError: + pass +try: + fault_guard.validate(obj, dep, {'items': [{}]}, receipt) + check('fault guard rejects live Pods', False) +except ValueError: + pass + +root = {'metadata': {'generation': 4}, 'status': {'observedGeneration': 4, 'lastAppliedRevision': 'local@sha256:r3', + 'lastHandledReconcileAt': 't3', 'conditions': [{'type': 'Ready', 'status': 'True'}]}} +check('root receipt at the fault revision', fault_guard.root_receipt(root, 'local@sha256:r3')['lastHandledReconcileAt'] == 't3') +for bad in ({'lastAppliedRevision': 'local@sha256:r2'}, {'observedGeneration': 3}, {'conditions': [{'type': 'Ready', 'status': 'False'}]}): + stale = json.loads(json.dumps(root)) + stale['status'].update(bad) + try: + fault_guard.root_receipt(stale, 'local@sha256:r3') + check('root receipt rejects %s' % sorted(bad), False) + except ValueError: + pass + +# Ownership audit: one Flux layer per shared object, kro only for workers. +def world(**faults): + inv = {k: list(v) for k, v in flux.LAYER_INVENTORY.items()} + base_inv = [] + objects = {} + for (kind, ns, name), layer in flux.SHARED.items(): + objects[(kind, ns, name)] = {'metadata': {'name': name, 'uid': 'u-' + name, 'labels': {'kustomize.toolkit.fluxcd.io/name': layer}}} + if layer == 'fleet-site-base': + base_inv.append('%s_%s_x_%s' % (ns or '', name, kind)) + worker = 'w-op-' + 'a' * 40 + for kind, ns in flux.WORKER_KINDS: + objects[(kind, ns, worker)] = {'metadata': {'name': worker, 'uid': 'k-' + kind, 'labels': {'kro.run/node-id': kind, 'app.kubernetes.io/managed-by': 'kro'}}} + if faults.get('kro_deployment'): + objects[('deployments', 'fleet-site', 'fleet-site-boot')]['metadata']['labels']['kro.run/node-id'] = 'boot' + if faults.get('flux_job'): + objects[('jobs', 'fleet-site', worker)]['metadata']['labels']['kustomize.toolkit.fluxcd.io/name'] = 'fleet-site-services' + if faults.get('job_in_inventory'): + inv['flux-system/fleet-site-services'] = sorted(inv['flux-system/fleet-site-services'] + ['fleet-site_%s_batch_Job' % worker]) + if faults.get('kro_configmap'): + objects[('configmaps', 'fleet-site', 'kro-extra')] = {'metadata': {'name': 'kro-extra', 'uid': 'x', 'labels': {'kro.run/node-id': 'extra'}}} + if faults.get('pvc_in_services'): + inv['flux-system/fleet-site-services'] = sorted(inv['flux-system/fleet-site-services'] + ['fleet-site_fleet-site-state__PersistentVolumeClaim']) + if faults.get('missing_service'): + del objects[('services', 'fleet-site', 'fleet-site-boot')] + if faults.get('manual_job'): + objects[('jobs', 'fleet-site', 'manual')] = {'metadata': {'name': 'manual', 'uid': 'm', 'labels': {}}} + deps = {'flux-system/fleet-site-base': ['fleet-coordination'] + (['kro'] if faults.get('base_on_kro') else []), + 'flux-system/fleet-site-services': ['fleet-site-base'], 'flux-system/fleet-site-graph': ['kro', 'fleet-site-base'], + 'flux-system/fleet-site-dispatch': ['fleet-site-graph', 'fleet-site-services', 'fleet-federation']} + ks = {n: {'inventory': inv.get(n, base_inv if n == 'flux-system/fleet-site-base' else []), 'dependsOn': [{'name': d} for d in deps.get(n, [])]} + for n in list(flux.LAYER_INVENTORY) + ['flux-system/fleet-site-base']} + return objects, {'cell': {'kustomizations': ks}, 'hub': {'kustomizations': {}}, 'platform': {'kustomizations': {}}} + + +def audit(**faults): + objects, snaps = world(**faults) + + def fake_kubectl(state, cluster, *args, check=True, **kw): + a = [x for x in args if x not in ('-o', 'json')] + ns = a[1] if a[0] == '-n' else None + kind, name = a[-2], a[-1] + o = objects.get((kind, ns, name)) + return argparse.Namespace(returncode=0 if o else 1, stdout=json.dumps(o or {}), stderr='') + + def fake_kget(state, cluster, *args, **kw): + ns, kind = args[1], args[3] + return {'items': [o for (k, n, _), o in objects.items() if k == kind and n == ns]} + saved = flux.kubectl, flux.kget + flux.kubectl, flux.kget = fake_kubectl, fake_kget + try: + return flux.ownership('unused', snaps) + finally: + flux.kubectl, flux.kget = saved + + +record, problems = audit() +check('ownership audit passes a single-writer site', problems == [] and len(record['kroWrittenObjects']) == 4, str(problems)) +for fault in ('kro_deployment', 'flux_job', 'job_in_inventory', 'kro_configmap', 'pvc_in_services', 'missing_service', 'manual_job', 'base_on_kro'): + check('ownership audit rejects ' + fault, audit(**{fault: True})[1] != []) + +if failures: + print('FAIL flux tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS flux tests') diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh new file mode 100755 index 00000000..a2f5e561 --- /dev/null +++ b/hack/multiplane/test-harness.sh @@ -0,0 +1,273 @@ +#!/bin/sh +# Offline tests for the multi-plane acceptance harness. Uses fake docker, colima +# and go executables; never contacts a container runtime or cluster. +set -eu +root=$(CDPATH='' cd -- "$(dirname "$0")/../.." && pwd) +for f in "$root"/hack/multiplane/*.sh "$root"/hack/local-vm/run.sh; do bash -n "$f"; done +python3 -m py_compile "$root"/hack/multiplane/*.py +python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" +exec python3 - "$root" <<'PY' +import json, os, pathlib, re, stat, subprocess, sys, tempfile, time + +root = pathlib.Path(sys.argv[1]) +harness = root / 'hack/multiplane/harness.py' +failures = [] + +def check(name, condition, detail=''): + if not condition: + failures.append(name + (': ' + detail if detail else '')) + +FAKE = r'''#!/usr/bin/env python3 +import json, os, sys +tool = os.path.basename(sys.argv[0]); a = sys.argv[1:] +scenario = os.environ.get('FAKE', '') +with open(os.environ['FAKE_TRACE'], 'a') as t: t.write(json.dumps([tool] + a) + '\n') +if tool == 'docker': + if a[:2] == ['context', 'inspect']: + if scenario == 'no-context': sys.exit(1) + print('unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock'); sys.exit(0) + if a[:1] == ['info']: + print(json.dumps({'Architecture': 'aarch64', 'MemTotal': 8308948992, 'NCPU': 4})); sys.exit(0) + if a[:1] == ['ps']: + if '-a' in a: print('fleet-mp-0000aaaa-vm\texited'); sys.exit(0) + print('fleet-mp-1234abcd-vm' if scenario == 'busy' else 'unrelated'); sys.exit(0) + if a[:1] == ['run']: + print('x86_64'); sys.exit(0) +if tool == 'kubectl' and 'exec' in a and 'deploy/fleet-site-runtime' in a: + if 'journal.json' in a[-1]: + stage = os.environ.get('FAKE_STAGE', 'installer-started') + print(json.dumps({'fence': 'F' * 32, 'operations': {'op': {'request': {'id': 'install-op-1', 'kind': 'install', 'epoch': 1, 'fenceToken': 'T' * 32}, + 'stage': stage, 'bootToken': 'B' * 64, 'receipt': 'R' * 64, 'result': {'phase': 'Unknown'}, 'bootClosed': False}}})); sys.exit(0) + if 'virsh' in a: + import hashlib + print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:24]); sys.exit(0) +if tool == 'colima': + if 'df' in a[-1]: print('/dev/vdb1 41000000 20000000 %d 50%% /var/lib/docker' % (int(os.environ.get('FAKE_FREE_KB', '20000000')))) + elif 'inotify' in a[-1]: print(os.environ.get('FAKE_INOTIFY', '1024')) + sys.exit(0) +sys.exit(0) +''' + +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bin_dir = tmp / 'bin'; bin_dir.mkdir() + for tool in ('docker', 'colima', 'go', 'kind', 'kubectl', 'helm', 'openssl'): + p = bin_dir / tool; p.write_text(FAKE.replace('#!/usr/bin/env python3', '#!' + sys.executable)); p.chmod(0o755) + trace = tmp / 'trace' + base = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_TRACE=str(trace)) + base.pop('FLEET_MULTIPLANE_INOTIFY', None) + + def run(args, env=None, **kw): + return subprocess.run([sys.executable, str(harness), *args], text=True, capture_output=True, env=dict(base, **(env or {})), **kw) + + def state(): + d = pathlib.Path(tempfile.mkdtemp(dir=tmp)); d.chmod(0o700); return d + + good_root = tmp / 'good'; (good_root / 'cmd/fleet-multiplane').mkdir(parents=True) + markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] + (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed') + bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) + (bad_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers)) + + # Preflight: pass, prerequisite failures (exit 2) and readiness block (exit 3). + for name, env, rootdir, expected in ( + ('pass', {}, good_root, 0), + ('no-context', {'FAKE': 'no-context'}, good_root, 2), + ('concurrent-runtime', {'FAKE': 'busy'}, good_root, 2), + ('low-disk', {'FAKE_FREE_KB': '1000'}, good_root, 2), + ('inotify-without-opt-in', {'FAKE_INOTIFY': '128'}, good_root, 2), + ('missing-location-denial', {}, bad_root, 3)): + s = state() + r = run(['preflight', '--state', str(s), '--root', str(rootdir), '--skip-tests'], env) + check('preflight ' + name, r.returncode == expected, 'exit %s: %s' % (r.returncode, r.stdout[-400:])) + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check('preflight record ' + name, pre['status'] == {0: 'passed', 2: 'preflight-failed', 3: 'blocked'}[expected]) + s = state() + r = run(['preflight', '--state', str(s), '--root', str(good_root), '--skip-tests'], {'FAKE_INOTIFY': '128', 'FLEET_MULTIPLANE_INOTIFY': '1024'}) + check('preflight inotify opt-in', r.returncode == 0, r.stdout[-300:]) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('preflight never mutates runtime', not any(c[0] == 'docker' and c[1] in ('rm', 'stop', 'kill', 'network', 'volume', 'system') for c in calls)) + check('preflight never starts colima without --bootstrap', not any(c[0] == 'colima' and 'start' in c for c in calls)) + + # Bounded phases: pass, fail, blocked passthrough, timeout kills the process group. + s = state() + check('phase pass', run(['phase', '--state', str(s), '--name', 'ok', '--timeout', '30', '--', 'sh', '-c', 'echo marker-ok']).returncode == 0) + check('phase fail', run(['phase', '--state', str(s), '--name', 'bad', '--timeout', '30', '--', 'sh', '-c', 'echo secret-in-stderr >&2; exit 7']).returncode == 1) + check('phase blocked', run(['phase', '--state', str(s), '--name', 'blocked', '--timeout', '30', '--', 'sh', '-c', 'exit 3']).returncode == 3) + started = time.monotonic() + pidfile = s / 'child.pid' + r = run(['phase', '--state', str(s), '--name', 'slow', '--timeout', '2', '--', 'sh', '-c', 'sleep 300 & echo $! > "$0"; wait', str(pidfile)]) + check('phase timeout code', r.returncode == 4, str(r.returncode)) + check('phase timeout bounded', time.monotonic() - started < 30) + time.sleep(0.5) + child = int(pidfile.read_text()) + try: + os.kill(child, 0); alive = True + except ProcessLookupError: + alive = False + check('phase timeout kills process group', not alive) + records = [json.loads(l) for l in (s / 'evidence/phases.jsonl').read_text().splitlines()] + check('phase records', [(x['name'], x['status']) for x in records] == [('ok', 'passed'), ('bad', 'failed'), ('blocked', 'blocked'), ('slow', 'timeout')], str(records)) + check('stdout markers retained', 'marker-ok' in (s / 'phases.log').read_text()) + check('stderr kept private', 'secret-in-stderr' not in (s / 'phases.log').read_text() and 'secret-in-stderr' not in (s / 'evidence/phases.jsonl').read_text()) + check('phase name validated', run(['phase', '--state', str(s), '--name', '../x', '--timeout', '1', '--', 'true']).returncode == 64) + + # Partial output and EOF must not bypass the phase deadline. + for name, script in ( + ('partial', 'import sys,time; sys.stdout.write("partial"); sys.stdout.flush(); time.sleep(60)'), + ('closed', 'import os,time; os.close(1); time.sleep(60)'), + ): + started = time.monotonic() + r = run(['phase', '--state', str(state()), '--name', name, '--timeout', '1', '--', sys.executable, '-c', script], timeout=10) + check(name + ' timeout', r.returncode == 4, r.stdout + r.stderr) + check(name + ' bounded', time.monotonic() - started < 8) + + # Provider observation never exposes fence, capability or receipt. + obs = state() + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5']) + check('wait-stage observes running installer', r.returncode == 0, r.stdout) + check('wait-stage sanitized', not any(x in r.stdout for x in ('B' * 64, 'R' * 64, 'T' * 32, 'F' * 32)), r.stdout) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5'], {'FAKE_STAGE': 'disk-started'}) + check('wait-stage rejects missed window', r.returncode == 1, r.stdout) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '2'], {'FAKE_STAGE': 'prepared'}) + check('wait-stage bounded', r.returncode == 4, r.stdout) + out = run(['journal', '--state', str(obs)]).stdout + check('journal sanitized', 'B' * 64 not in out and 'install-op-1' in out, out) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('provider observation only through the cell API', not any(c[0] == 'docker' and 'exec' in c for c in calls) + and any(c[0] == 'kubectl' and 'exec' in c and 'deploy/fleet-site-runtime' in c for c in calls)) + + # Secret scan: every retained credential form is detected and redacted. + s = state(); (s / 'evidence').mkdir() + (s / 'provider').mkdir(); (s / 'provider/tokens.csv').write_text('a' * 64 + ',bootstrap,bootstrap,system:masters\n') + (s / 'hub.json').write_text(json.dumps({'users': [{'user': {'token': 'k' * 40}}]})) + (s / 'provider-private').mkdir(); (s / 'provider-private/journal.json').write_text(json.dumps({'fence': 'f' * 32, 'operations': {'x': {'bootToken': 'b' * 64, 'request': {'fenceToken': 't' * 32}}}})) + (s / 'host.yaml').write_text('users:\n- user:\n client-key-data: ' + 'K' * 48 + '\n') + (s / 'evidence/clean.json').write_text('{"ok":true}') + check('scan clean', run(['scan', '--state', str(s)]).returncode == 0) + (s / 'worker.token').write_text('w' * 40 + '\n') + for secret in ('a' * 64, 'k' * 40, 'f' * 32, 'b' * 64, 't' * 32, 'K' * 48, 'w' * 40): + (s / 'evidence/leak.json').write_text('{"v":"%s"}' % secret) + check('scan detects ' + secret[0], run(['scan', '--state', str(s)]).returncode == 1) + check('scan redacts ' + secret[0], secret not in (s / 'evidence/leak.json').read_text()) + + # Result: status mapping and retained owned containers. + s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n') + for code, status in ((0, 'passed'), (1, 'failed'), (2, 'preflight-failed'), (3, 'blocked'), (4, 'timeout')): + run(['result', '--state', str(s), '--exit-code', str(code)]) + res = json.loads((s / 'evidence/result.json').read_text()) + check('result ' + status, res['status'] == status and res['productionAuthority'] is False) + check('result lists retained containers', res['retainedContainers'] == [{'name': 'fleet-mp-0000aaaa-vm', 'state': 'exited'}], str(res['retainedContainers'])) + check('result keeps unknown custody', 'Unknown' in res['custody']) + + # Teardown refuses without passed acceptance, before touching the runtime. + s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n'); (s / 'evidence').mkdir() + trace.write_text('') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) + check('teardown refuses unknown', r.returncode == 1 and 'refusing' in r.stderr, r.stderr) + (s / 'evidence/summary.json').write_text('{"acceptance":"failed"}') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) + check('teardown refuses failed summary', r.returncode == 1) + check('teardown refusal is effect-free', trace.read_text() == '') + (s / 'prefix').write_text('other-prefix\n') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s), '--discard-unknown'], text=True, capture_output=True, env=base) + check('teardown rejects foreign prefix', r.returncode == 1 and trace.read_text() == '') + r = subprocess.run(['bash', str(root / 'hack/multiplane/run.sh'), '--bogus'], text=True, capture_output=True, env=base) + check('run usage', r.returncode == 64) + + # Static guards for runtime-only step code the offline fakes cannot execute. + steps = (root / 'hack/multiplane/steps.sh').read_text() + evidence = (root / 'hack/multiplane/evidence.py').read_text() + for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): + check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) + sequence = (root / 'hack/multiplane/acceptance.sh').read_text() + order = ['allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', + 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', + 'reflection-faults', 'release', 'release-status-a', + 'reuse', 'reuse-status', 'delivery-faults', 'release-b', 'release-status-b', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] + positions = [sequence.find(' ' + name + ' ') for name in order] + check('acceptance phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) + for name in order: + if name in ('allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', + 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'): + continue + check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) + + # The kro graph and the worker exit-code contract must agree. kro owns only + # per-operation workers: the shared services and the durable site volume are + # Flux-owned and only referenced by the graph. + rgd = (root / 'config/site/graph/rgd.yaml').read_text() + services = (root / 'config/site/services/services.yaml').read_text() + main_go = (root / 'cmd/fleet-multiplane/main.go').read_text() + check('Job replacement waits for terminal Pods', 'podReplacementPolicy: Failed' in rgd) + check('rejected authority fails the Job', 'values: [65]' in rgd and 'exitRejected = 65' in main_go) + templates = re.findall(r'\n template:\n apiVersion: \S+\n kind: (\w+)', rgd) + check('graph templates only per-operation kinds', sorted(templates) == ['Job', 'Role', 'RoleBinding', 'ServiceAccount'], str(templates)) + check('every graph template is per handoff', rgd.count('forEach:\n - handoff: ${handoffs}') == 4 and rgd.count('${schema.spec.dispatch}') == 4) + refs = re.findall(r'\n externalRef:\n apiVersion: \S+\n kind: (\w+)', rgd) + check('graph references the shared site and the volume', sorted(refs) == ['Deployment', 'Deployment', 'Deployment', 'MachineAllocationHandoff', 'PersistentVolumeClaim', 'Service'], str(refs)) + check('workers run the runtime image', 'image: ${hypervisor.spec.template.spec.containers[0].image}' in rgd and 'image: "${FLEET_SITE_IMAGE}"' in services) + check('workers get per-operation resourceNames RBAC', 'resourceNames: ["${handoff.metadata.name}"]' in rgd) + # kro v0.9.4 rejects these resource IDs (pkg/graph/validation.go, kroReservedKeyWords and CEL reserved symbols). + reserved = {'apiVersion', 'context', 'dependency', 'dependencies', 'each', 'externalRef', 'externalReference', 'externalRefs', 'externalReferences', + 'graph', 'instance', 'item', 'items', 'kind', 'kro', 'metadata', 'namespace', 'object', 'resource', 'resourcegraphdefinition', + 'resourceGraphDefinition', 'resources', 'root', 'runtime', 'schema', 'self', 'serviceAccountName', 'spec', 'status', 'this', 'variables', + 'vars', 'version', 'true', 'false', 'null', 'in', 'as', 'break', 'const', 'continue', 'else', 'for', 'function', 'if', 'import', 'let', + 'loop', 'package', 'return', 'var', 'void', 'while'} + ids = re.findall(r'^ - id: (\S+)$', rgd, re.M) + check('graph resource IDs valid for kro', len(ids) == 10 and not set(ids) & reserved and all(re.fullmatch(r'[a-z][a-zA-Z0-9]*', i) for i in ids), str(ids)) + check('nothing in the graph is privileged', 'privileged: true' not in rgd) + check('only the runtime is privileged', services.count('privileged: true') == 1) + check('services own no volume', 'kind: PersistentVolumeClaim' not in services and 'kind: StorageClass' not in services) + check('boot Service at a fixed ClusterIP', 'clusterIP: "${FLEET_BOOT_SERVICE_IP}"' in services) + base = (root / 'config/site/base/site.yaml').read_text() + check('site volume is retained', 'reclaimPolicy: Retain' in base) + kro_rbac = (root / 'config/site/base/kro.yaml').read_text() + cluster_role = kro_rbac.split('kind: ClusterRole\n')[1].split('\n---')[0] + check('kro cluster-wide grant is read-only for site kinds', cluster_role.count('verbs: [get, list, watch]') == 5 + and cluster_role.count('create') == 1 and 'handoffdispatchers' in cluster_role.split('create')[0], cluster_role) + roles = {r.split('\n')[0]: r.split('\n---')[0] for r in kro_rbac.split('kind: Role\nmetadata: ')[1:]} + write_roles = {'{name: fleet-site-kro-workers, namespace: fleet-site}': ('jobs', 'serviceaccounts'), + '{name: fleet-site-kro-worker-rbac, namespace: fleet-coordination}': ('roles, rolebindings',)} + check('kro writes only worker kinds in their namespaces', sorted(roles) == sorted(write_roles) and all( + all(k in roles[n] for k in kinds) and not any(x in roles[n] for x in ('deployments', 'services', 'persistentvolumeclaims', 'configmaps', 'secrets')) + for n, kinds in write_roles.items()), str(sorted(roles))) + check('kro writes are shape-checked by admission', kro_rbac.count('kind: ValidatingAdmissionPolicy\n') == 2 and kro_rbac.count('kind: ValidatingAdmissionPolicyBinding\n') == 2 + and kro_rbac.count("request.userInfo.username == 'system:serviceaccount:kro-system:kro'") == 2 and 'parameterNotFoundAction: Deny' in kro_rbac) + kro = (root / 'config/multiplane/kro/kro.yaml').read_text() + check('unused chart ConfigMap grant removed, failing closed', 'postRenderers:' in kro and 'op: test' in kro and 'resources: [configmaps]' in kro and 'op: remove' in kro) + check('kro version pinned consistently', 'tag: v0.9.4@sha256:' in kro and "'version': 'v0.9.4'" in evidence and 'digest: sha256:4e8de4d3' in kro) + + # Imperative service installation is gone: only Flux installs services. + run_sh = (root / 'hack/multiplane/run.sh').read_text() + for name in ('run.sh', 'steps.sh', 'site.sh', 'topology.sh', 'milo.py', 'roles.py', 'verify-rbac.py'): + text = (root / 'hack/multiplane' / name).read_text() + check('no helm install in ' + name, 'helm install' not in text and 'helm upgrade' not in text) + check('no manifest apply of config in ' + name, not any(x in text for x in ("apply -f config/", "'apply','-f','config/multiplane", "'apply','-f','config/site", 'kind load'))) + check('no docker-run Milo API', 'docker' not in (root / 'hack/multiplane/milo.py').read_text().replace("os.environ['DOCKER_CONTEXT']", '')) + for f in ('flux-tools', 'topology', 'flux-source', 'flux-bootstrap-$c', 'flux-platform', 'flux-milo', 'federation-enrollment', 'flux-site', 'flux-verify'): + check('bootstrap phase present: ' + f, 'ph %s ' % f in run_sh or 'ph "%s" ' % f in run_sh) + check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) + check('fault injection suspends Flux first', 'suspend milo-consumer-a true' in steps and '"suspend":true' in (root / 'hack/multiplane/reflection-faults.py').read_text()) + check('RBAC revocation repaired by Flux, not the harness', "'apply'" not in (root / 'hack/multiplane/verify-rbac.py').read_text()) + for path in ('config/site/base/site.yaml', 'config/site/graph/rgd.yaml', 'config/site/instance/dispatcher.yaml', 'config/multiplane/coordination/crd.yaml', + 'config/multiplane/host/custody.yaml', 'config/multiplane/karmada/karmada.yaml', 'config/multiplane/karmada-members/members.yaml'): + check('prune-protected: ' + path, 'kustomize.toolkit.fluxcd.io/prune: disabled' in (root / path).read_text()) + check('site volume is create-once', base.count('kustomize.toolkit.fluxcd.io/ssa: IfNotPresent') == 2) + check('graph has no Flux substitution', 'postBuild' not in (root / 'config/multiplane/clusters/cell/cell.yaml').read_text().split('name: fleet-site-graph')[1]) + cell_layers = (root / 'config/multiplane/clusters/cell/cell.yaml').read_text() + site_layers = (root / 'config/multiplane/clusters/cell-site/site.yaml').read_text() + base_layer = cell_layers.split('name: fleet-site-base')[1].split('\n---')[0] + services_layer = site_layers.split('name: fleet-site-services')[1].split('\n---')[0] + dispatch_layer = site_layers.split('name: fleet-site-dispatch')[1] + check('shared site infrastructure does not depend on kro', 'name: kro' not in base_layer and 'name: kro' not in services_layer and '{name: fleet-site-base' in services_layer) + check('dispatcher waits for graph and shared services', '{name: fleet-site-graph' in dispatch_layer and '{name: fleet-site-services' in dispatch_layer) + check('site layers use scoped identities', 'serviceAccountName: fleet-site-services-reconciler' in services_layer and 'serviceAccountName: fleet-site-dispatch-reconciler' in dispatch_layer) + r = subprocess.run([sys.executable, str(root / 'hack/multiplane/test-flux.py'), str(root)], text=True, capture_output=True) + check('flux source and scenario tests', r.returncode == 0, (r.stdout + r.stderr)[-1500:]) + +if failures: + print('FAIL multi-plane harness tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS multi-plane harness tests') +PY diff --git a/hack/multiplane/test-k8s-evidence.py b/hack/multiplane/test-k8s-evidence.py new file mode 100644 index 00000000..18fd90a1 --- /dev/null +++ b/hack/multiplane/test-k8s-evidence.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Offline tests for k8s_evidence.py against a fake kubectl. + +Every helper command the live acceptance uses is executed once on the success +path and on representative failure paths, so call-signature and data-shape +mistakes fail here instead of mid-run. Never contacts a cluster. +""" +import json +import os +import pathlib +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]) +helper = root / 'hack/multiplane/k8s_evidence.py' +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +FAKE = r'''#!PYTHON +import json, os, sys +a = sys.argv[1:] +world = json.load(open(os.environ['FAKE_WORLD'])) +config = a[a.index('--kubeconfig') + 1] +args = [x for x in a if not x.startswith('--request-timeout')] +args = args[args.index('--kubeconfig') + 2:] +def ns(): + return args[args.index('-n') + 1] if '-n' in args else '' +def emit(v): print(json.dumps(v)); sys.exit(0) +if config.endswith('worker-kubeconfig.json'): + if args[-3:] == ['get', 'machineallocationhandoff', world['handoff']] or args[-5:-2] == ['get', 'machineallocationhandoff', world['handoff']]: + print('machineallocationhandoff/' + world['handoff']); sys.exit(0) + print('Error from server (Forbidden): denied', file=sys.stderr); sys.exit(1) +if args[:3] == ['config', 'view', '--raw']: + emit({'clusters': [{'cluster': {}}], 'contexts': [{'context': {}}], 'users': []}) +if 'exec' in args: + cmd = args[args.index('--') + 1:] + if cmd[:1] == ['cat'] and cmd[1].endswith('journal.json'): print(world['journal']); sys.exit(0) + if cmd[:1] == ['cat'] and '/qemu/' in cmd[1]: print(world['qemu']); sys.exit(0) + if cmd[:1] == ['virsh']: print(''); sys.exit(0) + sys.exit(1) +if args[:1] == ['create']: + obj = json.loads(sys.stdin.read()); world.setdefault('created', []).append(obj['metadata']['name']) + json.dump(world, open(os.environ['FAKE_WORLD'], 'w')); sys.exit(0) +if 'delete' in args: + name = args[args.index('delete') + 2] + world['jobs'].pop('w-' + name, None); json.dump(world, open(os.environ['FAKE_WORLD'], 'w')); sys.exit(0) +verb, kind = args[args.index('get') + 1], None +kind = args[args.index('get') + 1] +rest = args[args.index('get') + 2:] +name = rest[0] if rest and not rest[0].startswith('-') else None +if kind == 'job': + if name not in world['jobs']: print('NotFound', file=sys.stderr); sys.exit(1) + emit(world['jobs'][name]) +if kind == 'pods': + sel = args[args.index('-l') + 1].split('=', 1)[1] + emit({'items': [p for p in world['pods'] if p['metadata']['labels'].get('fleet.datumapis.com/handoff') == sel or p['metadata']['labels'].get('app.kubernetes.io/name') == sel]}) +if kind == 'pvc': emit({'metadata': {'uid': 'pvc-uid'}, 'spec': {'volumeName': 'pv-1'}}) +if kind == 'pv': emit({'metadata': {'uid': 'pv-uid'}, 'spec': {'persistentVolumeReclaimPolicy': 'Retain'}}) +if kind == 'machine': + emit(world['machines'][config.split('/')[-2]]) +if kind == 'role': emit({'metadata': {'labels': {'kro.run/node-id': 'workerRoles'}}, 'rules': [{'resourceNames': [world['handoff']], 'verbs': ['get']}]}) +if kind == 'machineallocationhandoffs': emit({'items': world['handoffs']}) +if kind == 'machineallocationhandoff': emit({'metadata': {'name': name}, 'spec': {}}) +sys.exit(1) +'''.replace('#!PYTHON', '#!' + sys.executable) + + +def job(name, uid, conditions, failed=0, succeeded=0): + return {'metadata': {'name': name, 'uid': uid, 'labels': {'kro.run/node-id': 'workers'}}, + 'spec': {'backoffLimit': 6, 'podReplacementPolicy': 'Failed', 'template': {'spec': {'serviceAccountName': name}}}, + 'status': {'failed': failed, 'succeeded': succeeded, 'conditions': [{'type': t, 'status': 'True', 'reason': r} for t, r in conditions]}} + + +def pod(name, uid, handoff, job_uid, phase, exit_code=None, app=None): + status = {'phase': phase, 'containerStatuses': [{'state': {'terminated': {'exitCode': exit_code}} if exit_code is not None else {'running': {}}}]} + labels = {'batch.kubernetes.io/controller-uid': job_uid} + labels['fleet.datumapis.com/handoff' if handoff else 'app.kubernetes.io/name'] = handoff or app + return {'metadata': {'name': name, 'uid': uid, 'labels': labels}, 'spec': {'nodeName': 'cell'}, 'status': status} + + +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bindir = tmp / 'bin'; bindir.mkdir() + (bindir / 'kubectl').write_text(FAKE); (bindir / 'kubectl').chmod(0o755) + state = tmp / 'state'; (state / 'evidence').mkdir(parents=True); (state / 'consumer-a').mkdir(); (state / 'consumer-b').mkdir() + (state / 'prefix').write_text('fleet-mp-1234abcd\n') + h = 'op-' + 'a' * 40 + (state / 'install-handoff').write_text(h + '\n') + request = {'id': 'install-1', 'kind': 'install', 'assetID': 'x', 'bindingID': 'b', 'epoch': 1, 'fenceToken': 'F' * 32} + world = {'handoff': h, 'journal': '{"operations":{}}', 'qemu': 'x: starting up a\nx: starting up b\n', + 'jobs': {'w-' + h: job('w-' + h, 'job-2', [('Complete', 'CompletionsReached')], succeeded=1)}, + 'pods': [pod('p2', 'pod-2', h, 'job-2', 'Succeeded', 0)] + [pod(d, d + '-uid', None, '', 'Running', app=d) for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')], + 'machines': {'consumer-a': {'status': {'phase': 'Ready', 'conditions': [{'type': 'Bound', 'status': 'True'}, {'type': 'Ready', 'status': 'True'}]}}, + 'consumer-b': {'status': {'phase': 'Bound', 'conditions': [{'type': 'Bound', 'status': 'True'}]}}}, + 'handoffs': [{'metadata': {'name': h}, 'spec': {'cell': 'fleet-mp-1234abcd-cell', 'requestJSON': json.dumps(request)}}]} + wpath = tmp / 'world.json' + env = dict(os.environ, PATH=str(bindir) + os.pathsep + os.environ['PATH'], FAKE_WORLD=str(wpath)) + + def save(): + wpath.write_text(json.dumps(world)) + + def run(*args): + save() + r = subprocess.run([sys.executable, str(helper), args[0], str(state), *args[1:]], text=True, capture_output=True, env=env) + world.update(json.loads(wpath.read_text())) + return r + + r = run('running-pod', h) + check('running-pod ignores completed pods', r.returncode == 0 and r.stdout.strip() == '', r.stdout + r.stderr) + r = run('job-pod', h, 'job-2') + check('job-pod finds pod by job uid', r.stdout.strip() == 'pod-2', r.stdout + r.stderr) + r = run('job', h) + check('job record', r.returncode == 0 and json.loads(r.stdout)['uid'] == 'job-2', r.stderr) + + # Interruption records. + ops = lambda stage: json.dumps([{'id': 'install-1', 'kind': 'install', 'stage': stage, 'phase': 'Unknown' if stage != 'done' else 'Succeeded'}]) + (state / 'interrupt-observed.json').write_text(json.dumps({'operation': {'id': 'install-1', 'stage': 'installer-started', 'domain': 'd'}, 'domainRunning': True})) + (state / 'interrupt-after.json').write_text(ops('installer-started')) + (state / 'interrupt-job-before-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 0})) + (state / 'interrupt-job-after-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 1})) + r = run('record-pod-interrupt', 'pod-0', 'pod-1') + check('record-pod-interrupt', r.returncode == 0, r.stderr) + (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) + (state / 'interrupt-job-after.json').write_text(ops('disk-started')) + r = run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') + check('record-job-interrupt', r.returncode == 0, r.stderr) + (state / 'interrupt-job-before.json').write_text(ops('done')) + check('record-job-interrupt rejects finished install', run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2').returncode != 0) + (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) + run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') + (state / 'resume-after.json').write_text(ops('done')) + r = run('record-resume', h) + check('record-resume', r.returncode == 0, r.stderr) + + # Lifecycle: snapshot, replace site Pods and the Job, record. + r = run('lifecycle-snapshot', h) + check('lifecycle-snapshot', r.returncode == 0, r.stderr) + (state / 'lifecycle-before.json').write_text(r.stdout) + world['pods'] = [pod('p3', 'pod-3', h, 'job-3', 'Succeeded', 0)] + [pod(d, d + '-new', None, '', 'Running', app=d) for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')] + world['jobs']['w-' + h] = job('w-' + h, 'job-3', [('Complete', 'CompletionsReached')], succeeded=1) + r = run('lifecycle-snapshot', h) + (state / 'lifecycle-after.json').write_text(r.stdout) + r = run('record-lifecycle', 'job-2', 'job-3') + check('record-lifecycle', r.returncode == 0 and (state / 'evidence/lifecycle.json').exists(), r.stderr) + world['journal'] = '{"operations":{"changed":true}}' + (state / 'lifecycle-after.json').write_text(run('lifecycle-snapshot', h).stdout) + check('record-lifecycle rejects journal change', run('record-lifecycle', 'job-2', 'job-3').returncode != 0) + + # Worker RBAC probes. + (state / 'worker.token').write_text('w' * 40) + r = run('worker-rbac', h) + check('worker-rbac', r.returncode == 0 and (state / 'k8s-worker-rbac.json').exists(), r.stderr) + + # Delivery faults: create, verify failure by policy, prune. + r = run('delivery-faults', 'create') + check('delivery-faults create', r.returncode == 0 and len(world.get('created', [])) == 3, r.stderr) + for fault in ('duplicate', 'wrong-cell', 'stale-epoch'): + name = (state / ('fault-%s-handoff' % fault)).read_text().strip() + check('fault name fits worker names: ' + fault, len('w-' + name) <= 63, name) + world['jobs']['w-' + name] = job('w-' + name, fault, [('Failed', 'PodFailurePolicy')], failed=1) + world['pods'].append(pod('f-' + fault, 'f-' + fault, name, fault, 'Failed', 65)) + r = run('delivery-faults', 'verify') + check('delivery-faults verify', r.returncode == 0, r.stderr) + r = run('delivery-faults', 'delete') + check('delivery-faults delete', r.returncode == 0 and json.loads((state / 'evidence/delivery-faults.json').read_text()).get('prunedByKro'), r.stderr) + world['pods'][-1]['status']['containerStatuses'][0]['state']['terminated']['exitCode'] = 75 + world['jobs']['w-' + name] = job('w-' + name, 'x', [('Failed', 'BackoffLimitExceeded')], failed=7) + check('delivery-faults rejects non-policy failure', run('delivery-faults', 'verify').returncode != 0) + + secrets = ['F' * 32, 'w' * 40] + leaked = [p.name for p in (state / 'evidence').rglob('*') if p.is_file() and any(s in p.read_text() for s in secrets)] + check('evidence records contain no fence or token', not leaked, str(leaked)) + +if failures: + print('FAIL k8s evidence tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS k8s evidence tests') diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh new file mode 100644 index 00000000..d10e43cf --- /dev/null +++ b/hack/multiplane/topology.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Create this run's disposable infrastructure: the local OCI registry and three +# kind clusters (platform for Milo, hub for management/Karmada, cell for the +# site). Installs no service: every service is reconciled by each cluster's +# Flux from the published source (hack/multiplane/flux.py, docs/operations/gitops.md). +set -euo pipefail +umask 077 +state=${1:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +node='kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f' +registry_image=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import flux; print(flux.REGISTRY_IMAGE)') +free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()'; } + +# The source and image registry: plain HTTP on the kind network (local seam). +reg_port=$(free_port) +docker run -d --name "$prefix-registry" --network kind --memory 128m --memory-swap 128m --cpus 0.5 \ + -p "127.0.0.1:$reg_port:5000" "$registry_image" >/dev/null +for _ in $(seq 1 30); do curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null 2>&1 && break; sleep 1; done +curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null || { echo 'registry did not start' >&2; exit 1; } + +# Platform: three Milo project APIs, each published on its own NodePort. +api_port=$(free_port) +{ + echo 'kind: Cluster' + echo 'apiVersion: kind.x-k8s.io/v1alpha4' + echo 'nodes:' + echo ' - role: control-plane' + echo ' extraPortMappings:' +} > "$state/platform-kind.yaml" +printf '{' > "$state/platform-ports.json" +sep= +for entry in provider:30441 consumer-a:30442 consumer-b:30443; do + role=${entry%%:*} np=${entry##*:} hp=$(free_port) + printf ' - {containerPort: %s, hostPort: %s, listenAddress: 127.0.0.1}\n' "$np" "$hp" >> "$state/platform-kind.yaml" + printf '%s"%s": %s' "$sep" "$role" "$hp" >> "$state/platform-ports.json"; sep=', ' +done +printf '}\n' >> "$state/platform-ports.json" +kind create cluster --name "$prefix-platform" --config "$state/platform-kind.yaml" --kubeconfig "$state/platform-admin.yaml" --image "$node" --wait 180s +docker update --memory 2300m --memory-swap 2300m --cpus 2 "$prefix-platform-control-plane" >/dev/null + +cat > "$state/hub-kind.yaml" </dev/null + +# The cell pulls the site image by digest from the run registry. +cat > "$state/cell-kind.yaml" <<'YAML' +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +containerdConfigPatches: + - |- + [plugins."io.containerd.grpc.v1.cri".registry] + config_path = "/etc/containerd/certs.d" +YAML +kind create cluster --name "$prefix-cell" --config "$state/cell-kind.yaml" --kubeconfig "$state/cell-admin.yaml" --image "$node" --wait 180s +docker exec "$prefix-cell-control-plane" mkdir -p "/etc/containerd/certs.d/$prefix-registry:5000" +printf '[host."http://%s-registry:5000"]\n capabilities = ["pull", "resolve"]\n' "$prefix" | + docker exec -i "$prefix-cell-control-plane" tee "/etc/containerd/certs.d/$prefix-registry:5000/hosts.toml" >/dev/null +# The cell node hosts the cell API, Flux, kro and the site, including the 3 GiB +# VM runtime Pod that runs the TCG guest. +docker update --memory 4400m --memory-swap 4400m --cpus 2 "$prefix-cell-control-plane" >/dev/null +python3 hack/multiplane/sysctl.py "$state" set + +python3 - "$state" "$prefix" "$reg_port" "$api_port" <<'PY' +import json, pathlib, sys +s, prefix, reg, api = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4] +env = {'registryHost': prefix + '-registry', 'registryPort': int(reg), 'karmadaPort': int(api), + 'cell': prefix + '-cell', 'cellEndpoint': 'https://%s-cell-control-plane:6443' % prefix} +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY +printf 'topology: registry, platform, hub and cell clusters created; no service installed\n' diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py new file mode 100755 index 00000000..2583bbcf --- /dev/null +++ b/hack/multiplane/verify-rbac.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Negative writes and credential revocation against real API servers.""" +import json,pathlib,subprocess,sys,time +s=pathlib.Path(sys.argv[1]);ns='fleet-coordination' +def call(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args],input=input,text=True,capture_output=True) +def forbidden(config,*args): + r=call(config,*args) + if r.returncode==0 or 'forbidden' not in r.stderr.lower():raise SystemExit('Expected Forbidden for '+config.name+' '+args[0]+': '+r.stderr[:200]) +# The site observer is the only cell identity that writes handoff status. +token=call(s/'cell-admin.yaml','-n','fleet-site','create','token','fleet-site-observer','--duration=10m') +if token.returncode:raise SystemExit(token.stderr) +admin=json.loads(call(s/'cell-admin.yaml','config','view','--raw','--minify','-o','json').stdout) +admin['users']=[{'name':'observer','user':{'token':token.stdout.strip()}}];admin['contexts'][0]['context']['user']='observer' +local=s/'observer-kubeconfig.json';local.write_text(json.dumps(admin));local.chmod(0o600) +try: + r=call(local,'-n',ns,'get','machineallocationhandoffs') + if r.returncode:raise SystemExit('observer cannot list delivered intent: '+r.stderr[:200]) + forbidden(local,'-n',ns,'create','configmap','forbidden-write','--from-literal=x=y') + forbidden(local,'-n',ns,'patch','machineallocationhandoff','forbidden-write','--type=merge','-p','{"spec":{"cell":"other"}}') + forbidden(local,'-n',ns,'delete','machineallocationhandoff','forbidden-write') + forbidden(local,'-n',ns,'get','secrets') + forbidden(local,'-n','fleet-site','create','job','forbidden','--image=x') + forbidden(s/'management-hub.json','-n',ns,'patch','machineallocationhandoff','forbidden-write','--subresource=status','--type=merge','-p','{"status":{}}') + for name in ('consumer-a','consumer-b'): + forbidden(s/name/'customer-project.json','-n','default','patch','machine','allocation','--subresource=status','--type=merge','-p','{"status":{"phase":"Ready"}}') + forbidden(s/name/'customer-project.json','-n','default','get','secrets') + # Revoke the actual observer RoleBinding and prove denied reads. The harness + # never restores it: the cell's Flux recreates it from the source. + old=json.loads(call(s/'cell-admin.yaml','-n',ns,'get','rolebinding','fleet-site-observer','-o','json').stdout)['metadata']['uid'] + r=call(s/'cell-admin.yaml','-n',ns,'delete','rolebinding','fleet-site-observer') + if r.returncode:raise SystemExit(r.stderr) + forbidden(local,'-n',ns,'get','machineallocationhandoffs') + r=call(s/'cell-admin.yaml','-n','flux-system','annotate','--overwrite','kustomization','fleet-site-base','reconcile.fluxcd.io/requestedAt=%f'%time.time()) + if r.returncode:raise SystemExit(r.stderr) + for _ in range(150): + b=call(s/'cell-admin.yaml','-n',ns,'get','rolebinding','fleet-site-observer','-o','json') + if b.returncode==0 and call(local,'-n',ns,'get','machineallocationhandoffs').returncode==0:break + time.sleep(2) + else:raise SystemExit('Flux did not restore the revoked observer RoleBinding') + binding=json.loads(b.stdout) + if binding['metadata']['uid']==old or binding['metadata'].get('labels',{}).get('kustomize.toolkit.fluxcd.io/name')!='fleet-site-base': + raise SystemExit('observer RoleBinding was not recreated by Flux') + (s/'evidence'/'flux-rbac-restore.json').write_text(json.dumps({'object':'fleet-coordination/RoleBinding/fleet-site-observer','revokedUID':old,'restoredUID':binding['metadata']['uid'], + 'restoredBy':'kustomize-controller (Kustomization fleet-site-base)','deniedWhileRevoked':True,'observerReadsRestored':True},indent=2)+'\n') +finally: + local.unlink(missing_ok=True) +print('Verified forbidden observer/project/hub writes and observer RoleBinding revocation; Flux restored the binding') +# kro's narrowed authority: cluster-wide reads, writes only of per-operation +# kinds in their namespaces, and admission policies that bind those writes to +# the worker shape. Checked as kro's own identity through impersonation; +# admission is exercised with server-side dry runs, so nothing is persisted. +kro='system:serviceaccount:kro-system:kro';site='fleet-site';h='machineallocationhandoffs.coordination.fleet.datumapis.com' +def can(*args): + r=call(s/'cell-admin.yaml','auth','can-i',*args,'--as',kro) + if r.stdout.strip() not in ('yes','no'):raise SystemExit('auth can-i failed: '+r.stderr[:200]) + return r.stdout.strip()=='yes' +allowed=[('create','jobs','-n',site),('create','serviceaccounts','-n',site),('create','roles','-n',ns),('create','rolebindings','-n',ns), + ('list','deployments','-A'),('list','services','-A'),('watch',h,'-A'),('get','persistentvolumeclaims','-n',site)] +denied=[('create','deployments','-n',site),('patch','deployments','-n',site),('create','services','-n',site),('delete','services','-n',site), + ('delete','persistentvolumeclaims','-n',site),('patch','configmaps','-n',site),('create','jobs','-n','default'),('create','jobs','-n','kube-system'), + ('create','roles','-n',site),('create','rolebindings','-n','kube-system'),('create','clusterroles'),('get','secrets','-n',site), + ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')] +bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] +if bad:raise SystemExit('kro RBAC is not the narrowed grant: '+'; '.join(bad)) +# Grants the kro chart keeps because kro needs them: it creates the CRD for each +# graph's kind, and elects a leader. Recorded as remaining authority, not hidden. +retained=[('create','customresourcedefinitions'),('delete','customresourcedefinitions'),('update','leases','-n','kro-system')] +retained={' '.join(a):can(*a) for a in retained} +image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] +def job(**change): + c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} + spec={'restartPolicy':'Never','serviceAccountName':'w-op-admission-probe','containers':[c],'volumes':[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'tmp','emptyDir':{}}]} + for k,v in change.items(): + (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v + return {'apiVersion':'batch/v1','kind':'Job','metadata':{'name':'w-op-admission-probe','namespace':site,'labels':{'fleet.datumapis.com/handoff':'op-admission-probe'}},'spec':{'template':{'spec':spec}}} +role=lambda rules:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'w-op-admission-probe','namespace':ns},'rules':rules} +own=[{'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationhandoffs'],'resourceNames':['op-admission-probe'],'verbs':['get']}] +# RBAC resolves a binding's Role before admission runs, so the probe binds an +# existing Role that kro fully holds; a dry run cannot create w- first. +binding=lambda name,sa,ref:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':name,'namespace':ns}, + 'subjects':[{'kind':'ServiceAccount','name':sa,'namespace':site}],'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':ref}} +sa=lambda name:{'apiVersion':'v1','kind':'ServiceAccount','metadata':{'name':name,'namespace':site}} +cases={'admitted':{'worker Job':job(),'worker Role':role(own),'worker ServiceAccount':sa('w-op-admission-probe')}, + 'denied':{'Job as the observer':job(serviceAccountName='fleet-site-observer'),'privileged Job':job(securityContext={'privileged':True,'allowPrivilegeEscalation':True}), + 'Job from another image':job(image='registry.k8s.io/pause:3.10'),'Job with a hostPath volume':job(volumes=[{'name':'host','hostPath':{'path':'/'}}]), + 'Job on the host network':job(hostNetwork=True),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list'])]), + 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} +record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} +for outcome,objs in cases.items(): + for name,obj in objs.items(): + r=call(s/'cell-admin.yaml','create','--dry-run=server','--as',kro,'-f','-',input=json.dumps(obj)) + ok=r.returncode==0 + by_policy='ValidatingAdmissionPolicy' in r.stderr and 'fleet-site-kro-worker-' in r.stderr + if (outcome=='admitted')!=ok or (not ok and not by_policy and 'forbidden' not in r.stderr.lower()): + raise SystemExit('kro admission %s for %s: %s'%('denied' if not ok else 'admitted',name,r.stderr[:300])) + record['admission'][name]={'expected':outcome,'admitted':ok,'deniedBy':None if ok else ('ValidatingAdmissionPolicy' if by_policy else 'RBAC')} +if any(v['deniedBy']!='ValidatingAdmissionPolicy' for v in record['admission'].values() if not v['admitted']): + raise SystemExit('expected the admission policies, not RBAC, to deny in-namespace shape violations: %s'%record['admission']) +(s/'evidence'/'kro-rbac.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') +print('Verified kro RBAC and admission confine it to per-operation objects: %d allowed, %d denied verbs; %d shapes admitted, %d denied by policy'%( + len(allowed),len(denied),len(cases['admitted']),len(cases['denied']))) diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index 3243c04b..0c05d862 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -1629,6 +1629,20 @@ func (c *Coordinator) HasClaimCustody(ctx context.Context, consumer ProjectIdent return true, nil } +// ClaimReleased reads terminal custody for the exact project and claim lifetime. +// Callers use this to avoid restoring protection after verified release; public +// status is not authority for this decision. Missing or corrupt custody fails. +func (c *Coordinator) ClaimReleased(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (bool, error) { + if !consumer.Valid() || claimUID == "" { + return false, ErrRecordInvalid + } + record, _, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) + if err != nil { + return false, err + } + return record.State == CustodyReleased, nil +} + func (c *Coordinator) getCustodyForAsset(ctx context.Context, asset *AssetRecord) (*ClaimCustodyRecord, *corev1.Secret, error) { return c.getCustodyScoped(ctx, asset.ClaimScope, asset.ClaimUID) } diff --git a/internal/coordination/mapping.go b/internal/coordination/mapping.go new file mode 100644 index 00000000..55cefb39 --- /dev/null +++ b/internal/coordination/mapping.go @@ -0,0 +1,71 @@ +package coordination + +import ( + "context" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/dynamic" +) + +// LocalAssetMapping is an explicit local-test binding of one project-scoped +// Device to the disposable provider's fixed physical ID. No alias or suffix +// matching is allowed. The exact original request remains durable in the local +// handoff and the backend retains its exact translated request before effects. +// This is a synthetic hardware enrollment seam, not production authority. +type LocalAssetMapping struct { + API dynamic.Interface + Namespace, Cell, ScopedAsset, PhysicalAsset string + Backend executor.Client +} + +func (m *LocalAssetMapping) request(ctx context.Context, id string) (Intent, simulator.Request, error) { + obj, err := m.API.Resource(Resource).Namespace(m.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) + if err != nil { + return Intent{}, simulator.Request{}, err + } + i, _, err := decode(obj) + if err != nil { + return i, simulator.Request{}, err + } + if i.Cell != m.Cell || i.Request.ID != id || m.ScopedAsset == "" || m.PhysicalAsset == "" || i.Request.AssetID != m.ScopedAsset { + return i, simulator.Request{}, executor.ErrFenced + } + translated := i.Request + translated.AssetID = m.PhysicalAsset + return i, translated, nil +} +func (m *LocalAssetMapping) translate(i Intent, translated simulator.Request, r simulator.OperationResult) (simulator.OperationResult, error) { + if err := ValidateResult(Intent{Cell: i.Cell, Request: translated}, r); err != nil { + return simulator.OperationResult{}, err + } + r.InputDigest, _ = simulator.RequestDigest(i.Request) + return r, nil +} +func (m *LocalAssetMapping) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { + i, t, err := m.request(ctx, r.ID) + if err != nil { + return simulator.OperationResult{}, err + } + if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { + return simulator.OperationResult{}, executor.ErrConflict + } + result, err := m.Backend.Execute(ctx, t) + if err != nil { + return simulator.OperationResult{}, err + } + return m.translate(i, t, result) +} +func (m *LocalAssetMapping) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + i, t, err := m.request(ctx, id) + if err != nil { + return simulator.OperationResult{}, false, err + } + r, found, err := m.Backend.Lookup(ctx, id) + if err != nil || !found { + return r, found, err + } + result, err := m.translate(i, t, r) + return result, true, err +} diff --git a/internal/coordination/mapping_test.go b/internal/coordination/mapping_test.go new file mode 100644 index 00000000..d1fbfd4e --- /dev/null +++ b/internal/coordination/mapping_test.go @@ -0,0 +1,41 @@ +package coordination + +import ( + "context" + "errors" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" + "testing" +) + +func TestLocalMappingRequiresExactAssetAndRecoversDigest(t *testing.T) { + i, s, _ := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + translated := i.Request + translated.AssetID = "local-physical-device" + digest, _ := simulator.RequestDigest(translated) + result := s.Reflected[0].Observation.Result + result.InputDigest = digest + backend := &effect{result: result} + mapping := LocalAssetMapping{API: api, Namespace: "private", Cell: i.Cell, ScopedAsset: i.Request.AssetID, PhysicalAsset: translated.AssetID, Backend: backend} + original, err := mapping.Execute(context.Background(), i.Request) + if err != nil { + t.Fatal(err) + } + if original.InputDigest != s.Reflected[0].Observation.Result.InputDigest { + t.Fatal("lost original digest") + } + recovered, found, err := mapping.Lookup(context.Background(), i.Request.ID) + if err != nil || !found || recovered.InputDigest != original.InputDigest { + t.Fatal("restart lost exact mapping", err) + } + mapping.ScopedAsset = "another-project/same-device" + if _, err := mapping.Execute(context.Background(), i.Request); !errors.Is(err, executor.ErrFenced) { + t.Fatal("accepted alias", err) + } + if backend.calls != 1 { + t.Fatal("duplicate execution") + } +} diff --git a/internal/coordination/recovery_adversarial_test.go b/internal/coordination/recovery_adversarial_test.go new file mode 100644 index 00000000..a23e92e8 --- /dev/null +++ b/internal/coordination/recovery_adversarial_test.go @@ -0,0 +1,159 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" +) + +// journaled models a provider that retains each operation before effects: +// Lookup of an unfinished operation is Unknown, and Execute of a retained ID +// resumes it (digest-checked) rather than starting another effect. +type journaled struct { + retained map[string]simulator.Request + done map[string]simulator.OperationResult + lookupErr error + starts int + resumes []simulator.Request + finish simulator.OperationResult + complete bool +} + +func (j *journaled) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { + if j.lookupErr != nil { + return simulator.OperationResult{}, false, j.lookupErr + } + if r, ok := j.done[id]; ok { + return r, true, nil + } + if _, ok := j.retained[id]; ok { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return simulator.OperationResult{}, false, nil +} +func (j *journaled) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { + if old, ok := j.retained[r.ID]; ok { + a, _ := simulator.RequestDigest(old) + b, _ := simulator.RequestDigest(r) + if a != b { + return simulator.OperationResult{}, executor.ErrConflict + } + j.resumes = append(j.resumes, r) + } else { + j.retained[r.ID] = r + j.starts++ + } + if !j.complete { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + j.done[r.ID] = j.finish + return j.finish, nil +} + +func observed(t *testing.T, obj *unstructured.Unstructured) bool { + t.Helper() + _, found, err := unstructured.NestedMap(obj.Object, "status", "observation") + if err != nil { + t.Fatal(err) + } + return found +} + +func TestAdversarialCellRestartResumesUnfinishedOperationOnce(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result} + name := Name(i.Request.ID) + newCell := func() *Cell { + return &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + } + // First delivery starts the operation; its outcome is lost. + if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost outcome must stay unknown: %v", err) + } + // A restarted cell sees Lookup Unknown and resumes; still unfinished. + if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unfinished operation must stay unknown: %v", err) + } + obj, err := api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if observed(t, obj) { + t.Fatal("unknown outcome was published as an observation") + } + provider.complete = true + if err := reconcile(newCell(), ctx, name); err != nil { + t.Fatalf("restart did not recover the retained operation: %v", err) + } + if err := reconcile(newCell(), ctx, name); err != nil { + t.Fatal(err) + } + if provider.starts != 1 || len(provider.resumes) != 2 { + t.Fatalf("want one start and two exact resumes, got %d starts %d resumes", provider.starts, len(provider.resumes)) + } + for _, r := range provider.resumes { + if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { + t.Fatal("resume did not re-deliver the exact retained request") + } + } + obj, err = api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if !observed(t, obj) { + t.Fatal("terminal observation missing after recovery") + } +} + +func TestAdversarialCellLookupFailuresNeverExecute(t *testing.T) { + for name, lookupErr := range map[string]error{ + "conflict": executor.ErrConflict, + "fenced": executor.ErrFenced, + "transport": errors.New("journal unreadable"), + } { + t.Run(name, func(t *testing.T) { + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result, complete: true, lookupErr: lookupErr} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, lookupErr) { + t.Fatalf("lookup failure not reported: %v", err) + } + if provider.starts != 0 || len(provider.resumes) != 0 { + t.Fatal("lookup failure led to an effect") + } + }) + } +} + +// foundUnknown reports a retained but unverifiable terminal record. Resuming +// would only replay the same bytes, so the cell must report it, not execute. +type foundUnknown struct{ calls int } + +func (f *foundUnknown) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, true, executor.ErrOutcomeUnknown +} +func (f *foundUnknown) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + f.calls++ + return simulator.OperationResult{}, nil +} + +func TestAdversarialCellFoundUnknownIsNotSuccess(t *testing.T) { + i, _, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &foundUnknown{} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) || e.calls != 0 { + t.Fatalf("found-unknown result: %v, executes %d", err, e.calls) + } +} diff --git a/internal/coordination/run.go b/internal/coordination/run.go new file mode 100644 index 00000000..c32ea32b --- /dev/null +++ b/internal/coordination/run.go @@ -0,0 +1,40 @@ +package coordination + +import ( + "context" + "errors" + "time" + + "go.datum.net/fleet/internal/executor" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// CellLabel selects the handoffs delivered for one cell. +const CellLabel = "coordination.fleet.datumapis.com/cell" + +// Observe refreshes journal-derived observations for this cell's delivered +// handoffs on a fixed interval. Execution, retry and replacement belong to the +// Kubernetes Job controller and KRO; this loop only republishes terminal +// results so management can check freshness. A pending or invalid handoff is +// reported to onError, which must not log handoff contents. +func (c *Cell) Observe(ctx context.Context, interval time.Duration, onError func(string, error)) error { + for { + list, err := c.API.Resource(Resource).Namespace(c.Namespace).List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + c.Name}) + if err != nil { + onError("", err) + } else { + for _, obj := range list.Items { + if err := c.Publish(ctx, obj.GetName()); err != nil && !errors.Is(err, executor.ErrOutcomeUnknown) { + onError(obj.GetName(), err) + } + } + } + t := time.NewTimer(interval) + select { + case <-ctx.Done(): + t.Stop() + return ctx.Err() + case <-t.C: + } + } +} diff --git a/internal/coordination/site_test.go b/internal/coordination/site_test.go new file mode 100644 index 00000000..6019a468 --- /dev/null +++ b/internal/coordination/site_test.go @@ -0,0 +1,127 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + 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/runtime/schema" + "k8s.io/client-go/dynamic/fake" +) + +// reconcile composes the two site roles: the worker Job executes, then the +// observer publishes from the provider journal. +func reconcile(c *Cell, ctx context.Context, name string) error { + if err := c.Execute(ctx, name); err != nil { + return err + } + return c.Publish(ctx, name) +} + +func TestWorkerExecuteNeverWritesStatus(t *testing.T) { + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &effect{result: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := c.Execute(context.Background(), Name(i.Request.ID)); err != nil || e.calls != 1 { + t.Fatalf("execute: %v calls %d", err, e.calls) + } + for _, a := range api.Actions() { + if a.GetVerb() != "get" { + t.Fatalf("worker used %s on %s", a.GetVerb(), a.GetSubresource()) + } + } +} + +func TestObserverPublishNeverExecutes(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{i.Request.ID: i.Request}, done: map[string]simulator.OperationResult{}} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unfinished journal must stay unknown: %v", err) + } + empty := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}} + c.Executor = empty + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("absent journal record must stay unknown: %v", err) + } + if provider.starts+len(provider.resumes)+empty.starts+len(empty.resumes) != 0 { + t.Fatal("observer executed an effect") + } + obj, _ := api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if observed(t, obj) { + t.Fatal("unknown outcome published") + } + // A terminal but mismatched journal result is not published either. + wrong := s.Reflected[0].Observation.Result + wrong.InputDigest = "0" + c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: wrong}} + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("mismatched terminal result accepted: %v", err) + } + c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result}} + if err := c.Publish(ctx, Name(i.Request.ID)); err != nil { + t.Fatal(err) + } + obj, _ = api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if !observed(t, obj) { + t.Fatal("terminal journal result was not published") + } +} + +// A re-delivered copy under another name, a wrong-cell intent, or an invalid +// intent never reaches the executor. +func TestDeliveryFaultsFenceBeforeEffects(t *testing.T) { + i, s, now := fixture() + duplicate := object("private", i) + duplicate.SetName("copy-of-" + Name(i.Request.ID)) + wrongCell := i + wrongCell.Cell = "other-cell" + wrongObj := object("private", wrongCell) + wrongObj.SetLabels(map[string]string{CellLabel: i.Cell}) + invalid := object("private", i) + invalid.SetName("op-invalid") + _ = unstructured.SetNestedField(invalid.Object, "{", "spec", "requestJSON") + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), duplicate, invalid) + _, _ = api.Resource(Resource).Namespace("private").Create(context.Background(), wrongObj, metav1.CreateOptions{}) + for name, want := range map[string]error{duplicate.GetName(): executor.ErrFenced, Name(i.Request.ID): executor.ErrFenced, "op-invalid": executor.ErrInvalid} { + e := &effect{result: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := c.Execute(context.Background(), name); !errors.Is(err, want) || e.calls != 0 { + t.Fatalf("%s: %v calls %d", name, err, e.calls) + } + if err := c.Publish(context.Background(), name); !errors.Is(err, want) { + t.Fatalf("%s publish: %v", name, err) + } + } +} + +func TestObserveListsOnlyThisCell(t *testing.T) { + i, s, now := fixture() + other := i + other.Cell = "other-cell" + other.Request.ID = "other-op" + api := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}, object("private", i), object("private", other)) + done := map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: &journaled{retained: map[string]simulator.Request{}, done: done}, Now: func() time.Time { return now }} + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + var errs []error + _ = c.Observe(ctx, time.Hour, func(_ string, err error) { errs = append(errs, err) }) + if len(errs) != 0 { + t.Fatalf("unexpected observer errors: %v", errs) + } + mine, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(i.Request.ID), metav1.GetOptions{}) + theirs, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(other.Request.ID), metav1.GetOptions{}) + if !observed(t, mine) || observed(t, theirs) { + t.Fatal("observer published outside its cell selector") + } +} diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go new file mode 100644 index 00000000..f3b836b5 --- /dev/null +++ b/internal/coordination/transport.go @@ -0,0 +1,301 @@ +// Package coordination implements the experimental management -> Karmada -> +// cell executor transport. It is not a production admission authority. +package coordination + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" +) + +var Resource = schema.GroupVersionResource{Group: "coordination.fleet.datumapis.com", Version: "v1alpha1", Resource: "machineallocationhandoffs"} + +const Kind = "MachineAllocationHandoff" + +// Intent is immutable. Request retains the allocator's exact operation, asset, +// allocation, epoch, fence and inputs before federation may deliver any effect. +type Intent struct { + Cell string `json:"cell"` + Request simulator.Request `json:"-"` +} + +// Encode exact request bytes as a string so an API server cannot reorder opaque +// input object fields and silently change the executor's retained digest. +func (i Intent) MarshalJSON() ([]byte, error) { + b, err := json.Marshal(i.Request) + if err != nil { + return nil, err + } + return json.Marshal(struct { + Cell string `json:"cell"` + RequestJSON string `json:"requestJSON"` + }{i.Cell, string(b)}) +} +func (i *Intent) UnmarshalJSON(b []byte) error { + var wire struct { + Cell string `json:"cell"` + RequestJSON string `json:"requestJSON"` + } + if err := json.Unmarshal(b, &wire); err != nil { + return err + } + i.Cell = wire.Cell + return json.Unmarshal([]byte(wire.RequestJSON), &i.Request) +} + +type Observation struct { + Cell string `json:"cell"` + IntentDigest string `json:"intentDigest"` + ObservedAt time.Time `json:"observedAt"` + Result simulator.OperationResult `json:"result"` +} +type Reflected struct { + ClusterName string `json:"clusterName"` + Observation Observation `json:"observation"` +} +type Status struct { + Observation *Observation `json:"observation,omitempty"` + Reflected []Reflected `json:"reflected,omitempty"` +} + +func Name(id string) string { + sum := sha256.Sum256([]byte(id)) + return "op-" + hex.EncodeToString(sum[:])[:40] +} +func Digest(i Intent) string { + b, _ := json.Marshal(i) + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} +func (i Intent) Validate() error { + r := i.Request + if i.Cell == "" || r.ID == "" || r.AssetID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" { + return errors.New("incomplete retained execution authority") + } + switch r.Kind { + case "install", "cleanup", "power": + default: + return errors.New("unsupported operation kind") + } + _, err := simulator.RequestDigest(r) + return err +} +func decode(obj *unstructured.Unstructured) (Intent, Status, error) { + var i Intent + var s Status + b, err := json.Marshal(obj.Object["spec"]) + if err != nil { + return i, s, err + } + if err = json.Unmarshal(b, &i); err != nil { + return i, s, err + } + b, err = json.Marshal(obj.Object["status"]) + if err != nil { + return i, s, err + } + if err = json.Unmarshal(b, &s); err != nil { + return i, s, err + } + return i, s, i.Validate() +} +func object(ns string, i Intent) *unstructured.Unstructured { + b, _ := json.Marshal(i) + var spec map[string]interface{} + _ = json.Unmarshal(b, &spec) + return &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": Resource.GroupVersion().String(), "kind": Kind, "metadata": map[string]interface{}{"name": Name(i.Request.ID), "namespace": ns, "labels": map[string]interface{}{CellLabel: i.Cell}}, "spec": spec}} +} + +// ValidateResult never interprets an incomplete/uncertain result as success. +func ValidateResult(i Intent, r simulator.OperationResult) error { + d, err := simulator.RequestDigest(i.Request) + if err != nil || r.ID != i.Request.ID || r.Kind != i.Request.Kind || r.InputDigest != d || r.Phase != "Succeeded" || r.CompletedAt == nil || r.CreatedAt.IsZero() || r.CompletedAt.Before(r.CreatedAt) { + return executor.ErrOutcomeUnknown + } + switch r.Kind { + case "install": + if r.Result != "installed" { + return executor.ErrOutcomeUnknown + } + case "cleanup": + if r.Result != "clean" { + return executor.ErrOutcomeUnknown + } + } + return nil +} +func ValidateReflection(i Intent, s Status, now time.Time, maxAge time.Duration) (simulator.OperationResult, error) { + // ClusterName is supplied by Karmada's status aggregator, independently of + // the cell-reported identity. Never take the first of conflicting replicas. + if i.Validate() != nil || maxAge <= 0 || len(s.Reflected) != 1 { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + r := s.Reflected[0] + o := r.Observation + if r.ClusterName != i.Cell || o.Cell != i.Cell || o.IntentDigest != Digest(i) || o.ObservedAt.IsZero() || o.ObservedAt.After(now) || now.Sub(o.ObservedAt) > maxAge { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + if err := ValidateResult(i, o.Result); err != nil { + return simulator.OperationResult{}, err + } + if o.Result.CompletedAt.After(o.ObservedAt) { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return o.Result, nil +} + +// Hub implements executor.Client. Only management holds this client. It writes +// immutable intent, reads federation-owned status, and never writes hub status. +// The caller must have retained lifecycle authority before Execute. +type Hub struct { + API dynamic.Interface + Namespace, Cell string + MaxAge time.Duration + Now func() time.Time +} + +func (h *Hub) now() time.Time { + if h.Now != nil { + return h.Now().UTC() + } + return time.Now().UTC() +} +func (h *Hub) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { + if h.API == nil || h.Namespace == "" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + i := Intent{Cell: h.Cell, Request: r} + if err := i.Validate(); err != nil { + return simulator.OperationResult{}, err + } + api := h.API.Resource(Resource).Namespace(h.Namespace) + obj, err := api.Create(ctx, object(h.Namespace, i), metav1.CreateOptions{}) + if apierrors.IsAlreadyExists(err) { + obj, err = api.Get(ctx, Name(r.ID), metav1.GetOptions{}) + } + if err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: handoff persistence unavailable", executor.ErrOutcomeUnknown) + } + retained, status, err := decode(obj) + if err != nil || Digest(retained) != Digest(i) { + return simulator.OperationResult{}, executor.ErrConflict + } + return ValidateReflection(retained, status, h.now(), h.MaxAge) +} +func (h *Hub) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if h.API == nil || h.Namespace == "" || id == "" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + obj, err := h.API.Resource(Resource).Namespace(h.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return simulator.OperationResult{}, false, nil + } + if err != nil { + return simulator.OperationResult{}, false, err + } + i, s, err := decode(obj) + if err != nil || i.Request.ID != id || i.Cell != h.Cell { + return simulator.OperationResult{}, true, executor.ErrConflict + } + r, err := ValidateReflection(i, s, h.now(), h.MaxAge) + return r, true, err +} + +// Cell is the selected location's view of delivered intent. Site execution is +// split by least privilege: a per-operation worker Job calls Execute and holds +// only read access to its one handoff; the site observer calls Publish and is +// the only writer of handoff status. Publish derives every observation from +// the provider journal, never from Job, Pod or KRO status. +type Cell struct { + API dynamic.Interface + Namespace, Name string + Executor executor.Client + Now func() time.Time +} + +// intent reads and validates one delivered handoff for this cell. +func (c *Cell) intent(ctx context.Context, name string) (*unstructured.Unstructured, Intent, error) { + if c.API == nil || c.Executor == nil || c.Namespace == "" || c.Name == "" { + return nil, Intent{}, executor.ErrOutcomeUnknown + } + obj, err := c.API.Resource(Resource).Namespace(c.Namespace).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return nil, Intent{}, err + } + i, _, err := decode(obj) + if err != nil { + return nil, Intent{}, fmt.Errorf("%w: invalid delivered intent", executor.ErrInvalid) + } + if i.Cell != c.Name || name != Name(i.Request.ID) || obj.GetDeletionTimestamp() != nil { + return nil, Intent{}, executor.ErrFenced + } + return obj, i, nil +} + +// Execute runs or resumes exactly the delivered operation and returns nil only +// for a validated terminal provider result. It never writes status. +// +// Lookup Unknown means the provider retained this exact operation but has not +// reached a terminal result. Resuming re-delivers the identical retained +// request under the same operation ID, which the executor contract replays +// against its own journal (digest-checked, never a new operation). Conflict, +// fencing and transport errors stop before any effect. +func (c *Cell) Execute(ctx context.Context, name string) error { + _, i, err := c.intent(ctx, name) + if err != nil { + return err + } + r, found, err := c.Executor.Lookup(ctx, i.Request.ID) + if err != nil && (found || !errors.Is(err, executor.ErrOutcomeUnknown)) { + return err + } + if !found { + if r, err = c.Executor.Execute(ctx, i.Request); err != nil { + return err + } + } + return ValidateResult(i, r) +} + +// Publish writes a fresh observation only for a validated terminal journal +// result. It never executes; absent or unfinished results stay Unknown. +func (c *Cell) Publish(ctx context.Context, name string) error { + obj, i, err := c.intent(ctx, name) + if err != nil { + return err + } + r, found, err := c.Executor.Lookup(ctx, i.Request.ID) + if err != nil { + return err + } + if !found { + return executor.ErrOutcomeUnknown + } + if err = ValidateResult(i, r); err != nil { + return err + } + now := time.Now().UTC() + if c.Now != nil { + now = c.Now().UTC() + } + o := Observation{Cell: c.Name, IntentDigest: Digest(i), ObservedAt: now, Result: r} + b, _ := json.Marshal(Status{Observation: &o}) + var status map[string]interface{} + _ = json.Unmarshal(b, &status) + obj.Object["status"] = status + _, err = c.API.Resource(Resource).Namespace(c.Namespace).UpdateStatus(ctx, obj, metav1.UpdateOptions{}) + return err +} diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go new file mode 100644 index 00000000..c9be4716 --- /dev/null +++ b/internal/coordination/transport_test.go @@ -0,0 +1,115 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic/fake" +) + +func fixture() (Intent, Status, time.Time) { + now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + i := Intent{Cell: "cell-a", Request: simulator.Request{ID: "op", Kind: "cleanup", AssetID: "device", BindingID: "allocation", Epoch: 2, FenceToken: "synthetic-test-fence"}} + digest, _ := simulator.RequestDigest(i.Request) + r := simulator.OperationResult{ID: "op", Kind: "cleanup", InputDigest: digest, Phase: "Succeeded", Result: "clean", CreatedAt: now.Add(-time.Second), CompletedAt: &now} + return i, Status{Reflected: []Reflected{{ClusterName: i.Cell, Observation: Observation{Cell: i.Cell, IntentDigest: Digest(i), ObservedAt: now, Result: r}}}}, now +} +func TestReflectionRejectsUncertainAndConflictingResults(t *testing.T) { + cases := map[string]func(*Intent, *Status, time.Time){ + "wrong federation cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].ClusterName = "cell-b" }, + "wrong reported cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Cell = "cell-b" }, + "stale": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(-time.Hour) }, + "future": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(time.Second) }, + "wrong epoch": func(i *Intent, _ *Status, _ time.Time) { i.Request.Epoch++ }, + "wrong allocation": func(i *Intent, _ *Status, _ time.Time) { i.Request.BindingID = "other" }, + "wrong fence": func(i *Intent, _ *Status, _ time.Time) { i.Request.FenceToken = "other" }, + "wrong inputs": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.InputDigest = "other" }, + "wrong operation": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.ID = "other" }, + "unknown": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Phase = "Unknown" }, + "unclean": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Result = "unknown" }, + "duplicate": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = append(s.Reflected, s.Reflected[0]) }, + "missing": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = nil }, + } + for name, change := range cases { + t.Run(name, func(t *testing.T) { + i, s, n := fixture() + change(&i, &s, n) + if _, err := ValidateReflection(i, s, n, time.Minute); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("accepted invalid reflection: %v", err) + } + }) + } + i, s, n := fixture() + if _, err := ValidateReflection(i, s, n, time.Minute); err != nil { + t.Fatal(err) + } +} + +type effect struct { + result simulator.OperationResult + calls int + fail bool +} + +func (e *effect) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return e.result, e.calls > 0, nil +} +func (e *effect) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { + e.calls++ + if e.fail { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return e.result, nil +} +func TestHubCellRestartAndNoFakeFederation(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + hubAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) + cellAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) + h := &Hub{API: hubAPI, Namespace: "private", Cell: i.Cell, MaxAge: time.Minute, Now: func() time.Time { return now }} + if _, err := h.Execute(ctx, i.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + obj, err := hubAPI.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if _, err = cellAPI.Resource(Resource).Namespace("private").Create(ctx, obj, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + e := &effect{result: s.Reflected[0].Observation.Result} + for range 2 { + c := &Cell{API: cellAPI, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err = reconcile(c, ctx, obj.GetName()); err != nil { + t.Fatal(err) + } + } + if e.calls != 1 { + t.Fatalf("duplicate effects: %d", e.calls) + } + // This unit test deliberately does not simulate federation or claim its success. + if _, _, err = h.Lookup(ctx, i.Request.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("cell-local success leaked to hub: %v", err) + } + changed := i.Request + changed.Epoch++ + if _, err = h.Execute(ctx, changed); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("accepted changed authority: %v", err) + } +} +func TestCellRejectsWrongCellBeforeEffects(t *testing.T) { + i, s, n := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &effect{result: s.Reflected[0].Observation.Result} + c := Cell{API: api, Namespace: "private", Name: "wrong", Executor: e, Now: func() time.Time { return n }} + if err := reconcile(&c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrFenced) || e.calls != 0 { + t.Fatalf("wrong-cell effect: %v, calls %d", err, e.calls) + } +} diff --git a/internal/localvm/multiplane_recovery_adversarial_test.go b/internal/localvm/multiplane_recovery_adversarial_test.go new file mode 100644 index 00000000..751bfd3f --- /dev/null +++ b/internal/localvm/multiplane_recovery_adversarial_test.go @@ -0,0 +1,139 @@ +package localvm + +import ( + "context" + "encoding/json" + "errors" + "os" + "testing" + "time" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" +) + +func TestAdversarialCellResumesRetainedInstallerWithoutSecondStart(t *testing.T) { + ctx := context.Background() + fixture := newVMFixture(t) + fixture.failStart = true + request := vmRequest("cell-recovery") + intent := coordination.Intent{Cell: "cell-a", Request: request} + name := coordination.Name(request.ID) + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, intent)) + mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} + cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&cell, ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost installer response must remain unknown: %v", err) + } + journal, err := fixture.p.read() + if err != nil { + t.Fatal(err) + } + retained := journal.Operations[request.ID] + if retained.Stage != "installer-started" || len(fixture.creates) != 1 { + t.Fatal("did not retain exactly one uncertain installer start") + } + if err := os.WriteFile(fixture.p.directory(retained)+"/installer.log", []byte("FLEET-INSTALLED:"+retained.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + fixture.failStart = false + restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&restarted, ctx, name); err != nil { + t.Fatalf("cell cannot resume exact retained request after installer completion: %v", err) + } + if len(fixture.creates) != 2 { + t.Fatalf("want one installer and one disk boot, got %d starts", len(fixture.creates)) + } + updated, err := api.Resource(coordination.Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + phase, _, _ := unstructured.NestedString(updated.Object, "status", "observation", "result", "phase") + if phase != "Succeeded" { + t.Fatalf("recovered terminal observation missing: %q", phase) + } +} + +func handoff(t *testing.T, intent coordination.Intent) *unstructured.Unstructured { + t.Helper() + encoded, err := json.Marshal(intent) + if err != nil { + t.Fatal(err) + } + var spec map[string]interface{} + if err := json.Unmarshal(encoded, &spec); err != nil { + t.Fatal(err) + } + return &unstructured.Unstructured{Object: map[string]interface{}{ + "apiVersion": coordination.Resource.GroupVersion().String(), + "kind": coordination.Kind, + "metadata": map[string]interface{}{"name": coordination.Name(intent.Request.ID), "namespace": "private"}, + "spec": spec, + }} +} + +// A cell restarted while the retained installer guest is still running must +// observe it, never boot a second installer, and never publish an observation. +// A different handoff for the same device must not act while it is unfinished. +func TestAdversarialCellRestartDuringRunningInstallerAndCompetingHandoff(t *testing.T) { + fixture := newVMFixture(t) + fixture.failStart = true + request := vmRequest("running-install") + cleanup := simulator.Request{ID: "competing-cleanup", Kind: "cleanup", AssetID: request.AssetID, BindingID: request.BindingID, Epoch: request.Epoch, FenceToken: request.FenceToken} + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, coordination.Intent{Cell: "cell-a", Request: request}), handoff(t, coordination.Intent{Cell: "cell-a", Request: cleanup})) + mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} + name := coordination.Name(request.ID) + cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&cell, context.Background(), name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost start must be unknown: %v", err) + } + journal, err := fixture.p.read() + if err != nil { + t.Fatal(err) + } + fixture.present = domain(journal.Operations[request.ID]) + for range 2 { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + err := reconcile(&restarted, ctx, name) + cancel() + if !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("running installer must remain unknown: %v", err) + } + } + if err := reconcile(&cell, context.Background(), coordination.Name(cleanup.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("competing handoff acted during unfinished install: %v", err) + } + if len(fixture.creates) != 1 { + t.Fatalf("restart started another guest: %v", fixture.creates) + } + journal, err = fixture.p.read() + if err != nil { + t.Fatal(err) + } + if journal.Operations[cleanup.ID] != nil || journal.Operations[request.ID].Stage != "installer-started" { + t.Fatal("unfinished install was superseded") + } + for _, id := range []string{request.ID, cleanup.ID} { + obj, err := api.Resource(coordination.Resource).Namespace("private").Get(context.Background(), coordination.Name(id), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedMap(obj.Object, "status"); found { + t.Fatalf("unknown outcome published for %s", id) + } + } +} + +// reconcile composes the site worker (Execute) and observer (Publish) roles. +func reconcile(c *coordination.Cell, ctx context.Context, name string) error { + if err := c.Execute(ctx, name); err != nil { + return err + } + return c.Publish(ctx, name) +} diff --git a/internal/multiplane/location_adversarial_test.go b/internal/multiplane/location_adversarial_test.go new file mode 100644 index 00000000..eee7c3d6 --- /dev/null +++ b/internal/multiplane/location_adversarial_test.go @@ -0,0 +1,131 @@ +package multiplane + +import ( + "context" + "errors" + "testing" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + core "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +func TestAdversarialRejectNonlocalMachineBeforeAllocation(t *testing.T) { + ctx := context.Background() + scheme := Scheme() + private := fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.CreateOption) error { + object.SetUID(types.UID("private-" + object.GetName())) + return api.Create(ctx, object, options...) + }}).Build() + coordinator, err := controller.NewCoordinator(private, PrivateNamespace, &disconnected{}, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + t.Fatal(err) + } + profile := &fleet.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "local-profile", UID: "source-profile"}} + profile.Spec.CPU.Architecture = "amd64" + profile.Spec.CPU.Cores = 2 + profile.Spec.Memory.Capacity = "2Gi" + class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} + capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} + for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) + } + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "not-the-local-location"}, PowerState: "Off"}} + namespace := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: "consumer-namespace"}} + localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "consumer-class"}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} + localProfile := profile.DeepCopyObject().(*fleet.MachineProfile) + localProfile.UID = "consumer-profile" + runner := Runner{ + Config: Config{Cell: "only-local-cell"}, Private: private, Coordinator: coordinator, + Provider: Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(class, profile, capacity).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}, + } + runner.Consumers[0] = Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(machine, namespace, localClass, localProfile).WithStatusSubresource(&fleet.Machine{}).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "consumer", UID: "consumer-project"}} + if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + t.Fatalf("nonlocal Machine was not rejected by location: %v", err) + } + // Rejection precedes custody, synthetic authority records and finalizers. + var secrets core.SecretList + if err := private.List(ctx, &secrets); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 0 { + t.Fatalf("wrong-location request retained %d private records", len(secrets.Items)) + } + var stored fleet.Machine + if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { + t.Fatal(err) + } + if len(stored.Finalizers) != 0 { + t.Fatal("wrong-location request installed a lifecycle finalizer") + } + // The served location is still refused when no cell is configured. + stored.Spec.LocationRef.Name = Location + if err := runner.Consumers[0].API.Update(ctx, &stored); err != nil { + t.Fatal(err) + } + runner.Config.Cell = "" + if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + t.Fatalf("location accepted without a bound cell: %v", err) + } + runner.Config.Cell = "only-local-cell" + req, err := runner.request(ctx, 0) + if err != nil { + t.Fatalf("served location rejected: %v", err) + } + if _, err := coordinator.ReleaseScoped(ctx, req.ConsumerProject, req.Claim.UID); err != nil { + t.Fatal(err) + } + result, err := coordinator.CompleteExternalRelease(ctx, req.Claim.UID, req.Authority, req.ExternalHold, req.ConsumerProject) + if err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("release: %+v %v", result, err) + } + if err := publishRelease(ctx, runner.Consumers[0].API, req.Claim); err != nil { + t.Fatal(err) + } + if _, err := runner.request(ctx, 0); err != nil { + t.Fatal(err) + } + if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { + t.Fatal(err) + } + if len(stored.Finalizers) != 0 { + t.Fatal("request restored finalizer after terminal custody") + } +} + +func TestAdversarialReleaseRemovesFinalizerAfterStatus(t *testing.T) { + ctx := context.Background() + m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine", Finalizers: []string{"other.example/keep", controller.MachineFinalizer}}} + m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: "installed"} + install := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "installed", Namespace: Namespace}, Status: fleet.InstallationStatus{Phase: "Ready", Conditions: []metav1.Condition{condition("Ready", metav1.ConditionTrue, 0, "Installed")}}} + api := fake.NewClientBuilder().WithScheme(Scheme()).WithObjects(m, install).WithStatusSubresource(&fleet.Machine{}, &fleet.Installation{}).Build() + var stored fleet.Machine + if err := api.Get(ctx, client.ObjectKeyFromObject(m), &stored); err != nil { + t.Fatal(err) + } + if err := publishRelease(ctx, api, &stored); err != nil { + t.Fatal(err) + } + if err := api.Get(ctx, client.ObjectKeyFromObject(m), &stored); err != nil { + t.Fatal(err) + } + if stored.Status.CurrentInstallationRef != nil { + t.Fatal("released machine retains current installation") + } + if err := api.Get(ctx, client.ObjectKeyFromObject(install), install); err != nil { + t.Fatal(err) + } + if meta.IsStatusConditionTrue(install.Status.Conditions, "Ready") || install.Status.Phase != "Released" { + t.Fatal("cleaned installation still ready") + } + if stored.Status.Phase != "Released" || len(stored.Finalizers) != 1 || stored.Finalizers[0] != "other.example/keep" { + t.Fatalf("release not published exactly: phase %q finalizers %v", stored.Status.Phase, stored.Finalizers) + } +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go new file mode 100644 index 00000000..8f62f34f --- /dev/null +++ b/internal/multiplane/runner.go @@ -0,0 +1,488 @@ +// Package multiplane is an explicit local acceptance composition of the shared +// lifecycle, real Milo project APIs, and the Karmada executor transport. +// Admission, quota, catalog publication and hardware evidence are synthetic. +package multiplane + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/manager" + rm "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + core "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + meta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const Namespace = "default" +const PrivateNamespace = "fleet-system-private" + +// Location is the only location this acceptance composition serves. It is bound +// to exactly one Karmada member, Config.Cell, and to the one local capacity +// fixture. There is no location catalog: any other Machine locationRef is +// rejected before claim custody, authority records, finalizers, or allocation, +// so a request for elsewhere can never reserve or effect local hardware. +const Location = "local" + +var ErrLocationNotServed = errors.New("machine location is not served by the configured cell") + +type Config struct{ State, HubKubeconfig, PrivateKubeconfig, Cell, Image string } +type Project struct { + API client.Client + Identity controller.ProjectIdentity +} +type Runner struct { + Config Config + Provider Project + Consumers [2]Project + Private client.Client + Hub *coordination.Hub + Coordinator *controller.Coordinator +} + +func Scheme() *runtime.Scheme { + s := runtime.NewScheme() + _ = core.AddToScheme(s) + _ = fleet.AddToScheme(s) + _ = rm.AddToScheme(s) + return s +} +func API(path string) (client.Client, error) { + c, err := clientcmd.BuildConfigFromFlags("", path) + if err != nil { + return nil, err + } + c.Timeout = 30 * time.Second + return client.New(c, client.Options{Scheme: Scheme()}) +} +func New(ctx context.Context, c Config) (*Runner, error) { + r := &Runner{Config: c} + var err error + r.Private, err = API(c.PrivateKubeconfig) + if err != nil { + return nil, err + } + cfg, err := clientcmd.BuildConfigFromFlags("", c.HubKubeconfig) + if err != nil { + return nil, err + } + cfg.Timeout = 30 * time.Second + hub, err := dynamic.NewForConfig(cfg) + if err != nil { + return nil, err + } + r.Hub = &coordination.Hub{API: hub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} + r.Coordinator, err = controller.NewCoordinator(r.Private, PrivateNamespace, r.Hub, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + return nil, err + } + for index, name := range []string{"provider", "consumer-a", "consumer-b"} { + root, err := API(filepath.Join(c.State, name, "management-root.json")) + if err != nil { + return nil, err + } + identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) + if err != nil { + return nil, err + } + project, err := API(filepath.Join(c.State, name, "management-project.json")) + if err != nil { + return nil, err + } + p := Project{API: project, Identity: identity} + if index == 0 { + r.Provider = p + } else { + r.Consumers[index-1] = p + } + } + return r, nil +} +func (r *Runner) ScopedAsset() string { + return r.Provider.Identity.AuthorityID + "/" + string(r.Provider.Identity.UID) + "/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" +} +func condition(kind string, status metav1.ConditionStatus, generation int64, reason string) metav1.Condition { + return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, Reason: reason, Message: "Local multi-plane acceptance; synthetic IAM, quota, catalog and networkless fixtures", LastTransitionTime: metav1.Now()} +} +func ensure(ctx context.Context, c client.Client, obj client.Object) error { + before, _ := json.Marshal(obj) + var want map[string]interface{} + _ = json.Unmarshal(before, &want) + err := c.Create(ctx, obj) + if !apierrors.IsAlreadyExists(err) { + return err + } + if err := c.Get(ctx, client.ObjectKeyFromObject(obj), obj); err != nil { + return err + } + after, _ := json.Marshal(obj) + var got map[string]interface{} + _ = json.Unmarshal(after, &got) + w, _ := json.Marshal(want["spec"]) + g, _ := json.Marshal(got["spec"]) + if string(w) != string(g) || obj.GetDeletionTimestamp() != nil { + return errors.New("existing fixture differs; refusing replacement") + } + return nil +} + +// Seed uses bootstrap only for provider facts/publication; requests use distinct +// customer credentials and a watch starts before each create. +func Seed(ctx context.Context, c Config) error { + var profile fleet.MachineProfile + var class fleet.MachineClass + var capacity fleet.MachineCapacity + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-profile"},"spec":{"cpu":{"architecture":"amd64","cores":2},"memory":{"capacity":"2Gi"}}}`), &profile); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-class"},"spec":{"profilePolicy":{"allowedProfiles":[{"name":"local-profile"}],"customProfiles":{"enabled":false}},"capacity":{"machineCapacities":{"namespace":"fleet-provider","selector":{"matchLabels":{"pool":"local"}}}}}}`), &class); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-capacity","namespace":"fleet-provider","labels":{"pool":"local"}},"spec":{"deviceRef":{"name":"synthetic-device-central-01"},"allocationPolicy":"Enabled","cleaningPolicyRef":{"name":"local-cleaning"},"reclaimPolicy":"Retain"}}`), &capacity); err != nil { + return err + } + provider, err := API(filepath.Join(c.State, "provider", "bootstrap-project.json")) + if err != nil { + return err + } + for _, obj := range []client.Object{&profile, &class, &capacity} { + if err := ensure(ctx, provider, obj); err != nil { + return err + } + } + class.Status.EvaluatedRevision = "local-fixture-v1" + if err := provider.Status().Update(ctx, &class); err != nil { + return err + } + capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} + for _, kind := range []string{"Available", "Verified", "Prepared", "Healthy"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, capacity.Generation, "SyntheticHardwareObservation")) + } + if err := provider.Status().Update(ctx, &capacity); err != nil { + return err + } + var routing []map[string]string + for _, name := range []string{"consumer-a", "consumer-b"} { + api, err := API(filepath.Join(c.State, name, "bootstrap-project.json")) + if err != nil { + return err + } + cp := profile.DeepCopyObject().(*fleet.MachineProfile) + cp.ObjectMeta = metav1.ObjectMeta{Name: profile.Name} + cc := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: class.Name}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: class.Name}}} + if err := ensure(ctx, api, cp); err != nil { + return err + } + if err := ensure(ctx, api, cc); err != nil { + return err + } + customer, err := clientcmd.BuildConfigFromFlags("", filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + return err + } + d, err := dynamic.NewForConfig(customer) + if err != nil { + return err + } + gvr := fleet.GroupVersion.WithResource("machines") + seconds := int64(30) + w, err := d.Resource(gvr).Namespace(Namespace).Watch(ctx, metav1.ListOptions{TimeoutSeconds: &seconds}) + if err != nil { + return err + } + user, err := API(filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + w.Stop() + return err + } + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}, PowerState: "Off"}} + if err := ensure(ctx, user, machine); err != nil { + w.Stop() + return err + } + select { + case event, ok := <-w.ResultChan(): + observed, typed := event.Object.(metav1.Object) + if !ok || event.Type != "ADDED" || !typed || observed.GetUID() != machine.UID || observed.GetName() != machine.Name || observed.GetNamespace() != Namespace { + w.Stop() + return errors.New("Milo create watch did not deliver Added") + } + case <-ctx.Done(): + w.Stop() + return ctx.Err() + } + w.Stop() + installation := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "debian-pxe", Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: machine.Name}, ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: c.Image}}} + if err := ensure(ctx, user, installation); err != nil { + return err + } + var ns core.Namespace + if err := api.Get(ctx, client.ObjectKey{Name: Namespace}, &ns); err != nil { + return err + } + root, err := API(filepath.Join(c.State, name, "management-root.json")) + if err != nil { + return err + } + identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) + if err != nil { + return err + } + routing = append(routing, map[string]string{"route": name, "namespace": Namespace, "namespaceUID": string(ns.UID), "projectUID": string(identity.UID), "machineUID": string(machine.UID), "watch": "Added exact UID"}) + + } + evidence, err := json.MarshalIndent(routing, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(c.State, "routing.json"), evidence, 0600) + +} +func (r *Runner) request(ctx context.Context, index int) (controller.AllocationRequest, error) { + p := r.Consumers[index] + var m fleet.Machine + var ns core.Namespace + var class fleet.MachineClass + var profile fleet.MachineProfile + var capacity fleet.MachineCapacity + var localClass fleet.MachineClass + var localProfile fleet.MachineProfile + objects := []struct { + api client.Client + key client.ObjectKey + obj client.Object + }{{p.API, client.ObjectKey{Namespace: Namespace, Name: "allocation"}, &m}, {p.API, client.ObjectKey{Name: Namespace}, &ns}, {r.Provider.API, client.ObjectKey{Name: "local-class"}, &class}, {r.Provider.API, client.ObjectKey{Name: "local-profile"}, &profile}, {r.Provider.API, client.ObjectKey{Namespace: "fleet-provider", Name: "local-capacity"}, &capacity}, {p.API, client.ObjectKey{Name: "local-class"}, &localClass}, {p.API, client.ObjectKey{Name: "local-profile"}, &localProfile}} + for _, o := range objects { + if err := o.api.Get(ctx, o.key, o.obj); err != nil { + return controller.AllocationRequest{}, err + } + } + if m.Spec.LocationRef.Name != Location || r.Config.Cell == "" || r.Hub != nil && r.Hub.Cell != r.Config.Cell { + return controller.AllocationRequest{}, fmt.Errorf("%w: %q", ErrLocationNotServed, m.Spec.LocationRef.Name) + } + if localClass.Spec.Source == nil || localClass.Spec.Source.Project != "provider" || localClass.Spec.Source.Name != class.Name { + return controller.AllocationRequest{}, errors.New("publication source mismatch") + } + observed := meta.FindStatusCondition(capacity.Status.Conditions, "Verified") + if observed == nil { + return controller.AllocationRequest{}, errors.New("missing hardware fixture evidence") + } + admission := controller.AdmissionAuthority{PrincipalUID: "local-fixture:" + string(p.Identity.UID), DecisionID: "local-fixture:" + string(m.UID)} + if err := r.Coordinator.EnsureClaimCustody(ctx, &m, ns.UID, admission, p.Identity); err != nil { + return controller.AllocationRequest{}, err + } + // Retain a concrete synthetic contract record, not just an invented reference. + contract, _ := json.Marshal(struct { + Consumer, Provider controller.ProjectIdentity + Claim, Capacity, Class, Profile types.UID + }{p.Identity, r.Provider.Identity, m.UID, capacity.UID, class.UID, profile.UID}) + sum := sha256.Sum256(contract) + digest := hex.EncodeToString(sum[:]) + name := "mp-authority-" + digest[:24] + secret := &core.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: PrivateNamespace}, Data: map[string][]byte{"contract.json": contract}} + if err := r.Private.Create(ctx, secret); apierrors.IsAlreadyExists(err) { + var existing core.Secret + if err := r.Private.Get(ctx, client.ObjectKeyFromObject(secret), &existing); err != nil { + return controller.AllocationRequest{}, err + } + if string(existing.Data["contract.json"]) != string(contract) { + return controller.AllocationRequest{}, errors.New("retained synthetic authority conflict") + } + secret = &existing + } else if err != nil { + return controller.AllocationRequest{}, err + } + authority := controller.AuthorityRef{Provider: "local-fixture", RecordName: name, RecordID: string(secret.UID), ContractDigest: digest} + hold := controller.ExternalHoldRef{Provider: "local-fixture", Namespace: PrivateNamespace, Name: name, UID: secret.UID} + if err := r.Coordinator.RetainClaimAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority); err != nil { + return controller.AllocationRequest{}, err + } + if err := r.Coordinator.RetainAllocationAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority, hold); err != nil { + return controller.AllocationRequest{}, err + } + hasFinalizer := false + for _, f := range m.Finalizers { + if f == controller.MachineFinalizer { + hasFinalizer = true + } + } + released, err := r.Coordinator.ClaimReleased(ctx, p.Identity, m.UID) + if err != nil { + return controller.AllocationRequest{}, err + } + if !hasFinalizer && !released { + m.Finalizers = append(m.Finalizers, controller.MachineFinalizer) + if err := p.API.Update(ctx, &m); err != nil { + return controller.AllocationRequest{}, err + } + } + return controller.AllocationRequest{Claim: &m, Class: &class, Profile: &profile, MachineCapacities: []fleet.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: observed.LastTransitionTime.Time}, NamespaceUID: ns.UID, Admission: admission, LocalClassName: localClass.Name, LocalClassUID: localClass.UID, LocalProfileName: localProfile.Name, LocalProfileUID: localProfile.UID, ConsumerProject: p.Identity, ProviderProject: r.Provider.Identity, Authority: authority, ExternalHold: hold}, nil +} +func (r *Runner) Allocate(ctx context.Context) error { + a, err := r.request(ctx, 0) + if err != nil { + return err + } + b, err := r.request(ctx, 1) + if err != nil { + return err + } + if a.NamespaceUID == b.NamespaceUID || a.ConsumerProject.SameLifetime(b.ConsumerProject) { + return errors.New("consumer control planes do not have distinct identities") + } + if _, err = r.Coordinator.Allocate(ctx, a); err != nil { + return err + } + if _, err = r.Coordinator.Allocate(ctx, b); !errors.Is(err, controller.ErrInsufficientCapacity) { + return fmt.Errorf("contention must retain one winner: %v", err) + } + for index, request := range []controller.AllocationRequest{a, b} { + m := request.Claim + phase, reason := "Bound", "AwaitingVerifiedInstallation" + status := metav1.ConditionTrue + if index == 1 { + phase, reason, status = "Pending", "InsufficientCapacity", metav1.ConditionFalse + } + m.Status.Phase = phase + m.Status.Conditions = []metav1.Condition{condition("Bound", status, m.Generation, reason), condition("Ready", metav1.ConditionFalse, m.Generation, reason)} + if err := r.Consumers[index].API.Status().Update(ctx, m); err != nil { + return err + } + } + return nil +} +func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } + +func (r *Runner) InstallIndex(ctx context.Context, index int) error { + request, err := r.request(ctx, index) + if err != nil { + return err + } + var install fleet.Installation + if err := r.Consumers[index].API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + return err + } + result, err := r.Coordinator.Install(ctx, controller.InstallationRequest{Claim: request.Claim, Installation: &install, NamespaceUID: request.NamespaceUID, ConsumerProject: request.ConsumerProject, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: request.Admission.PrincipalUID, DecisionID: "local-install:" + string(install.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + imageDigest(install.Spec.ImageRef.Name)}}) + if err != nil { + return err + } + verified, found, err := r.Hub.Lookup(ctx, result.Record.OperationID) + if err != nil || !found || verified.InputDigest != result.RequestDigest { + return executor.ErrOutcomeUnknown + } + install.Status.Phase = "Ready" + install.Status.Conditions = []metav1.Condition{condition("Ready", metav1.ConditionTrue, install.Generation, "LocalPXEVerifiedViaKarmada")} + if err := r.Consumers[index].API.Status().Update(ctx, &install); err != nil { + return err + } + m := request.Claim + m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: install.Name} + m.Status.Phase = "Ready" + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionTrue, m.Generation, "LocalPXEVerifiedViaKarmada")) + return r.Consumers[index].API.Status().Update(ctx, m) +} +func (r *Runner) Release(ctx context.Context) error { return r.ReleaseIndex(ctx, 0) } +func (r *Runner) ReleaseSecond(ctx context.Context) error { return r.ReleaseIndex(ctx, 1) } +func (r *Runner) ReleaseIndex(ctx context.Context, index int) error { + request, err := r.request(ctx, index) + if err != nil { + return err + } + result, err := r.Coordinator.ReleaseScoped(ctx, request.ConsumerProject, request.Claim.UID) + if err != nil { + return err + } + if result.ExternalSettlementRequired { + result, err = r.Coordinator.CompleteExternalRelease(ctx, request.Claim.UID, request.Authority, request.ExternalHold, request.ConsumerProject) + if err != nil { + return err + } + } + if !result.SafeToRemoveFinalizer { + return executor.ErrOutcomeUnknown + } + return publishRelease(ctx, r.Consumers[index].API, request.Claim) +} + +// publishRelease runs only after verified cleanup made removal safe. Status is +// written first because a status response overwrites the in-memory object, +// including metadata, from the server; the finalizer is removed afterwards +// from that fresh copy so the removal is not silently reverted. +func publishRelease(ctx context.Context, api client.Client, m *fleet.Machine) error { + // Retire the current installation before clearing the reference, so retries + // can finish projection if either API write fails after cleanup. + if ref := m.Status.CurrentInstallationRef; ref != nil { + var install fleet.Installation + err := api.Get(ctx, client.ObjectKey{Namespace: m.Namespace, Name: ref.Name}, &install) + if err != nil && !apierrors.IsNotFound(err) { + return err + } + if err == nil { + install.Status.Phase = "Released" + meta.SetStatusCondition(&install.Status.Conditions, condition("Ready", metav1.ConditionFalse, install.Generation, "Released")) + if err := api.Status().Update(ctx, &install); err != nil { + return err + } + } + } + m.Status.CurrentInstallationRef = nil + m.Status.Phase = "Released" + meta.SetStatusCondition(&m.Status.Conditions, condition("Bound", metav1.ConditionFalse, m.Generation, "Released")) + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionFalse, m.Generation, "Released")) + if err := api.Status().Update(ctx, m); err != nil { + return err + } + retainedFinalizers := make([]string, 0, len(m.Finalizers)) + for _, f := range m.Finalizers { + if f != controller.MachineFinalizer { + retainedFinalizers = append(retainedFinalizers, f) + } + } + m.Finalizers = retainedFinalizers + return api.Update(ctx, m) +} +func (r *Runner) Reuse(ctx context.Context) error { + b, err := r.request(ctx, 1) + if err != nil { + return err + } + if _, err = r.Coordinator.Allocate(ctx, b); err != nil { + return err + } + // Public status follows only the coordinator's committed reuse binding; + // readiness still requires a verified installation for this allocation. + m := b.Claim + m.Status.Phase = "Bound" + meta.SetStatusCondition(&m.Status.Conditions, condition("Bound", metav1.ConditionTrue, m.Generation, "AwaitingVerifiedInstallation")) + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionFalse, m.Generation, "AwaitingVerifiedInstallation")) + return r.Consumers[1].API.Status().Update(ctx, m) +} +func ReadConfig(path string) (Config, error) { + var c Config + b, err := os.ReadFile(path) + if err != nil { + return c, err + } + err = json.Unmarshal(b, &c) + return c, err +} + +func imageDigest(value string) string { _, digest, _ := strings.Cut(value, "@"); return digest } diff --git a/internal/multiplane/runner_test.go b/internal/multiplane/runner_test.go new file mode 100644 index 00000000..6bbdb1f2 --- /dev/null +++ b/internal/multiplane/runner_test.go @@ -0,0 +1,105 @@ +package multiplane + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + core "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +type disconnected struct{ calls int } + +func (d *disconnected) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + d.calls++ + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} +func (d *disconnected) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} +func TestIndependentProjectsContendAndUnknownRetainsCustody(t *testing.T) { + ctx := context.Background() + s := Scheme() + private := fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + obj.SetUID(types.UID("private-" + obj.GetName())) + return c.Create(ctx, obj, opts...) + }}).Build() + var profile fleet.MachineProfile + profile.Name = "local-profile" + profile.UID = "source-profile" + profile.Spec.CPU.Architecture = "amd64" + profile.Spec.CPU.Cores = 2 + profile.Spec.Memory.Capacity = "2Gi" + class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} + capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} + for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) + } + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(class, &profile, capacity).Build() + backend := &disconnected{} + coordinator, err := controller.NewCoordinator(private, PrivateNamespace, backend, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + t.Fatal(err) + } + r := Runner{Config: Config{Cell: "cell-a"}, Private: private, Coordinator: coordinator, Provider: Project{API: provider, Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}} + for index, name := range []string{"a", "b"} { + ns := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: types.UID(name + "-namespace")}} + // Identical namespace, Machine name AND UID: only project authority separates them. + m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "same-machine-uid"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "local"}, PowerState: "Off"}} + localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: types.UID(name + "-class")}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} + cp := profile.DeepCopyObject().(*fleet.MachineProfile) + cp.UID = types.UID(name + "-profile") + r.Consumers[index] = Project{API: fake.NewClientBuilder().WithScheme(s).WithObjects(ns, m, localClass, cp).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: name, UID: types.UID(name + "-project")}} + } + a, err := r.request(ctx, 0) + if err != nil { + t.Fatal(err) + } + b, err := r.request(ctx, 1) + if err != nil { + t.Fatal(err) + } + results := make([]error, 2) + var wg sync.WaitGroup + for i, q := range []controller.AllocationRequest{a, b} { + wg.Add(1) + go func() { defer wg.Done(); _, results[i] = r.Coordinator.Allocate(ctx, q) }() + } + wg.Wait() + winner, loser := -1, -1 + for i, err := range results { + if err == nil { + if winner != -1 { + t.Fatal("both projects won") + } + winner = i + } else if errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid) { + loser = i + } else { + t.Fatal(err) + } + } + if winner < 0 || loser < 0 { + t.Fatal("contention did not produce one winner", results) + } + claims := []controller.AllocationRequest{a, b} + _, err = r.Coordinator.ReleaseScoped(ctx, claims[winner].ConsumerProject, claims[winner].Claim.UID) + if !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("disconnected cleanup must be unknown: %v", err) + } + _, err = r.Coordinator.Allocate(ctx, claims[loser]) + if !(errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid)) { + t.Fatalf("unknown cleanup exposed capacity: %v", err) + } +} From 8c38ad8dd5ecbe788362a8a392c7fc867faa5a7c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:34:29 -0600 Subject: [PATCH 10/12] feat(redfish): Redfish executor on gofish with a DMTF emulator lab mode internal/redfish implements the executor contract over Redfish using gofish v0.27.0 for transport and schema decoding, behind Fleet's own guards: exact endpoint and System identity checks across every page of the Systems collection, advertised allowable-value checks, no redirects or environment proxy, bounded bodies and errors that never carry credentials or URLs. Each boot override is one conditional PATCH (If-Match when an ETag is present) with readback and no Settings fallback; each reset is one POST with no resend. Recovery is observation-based and treats lost responses as Unknown. On may be repeated, bounded to three attempts, only while the System is still Off, armed and silent; this is not exactly-once delivery. Cleanup PXE-boots a wipe environment that zeroes and reads back the disk. task multiplane:redfish-acceptance runs the multi-plane composition with Redfish workers that have no libvirt path, against the unmodified DMTF Redfish Interface Emulator 1.2.2 and a lab-only libvirt adapter driving two persistent lab VMs. Credentials are synthetic and per run. This is not physical BMC or hardware qualification; see docs/operations/redfish-lab.md. Co-Authored-By: Claude Opus 5.5 --- Taskfile.yaml | 7 + cmd/fleet-multiplane/main.go | 93 +- config/site/redfish/base/bmc.yaml | 7 + config/site/redfish/base/kustomization.yaml | 40 + config/site/redfish/graph/kustomization.yaml | 56 ++ config/site/redfish/services/bmc.yaml | 68 ++ .../site/redfish/services/kustomization.yaml | 50 ++ docs/development/README.md | 6 + docs/operations/README.md | 1 + docs/operations/local-vm.md | 4 + docs/operations/multiplane.md | 4 + docs/operations/redfish-lab.md | 624 ++++++++++++++ docs/operations/site-execution.md | 3 +- go.mod | 1 + go.sum | 2 + hack/local-vm/init | 25 +- hack/local-vm/site-runtime | 9 + hack/multiplane/acceptance-redfish.sh | 55 ++ hack/multiplane/evidence.py | 123 ++- hack/multiplane/flux.py | 24 +- hack/multiplane/harness.py | 11 +- hack/multiplane/k8s_evidence.py | 7 +- hack/multiplane/redfish_steps.py | 314 +++++++ hack/multiplane/run.sh | 30 +- hack/multiplane/site.sh | 22 + hack/multiplane/steps.sh | 7 +- hack/multiplane/teardown.sh | 7 +- hack/multiplane/test-harness.sh | 2 + hack/multiplane/test-redfish.py | 171 ++++ hack/multiplane/verify-rbac.py | 14 +- hack/redfish-lab/Containerfile | 17 + hack/redfish-lab/emulator-config.json | 7 + hack/redfish-lab/fake_virsh.py | 33 + hack/redfish-lab/fleet_lab_adapter.py | 387 +++++++++ hack/redfish-lab/populate-config.json | 24 + hack/redfish-lab/requirements.lock | 203 +++++ hack/redfish-lab/targets.json | 8 + hack/redfish-lab/test_adapter.py | 117 +++ hack/redfish-lab/upstream.sh | 24 + internal/multiplane/runner.go | 4 + internal/redfish/boot.go | 217 +++++ internal/redfish/client.go | 413 +++++++++ internal/redfish/client_test.go | 247 ++++++ internal/redfish/provider.go | 814 ++++++++++++++++++ internal/redfish/provider_test.go | 629 ++++++++++++++ 45 files changed, 4903 insertions(+), 28 deletions(-) create mode 100644 config/site/redfish/base/bmc.yaml create mode 100644 config/site/redfish/base/kustomization.yaml create mode 100644 config/site/redfish/graph/kustomization.yaml create mode 100644 config/site/redfish/services/bmc.yaml create mode 100644 config/site/redfish/services/kustomization.yaml create mode 100644 docs/operations/redfish-lab.md create mode 100755 hack/multiplane/acceptance-redfish.sh create mode 100644 hack/multiplane/redfish_steps.py create mode 100644 hack/multiplane/test-redfish.py create mode 100644 hack/redfish-lab/Containerfile create mode 100644 hack/redfish-lab/emulator-config.json create mode 100755 hack/redfish-lab/fake_virsh.py create mode 100755 hack/redfish-lab/fleet_lab_adapter.py create mode 100644 hack/redfish-lab/populate-config.json create mode 100644 hack/redfish-lab/requirements.lock create mode 100644 hack/redfish-lab/targets.json create mode 100644 hack/redfish-lab/test_adapter.py create mode 100755 hack/redfish-lab/upstream.sh create mode 100644 internal/redfish/boot.go create mode 100644 internal/redfish/client.go create mode 100644 internal/redfish/client_test.go create mode 100644 internal/redfish/provider.go create mode 100644 internal/redfish/provider_test.go diff --git a/Taskfile.yaml b/Taskfile.yaml index 6bda8974..3665602e 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -14,6 +14,13 @@ tasks: 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:preflight: desc: Check local prerequisites and implementation readiness without creating resources. env: diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 004b6208..d63f851a 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -9,6 +9,7 @@ import ( "fmt" "os" "os/signal" + "strings" "syscall" "time" @@ -16,6 +17,7 @@ import ( "go.datum.net/fleet/internal/executor" "go.datum.net/fleet/internal/localvm" "go.datum.net/fleet/internal/multiplane" + "go.datum.net/fleet/internal/redfish" "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" @@ -29,7 +31,7 @@ func main() { } func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials| [flags]") + return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one reconcile attempt for fault injection") @@ -40,11 +42,16 @@ func run() error { kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") cell := fs.String("cell", "", "exact Karmada member name") scoped := fs.String("scoped-asset", "", "exact retained provider-scoped Device ID") + 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)") if err := fs.Parse(os.Args[2:]); err != nil { return err } switch os.Args[1] { - case "seed", "allocate", "install", "admit-install", "release", "release-b", "reuse", "asset": + case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse", "asset": config, err := multiplane.ReadConfig(*configPath) if err != nil { return err @@ -68,6 +75,8 @@ func run() error { action = r.Allocate case "install", "admit-install": action = r.Install + case "install-b": + action = r.InstallSecond case "release": action = r.Release case "release-b": @@ -100,6 +109,31 @@ func run() error { time.Sleep(3 * time.Second) } } + if os.Args[1] == "redfish-probe" { + return probe(*endpoint, *credentials, *system, *uuid) + } + if redfishMode() { + switch os.Args[1] { + case "boot-service", "boot-denials": + p, err := redfish.OpenReadOnly() + if err != nil { + return err + } + if os.Args[1] == "boot-service" { + return p.ServeBoot() + } + var extra []string + if *extraMAC != "" { + extra = append(extra, *extraMAC) + } + summary, err := p.CheckClosedBoot(*origin, extra) + if err != nil { + return err + } + fmt.Println(summary) + return nil + } + } switch os.Args[1] { case "image", "boot-service", "boot-denials": // Read-only: the boot service mounts the journal read-only. @@ -143,7 +177,13 @@ func run() error { defer cancel() if os.Args[1] == "site-observer" { // The observer never executes: its provider is read-only. - p, err := localvm.OpenReadOnly() + var p executor.Client + var err error + if redfishMode() { + p, err = redfish.OpenReadOnly() + } else { + p, err = localvm.OpenReadOnly() + } if err != nil { return err } @@ -153,7 +193,15 @@ func run() error { fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) }) } - p, err := localvm.Open() + // A Redfish worker has no libvirt fallback: redfish.Open refuses any + // hypervisor configuration, and the worker reaches the target only + // through its enrolled BMC. + var p executor.Client + if redfishMode() { + p, err = redfish.Open() + } else { + p, err = localvm.Open() + } if err != nil { return err } @@ -172,6 +220,43 @@ func run() error { const coordinationNamespace = "fleet-coordination" +// redfishMode selects the Redfish executor for site roles. The site's Flux +// layers set it; there is no automatic choice between providers. +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. +func probe(endpoint, credentials, system, uuid 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.NewClient(endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) + if 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.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: rejected authority // fails the Job without retry; anything else is retried by the Job controller // against the same retained operation. Exit 0 only follows a validated 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/kustomization.yaml b/config/site/redfish/base/kustomization.yaml new file mode 100644 index 00000000..f9bf8fbd --- /dev/null +++ b/config/site/redfish/base/kustomization.yaml @@ -0,0 +1,40 @@ +# 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 +patches: + - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-jobs} + patch: |- + # Guard: fail the build if the shared policy's volume rule moved. + - op: test + path: /spec/validations/5/message + value: a worker Job may mount only the site journal claim and emptyDir + - op: replace + path: /spec/validations/5 + value: + expression: >- + !has(variables.pod.volumes) || variables.pod.volumes.all(v, + (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir) || + (has(v.secret) && v.secret.secretName == 'fleet-site-bmc-credentials')) + message: a Redfish worker Job may mount only the site journal claim, emptyDir and the BMC credential + # 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 diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml new file mode 100644 index 00000000..437677c4 --- /dev/null +++ b/config/site/redfish/graph/kustomization.yaml @@ -0,0 +1,56 @@ +# Redfish-mode dispatcher graph: the shared graph with the worker template +# switched to the Redfish provider. Workers mount the journal, the boot +# evidence and the lab console capture (all read-only except the journal) and +# the synthetic BMC credential; they have no libvirt socket. 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_CREDENTIALS, value: /etc/fleet-redfish} + - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} + # Explicit site enrollment: each physical asset ID maps to exactly one + # Redfish System (Id and UUID), NIC and console capture. Only target A + # is published as capacity; target B is enrolled to prove isolation. + - name: FLEET_REDFISH_ENROLLMENT + value: '{"endpoint":"http://10.96.0.81:8000","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + - {name: HOME, value: /tmp} + - 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: credentials, mountPath: /etc/fleet-redfish, readOnly: true} + - {name: tmp, mountPath: /tmp} + - op: add + path: /spec/resources/9/template/spec/template/spec/volumes/- + value: + name: credentials + secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1bmc + value: ${bmc.metadata.name} + - 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..39407870 --- /dev/null +++ b/config/site/redfish/services/bmc.yaml @@ -0,0 +1,68 @@ +# 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; Fleet workers reach it only over HTTP with the synthetic +# credential. Plain HTTP on the cluster network is a documented lab seam. +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: 8000, targetPort: 8000, 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"} + - {name: HOME, value: /tmp} + ports: + - {name: redfish, containerPort: 8000} + readinessProbe: + httpGet: {path: /redfish/v1/, port: 8000} + 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: tmp, mountPath: /tmp} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} + - name: credentials + secret: {secretName: fleet-site-bmc-credentials, 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..70dce65d --- /dev/null +++ b/config/site/redfish/services/kustomization.yaml @@ -0,0 +1,50 @@ +# 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} + - 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/docs/development/README.md b/docs/development/README.md index 66164926..3eb2fe48 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -31,6 +31,12 @@ 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. +`internal/redfish` implements a Redfish executor behind the same contracts: discovery, +one-time boot overrides, power, observation-based recovery and a booted wipe +cleanup. [Redfish-mode acceptance](../operations/redfish-lab.md) +(`task multiplane:redfish-acceptance`) exercises it against the unmodified DMTF Redfish +Interface Emulator and a lab-only libvirt adapter. It is not qualified against a +physical BMC or server, and the production manager does not use it. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/operations/README.md b/docs/operations/README.md index a21ad1f7..d6a1fb64 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -15,6 +15,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise allocation, install recovery, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | +| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 06ba44f7..f7b107e2 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -84,6 +84,10 @@ QEMU running, an old receipt, or missing evidence never yields installed success There is no ongoing guest agent. The minimal guest deliberately powers off after verification; this does not qualify a production distribution or workload. +The installer also accepts `fleet.mode=wipe`, which zeroes and verifies the disk. +Only the [Redfish mode](redfish-lab.md) boots it; this harness never selects it, +and its install path is unchanged. + Reinstall creates a new blank disk and a new receipt under the same allocation. Prior incarnation disks remain private until cleanup; they are never booted or exposed to another consumer. Cleanup deletes only retained disks for that exact diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index bb097fff..f521f59a 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -16,6 +16,10 @@ composition. The shared lifecycle adds only the read-only `Coordinator.ClaimReleased` custody query, and the executor interface documents exact-request replay and its narrow not-found-plus-Unknown lookup contract. +The [Redfish mode](redfish-lab.md) (`task multiplane:redfish-acceptance`) runs the +same composition with a Redfish executor. Its workers have no libvirt socket and +reach two persistent lab VMs only through the DMTF Redfish Interface Emulator. + ## Topology and versions | Surface | Local implementation | Writer | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md new file mode 100644 index 00000000..08446eb4 --- /dev/null +++ b/docs/operations/redfish-lab.md @@ -0,0 +1,624 @@ +# Redfish-mode acceptance with the DMTF Redfish Interface Emulator + +This opt-in mode of the [multi-plane acceptance](multiplane.md) replaces the +cell worker's libvirt path with a Redfish executor. Workers reach two persistent +lab VMs only through the DMTF Redfish Interface Emulator and a small lab-only +adapter. Everything else is the existing pipeline: + +- native Milo project APIs; +- the shared allocator and installation lifecycle; +- Karmada delivery and reflection; +- kro-created per-operation Jobs; +- Flux-owned shared services. + +It is a **local MVP proof**, not hardware qualification. No physical server, BMC, +vendor Redfish implementation, UEFI firmware, TLS or production secret store +was involved. See [what remains unqualified](#limitations-and-physical-hardware-readiness). + +```sh +task multiplane:redfish-acceptance +# equivalent: +FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh --redfish +``` + +Prerequisites, exit codes, the state and evidence layout, `--keep`, +`--leave-running`, `stop.sh` and `teardown.sh` are those of the +[multi-plane harness](multiplane.md#run). Redfish mode also needs network access +to GitHub release archives, Docker Hub and PyPI to build the lab BMC image. + +## Upstream emulator and provenance + +| Item | Pin | +| --- | --- | +| Project | [DMTF Redfish-Interface-Emulator](https://github.com/DMTF/Redfish-Interface-Emulator), BSD-3-Clause | +| Version | Release `1.2.2` (2025-09-12), commit `5f51d8ac48e46665a2a85242434f125aa7b25172` | +| Source archive | `https://github.com/DMTF/Redfish-Interface-Emulator/archive/refs/tags/1.2.2.tar.gz`, SHA-256 `acee609abaedaf123b56e7ca5b2534da94bdee6fc1183dde72699c30d63de79f`, verified by `hack/redfish-lab/upstream.sh` before extraction | +| Python | `python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c` | +| Python packages | Exact versions with every PyPI file hash in `hack/redfish-lab/requirements.lock`, installed with `pip --require-hashes --no-deps` (Flask 2.3.3, Werkzeug 2.3.8, Flask-RESTful 0.3.10 and their dependencies). Upstream's `requirements.txt` lists names only. | +| libvirt client | Debian `libvirt-clients` from apt, used only by the adapter. This apt resolution is not reproducible, the same caveat as the site image. | + +The 1.2.2 release was 14 months old at integration and is the newest release. +The emulator tree is copied into the image **unmodified**. Configuration comes +from Fleet files: `emulator-config.json`, an infragen `populate-config.json` +with one chassis and two Systems, and `targets.json`. The image ID, its registry +digest and the archive provenance are recorded in `evidence/image-id` and +`evidence/redfish-upstream.json`. + +**No OpenStack component is used.** The image contains no Sushy, sushy-tools, +Ironic or VirtualBMC. The Fleet executor's Redfish client is built on gofish +([BMC client library](#bmc-client-library)). `hack/multiplane/test-redfish.py` +fails if any of these names appears in the lock file, adapter or image +definition. + +### What upstream provides and what the adapter adds + +Inspection of the 1.2.2 source found these limits: + +- `ComputerSystem.Reset` only rewrites an in-memory `PowerState`. +- A System PATCH accepts only `Name`, `HostName`, `AssetTag`, `SerialNumber` + and `UUID`, so it rejects `Boot`. +- `flask_httpauth` is listed but never used, and `AccountService` hard-codes + accounts. **No request is authenticated.** +- `DELETE /redfish/v1/reset` resets the whole emulator. + +The adapter is `hack/redfish-lab/fleet_lab_adapter.py`. It imports the upstream +`emulator` module into the same Flask process and registers request hooks; it +does not fork or patch upstream files. + +| Concern | Served by | +| --- | --- | +| Service root, Systems collection and members, Chassis, Managers, ActionInfo, routing and JSON serialization | Upstream, unmodified | +| HTTP Basic authentication against a mounted credential (the service root stays anonymous, per the Redfish specification) | Adapter | +| `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | +| `PowerState` read from libvirt on every System read | Adapter | +| `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | +| `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` set from the lab target | Adapter | +| Definition of the lab domains and the provisioning network, re-created with the same identity if the runtime loses them | Adapter | +| Append-only request audit: method, path, status, principal class, ResetType, boot override, effect and fault. It never records bodies or credentials. | Adapter | +| `DELETE /redfish/v1/reset` and non-Redfish paths | Refused by the adapter | +| Bounded, one-shot lab faults (`reject-auth`, `hide-reset`, `drop-response`) from a fault file | Adapter, lab only | + +`hack/redfish-lab/test_adapter.py` runs inside the built image, with the real +upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. + +## Topology on the selected cell + +```text + cell Flux layers (Redfish overlays of config/site) + fleet-site-runtime (privileged) fleet-site-bmc (unprivileged, all caps dropped) + libvirtd + QEMU TCG ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter + lab-target-a lab-target-b ▲ Redfish over HTTP, Basic auth + (persistent disks, serial capture) │ Service 10.96.0.81:8000 + │ firmware DHCP/iPXE (static) │ + ▼ │ + fleet-site-boot (journal read-only) kro worker Job (per handoff, Redfish only) + per-MAC chain, artifacts journal rw, boot evidence ro, + console capture ro, BMC credential +``` + +| Component | Owner | Holds | +| --- | --- | --- | +| `fleet-site-runtime` Deployment | Flux `fleet-site-services` (Redfish overlay) | libvirtd and QEMU; creates the two 2 GiB target disks once on the retained volume (`lab-disks`) and the console capture directory (`lab-console`) | +| `fleet-site-bmc` Deployment and Service (fixed ClusterIP `10.96.0.81`) | Flux `fleet-site-services` | The emulator and adapter; the libvirt socket, NVRAM and audit (`bmc-state`), and the credential Secret | +| `fleet-site-bmc` ServiceAccount | Flux `fleet-site-base` (Redfish overlay) | No API token | +| `fleet-site-bmc-credentials` Secret | Created by the harness in the `redfish-enroll` phase; in no source revision or Flux inventory | A synthetic username and a random 256-bit password per run | +| Boot service and observer | Flux, as before | The Redfish read-only provider; no credential | +| `w-` Job, ServiceAccount, Role, RoleBinding | kro, as before | The Redfish worker; **no libvirt socket**, no lab disks | + +Flux selects the overlays with the same source revision: in Redfish mode the +staged cell environment points `fleet-site-base`, `fleet-site-graph` and +`fleet-site-services` at `config/site/redfish/*`. Shared objects are still owned +by exactly one Flux layer, and kro still writes only per-operation objects. The +ownership audit covers the BMC Deployment, Service and ServiceAccount. + +### Lab targets: identity before allocation + +| Target | Redfish System | UUID | NIC MAC / lease | Fleet asset | Role | +| --- | --- | --- | --- | --- | --- | +| A | `System-1` | `7f3d0c2e-…-0a1b2c3d4e0a` | `52:54:00:77:01:0a` / `.10` | `…/Device/synthetic-device-central-01` | The only published capacity | +| B | `System-2` | `7f3d0c2e-…-0a1b2c3d4e0b` | `52:54:00:77:01:0b` / `.11` | `…/Device/synthetic-device-central-02` | Enrolled, never allocated; proves target isolation | + +The disks, domain UUIDs and MACs exist before any allocation. Each installation +or cleanup reuses target A's single persistent disk. The site enrollment is an +explicit asset-to-System mapping in the worker template, with the endpoint, +System Id, UUID, MAC, disk size and console capture name. The executor writes it +once into the journal directory and refuses a changed enrollment later. + +## Redfish executor contract + +`internal/redfish` implements `executor.Client` behind the unchanged +`LocalAssetMapping`, coordination and lifecycle code. It has no process +execution, libvirt client or lab dependency. A Go test parses its imports to +enforce this. `Open` refuses a `FLEET_LIBVIRT_URI` and a mounted +`/run/fleet-libvirt`, so a Redfish worker has no hypervisor fallback. + +**Discovery (GETs only).** The executor walks the service root to the Systems +collection and reads every member. Exactly one member must carry the enrolled +UUID, and it must have the enrolled Id. A member with the enrolled Id and +another UUID is a renumbered or swapped target and is refused. The reset target +and ActionInfo must belong to that System. `On`, `ForceOff`, `Pxe` and `Hdd` must +be advertised, and `Once` too when the System advertises its enabled values. It +never follows redirects or `@odata.id` paths outside `/redfish/v1`. A rejected +credential, a missing capability or an identity mismatch leaves the operation +`admitted`, Unknown and effect-free. + +**BMC client library.** See [BMC client library](#bmc-client-library) for +which requests go through gofish and which helpers are deliberately not used. + +**Exact inputs before effects.** The journal retains these before any Redfish +request, under the same lock and fencing rules as the libvirt provider: + +- the exact request and its digest; +- the enrolled target; +- a random receipt and boot capability, with a 20-minute boot window; +- allocation epoch, binding and fence. + +The discovered System is retained before the first effect. + +**Phases.** An install is a network-boot installer phase (`Pxe`) followed by a +disk-boot phase (`Hdd`). A cleanup is one network-boot wipe phase. Each phase +proceeds in order: + +1. Power off if needed. This is idempotent, because nothing of the phase has + booted. +2. Arm a one-time override and read it back. +3. Retain `-requested`, then `POST Reset On`. +4. Observe until the phase may have started. +5. Wait for the exact receipt and power off. + +**Lost responses and recovery.** HTTP success is never evidence. Any sign of a +boot is treated as "may have run", and the phase is never requested again: + +- power not `Off`; +- the one-time override consumed; +- a boot delivery for the operation; +- a receipt. + +A repeated `On` is sent only when the target is still `Off`, still armed and +silent after a 45-second settle window, within three retained attempts. + +**Completion.** A phase completes only with exactly one console line +`FLEET-INSTALLED:`, `FLEET-DISK-BOOT:` or +`FLEET-WIPED::`, and power `Off`. A second identical receipt +means a duplicate execution and fails rather than succeeding. The installer +phase also requires completed boot deliveries of the script, kernel and initrd; +boot admission then closes durably. Worker exit codes and the +Job/observer/management split are unchanged: +[exit 0 never implies readiness](site-execution.md#authority-and-failure-contract). + +**Cleanup uses a booted environment.** The wipe environment is the same pinned +kernel and initrd with `fleet.mode=wipe`. It zeroes the whole disk with `dd`, +drops caches, compares every byte with `/dev/zero` and only then prints its +receipt. The harness independently hashes target A's disk file as all zeroes +after the final cleanup. This is **logical test cleanup of a virtual disk, not +media sanitization**: it does not address SSD remapping, over-provisioning, HPA +or DCO areas, firmware caches or crypto-erase. + +## BMC client library + +`internal/redfish/client.go` uses +[gofish](https://github.com/stmcginnis/gofish) **v0.27.0** (2026-10-05, the +newest release at adoption, BSD-3-Clause, no transitive module dependencies). It +replaced the handwritten `net/http` request helper and the `map[string]any` +decoding of the service root, Systems collection and ComputerSystem. The +provider (`provider.go`) is unchanged: it still owns validation, the journal, +sequencing, recovery and results, and calls the same `Discover`, `Observe`, +`SetBootOnce` and `Reset` methods. + +**What gofish provides here:** + +- the HTTP client: basic authentication, JSON requests and Redfish error + decoding (`schemas.Error` status codes); +- typed `ComputerSystem` decoding: `Id`, `UUID`, `@odata.id`, `PowerState`, + the boot override and its target `AllowableValues`, and the ETag; +- Systems collection walking, including `Members@odata.nextLink` pages. The + previous client read only the first page, so a duplicate UUID on a later + page went unseen; discovery now reads every page, and a partially read + collection fails discovery. + +**What Fleet still does itself, and why:** + +- **Transport guard.** Every request passes a Fleet `RoundTripper`: the + configured scheme and host only, paths under `/redfish/v1` without `..`, no + query on a mutation, `OData-Version: 4.0`, and a 1 MiB response bound. A + link returned by the BMC cannot send the credential elsewhere. Redirects are + never followed. The environment proxy is not used, so the credential goes + only to the enrolled endpoint. TLS uses the system trust store; there is no + certificate pinning or private CA yet. The endpoint must still be a literal + `http(s)://IPv4:port`. +- **Identity and capability checks.** These are unchanged: one UUID match + across all members with the enrolled Id, a reset target and ActionInfo on + that System, and `On`, `ForceOff`, `Pxe`, `Hdd` and `Once` checked against + advertised values. +- **ActionInfo and Reset annotations.** gofish keeps the reset target, the + ActionInfo link and the `BootSourceOverrideEnabled` allowable values in + unexported fields, so Fleet reads them from the System's raw JSON. + ActionInfo is decoded leniently: gofish's typed `ActionInfo` rejects the + DMTF emulator 1.2.2 document, whose `"Required": "true"` is a string. +- **Error classification.** Errors collapse to credential rejected, + unsupported, identity, precondition failed, HTTP status, or + transport/unreadable response. They never carry a URL, header or response + body. +- **Mutations.** Each is exactly one request, issued through gofish's raw + `PatchWithHeaders` and `PostWithHeaders`. Audited gofish helpers that are + **not** used: + - `ComputerSystem.SetBoot` sends a second PATCH to the `@Redfish.Settings` + resource when the first fails, which could be a lost response. + - `ComputerSystem.Reset` (via `PostWithTask`) resends without `If-Match` + after a 412. + - Sessions (`CreateSession`) would be a BMC mutation with its own lifetime + and cleanup. Basic authentication is used instead, as before. + + The boot override PATCH now carries `If-Match` with the ETag observed + immediately before it, when the BMC returns one. A 412 is reported as + `ErrPrecondition` and not retried. The operation stays Unknown before the + boot is requested, and the next attempt re-observes and re-arms; this is + pre-boot and idempotent, as before. Reset POSTs carry no `If-Match`. A 202 + task monitor is not followed: power and boot state are observed, as before. + +**bmclib was evaluated and not adopted.** bmclib v2.3.5 (2026-03-22, the +newest release) was rejected for these reasons: + +- It pins gofish v0.20.0, whose API is incompatible with v0.27.0, so both + libraries cannot be used together. +- Its Redfish provider selects a System by index or name, not by UUID. +- Its `SystemBootDeviceSet` retries a failed PATCH with fewer fields. +- `SystemPowerOn` skips the request when the System already reports `On`. + This is incompatible with Fleet's recorded-request recovery. +- Its `bmc` power facade tries the next provider after an error. + +Its vendor providers (Dell, Supermicro, ASRockRack, OpenBMC, IPMI) target BIOS, +firmware and virtual-media work that this executor does not perform. **No +vendor-specific compatibility is added by this change.** It reuses a +maintained Redfish client and schema model. It also fixes collection paging +and adds `If-Match` on the boot override. + +**Known compatibility risks to qualify:** + +- **Strict decoding.** gofish decodes the whole ComputerSystem strictly. A + vendor property with an off-schema type fails discovery and observation as + "unreadable response", with no effect issued. The emulator's System decodes + cleanly. +- **`If-Match` rejection.** gofish documents that some BMCs reject `If-Match` + on some endpoints, for example Dell iDRAC10. On such a BMC arming fails + visibly as Unknown instead of sending an unconditional PATCH. Changing that + is a per-vendor decision for qualification. + +## Synthetic credentials and networking + +These are documented lab seams, not production designs: + +- **Credential.** HTTP Basic over plain HTTP on the cell network, with one + synthetic per-run credential shared by the adapter (server side) and Redfish + workers (client side). There is no TLS, rotation, vault or per-BMC account. + The Secret is never in Git, a source revision or evidence. The harness keeps + the password in a `.token` file so the evidence secret scan covers it. Worker + and harness logs print outcome classes only. +- **Provisioning network.** The adapter defines one static libvirt network. + dnsmasq gives each enrolled MAC a fixed address and the same boot file. That + iPXE script chains to `/pxe/${net0/mac:hexhyp}/boot.ipxe`. The boot service + serves a script only to the MAC of a retained operation with open admission. + The MAC is routing information, not authentication: a peer on this network + could impersonate it during the window, and the capability URLs travel in + clear. +- **Receipts.** The worker reads the target's serial-console capture read-only, + as a stand-in for serial-over-LAN or an installer callback. It is observation, + not control. +- **Admission.** The Redfish overlay's admission policy limits kro worker Jobs + to the journal claim, `emptyDir` and the BMC credential. It denies a + `libvirt*` subPath, `/run/fleet-libvirt` or lab-disk mount and a + `FLEET_LIBVIRT_URI`, and requires `FLEET_SITE_PROVIDER=redfish`. The `rbac` + phase proves each denial as kro's identity, and evidence re-checks every real + worker Job spec. + +## Acceptance phases + +`hack/multiplane/acceptance-redfish.sh` runs every scenario of the +[libvirt-mode sequence](multiplane.md#acceptance-phases) through the same +federation and kro path, with these differences. + +**Before topology:** + +- `bmc-upstream` fetches and verifies the pinned archive; +- `bmc-image` builds the lab BMC image; +- `bmc-self-test` runs the adapter self-test with no network. + +**Before Flux installs the shared services:** `redfish-enroll` creates the +synthetic credential Secret. + +**Redfish phases:** + +| Phase | What it proves | +| --- | --- | +| `redfish-baseline` | Both target disks exist and neither target was ever started; records target B's disk digest | +| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. The BMC audit shows only GETs in the window. | +| `redfish-bmc-interrupt` | As soon as the installer is running, the BMC Pod is force-deleted and replaced. The guest keeps running; the worker tolerates a bounded BMC outage. | +| `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | +| `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | +| `resume` | The recreated Job completes the exact operation with one succeeded Pod | +| `install-b` | After verified cleanup and reuse, consumer B installs on the same physical target in epoch 2 with a new receipt | +| `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | +| `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | + +The final `evidence` phase adds these independent checks in Redfish mode: + +- **Console.** Target A's console holds exactly one receipt line per boot, in + operation order: install, disk boot, wipe, install, disk boot, wipe. +- **QEMU.** libvirt's append-only log shows exactly six starts of target A, in + the boot order network, disk, network, network, disk, network (read from + `bootindex`), and none of target B. +- **BMC audit.** Exactly six effective `On` requests, all to System-1, of which + exactly one carried the lost-response fault. +- **Kubernetes and admission.** Every worker Job selects the Redfish provider + with no hypervisor mount or URI, and the admission probes denied each + hypervisor path. + +Redfish-specific evidence files are `redfish-upstream.json`, +`redfish-enrollment.json` (no password), `redfish-discovery-faults.json`, +`redfish-lost-response.json`, `redfish-bmc-interrupt.json`, +`redfish-isolation.json` and `redfish-audit.jsonl`. `summary.json` records the +`physicalHardware`, `physicalBMC`, `vendorRedfishQualified`, `bmcTLS` and +`mediaSanitization` flags as `false`. + +## Offline checks + +```sh +go test -race -count=1 ./internal/redfish ./cmd/fleet-multiplane ./internal/multiplane +task multiplane:test-harness # includes hack/multiplane/test-redfish.py +``` + +The Go tests use a fake BMC whose fake guest fetches its script and artifacts +from the real boot handler and writes console receipts. They cover: + +- install, disk boot, cleanup and reuse; +- exact replay; +- a rejected credential, unsupported reset and renumbered or swapped UUIDs, + each with no effect; +- a lost response after the effect, recovered without a repeat; +- a lost request repeated exactly once; +- duplicate receipts and identity change failing; +- changed-retry conflict, stale-epoch fencing and an unenrolled asset; +- journal-lock exclusion; +- boot scoping by MAC, capability, admission and fence; +- refusal of libvirt configuration, and the import-graph guard. + +`client_test.go` covers the gofish-backed client against a recording stub: + +- discovery across a paged Systems collection; +- a duplicate UUID on a later page refused; +- an unreadable, rejected, foreign or cross-host member refused, with no + mutation; +- a reset target or ActionInfo off the System, or no `Once`, refused; +- an oversized response refused; +- the boot override sent as one PATCH with the observed `If-Match`; +- a 412 or 500 not retried and never redirected to the Settings resource; +- a Reset that gets 412, 503 or no response before the timeout sent exactly + once, without `If-Match` or a session; +- an untrusted TLS certificate refused; +- no environment proxy; +- no credential, response body or endpoint in any error. + +The provider's fake BMC serves the emulator's string `"Required"` in +ActionInfo. + +`test-redfish.py` renders the overlays and a staged Redfish revision with +kustomize and checks the following: + +- worker mounts and environment; +- privilege and socket holders; +- enrollment matching `targets.json`; +- variable substitution; +- phase coverage; +- that no fault hook appears in `internal/redfish`; +- source pins, and no OpenStack dependency. + +## Execution record + +### Attempts before the first pass (2026-11-16) + +Every attempt below was a fresh topology owned by this task. Each failure was +inspected from its retained private state, including the stopped cell node's +volume read with `docker cp` and no restart. Each was then discarded with +`teardown.sh --discard-unknown`, which is **not release evidence**. No Unknown +operation was reset or declared ready. + +1. **`fleet-mp-8a37c720`** failed in `milo-bootstrap`, before any allocation or + effect. The new `$state/provider` mode marker collided with the Milo provider + project's credential directory. The marker is now `$state/site-provider`, and + `test-redfish.py` guards it. +2. **`fleet-mp-24371388`** failed in `interrupt-pod` after 37 phases had passed, + including discovery faults and lost-response recovery on the installer `On`. + The real PXE install (one network start, one `On`, an exact receipt) took + about 47 seconds, which left no window for the worker interruptions. The BMC + interruption now runs as soon as the installer starts, and the lost-response + fault targets the disk-boot `On`. +3. **`fleet-mp-052586a6`** failed in `release` after 50 phases. The wipe + environment zeroed the disk, but `cmp -n 2147483648` was rejected (`not in + 0..2147483647`). The guest therefore printed no receipt and powered off, and + the worker kept the cleanup Unknown and retried without inferring success. +4. **`fleet-mp-90c15839`** failed the same way. The chunked `cmp -i` fix had been + tested with GNU `cmp`, but the guest's static BusyBox shell runs its own + applets first, and BusyBox `cmp` has no `-i`. The verifier now calls + `/bin/busybox cmp -n 1GiB … SKIP1 0` per chunk, tested against Debian's + BusyBox 1.35 for a clean disk and for a dirty byte in either GiB. Again no + receipt was printed and the cleanup stayed Unknown. +5. A launch exited 2 in preflight, with 11.6 GiB free against the 12 GiB gate, + and created nothing. Teardown had not removed the new BMC image tags. It now + does, and `test-redfish.py` checks it. This task's leftover BMC tags and + unused build cache were removed. +6. **`fleet-mp-836a521e`** failed in `delivery-faults` after 54 phases. The + booted wipe cleanup, release projection and reuse had passed. Three fault + Jobs started together, and one worker's `redfish.Open` lost the non-blocking + journal lock while recording the enrollment, exiting 1 before validating its + delivered authority. Its retry then failed by policy with 65. Enrollment is + now retained by an atomic create-by-link and an unlocked compare, and a Go + test opens eight workers concurrently while another holds the journal lock. + No effect was issued for any fault handoff. + +7. **`fleet-mp-f7008e93`** failed in `flux-bootstrap-hub`, before any fixture or + effect. The hub node's pulls of the digest-pinned Flux controller images from + `ghcr.io` hit `DeadlineExceeded`, a transient external network failure. The + stopped hub node was started only to read its Pod events. + +8. **`fleet-mp-17555913`** failed in `redfish-bmc-interrupt` after 33 phases. Run + right after dispatch, the step read the journal before the first worker had + created it, and treated the absent file as fatal. The wait now treats an + absent journal as not yet started. The install was in flight when the run + stopped; its custody was Unknown. + +9. **`fleet-mp-5c4ce7c2`** passed 62 of 63 phases, including every Redfish, + federation, Flux, release, reuse, reinstall and isolation phase. Target B + never started and its disk digest was unchanged, and target A's disk hashed + as all zeroes after six boots and twelve Redfish effects. It failed in the + final `evidence` phase: a reworded `redfish-baseline` message no longer + matched its evidence marker. `test-redfish.py` now checks that every + Redfish evidence marker is printed by a phase. This run is not counted as a + pass. + +Attempts 1 to 4 used the original `net/http` client; attempts 6 to 9 used the +gofish client. + +### Fresh pass (2026-11-16) + +`FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh --redfish` (the command +behind `task multiplane:redfish-acceptance`) exited 0, with the readiness test +gate enabled, which includes `./internal/redfish`. Run details: + +- state `/tmp/fleet-multiplane.NryZRD`, prefix `fleet-mp-34dd4bcc`; +- all 65 bounded phases passed in 34 minutes (22:20 to 22:54 UTC); +- SHA-256 of `source-SHA256SUMS` (177 entries): + `6409311d0af13cdffeb09333b3ef7822c25b296b20ed4c06214349c5e9ee0963`; +- site binary `f0ddaf41…`, host binary `b43045e0…`; both use the gofish client; +- site image `sha256:d8e874680f7ee6f047a0cf03f85b25270ec13df1f381448b8c2f7dd5e1e3c24b`; +- lab BMC image `sha256:e4cd737b991570b8f2e6ac373ada523b18bafbd560bebca466851017fdbc0f55`; +- both pulled by the cell by registry digest; +- seven Flux source revisions from the dirty checkout at HEAD `d7ff793b`. + +After the run, `teardown.sh` was changed to also delete the run's synthetic BMC +credential file after a pass, and `test-redfish.py` gained checks for that. +This run's teardown had removed every container, cluster and image tag but left +that file, which was deleted by hand. No other fingerprinted file changed. + +Only `evidence/` is shareable. It holds `summary.json`, `result.json`, +`phases.jsonl`, the `redfish-*.json` files, `redfish-audit.jsonl` and the files +listed for the multi-plane harness. The facts below come from that evidence. + +- **Upstream and authentication.** The pinned emulator archive was verified, + and the image self-test passed. Live discovery through the production client + found `System-1` and `System-2` exactly. A wrong credential exited 10, the + swapped and unknown UUIDs exited 12, and an injected unadvertised `On` exited + 11. Those 38 requests were GETs only, one of them rejected. +- **Install with interruptions.** The BMC Pod was force-deleted at + `installer-started` and replaced while the guest kept running. The worker Pod + was then force-deleted, and the Job controller replaced it. The Job was + deleted mid-installer, and kro recreated it. +- **Lost response.** The disk-boot `On` took effect, but its response was + withheld for 45 seconds. The worker exited 75. Its replacement observed the + consumed override and powered target and did not repeat the `On` + (`powerOnRequests` = one installer and one disk request). +- **Partition and federation.** As in the libvirt mode, partition kept public + Ready False with the Job Complete. Heal, idempotent install and lifecycle + recreation passed. Graph lifecycle, drift repair, controller restart, + fail-closed and retention passed with the BMC included in the ownership + audit. Nine reflection faults were rejected. +- **Cleanup and reuse.** Consumer A's cleanup PXE-booted the wipe environment. + Consumer B reused the target in epoch 2, installed on it with a new receipt, + and was cleaned the same way. Release projection was verified for both. +- **Delivery faults.** The duplicate, wrong-cell and stale-epoch deliveries each + failed once with exit 65 by `podFailurePolicy`, with the journal unchanged, + and kro pruned them. Wrong location was denied with free capacity. +- **Closed boot.** 24 live HTTP denials covered the closed per-MAC scripts and + capabilities of all four operations, target B's MAC and unknown identities. +- **Independent checks.** + - Target A's console held exactly one receipt per boot in operation order. + - libvirt logged six target A starts: network, disk, network, network, disk, + network. + - The BMC audit shows exactly twelve effects, all to System-1: six one-time + overrides and six effective `On` requests, one of them faulted. + - Target B had no start, no console line, no effect and an unchanged disk + digest. Target A's disk hashed as all zeroes. + - All four worker Jobs, created by kro, selected the Redfish provider with no + libvirt mount or URI. + - Admission denied the libvirt socket, lab disk, libvirt URI, libvirt-provider + and foreign-Secret worker shapes, and admitted the Redfish worker shape. +- **Memory, secrets and teardown.** There were zero OOM kills. 40 evidence files + were clean against 27 retained secrets, including the BMC password. Teardown + removed every `fleet-mp-34dd4bcc` container, cluster and image tag, and + restored inotify to 128. + +This proves the composed pipeline against an emulator and lab VMs. It is not +an independent review, and it does not qualify any physical BMC or server. + +### Repeat pass (2026-11-17) + +The same command was rerun on a fresh topology and exited 0. Run details: + +- state `/tmp/fleet-multiplane.MF4gq9`, prefix `fleet-mp-717e7e96`; +- all 65 bounded phases passed in 34 minutes (23:53 to 00:27 UTC); +- SHA-256 of `source-SHA256SUMS` (177 entries): + `c560df28646c1fe2f9b5315886ffe0f9a12fca20c6703c8af10be849ac850023`; +- site binary `f0ddaf41…` and host binary `b43045e0…`, identical to the first + pass, so the executor and its gofish client are unchanged; +- site image `sha256:b484df32c64072896d019e38ed31d065daeb3d9a1d775fc47a5a6681111a6dc4`; +- lab BMC image `sha256:10b8bbb739a4288e734b3a515adb2a92c8fbd1c3170b9ebeab5fc0d74568e935`. + +The evidence shows the following: + +- **Discovery probes.** They matched the first pass: both Systems were found, + with ResetTypes read from the emulator's ActionInfo. The probes exited 10, + 12, 12 and 11 for the injected faults, with no effect. +- **Lost response.** The lost disk-boot `On` was recovered without a repeat + (`powerOnRequests` = one installer and one disk request). +- **Isolation.** Target B received no effect, and target A's disk hashed as + all zeroes. +- **BMC audit.** It recorded 589 GET 200, 6 PATCH 200, 6 POST 204 and one GET + 401. There were no 412 or 5xx responses and no session creation. The + emulator sends no ETag, so `If-Match` was not exercised. +- **Teardown.** This time teardown itself removed the synthetic BMC + credential file and left no containers. + +Physical hardware, physical BMC, vendor Redfish, BMC TLS and media +sanitization all remain `false` in `summary.json`. + +## Limitations and physical-hardware readiness + +These differences from physical hardware are known and **not** addressed by this +MVP. They are listed as an explicit qualification checklist: + +1. **Real BMC.** Qualify the executor against at least one vendor Redfish + implementation. Check ActionInfo and inline `AllowableValues`, the actual + reset semantics (some BMCs reject `On` while on, or report `PoweringOn`), and + whether `Once` overrides are consumed at POST. Check ETag/`If-Match` + behavior on the boot override PATCH (a 412 is never retried + unconditionally), strict gofish decoding of the vendor's ComputerSystem, + session (`X-Auth-Token`) authentication and rate limits. +2. **UEFI.** Only legacy BIOS (SeaBIOS) PXE is exercised. Verify + `BootSourceOverrideMode`, UEFI PXE or HTTP boot, Secure Boot policy and boot + order persistence. +3. **Receipts.** Replace the read-only console capture with serial-over-LAN or + an authenticated installer callback, and decide its trust model. +4. **Credentials and transport.** TLS with pinned CA or certificate, per-BMC + accounts, a credential broker so workers never hold a long-lived password, + and rotation and revocation. +5. **Provisioning network.** Integrate with the networking/IPAM owner: per-host + DHCP or a dedicated provisioning VLAN, and authentication beyond MAC. +6. **Cleanup assurance.** Use vendor or NIST SP 800-88 sanitization (secure + erase, crypto-erase, sanitize commands) with verifiable device evidence. + Distinguish it from this logical overwrite. +7. **Power semantics.** Physical power transitions take longer, may fail and may + report intermediate states. Revisit the settle window, the outage tolerance + and the three-attempt `On` budget. Revisit installer and disk-boot power-off + as the completion signal; a real OS reboots and keeps running. +8. **Fencing and journal.** One site journal fences all targets with one + allocatable target. Per-asset fencing, journal durability and HA are not + designed. Never reset the journal of a retained target + ([known limitations](multiplane.md#known-limitations-of-the-local-mvp)). +9. **Enrollment.** The asset-to-System mapping is a static source value. + Enrollment trust, BMC discovery and attestation of the System identity + (beyond Id and UUID) are open. +10. **Operator recovery.** Unknown operations, for example a power-off without + a receipt or an exhausted `On` budget, have no automated resolution. The + only recovery is to discard the disposable topology after inspection. + +The existing local-MVP limitations also apply: single node, trusted graph and +service authors, and no image upgrade lifecycle. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 0bf57f76..440a417d 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -359,7 +359,8 @@ container and is unchanged. | Pod/Job lifecycle not changing journal, guest or allocation | Implemented and exercised | | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | -| Redfish/BMC execution Jobs | Not implemented | +| Redfish execution Jobs with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md) for its run record | +| Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | ## Independent review of the recorded run diff --git a/go.mod b/go.mod index 4842e0f4..13bb3a0b 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module go.datum.net/fleet go 1.26.4 require ( + github.com/stmcginnis/gofish v0.27.0 go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524 go.miloapis.com/milo v0.32.5 go.yaml.in/yaml/v3 v3.0.4 diff --git a/go.sum b/go.sum index 38d6778d..2ba69aae 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,8 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stmcginnis/gofish v0.27.0 h1:jyM2BlBhULXtHnayY+/wnkZYXKjIO0ZdR3oBXKl1VYs= +github.com/stmcginnis/gofish v0.27.0/go.mod h1:PzF5i8ecRG9A2ol8XT64npKUunyraJ+7t0kYMpQAtqU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= diff --git a/hack/local-vm/init b/hack/local-vm/init index fce1814a..a4303d6b 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -9,8 +9,31 @@ set -exo pipefail modprobe virtio_pci modprobe virtio_blk modprobe ext4 -for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; esac; done +mode=install +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; esac; done [ ${#receipt} = 64 ] || /bin/busybox poweroff -f +if [ "$mode" = wipe ]; then + # Redfish-mode cleanup environment: zero the whole disk, then verify by + # reading it back. The receipt is printed only after the readback compared + # equal. This is a logical overwrite of a virtual disk, not media sanitization. + trap '/bin/busybox poweroff -f' EXIT + size=$(($(cat /sys/block/vda/size) * 512)) + dd if=/dev/zero of=/dev/vda bs=4M count=$((size / 4194304)) conv=fsync + sync + echo 3 > /proc/sys/vm/drop_caches + # This static BusyBox shell runs its own applets first. BusyBox cmp limits -n + # to INT_MAX and takes skips positionally: compare 1 GiB chunks at offsets. + off=0 + while [ "$off" -lt "$size" ]; do + n=$((size - off)); [ "$n" -le 1073741824 ] || n=1073741824 + /bin/busybox cmp -n "$n" /dev/vda /dev/zero "$off" 0 || exit 1 + off=$((off + n)) + done + printf 'FLEET-WIPED:%s:%s\n' "$receipt" "$size" + sync + exit 0 +fi +[ "$mode" = install ] || /bin/busybox poweroff -f printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda mkfs.ext4 -F /dev/vda1 mkdir -p /target diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index 2d71dd70..3f85135c 100755 --- a/hack/local-vm/site-runtime +++ b/hack/local-vm/site-runtime @@ -17,6 +17,15 @@ iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN iptables -t mangle -A FLEET-PXE -j DROP iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE +if [ "${FLEET_SITE_PROVIDER:-libvirt}" = redfish ]; then + # Redfish mode: persistent lab targets. Their disks are created once on the + # retained volume and never recreated; the lab BMC adapter defines the + # domains and the provisioning network through this daemon's socket. + mkdir -p /var/lib/fleet-lab/disks /var/lib/fleet-lab-console + for t in target-a target-b; do + [ -e "/var/lib/fleet-lab/disks/$t.raw" ] || truncate -s 2G "/var/lib/fleet-lab/disks/$t.raw" + done +fi virtlogd --daemon virtlockd --daemon exec /usr/bin/tini -- libvirtd diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh new file mode 100755 index 00000000..8dc89273 --- /dev/null +++ b/hack/multiplane/acceptance-redfish.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Ordered Redfish-mode acceptance phases (run.sh --redfish). The same +# allocator, installation, Karmada, kro and Flux path as acceptance.sh; the +# site worker drives lab targets only through the DMTF Redfish emulator. +# Each phase is bounded and recorded; the first failure stops the run. +set -euo pipefail +umask 077 +state=${1:?private state directory} +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_SITE_PROVIDER=redfish +host="$state/fleet-multiplane-host" +ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } +rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } +flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } + +ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +rf baseline 300 +rf discovery-faults 600 +ph allocate 900 "$host" allocate --config "$state/acceptance.json" +step verify-contention 120 +ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" +step await-delivery 300 +rf arm-lost-response 120 +step partition 300 +step dispatch 900 +rf bmc-interrupt 600 +step interrupt-pod 1200 +step interrupt-job 600 +rf lost-response 1200 +step resume 2400 +step worker-rbac 120 +step partition-readiness 900 +step heal 1200 +ph install 900 "$host" install --config "$state/acceptance.json" +ph install-repeat 900 "$host" install --config "$state/acceptance.json" +step lifecycle 900 +flux graph-lifecycle 1200 +flux drift 900 +flux restart 1200 +flux fail-closed 1500 +flux retention 1500 +ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" +ph release 2400 "$host" release --config "$state/acceptance.json" +step release-status-a 120 +ph reuse 900 "$host" reuse --config "$state/acceptance.json" +step reuse-status 120 +step delivery-faults 900 +ph install-b 2400 "$host" install-b --config "$state/acceptance.json" +ph release-b 2400 "$host" release-b --config "$state/acceptance.json" +step release-status-b 120 +step wrong-location 300 +step boot-denials 300 +step flux-final 900 +rf isolation 600 +ph evidence 600 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 95c96ee5..8d18e0b6 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -18,6 +18,7 @@ prefix = (s / 'prefix').read_text().strip() ev = s / 'evidence' os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' +REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' def out(*args): @@ -81,6 +82,11 @@ def copy_out(source, destination): 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in ( 'wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing')) +if REDFISH: + markers += ('bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified', 'bmc-self-test: upstream emulator and lab adapter self-test passed', + 'redfish-enroll: synthetic BMC credential Secret created', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', + 'redfish-lost-response: On took effect but its response was lost', 'redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install', + 'install-b: verified', 'redfish-isolation: target B never started') for marker in markers: if marker not in phases: fail('missing acceptance phase: ' + marker) @@ -155,7 +161,90 @@ def libvirt_provider(): return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials -ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = libvirt_provider() +def redfish_provider(): + """Redfish mode: the persistent lab target A carries every operation. + Independent of the journal, its serial console proves one exact receipt + per boot, libvirt's QEMU log proves the boot order and count, the BMC + audit proves one On per boot, and target B never ran.""" + raw.mkdir(mode=0o700, exist_ok=True) + copy_out('/var/lib/fleet-local', raw) + copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') + copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') + copy_out('/var/lib/fleet-lab-console', raw / 'lab-console') + j = json.loads((raw / 'journal.json').read_text()) + ops = sorted(j['operations'].values(), key=lambda o: o['result']['createdAt']) + installs = [o for o in ops if o['request']['kind'] == 'install'] + cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] + if j.get('provider') != 'redfish' or len(installs) != 2 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): + fail('expected the Redfish provider, two installs and two verified cleanups') + if [o['request']['kind'] for o in ops] != ['install', 'cleanup', 'install', 'cleanup'] or not j.get('closed'): + fail('expected install, cleanup, reinstall, cleanup with the final epoch closed') + epochs = sorted({o['request']['epoch'] for o in ops}) + if epochs != [1, 2]: + fail('expected allocation epochs 1 and 2, got %s' % epochs) + enrolled = json.loads((raw / 'enrollment.json').read_text()) + a = next(t for t in enrolled['targets'] if t['systemID'] == 'System-1') + for o in ops: + if o['target'] != a or o['system']['path'] != '/redfish/v1/Systems/System-1' or o['system']['uuid'] != a['systemUUID'] or not o.get('bootClosed'): + fail('an operation did not retain the exact enrolled target A System with closed boot admission') + interrupt = json.loads((ev / 'interrupt.json').read_text()) + if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: + fail('interrupt evidence does not identify the retained install operation mid-installer') + console = [l.strip() for l in (raw / 'lab-console' / 'target-a.log').read_text(errors='replace').splitlines()] + expected, receipts = [], [] + for o in ops: + want = ['FLEET-INSTALLED:' + o['receipt'], 'FLEET-DISK-BOOT:' + o['receipt']] if o['request']['kind'] == 'install' else ['FLEET-WIPED:%s:%d' % (o['receipt'], a['diskBytes'])] + for line in want: + if console.count(line) != 1: + fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['request']['kind'])) + expected.append(console.index(line)) + receipts.append({'operation': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], + 'receipts': [line.split(':')[0] for line in want], 'receiptSHA256': hashlib.sha256(o['receipt'].encode()).hexdigest()}) + log = raw / 'boot-evidence' / hashlib.sha256(o['request']['id'].encode()).hexdigest() / 'boot-delivery.log' + written = log.read_text() if log.exists() else '' + for name in ('boot.ipxe', 'kernel', 'installer.gz'): + if 'write-complete ' + name + ' bytes=' not in written: + fail('missing completed boot delivery of %s for %s' % (name, o['request']['kind'])) + if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): + fail('console receipts are out of order or include another operation') + if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 2: + fail('the installer partitioned the target disk other than once per install') + qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') + blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] + def network(block): + return any(a['mac'] in seg and ('"bootindex":1' in seg or 'bootindex=1' in seg) for seg in re.split(r'\s-device\s', block)) + order = ['network' if network(b) else 'disk' for b in blocks] + starts = {'targetA': order, 'targetB': (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').read_text(errors='replace').count(': starting up ') + if (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').exists() else 0} + if order != ['network', 'disk', 'network', 'network', 'disk', 'network'] or starts['targetB']: + fail('expected target A boots network, disk, network, network, disk, network and no target B start; got %s' % starts) + audit = [json.loads(l) for l in (ev / 'redfish-audit.jsonl').read_text().splitlines()] + effects = [e for e in audit if e['method'] not in ('GET', 'HEAD')] + ons = [e for e in effects if e.get('resetType') == 'On'] + if len(ons) != 6 or any(not e.get('effect', '').startswith('started') for e in ons) or any('/System-1' not in e['path'] for e in effects): + fail('expected exactly six effective On requests, all to System-1, and no other target effect') + if sum(1 for e in ons if e.get('fault') == 'drop-response-after-effect') != 1: + fail('the lost-response fault did not fire exactly once') + if runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--name').strip(): + fail('a lab target is still running') + admission = json.loads((ev / 'kro-rbac.json').read_text())['admission'] + for case in ('Redfish worker mounting the libvirt socket', 'Redfish worker mounting the lab disks', 'Redfish worker with a libvirt URI', 'worker selecting the libvirt provider'): + if admission.get(case, {}).get('deniedBy') != 'ValidatingAdmissionPolicy': + fail('kro admission did not deny: ' + case) + if not admission.get('Redfish worker Job with the BMC credential', {}).get('admitted'): + fail('kro admission did not admit the Redfish worker shape') + for name in ('redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', 'redfish-bmc-interrupt.json', 'redfish-isolation.json'): + if not (ev / name).exists(): + fail('missing Redfish evidence ' + name) + denials = (s / 'boot-denials.txt').read_text().strip() if (s / 'boot-denials.txt').exists() else '' + if not denials.startswith('PASS'): + fail('missing live closed-boot HTTP denial evidence') + starts['redfishEffects'] = [{k: e.get(k) for k in ('method', 'path', 'status', 'resetType', 'boot', 'effect', 'fault')} for e in effects] + return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + + +raw = s / 'provider-private' +ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = (redfish_provider if REDFISH else libvirt_provider)() # Kubernetes execution: what actually ran, as names, UIDs, phases and conditions. kro = kget('-n', 'kro-system', 'get', 'deployment')['items'] @@ -182,7 +271,17 @@ def libvirt_provider(): 'serviceAccount': job['spec']['template']['spec']['serviceAccountName'], 'podReplacementPolicy': job['spec'].get('podReplacementPolicy'), 'podFailurePolicy': job['spec'].get('podFailurePolicy'), 'backoffLimit': job['spec'].get('backoffLimit'), 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id')}) -if sorted(j['kind'] for j in worker_jobs) != ['cleanup', 'cleanup', 'install'] or any(j['createdBy'] != 'workers' for j in worker_jobs): +if REDFISH: + # Every Redfish worker that ran: Redfish provider, no hypervisor path. + for job in jobs: + pod = job['spec']['template']['spec'] + c = pod['containers'][0] + env = {e['name']: e.get('value') for e in c.get('env', [])} + mounts = [m.get('subPath', '') + ':' + m['mountPath'] for m in c.get('volumeMounts', [])] + if env.get('FLEET_SITE_PROVIDER') != 'redfish' or 'FLEET_LIBVIRT_URI' in env or any('libvirt' in m or 'lab-disks' in m for m in mounts) or any('hostPath' in v for v in pod.get('volumes', [])): + fail('a Redfish worker Job had a hypervisor path: ' + job['metadata']['name']) +expected_jobs = ['cleanup', 'cleanup', 'install', 'install'] if REDFISH else ['cleanup', 'cleanup', 'install'] +if sorted(j['kind'] for j in worker_jobs) != expected_jobs or any(j['createdBy'] != 'workers' for j in worker_jobs): fail('expected kro-created worker Jobs for exactly one install and two cleanups, got %s' % [(j['kind'], j['createdBy']) for j in worker_jobs]) pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') pv = kget('get', 'pv', pvc['spec']['volumeName']) @@ -212,7 +311,7 @@ def libvirt_provider(): } if execution['kro']['helmReleaseOwner'] != 'kro': fail('kro controller is not owned by the Flux HelmRelease') -if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime']) or any( +if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime'] + (['fleet-site-bmc'] if REDFISH else [])) or any( d['availableReplicas'] != 1 or d['fluxLayer'] != 'fleet-site-services' or d['kroLabels'] for d in deployments.values()): fail('site volume or Flux-owned shared Deployments not as expected') (ev / 'kubernetes-execution.json').write_text(json.dumps(execution, indent=2, sort_keys=True) + '\n') @@ -266,11 +365,27 @@ def libvirt_provider(): 'reflection faults injected with bootstrap credentials while the Karmada controller is stopped'], 'privateArtifacts': 'state directory outside evidence/ contains authority; do not publish', } +if REDFISH: + summary['qualification'].update(redfishExecutor=True, dmtfRedfishInterfaceEmulator='1.2.2 (unmodified) + lab-only libvirt adapter', bootedCleanupEnvironment=True, + physicalHardware=False, physicalBMC=False, vendorRedfishQualified=False, bmcTLS=False, mediaSanitization=False) + summary['scenarios']['cleanupAndReuse'] = {'epochs': epochs, 'installs': len(installs), 'cleanups': len(cleanups), 'reinstallOnReusedTarget': True, + 'cleanup': 'PXE-booted wipe environment zeroed and read back the whole 2 GiB virtual disk; the harness hashed the disk file as all zeroes. Logical test cleanup, not media sanitization.'} + summary['scenarios']['redfish'] = {'evidence': ['redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', + 'redfish-bmc-interrupt.json', 'redfish-isolation.json', 'redfish-audit.jsonl'], + 'bootOrderTargetA': starts['targetA'], 'targetBStarts': starts['targetB'], 'effects': starts['redfishEffects']} + summary['seams'] = [x for x in summary['seams'] if 'root libvirtd' not in x] + [ + 'DMTF Redfish Interface Emulator with a lab-only adapter in place of a physical BMC; libvirt/QEMU TCG VMs in place of servers', + 'plain-HTTP Basic authentication with a synthetic per-run credential Secret enrolled by the harness (no TLS, rotation or vault)', + 'static lab provisioning network (libvirt dnsmasq) with MAC-chained iPXE; MAC is routing, not authentication', + 'installation receipts read from a read-only serial-console capture (stand-in for SOL or an installer callback)', + 'trusted graph authors: worker Jobs hold the synthetic BMC credential; only the runtime and the lab BMC hold the libvirt socket', + 'one site journal fences every lab target (one allocatable target)'] (ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') for name in ('source-SHA256SUMS', 'sysctl.json'): if (s / name).exists(): (ev / name).write_text((s / name).read_text()) paths = [s / 'site-bin' / 'fleet-multiplane', s / 'fleet-multiplane-host'] (ev / 'binary-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest() + ' ' + p.name + '\n' for p in paths)) -(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n') +(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n' + ( + 'bmc image ' + out('docker', 'image', 'inspect', prefix + '-bmc-image', '--format', '{{.Id}}').strip() + '\nbmc registry digest ' + write_env['bmcImageDigest'] + '\n' if REDFISH else '')) print('evidence: sanitized summary ' + str(ev / 'summary.json')) diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 30bac12f..1766e672 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -87,11 +87,19 @@ ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base', ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base'} # Exact inventories of the layers that must hold nothing else. -SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') +# Site provider: libvirt (default) or redfish, from run.sh --provider. Redfish +# mode selects the config/site/redfish overlays and adds the Flux-owned lab BMC. +PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') +BMC_SERVICE_IP = '10.96.0.81' +SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') + (('fleet-site-bmc',) if PROVIDER == 'redfish' else ()) +if PROVIDER == 'redfish': + SHARED.update({('deployments', SITE, 'fleet-site-bmc'): 'fleet-site-services', ('services', SITE, 'fleet-site-bmc'): 'fleet-site-services', + ('serviceaccounts', SITE, 'fleet-site-bmc'): 'fleet-site-base'}) LAYER_INVENTORY = { 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', - 'fleet-site_fleet-site-observer_apps_Deployment']), + 'fleet-site_fleet-site-observer_apps_Deployment'] + ( + ['fleet-site_fleet-site-bmc__Service', 'fleet-site_fleet-site-bmc_apps_Deployment'] if PROVIDER == 'redfish' else [])), 'flux-system/fleet-site-graph': ['_fleet-handoff-dispatcher_kro.run_ResourceGraphDefinition'], 'flux-system/fleet-site-dispatch': ['fleet-site_dispatcher_site.fleet.datumapis.com_HandoffDispatcher'], } @@ -257,6 +265,13 @@ def stage(args): # Karmada-API Kustomizations live beside their kubeconfig Secret. maps.append(config_map('fleet-environment', 'karmada-system', data)) if cluster == 'cell': + if PROVIDER == 'redfish': + # Environment selection, as a commit would make it: the cell's + # site layers reconcile the Redfish overlays of the same source. + for layer in ('fleet-site-base', 'fleet-site-graph') + (('fleet-site-services',) if args.site != 'absent' else ()): + patches.append(child_path(layer, './config/site/redfish/' + layer.rsplit('-', 1)[1])) + if args.site != 'absent': + data.update(FLEET_BMC_IMAGE=env['bmcImage'], FLEET_BMC_SERVICE_IP=BMC_SERVICE_IP) if args.site != 'absent': resources.insert(2, '../../config/multiplane/clusters/cell-site') data.update(FLEET_SCOPED_ASSET=env['scopedAsset'], FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, @@ -292,6 +307,11 @@ def stage(args): return 0 +def child_path(name, path): + """Point a child Kustomization at another path of the same source revision.""" + return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: replace\n path: /spec/path\n value: %s\n' % (name, path) + + def child_patch(name, patches): """Patch a child Kustomization's spec.patches: the effect of a source commit.""" return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: add\n path: /spec/patches\n value: %s\n' % ( diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index 9127cd17..19cbb231 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -28,6 +28,13 @@ REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) READINESS_PACKAGES = ('./internal/coordination', './internal/multiplane', './internal/localvm', './cmd/fleet-multiplane') +# Redfish mode (run.sh --redfish) adds its executor and probe to the readiness gate. +PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') +if PROVIDER == 'redfish': + REQUIRED_SOURCE_MARKERS += ('"redfish-probe"', '"install-b"', 'redfish.Open()') + READINESS_PACKAGES += ('./internal/redfish',) +# Lab targets behind the Redfish emulator: System Id -> persistent libvirt domain. +LAB_DOMAINS = {'System-1': 'fleet-lab-target-a', 'System-2': 'fleet-lab-target-b'} def now(): @@ -257,7 +264,7 @@ def journal(state): def domains(state): - # Running domains only. + # Running domains only; Redfish lab targets stay defined while powered off. code, out, _ = runtime_exec(state, 'virsh', '--connect', LIBVIRT_URI, 'list', '--name') return out.split() if code == 0 else None @@ -272,7 +279,7 @@ def sanitized_operations(j): for r in (j or {}).get('operations', {}).values(): ops.append({'id': r['request']['id'], 'kind': r['request']['kind'], 'epoch': r['request']['epoch'], 'stage': r.get('stage'), 'phase': r.get('result', {}).get('phase'), 'bootClosed': r.get('bootClosed', False), - 'domain': domain_name(r['request']['id'])}) + 'domain': LAB_DOMAINS.get(r.get('target', {}).get('systemID'), '?') if (j or {}).get('provider') == 'redfish' else domain_name(r['request']['id'])}) return ops diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 17f7daef..0cc3c4d6 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -8,12 +8,14 @@ import datetime import hashlib import json +import os import pathlib import subprocess import sys NS, SITE = 'fleet-coordination', 'fleet-site' LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' +REDFISH = os.environ.get('FLEET_SITE_PROVIDER') == 'redfish' def now(): @@ -150,7 +152,8 @@ def record_resume(state, name): def qemu_starts(state, operation): - domain = 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] + # Redfish mode: the persistent lab target A carries every operation. + domain = 'fleet-lab-target-a' if REDFISH else 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] r = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/log/libvirt/qemu/' + domain + '.log', check=False) return r.stdout.count(': starting up ') if r.returncode == 0 else None @@ -165,7 +168,7 @@ def lifecycle_snapshot(state, name): site_pods = {d: [p['metadata']['uid'] for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=' + d)['items']] for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')} print(json.dumps({'observedAt': now(), 'journalSHA256': hashlib.sha256(runtime(state, 'cat', '/var/lib/fleet-local/journal.json').encode()).hexdigest(), - 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', '--all').split(), + 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', *([] if REDFISH else ['--all'])).split(), 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvReclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'machineA': {'phase': machine.get('status', {}).get('phase'), 'bound': conds.get('Bound'), 'ready': conds.get('Ready')}, 'sitePods': site_pods, 'job': job(state, name)}, sort_keys=True)) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py new file mode 100644 index 00000000..b6ec0ffc --- /dev/null +++ b/hack/multiplane/redfish_steps.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Redfish-mode acceptance steps (hack/multiplane/run.sh --redfish). + +Every observation goes through the selected cell's API. Lab faults are written +only through the lab BMC adapter's fault file (bounded, one-shot) and are +recorded. Evidence records methods, paths, outcome classes, UIDs and digests, +never the BMC credential, fences, boot capabilities or request bodies. + + enroll create the synthetic BMC credential Secret (never in Git) + baseline snapshot target B and the BMC audit before any operation + discovery-faults real emulator: read-only discovery with good/wrong + credentials, identity mismatch and a hidden ResetType + arm-lost-response one-shot: withhold the response to target A's second + effective On (the disk boot of the first install) + lost-response the worker lost the On response after the effect; + recovery observed the target instead of repeating it + bmc-interrupt delete the BMC Pod mid-installer; the guest keeps running + isolation target B untouched, target A disk verifiably zeroed +""" +import datetime +import hashlib +import json +import pathlib +import secrets +import socket +import subprocess +import sys +import time + +SITE = 'fleet-site' +TARGET_A = {'system': 'System-1', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a', 'domain': 'fleet-lab-target-a', 'disk': '/var/lib/fleet-lab/disks/target-a.raw'} +TARGET_B = {'system': 'System-2', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b', 'domain': 'fleet-lab-target-b', 'disk': '/var/lib/fleet-lab/disks/target-b.raw'} +DISK_BYTES = 2 << 30 +LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' +SECRET = 'fleet-site-bmc-credentials' + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def die(message): + raise SystemExit(message) + + +def kubectl(s, *args, check=True, input=None, timeout=60): + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '--request-timeout=30s', *args], text=True, capture_output=True, input=input, timeout=timeout) + if check and r.returncode: + die('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[-300:])) + return r + + +def kget(s, *args): + return json.loads(kubectl(s, *args, '-o', 'json').stdout) + + +def runtime(s, *command, check=True): + return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command, check=check, timeout=180) + + +def bmc(s, *command, check=True): + return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-bmc', '-c', 'bmc', '--', *command, check=check) + + +def write(path, value): + pathlib.Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + + +def audit(s): + r = bmc(s, 'cat', '/var/lib/fleet-bmc/audit.log', check=False) + return [json.loads(l) for l in r.stdout.splitlines() if l.strip()] if r.returncode == 0 else [] + + +def mutating(entries, system=None): + return [e for e in entries if e['method'] not in ('GET', 'HEAD') and (system is None or e['path'].rstrip('/').startswith('/redfish/v1/Systems/' + system))] + + +def journal(s): + return json.loads(runtime(s, 'cat', '/var/lib/fleet-local/journal.json').stdout) + + +def installs(s, pending_ok=False): + # pending_ok: before the first worker retains its operation there is no journal yet. + if pending_ok: + r = runtime(s, 'cat', '/var/lib/fleet-local/journal.json', check=False) + if r.returncode: + return [] + ops = json.loads(r.stdout)['operations'].values() + else: + ops = journal(s)['operations'].values() + return [o for o in ops if o['request']['kind'] == 'install'] + + +def qemu_starts(s, domain): + r = runtime(s, 'cat', '/var/log/libvirt/qemu/%s.log' % domain, check=False) + return r.stdout.count(': starting up ') if r.returncode == 0 else 0 + + +def disk_sha(s, path): + return runtime(s, 'sha256sum', path).stdout.split()[0] + + +def console_lines(s, name): + r = runtime(s, 'cat', '/var/lib/fleet-lab-console/' + name, check=False) + return [l.strip() for l in r.stdout.splitlines()] if r.returncode == 0 else [] + + +def running(s): + return runtime(s, 'virsh', '--connect', LIBVIRT, 'list', '--name').stdout.split() + + +def enroll(s): + d = s / 'redfish' + d.mkdir(mode=0o700, exist_ok=True) + (d / 'bmc-username').write_text('fleet-lab-operator\n') + # The .token suffix enrolls the value in the harness secret scan. + (d / 'bmc-password.token').write_text(secrets.token_hex(32) + '\n') + for p in d.iterdir(): + p.chmod(0o600) + kubectl(s, '-n', SITE, 'create', 'secret', 'generic', SECRET, '--from-file=username=%s' % (d / 'bmc-username'), '--from-file=password=%s' % (d / 'bmc-password.token')) + write(s / 'evidence' / 'redfish-enrollment.json', { + 'observedAt': now(), 'credentialSecret': SITE + '/' + SECRET, 'username': 'fleet-lab-operator', + 'password': 'synthetic random 256-bit value generated per run; never recorded or committed', + 'transport': 'plain HTTP Basic on the cell network to the fixed BMC Service 10.96.0.81:8000 (lab seam)', + 'readers': ['lab BMC adapter (server side)', 'per-operation Redfish worker Pods (client side)'], + 'enrollment': json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]), + 'labTargets': json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())}) + print('redfish-enroll: synthetic BMC credential Secret created in the cell; not part of any source revision') + + +def baseline(s): + # Read target B through the BMC once so the adapter defines it, as any + # discovery would, then record its untouched state. + for _ in range(60): + if kubectl(s, '-n', SITE, 'get', 'deployment', 'fleet-site-bmc', '-o', 'jsonpath={.status.availableReplicas}', check=False).stdout == '1': + break + time.sleep(2) + record = {'observedAt': now(), 'targetB': {'diskSHA256': disk_sha(s, TARGET_B['disk']), 'qemuStarts': qemu_starts(s, TARGET_B['domain']), + 'consoleLines': len(console_lines(s, 'target-b.log'))}, + 'targetA': {'diskSHA256': disk_sha(s, TARGET_A['disk']), 'qemuStarts': qemu_starts(s, TARGET_A['domain'])}, + 'auditEntries': len(audit(s)), 'runningDomains': running(s)} + if record['targetB']['qemuStarts'] or record['targetA']['qemuStarts'] or record['runningDomains']: + die('lab targets were started before any operation: %s' % record) + write(s / 'redfish-baseline.json', record) + print('redfish-baseline: both lab target disks present and neither target ever started; target B disk %s...' % record['targetB']['diskSHA256'][:12]) + + +def port_forward(s): + sock = socket.socket() + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + sock.close() + p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', SITE, 'port-forward', 'svc/fleet-site-bmc', '%d:8000' % port], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(60): + try: + socket.create_connection(('127.0.0.1', port), 1).close() + return p, port + except OSError: + time.sleep(0.5) + p.kill() + die('could not port-forward to the BMC Service') + + +def discovery_faults(s): + d = s / 'redfish' + good, bad = d / 'probe-good', d / 'probe-bad' + for p, password in ((good, (d / 'bmc-password.token').read_text()), (bad, secrets.token_hex(16) + '\n')): + p.mkdir(mode=0o700, exist_ok=True) + (p / 'username').write_text((d / 'bmc-username').read_text()) + (p / 'password').write_text(password) + pf, port = port_forward(s) + before = len(audit(s)) + cases = [] + try: + def probe(name, creds, system, uuid, want): + r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'http://127.0.0.1:%d' % port, '--credentials', str(creds), + '--system', system, '--uuid', uuid], text=True, capture_output=True, timeout=120) + line = (r.stdout.strip().splitlines() or [''])[-1] + cases.append({'case': name, 'system': system, 'exitCode': r.returncode, 'outcome': line}) + if r.returncode != want: + die('%s: expected exit %d, got %d: %s %s' % (name, want, r.returncode, line, r.stderr[-200:])) + probe('target A with the enrolled credential', good, TARGET_A['system'], TARGET_A['uuid'], 0) + probe('target B with the enrolled credential', good, TARGET_B['system'], TARGET_B['uuid'], 0) + probe('wrong credential', bad, TARGET_A['system'], TARGET_A['uuid'], 10) + probe("target A's Id with target B's UUID (swapped mapping)", good, TARGET_A['system'], TARGET_B['uuid'], 12) + probe('unknown UUID', good, TARGET_A['system'], '00000000-0000-0000-0000-000000000000', 12) + bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'hide-reset', 'On') + try: + probe('ResetType On not advertised (injected)', good, TARGET_A['system'], TARGET_A['uuid'], 11) + finally: + bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'clear') + probe('target A after the fault is cleared', good, TARGET_A['system'], TARGET_A['uuid'], 0) + finally: + pf.kill() + for p in (good, bad): + for f in p.iterdir(): + f.unlink() + p.rmdir() + window = audit(s)[before:] + if mutating(window) or not any(e['principal'] == 'rejected' for e in window): + die('discovery probes issued an effect or the wrong credential was not rejected: %s' % mutating(window)) + write(s / 'evidence' / 'redfish-discovery-faults.json', {'observedAt': now(), 'emulator': 'DMTF Redfish-Interface-Emulator 1.2.2 + lab adapter (live, in the cell)', + 'client': 'internal/redfish discovery through fleet-multiplane redfish-probe', 'cases': cases, + 'auditRequests': len(window), 'mutatingRequests': 0, + 'rejectedRequests': sum(1 for e in window if e['principal'] == 'rejected')}) + print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only') + + +def arm_lost_response(s): + # The installer phase is about a minute under TCG and carries the worker + # Pod, Job and BMC interruptions; the disk boot's On carries this fault. + out = bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'drop-response', TARGET_A['system'], 'On', '45', '1').stdout + (s / 'redfish-lost-response-armed').write_text(now() + '\n') + print('redfish-arm-lost-response: one-shot fault armed: the second effective On for System-1 (the disk boot) withholds its response for 45s (client timeout 20s): %s' % out.strip()) + + +def lost_response(s): + name = (s / 'install-handoff').read_text().strip() + deadline = time.monotonic() + 900 + record = None + while time.monotonic() < deadline: + fired = [e for e in audit(s) if e.get('fault') == 'drop-response-after-effect'] + pods = kget(s, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items'] + exits = [c['state']['terminated']['exitCode'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] + if fired and 75 in exits: + failed = next(p for p in pods for c in p['status'].get('containerStatuses', []) if c.get('state', {}).get('terminated', {}).get('exitCode') == 75) + log = kubectl(s, '-n', SITE, 'logs', failed['metadata']['name'], '-c', 'worker', check=False).stdout + # The audit entry is written after the withheld response. + record = {'faultRecordedAt': fired[0]['at'], 'faultedRequest': {k: fired[0].get(k) for k in ('method', 'path', 'resetType', 'effect', 'status')}, + 'failedPodUID': failed['metadata']['uid'], 'failedPodExitCode': 75, + 'workerOutcomeClass': 'outcome unknown' if 'outcome unknown' in log else log.strip()[-160:]} + break + time.sleep(2) + if not record: + die('lost-response fault did not fire and fail one worker with exit 75') + for _ in range(300): + ops = installs(s) + if len(ops) == 1 and ops[0]['stage'] in ('disk-started', 'disk-verified', 'done'): + break + time.sleep(2) + ops = installs(s) + ons = [e for e in mutating(audit(s), TARGET_A['system']) if e.get('resetType') == 'On'] + if len(ops) != 1 or ops[0]['stage'] not in ('disk-started', 'disk-verified', 'done') or len(ons) != 2 or ops[0].get('powerOnRequests') != {'installer': 1, 'disk': 1}: + die('recovery after the lost response repeated or did not observe the boot: %d On requests, %s' % (len(ons), ops[0].get('stage') if ops else None)) + record.update(observedAt=now(), operationID=ops[0]['request']['id'], stageAfterRecovery=ops[0]['stage'], phase='disk boot', powerOnRequests=ops[0]['powerOnRequests'], + onRequestsToTargetA=len(ons), runningDomains=running(s), + recovery='replacement worker observed PowerState and the consumed one-time override; it did not repeat On') + write(s / 'evidence' / 'redfish-lost-response.json', record) + print('redfish-lost-response: On took effect but its response was lost; the worker exited 75 Unknown; its replacement observed the running target and did not repeat the effect') + + +def bmc_interrupt(s): + ops = [] + for _ in range(600): + ops = installs(s, pending_ok=True) + if len(ops) == 1 and ops[0]['stage'] == 'installer-started' and TARGET_A['domain'] in running(s): + break + if len(ops) == 1 and ops[0]['stage'] not in ('admitted', 'discovered', 'installer-armed', 'installer-requested', 'installer-started'): + die('the installer finished before the BMC could be interrupted: %s' % ops[0]['stage']) + time.sleep(0.5) + else: + die('BMC interruption requires the install mid-installer with target A running') + old = kget(s, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=fleet-site-bmc')['items'] + kubectl(s, '-n', SITE, 'delete', 'pod', '-l', 'app.kubernetes.io/name=fleet-site-bmc', '--grace-period=0', '--force', check=False) + new = None + for _ in range(180): + pods = [p for p in kget(s, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=fleet-site-bmc')['items'] + if p['metadata']['uid'] not in {o['metadata']['uid'] for o in old} and any(c['type'] == 'Ready' and c['status'] == 'True' for c in p['status'].get('conditions', []))] + if pods: + new = pods[0] + break + time.sleep(1) + if not new: + die('BMC Pod was not replaced') + after = installs(s) + if TARGET_A['domain'] not in running(s) and after[0]['stage'] == 'installer-started': + die('the guest stopped when the BMC was interrupted') + write(s / 'evidence' / 'redfish-bmc-interrupt.json', {'observedAt': now(), 'deletedBMCPodUIDs': [o['metadata']['uid'] for o in old], 'replacementBMCPodUID': new['metadata']['uid'], + 'operationID': ops[0]['request']['id'], 'stageAtInterrupt': 'installer-started', 'stageAfter': after[0]['stage'], + 'guestRunningAfter': TARGET_A['domain'] in running(s), + 'note': 'the BMC adapter re-reads NVRAM and libvirt state; the worker tolerates a bounded BMC outage while observing'}) + print('redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install and replaced; the guest kept running and the operation stayed unfinished') + + +def isolation(s): + base = json.loads((s / 'redfish-baseline.json').read_text()) + entries = audit(s) + zero = hashlib.sha256() + block = bytes(1 << 20) + for _ in range(DISK_BYTES >> 20): + zero.update(block) + record = {'observedAt': now(), + 'targetB': {'diskSHA256Before': base['targetB']['diskSHA256'], 'diskSHA256After': disk_sha(s, TARGET_B['disk']), 'qemuStarts': qemu_starts(s, TARGET_B['domain']), + 'consoleLines': len(console_lines(s, 'target-b.log')), 'mutatingRedfishRequests': mutating(entries, TARGET_B['system'])}, + 'targetA': {'diskSHA256': disk_sha(s, TARGET_A['disk']), 'zeroDiskSHA256': zero.hexdigest(), 'qemuStarts': qemu_starts(s, TARGET_A['domain']), + 'mutatingRedfishRequests': [{k: e.get(k) for k in ('method', 'path', 'status', 'resetType', 'boot', 'effect', 'fault')} for e in mutating(entries, TARGET_A['system'])]}, + 'runningDomains': running(s), 'auditEntries': len(entries)} + b, a = record['targetB'], record['targetA'] + if b['diskSHA256Before'] != b['diskSHA256After'] or b['qemuStarts'] or b['consoleLines'] != base['targetB']['consoleLines'] or b['mutatingRedfishRequests']: + die('target B was touched: %s' % b) + if a['diskSHA256'] != a['zeroDiskSHA256']: + die('target A disk is not all zeroes after the final verified cleanup') + if record['runningDomains']: + die('a lab target is still running: %s' % record['runningDomains']) + write(s / 'evidence' / 'redfish-isolation.json', record) + (s / 'evidence' / 'redfish-audit.jsonl').write_text(''.join(json.dumps(e, sort_keys=True) + '\n' for e in entries)) + print('redfish-isolation: target B never started, never received a Redfish effect and its disk is unchanged; target A disk independently hashes as all zeroes after the final cleanup') + + +if __name__ == '__main__': + step, state = sys.argv[1], pathlib.Path(sys.argv[2]) + {'enroll': enroll, 'baseline': baseline, 'discovery-faults': discovery_faults, 'arm-lost-response': arm_lost_response, + 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation}[step](state) diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 3fe58150..73111d06 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -8,8 +8,8 @@ set -euo pipefail cd "$(dirname "$0")/../.." umask 077 -usage() { echo 'usage: hack/multiplane/run.sh [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } -preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() +usage() { echo 'usage: hack/multiplane/run.sh [--redfish] [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt for arg in "$@"; do case "$arg" in --preflight-only) preflight_only=1 ;; @@ -17,14 +17,18 @@ for arg in "$@"; do --keep) keep=1 ;; --leave-running) leave=1 ;; --skip-readiness-tests) skip_tests=(--skip-tests) ;; + # Redfish mode: workers drive lab VMs only through the DMTF Redfish emulator + # and its lab adapter (docs/operations/redfish-lab.md). + --redfish) provider=redfish ;; *) usage ;; esac done -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider harness=(python3 hack/multiplane/harness.py) state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") mkdir -m 0700 "$state/evidence" -printf 'Private run state: %s\nShareable evidence: %s/evidence\n' "$state" "$state" +printf '%s\n' "$provider" > "$state/site-provider" +printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\n' "$state" "$state" "$provider" finish() { code=$1 @@ -53,7 +57,7 @@ printf '%s\n' "$prefix" > "$state/prefix" python3 - "$state" <<'PY' import hashlib,pathlib,sys paths=[] -for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','config/multiplane','config/site','config/base/crd'): +for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','hack/redfish-lab','config/multiplane','config/site','config/base/crd'): paths += [p for p in pathlib.Path(name).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')] paths += [pathlib.Path(name) for name in ('go.mod', 'go.sum')] (pathlib.Path(sys.argv[1])/'source-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n' for p in sorted(paths))) @@ -68,6 +72,13 @@ ph site-image-verify 120 sh -c ' printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null docker run --rm -e FLEET_LOCAL_VM_ACCEL=tcg --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" +if [[ $provider == redfish ]]; then + # The unmodified upstream emulator, verified before extraction, plus the + # lab-only adapter; its self-test runs the real emulator with a fake virsh. + ph bmc-upstream 300 sh -c 'bash hack/redfish-lab/upstream.sh "$1/redfish-upstream" > "$1/evidence/redfish-upstream.json" && echo "bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified"' sh "$state" + ph bmc-image 1800 docker build --build-context "upstream=$state/redfish-upstream/src/Redfish-Interface-Emulator-1.2.2" -t "$prefix-bmc-image" -f hack/redfish-lab/Containerfile hack/redfish-lab + ph bmc-self-test 300 sh -c 'docker run --rm --network none --entrypoint python3 "$1-bmc-image" /opt/fleet-lab/test_adapter.py >/dev/null 2>&1 && echo "bmc-self-test: upstream emulator and lab adapter self-test passed"' sh "$prefix" +fi ph flux-tools 300 "${flux[@]}" tools "$state" docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null # Disposable infrastructure only: registry and three kind clusters, no services. @@ -89,16 +100,21 @@ s=pathlib.Path(sys.argv[1]).resolve();c={'State':str(s),'HubKubeconfig':str(s/'m PY ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" ph scoped-asset 120 sh -c '"$1/fleet-multiplane-host" asset --config "$1/acceptance.json" > "$1/scoped-asset" && echo "scoped asset recorded"' sh "$state" +[[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" # Revision 2: the Flux-owned shared site services and the HandoffDispatcher # instance, dispatch disabled. ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 ph site-install 900 bash hack/multiplane/site.sh check "$state" ph flux-verify 300 "${flux[@]}" verify "$state" -bash hack/multiplane/acceptance.sh "$state" +if [[ $provider == redfish ]]; then + bash hack/multiplane/acceptance-redfish.sh "$state" +else + bash hack/multiplane/acceptance.sh "$state" +fi ph secret-scan 120 "${harness[@]}" scan --state "$state" if [[ $keep == 1 ]]; then ph stop 300 bash hack/multiplane/stop.sh "$state" else ph teardown 900 bash hack/multiplane/teardown.sh "$state" fi -printf 'Local topology/PXE acceptance passed. Production authority and physical hardware remain unqualified.\n' +printf 'Local topology/PXE acceptance (%s provider) passed. Production authority and physical hardware remain unqualified.\n' "$provider" diff --git a/hack/multiplane/site.sh b/hack/multiplane/site.sh index d7c35536..d816df6e 100755 --- a/hack/multiplane/site.sh +++ b/hack/multiplane/site.sh @@ -13,7 +13,9 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } export DOCKER_CONTEXT=colima-fleet-acceptance-tcg cell="$state/cell-admin.yaml" +provider=$(cat "$state/site-provider" 2>/dev/null || echo libvirt) deployments=(fleet-site-runtime fleet-site-boot fleet-site-observer) +[[ $provider != redfish ]] || deployments+=(fleet-site-bmc) k() { kubectl --kubeconfig "$cell" --request-timeout=30s "$@"; } case "$step" in @@ -32,6 +34,21 @@ env['siteImageDigest'] = digest (s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') PY printf 'site image: pushed to the run registry as fleet-site@%s; the cell pulls it by digest\n' "$digest" + if [[ $provider == redfish ]]; then + docker tag "$prefix-bmc-image" "127.0.0.1:$port/fleet-bmc:$prefix" >/dev/null + docker push "127.0.0.1:$port/fleet-bmc:$prefix" >/dev/null + bmc=$(docker image inspect "127.0.0.1:$port/fleet-bmc:$prefix" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^127.0.0.1:$port/fleet-bmc@" | cut -d@ -f2) + [[ $bmc =~ ^sha256:[a-f0-9]{64}$ ]] || { echo "no registry digest for the BMC image" >&2; exit 1; } + python3 - "$state" "$prefix" "$bmc" <<'PY' +import json, pathlib, sys +s, prefix, digest = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3] +env = json.loads((s / 'gitops-environment.json').read_text()) +env['bmcImage'] = '%s-registry:5000/fleet-bmc@%s' % (prefix, digest) +env['bmcImageDigest'] = digest +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY + printf 'bmc image: pushed the DMTF emulator lab BMC as fleet-bmc@%s\n' "$bmc" + fi ;; check) for d in "${deployments[@]}"; do @@ -44,6 +61,11 @@ PY policy=$(k get pv "$pv" -o jsonpath='{.spec.persistentVolumeReclaimPolicy}') [[ $policy == Retain ]] || { echo "site volume reclaim policy $policy" >&2; exit 1; } want=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["siteImage"])' "$state/gitops-environment.json") + if [[ $provider == redfish ]]; then + bmc=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["bmcImage"])' "$state/gitops-environment.json") + [[ $(k -n fleet-site get deployment fleet-site-bmc -o jsonpath='{.spec.template.spec.containers[0].image}') == "$bmc" ]] || { echo 'BMC does not run the published digest' >&2; exit 1; } + [[ $(k -n fleet-site get deployment fleet-site-bmc -o jsonpath='{.metadata.labels.kustomize\.toolkit\.fluxcd\.io/name}') == fleet-site-services ]] || { echo 'BMC is not owned by the Flux services layer' >&2; exit 1; } + fi for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do image=$(k -n fleet-site get deployment "$d" -o jsonpath='{.spec.template.spec.containers[0].image}') [[ $image == "$want" ]] || { echo "$d runs $image, not the published digest" >&2; exit 1; } diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 81ee78ee..e6c07852 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -285,7 +285,12 @@ PY # The origin comes from the Flux-owned Service, which drift repair recreated. origin="http://$(site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}'):8080" [[ $origin == "$(site get handoffdispatcher dispatcher -o jsonpath='{.status.bootOrigin}')" ]] || { echo 'dispatcher boot origin differs from the boot Service' >&2; exit 1; } - runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + if [[ $(cat "$state/site-provider" 2>/dev/null) == redfish ]]; then + # Redfish mode also probes the never-allocated target B's MAC. + runtime env FLEET_BOOT_ORIGIN="$origin" FLEET_BOOT_EVIDENCE=/var/lib/fleet-boot fleet-multiplane boot-denials --origin "$origin" --extra-mac 52:54:00:77:01:0b > "$state/boot-denials.txt" + else + runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + fi grep -q '^PASS ' "$state/boot-denials.txt" || { echo 'closed-boot probe failed' >&2; exit 1; } printf 'boot-denials: %s through the boot Service\n' "$(cat "$state/boot-denials.txt")" ;; diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index 299898a5..009d4033 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -37,9 +37,10 @@ image_tag_removed=true pushed=() if [[ -f $state/gitops-environment.json ]]; then port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") - pushed=("127.0.0.1:$port/fleet-site:$prefix") + # Redfish mode also built and pushed the lab BMC image. + pushed=("127.0.0.1:$port/fleet-site:$prefix" "127.0.0.1:$port/fleet-bmc:$prefix") fi -for image in "$prefix-site-image" "$prefix-provider-image" ${pushed[@]+"${pushed[@]}"}; do +for image in "$prefix-site-image" "$prefix-provider-image" "$prefix-bmc-image" ${pushed[@]+"${pushed[@]}"}; do docker image rm "$image" >/dev/null 2>&1 || true if docker image inspect "$image" >/dev/null 2>&1; then image_tag_removed=false; fi done @@ -48,7 +49,7 @@ remaining=$(docker ps -a --filter "name=^$prefix-" --format '{{.Names}}') rm -f "$state/kind-delete.kubeconfig" if [[ $mode == passed ]]; then # Credentials and raw journals are no longer needed once the run has passed. - rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" + rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" "$state/redfish" rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/private.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ "$state"/status-fault.json "$state"/acceptance.json "$state"/fleet-multiplane "$state"/fleet-multiplane-host rm -rf "$state/site-bin" "$state/kro-chart" "$state/flux-tools/flux" "$state"/flux-tools/*.tar.gz diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index a2f5e561..8b1cb2b1 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -6,6 +6,8 @@ root=$(CDPATH='' cd -- "$(dirname "$0")/../.." && pwd) for f in "$root"/hack/multiplane/*.sh "$root"/hack/local-vm/run.sh; do bash -n "$f"; done python3 -m py_compile "$root"/hack/multiplane/*.py python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" +python3 "$root"/hack/multiplane/test-redfish.py "$root" +python3 -m py_compile "$root"/hack/redfish-lab/*.py exec python3 - "$root" <<'PY' import json, os, pathlib, re, stat, subprocess, sys, tempfile, time diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py new file mode 100644 index 00000000..317dcf0d --- /dev/null +++ b/hack/multiplane/test-redfish.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Offline checks for the Redfish acceptance mode (run.sh --redfish). + +Renders the Redfish site overlays and a staged Redfish source revision with +the real kustomize, and checks the static contracts the live run relies on: +workers have no hypervisor path, only the runtime is privileged, the lab +enrollment matches the lab targets, and every phase is implemented. Never +contacts a container runtime or cluster. +""" +import argparse +import json +import os +import pathlib +import re +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]).resolve() +os.environ['FLEET_SITE_PROVIDER'] = 'redfish' +sys.path.insert(0, str(root / 'hack/multiplane')) +import flux # noqa: E402 (reads FLEET_SITE_PROVIDER at import) + + +def documents(text): + """Rendered YAML as objects: PyYAML when present, otherwise yq (both are on CI runners).""" + try: + import yaml + return [d for d in yaml.safe_load_all(text) if d] + except ImportError: + out = subprocess.run(['yq', '-o=json', '-I=0', '.'], input=text, text=True, capture_output=True, check=True).stdout + return [json.loads(line) for line in out.splitlines() if line.strip() not in ('', 'null')] + +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +def build(path): + r = subprocess.run(['kustomize', 'build', str(path)], text=True, capture_output=True) + if r.returncode: + failures.append('render %s: %s' % (path, r.stderr[-300:])) + return [] + return documents(r.stdout) + + +graph = build(root / 'config/site/redfish/graph') +rgd = next((d for d in graph if d.get('kind') == 'ResourceGraphDefinition'), {}) +resources = {r['id']: r for r in rgd.get('spec', {}).get('resources', [])} +worker = resources.get('workers', {}).get('template', {}).get('spec', {}).get('template', {}).get('spec', {}) +container = (worker.get('containers') or [{}])[0] +env = {e['name']: e.get('value') for e in container.get('env', [])} +mounts = container.get('volumeMounts', []) +check('Redfish worker selects the Redfish provider', env.get('FLEET_SITE_PROVIDER') == 'redfish' and 'FLEET_LIBVIRT_URI' not in env, str(env.keys())) +check('Redfish worker has no libvirt socket or lab disk mount', not any('libvirt' in m.get('subPath', '') + m['mountPath'] or 'lab-disks' in m.get('subPath', '') for m in mounts), str(mounts)) +check('Redfish worker console capture is read-only', any(m.get('subPath') == 'lab-console' and m.get('readOnly') for m in mounts)) +check('Redfish worker credential is the BMC Secret only', [v['secret']['secretName'] for v in worker.get('volumes', []) if 'secret' in v] == ['fleet-site-bmc-credentials'] + and not any('hostPath' in v for v in worker.get('volumes', []))) +check('Redfish worker waits for the Flux-owned BMC', 'bmc' in resources and resources['bmc'].get('externalRef', {}).get('metadata', {}).get('name') == 'fleet-site-bmc' + and '${bmc.metadata.name}' in json.dumps(resources.get('workers', {}))) +check('graph ids still valid for kro', all(re.fullmatch(r'[a-z][a-zA-Z0-9]*', i) for i in resources) and 'runtime' not in resources, str(list(resources))) +check('privileged nothing in the Redfish graph', 'privileged' not in json.dumps(rgd)) + +enrollment = json.loads(env.get('FLEET_REDFISH_ENROLLMENT', '{}')) +targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) +by_system = {t['system']: t for t in targets} +check('enrollment endpoint is the fixed BMC Service', enrollment.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP) +check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( + t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['mac'] == t['mac'] + and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) +check('only target A is the published capacity Device', enrollment['targets'][0]['assetID'].endswith('/synthetic-device-central-01') if enrollment.get('targets') else False) + +services = build(root / 'config/site/redfish/services') +deployments = {d['metadata']['name']: d for d in services if d.get('kind') == 'Deployment'} +check('Redfish services add the BMC', sorted(deployments) == ['fleet-site-bmc', 'fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime'], str(sorted(deployments))) +privileged = [n for n, d in deployments.items() if any(c.get('securityContext', {}).get('privileged') for c in d['spec']['template']['spec']['containers'])] +check('only the runtime is privileged in Redfish mode', privileged == ['fleet-site-runtime'], str(privileged)) +socket_holders = sorted(n for n, d in deployments.items() if any(m.get('subPath') == 'libvirt-socket' for c in d['spec']['template']['spec']['containers'] for m in c.get('volumeMounts', []))) +check('only the runtime and the lab BMC hold the libvirt socket', socket_holders == ['fleet-site-bmc', 'fleet-site-runtime'], str(socket_holders)) +bmc = deployments.get('fleet-site-bmc', {}) +check('BMC image and Service IP substituted by Flux', '${FLEET_BMC_IMAGE}' in json.dumps(bmc) and any( + d.get('kind') == 'Service' and d['metadata']['name'] == 'fleet-site-bmc' and d['spec']['clusterIP'] == '${FLEET_BMC_SERVICE_IP}' for d in services)) +check('every site role selects the Redfish provider', all(any(e.get('name') == 'FLEET_SITE_PROVIDER' and e.get('value') == 'redfish' for e in deployments[n]['spec']['template']['spec']['containers'][0].get('env', [])) + for n in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer'))) + +base = build(root / 'config/site/redfish/base') +policy = next((d for d in base if d.get('kind') == 'ValidatingAdmissionPolicy' and d['metadata']['name'] == 'fleet-site-kro-worker-jobs'), {}) +text = json.dumps(policy) +check('admission denies libvirt mounts and URIs for kro worker Jobs', "startsWith('/run/fleet-libvirt')" in text and "FLEET_LIBVIRT_URI" in text and 'fleet-site-bmc-credentials' in text) +check('BMC identity in the base', any(d.get('kind') == 'ServiceAccount' and d['metadata']['name'] == 'fleet-site-bmc' for d in base)) +check('no Secret in any Redfish overlay', not any(d.get('kind') == 'Secret' for d in base + services + graph)) + +# A staged Redfish revision points the cell's site layers at the overlays. +with tempfile.TemporaryDirectory() as tmp: + s = pathlib.Path(tmp) / 'state' + (s / 'flux-tools').mkdir(parents=True) + (s / 'evidence').mkdir() + (s / 'prefix').write_text('fleet-mp-0000abcd\n') + # The same stand-in for the release install.yaml that test-flux.py uses. + fake = 'apiVersion: v1\nkind: Namespace\nmetadata: {name: flux-system}\n' + for name in ('source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller', 'image-automation-controller', + 'image-reflector-controller', 'source-watcher'): + fake += '---\napiVersion: apps/v1\nkind: Deployment\nmetadata: {name: %s, namespace: flux-system}\nspec:\n template:\n spec:\n containers:\n - {name: manager, image: ghcr.io/fluxcd/%s:v0, args: []}\n' % (name, name) + fake += '---\napiVersion: v1\nkind: Service\nmetadata: {name: source-watcher, namespace: flux-system}\n' + (s / 'flux-tools' / 'install.yaml').write_text(fake) + flux.INSTALL_SHA256 = flux.sha256(s / 'flux-tools' / 'install.yaml') + (s / 'gitops-environment.json').write_text(json.dumps({'registryHost': 'fleet-mp-0000abcd-registry', 'registryPort': 5555, 'karmadaPort': 1, 'cell': 'fleet-mp-0000abcd-cell', + 'cellEndpoint': 'https://x:6443', 'siteImage': 'r/fleet-site@sha256:' + 'a' * 64, 'siteImageDigest': 'sha256:' + 'a' * 64, + 'bmcImage': 'r/fleet-bmc@sha256:' + 'b' * 64, 'bmcImageDigest': 'sha256:' + 'b' * 64})) + (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') + args = argparse.Namespace(state=str(s), root=str(root), revision=2, site='off', bad_kro_chart=False, drop_site_volume=True, purpose='test', cluster=[], timeout=5) + check('stage a Redfish revision', flux.stage(args) == 0) + cell = subprocess.run(['kustomize', 'build', str(s / 'gitops/r2/environment/cell')], text=True, capture_output=True).stdout + for layer in ('base', 'services', 'graph'): + check('cell %s layer uses the Redfish overlay' % layer, 'path: ./config/site/redfish/' + layer in cell) + check('Redfish environment values defined', 'FLEET_BMC_IMAGE: r/fleet-bmc@sha256:' in cell.replace('"', '') and ('FLEET_BMC_SERVICE_IP: %s' % flux.BMC_SERVICE_IP) in cell.replace('"', '')) + check('volume-removal patch still targets the Redfish base', '$patch: delete' in cell) + used = set() + for f in (root / 'config/site/redfish/services').glob('*.yaml'): + used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) + defined = set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell, re.M)) + check('Redfish substituted variables defined', used <= defined, str(sorted(used - defined))) +check('ownership audit expects the BMC', ('deployments', 'fleet-site', 'fleet-site-bmc') in flux.SHARED and 'fleet-site-bmc' in flux.SITE_DEPLOYMENTS) + +# Every Redfish phase is implemented, and the lab fault hooks stay in the lab. +sequence = (root / 'hack/multiplane/acceptance-redfish.sh').read_text() +steps = (root / 'hack/multiplane/steps.sh').read_text() +redfish_steps = (root / 'hack/multiplane/redfish_steps.py').read_text() +for name in re.findall(r'^step (\S+)', sequence, re.M): + check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) +for name in re.findall(r'^rf (\S+)', sequence, re.M): + check('redfish step implemented: ' + name, "'%s':" % name in redfish_steps) +order = ['baseline', 'discovery-faults', 'allocate', 'arm-lost-response', 'dispatch', 'bmc-interrupt', 'interrupt-pod', 'interrupt-job', 'lost-response', 'resume', 'release', + 'reuse', 'delivery-faults', 'install-b', 'release-b', 'boot-denials', 'isolation', 'evidence'] +positions = [sequence.find(' ' + n + ' ') for n in order] +check('Redfish phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) +for name in ('internal/redfish/client.go', 'internal/redfish/provider.go', 'internal/redfish/boot.go'): + src = (root / name).read_text() + check('no lab fault hook in production code: ' + name, not re.search(r'\bfaults?\b|drop-response|hide-reset', src, re.I)) +adapter = (root / 'hack/redfish-lab/fleet_lab_adapter.py').read_text() +check('adapter keeps upstream unmodified (imports it)', 'import emulator' in adapter and 'COPY --from=upstream . /opt/redfish-emulator' in (root / 'hack/redfish-lab/Containerfile').read_text()) +check('upstream source pinned by digest and commit', re.search(r'sha256=[0-9a-f]{64}', (root / 'hack/redfish-lab/upstream.sh').read_text()) is not None + and '5f51d8ac48e46665a2a85242434f125aa7b25172' in (root / 'hack/redfish-lab/upstream.sh').read_text()) +check('BMC base image pinned by digest', re.search(r'^FROM \S+@sha256:[0-9a-f]{64}$', (root / 'hack/redfish-lab/Containerfile').read_text(), re.M) is not None) +lock = (root / 'hack/redfish-lab/requirements.lock').read_text() +check('Python dependencies hash-pinned', all('==' in l for l in lock.splitlines() if l and not l.startswith(('#', ' '))) and lock.count('--hash=sha256:') >= 18) +check('no OpenStack dependency', not re.search(r'sushy|openstack|ironic', (lock + adapter + (root / 'hack/redfish-lab/Containerfile').read_text()).lower())) + +run_sh = (root / 'hack/multiplane/run.sh').read_text() +# $state/provider is the Milo provider project's credential directory. +check('site provider marker does not collide with the provider project state', '"$state/site-provider"' in run_sh and '> "$state/provider"' not in run_sh) + +# Every Redfish evidence marker must be printed by some phase, or the +# evidence phase fails after a fully passing run. +evidence_src = (root / 'hack/multiplane/evidence.py').read_text() +block = evidence_src.split('if REDFISH:\n markers += (')[1].split(')\nfor marker')[0] +sources = ''.join(p.read_text() for p in list((root / 'hack/multiplane').glob('*.py')) + list((root / 'hack/multiplane').glob('*.sh')) + [root / 'cmd/fleet-multiplane/main.go'] + if p.name != 'evidence.py') +for marker in re.findall(r"'([^']+)'", block): + check('evidence marker is printed by a phase: ' + marker, marker in sources or marker.split(': ')[0] + ': verified' == marker) +teardown = (root / 'hack/multiplane/teardown.sh').read_text() +check('teardown removes the synthetic BMC credential after a pass', '"$state/redfish"' in teardown) +check('teardown removes the BMC image tags', '"$prefix-bmc-image"' in teardown and 'fleet-bmc:$prefix' in teardown) + +if failures: + print('FAIL Redfish mode tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS Redfish mode tests') diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 2583bbcf..1c733932 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Negative writes and credential revocation against real API servers.""" -import json,pathlib,subprocess,sys,time +import json,os,pathlib,subprocess,sys,time s=pathlib.Path(sys.argv[1]);ns='fleet-coordination' def call(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args],input=input,text=True,capture_output=True) def forbidden(config,*args): @@ -67,8 +67,10 @@ def can(*args): retained=[('create','customresourcedefinitions'),('delete','customresourcedefinitions'),('update','leases','-n','kro-system')] retained={' '.join(a):can(*a) for a in retained} image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] +redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish' def job(**change): c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} + if redfish:c['env']=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'}] spec={'restartPolicy':'Never','serviceAccountName':'w-op-admission-probe','containers':[c],'volumes':[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'tmp','emptyDir':{}}]} for k,v in change.items(): (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v @@ -85,6 +87,16 @@ def job(**change): 'Job from another image':job(image='registry.k8s.io/pause:3.10'),'Job with a hostPath volume':job(volumes=[{'name':'host','hostPath':{'path':'/'}}]), 'Job on the host network':job(hostNetwork=True),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list'])]), 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} +if redfish: + # Redfish workers have no hypervisor path: the libvirt socket, the lab disks + # and a libvirt URI are denied by policy; only the BMC credential is added. + creds=[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'credentials','secret':{'secretName':'fleet-site-bmc-credentials'}}] + cases['admitted']['Redfish worker Job with the BMC credential']=job(volumes=creds) + cases['denied'].update({'Redfish worker mounting the libvirt socket':job(volumeMounts=[{'name':'state','mountPath':'/run/fleet-libvirt','subPath':'libvirt-socket'}]), + 'Redfish worker mounting the lab disks':job(volumeMounts=[{'name':'state','mountPath':'/var/lib/fleet-lab/disks','subPath':'lab-disks'}]), + 'Redfish worker with a libvirt URI':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'},{'name':'FLEET_LIBVIRT_URI','value':'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock'}]), + 'worker selecting the libvirt provider':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'libvirt'}]), + 'Redfish worker mounting another Secret':job(volumes=[{'name':'other','secret':{'secretName':'fleet-site-other'}}])}) record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} for outcome,objs in cases.items(): for name,obj in objs.items(): diff --git a/hack/redfish-lab/Containerfile b/hack/redfish-lab/Containerfile new file mode 100644 index 00000000..90191e4c --- /dev/null +++ b/hack/redfish-lab/Containerfile @@ -0,0 +1,17 @@ +# Lab BMC: the unmodified DMTF Redfish Interface Emulator 1.2.2 plus the +# lab-only libvirt adapter. The upstream tree comes from the named build +# context "upstream", which the harness fills from the release archive only +# after verifying its SHA-256 (hack/redfish-lab/upstream.sh). Python +# dependencies are hash-pinned; apt resolution of libvirt-clients is not +# reproducible (the same caveat as the site image). +FROM python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libvirt-clients && rm -rf /var/lib/apt/lists/* +COPY requirements.lock /tmp/requirements.lock +RUN pip install --no-cache-dir --no-deps --require-hashes -r /tmp/requirements.lock && rm /tmp/requirements.lock +COPY --from=upstream . /opt/redfish-emulator +COPY emulator-config.json populate-config.json targets.json /etc/fleet-bmc/ +COPY fleet_lab_adapter.py test_adapter.py fake_virsh.py /opt/fleet-lab/ +RUN chmod 755 /opt/fleet-lab/*.py +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +ENTRYPOINT ["python3", "/opt/fleet-lab/fleet_lab_adapter.py"] +CMD ["serve"] diff --git a/hack/redfish-lab/emulator-config.json b/hack/redfish-lab/emulator-config.json new file mode 100644 index 00000000..33297317 --- /dev/null +++ b/hack/redfish-lab/emulator-config.json @@ -0,0 +1,7 @@ +{ + "MODE": "Local", + "HTTPS": "Disable", + "TRAYS": [], + "SPEC": "Redfish", + "POPULATE": "/etc/fleet-bmc/populate-config.json" +} diff --git a/hack/redfish-lab/fake_virsh.py b/hack/redfish-lab/fake_virsh.py new file mode 100755 index 00000000..d936439b --- /dev/null +++ b/hack/redfish-lab/fake_virsh.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Offline stand-in for virsh used only by test_adapter.py: records calls, keeps state in JSON.""" +import json, os, re, sys +state_path = os.environ['FAKE_VIRSH_STATE'] +s = json.load(open(state_path)) if os.path.exists(state_path) else {'domains': {}, 'networks': {}, 'calls': []} +args = sys.argv[3:] # drop --connect URI +s['calls'].append(args[0]) +def done(out='', code=0): + json.dump(s, open(state_path, 'w')) + print(out); sys.exit(code) +cmd = args[0] +if os.environ.get('FAKE_VIRSH_DOWN'): + print('cannot connect', file=sys.stderr); done(code=1) +if cmd == 'net-info': + n = s['networks'].get(args[1]) + done('Active: %s' % ('yes' if n and n['active'] else 'no')) if n else done(code=1) +if cmd == 'net-define': + s['networks'][re.search(r'([^<]+)', sys.stdin.read()).group(1)] = {'active': False}; done() +if cmd == 'net-start': + s['networks'][args[1]]['active'] = True; done() +if cmd == 'define': + xml = sys.stdin.read(); name = re.search(r'([^<]+)', xml).group(1) + d = s['domains'].setdefault(name, {'running': False, 'starts': []}) + d['uuid'] = re.search(r'([^<]+)', xml).group(1); d['boot'] = re.search(r"{domain}{uuid}20482" + "" + "hvm" + "destroydestroydestroy" + "/usr/bin/qemu-system-x86_64" + "" + "" + "" + "" + "").format(boot=boot, **t) + + +def network_xml(targets, boot_ip): + hosts = ''.join("" % (t['mac'], t['ip']) for t in targets.values()) + ips = sorted(t['ip'] for t in targets.values()) + return ("" + NETWORK + "" + "%s" + "") % (ips[0], ips[-1], hosts, boot_ip) + + +class Lab: + """Exact System -> persistent libvirt domain mapping and BMC NVRAM.""" + + def __init__(self, targets, state, boot_ip): + self.targets, self.state, self.boot_ip = targets, state, boot_ip + self.nvram_path = os.path.join(state, 'nvram.json') + self.nvram = read_json(self.nvram_path, {}) + for sid in targets: + self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'}) + atomic_write(self.nvram_path, self.nvram) + + def ensure(self, sid): + """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" + t = self.targets[sid] + try: + info = virsh('net-info', NETWORK) + if not re.search(r'^Active:\s+yes', info, re.M): + virsh('net-start', NETWORK) + except LibvirtError: + virsh('net-define', '/dev/stdin', input=network_xml(self.targets, self.boot_ip)) + virsh('net-start', NETWORK) + try: + uuid = virsh('domuuid', t['domain']) + except LibvirtError: + virsh('define', '/dev/stdin', input=domain_xml(t, 'hd')) + uuid = virsh('domuuid', t['domain']) + if uuid != t['uuid']: + raise LibvirtError('lab domain identity changed; refusing to control it') + + def power(self, sid): + state = virsh('domstate', self.targets[sid]['domain']) + if state in ('running', 'paused', 'idle', 'blocked'): + return 'On' + if state == 'in shutdown': + return 'PoweringOff' + return 'Off' + + def save(self): + atomic_write(self.nvram_path, self.nvram) + + def power_on(self, sid): + t, boot = self.targets[sid], 'hd' + override = self.nvram[sid] + if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd'): + boot = 'network' if override['BootSourceOverrideTarget'] == 'Pxe' else 'hd' + # Once is consumed by this boot. Persisted before start, like NVRAM. + self.nvram[sid] = {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'} + self.save() + virsh('define', '/dev/stdin', input=domain_xml(t, boot)) + virsh('start', t['domain']) + return boot + + +def error(status, message): + return {'error': {'code': 'Base.1.0.GeneralError', 'message': message}}, status + + +def challenge(): + body, status = error(401, 'authentication required') + return body, status, {'WWW-Authenticate': 'Basic realm="fleet-lab-bmc"'} + + +def create_app(targets, state, credentials, boot_ip): + os.makedirs(state, exist_ok=True) + os.chdir(CONFIG_DIR) + sys.path.insert(0, UPSTREAM) + import logging + import g # upstream module: Flask app and flask_restful API + import emulator # noqa: F401 upstream: loads resources and runs infragen populate on import + from api_emulator.redfish import ComputerSystem_api as cs + from api_emulator.redfish import ResetActionInfo_api as rai + from flask import g as request_context, request + logging.getLogger().setLevel(logging.WARNING) + lab = Lab(targets, state, boot_ip) + faults = FaultFile(state) + audit_path = os.path.join(state, 'audit.log') + + def publish(sid, power=None): + m = cs.members[sid] + m['UUID'] = targets[sid]['uuid'] + m['Name'] = targets[sid]['name'] + m['Manufacturer'] = 'DMTF Redfish Interface Emulator (Fleet lab adapter)' + m['Model'] = 'libvirt/QEMU lab target' + m['Boot'] = dict(lab.nvram[sid], BootSourceOverrideMode='Legacy', **{ + 'BootSourceOverrideTarget@Redfish.AllowableValues': list(BOOT_TARGETS), + 'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)}) + if power: + m['PowerState'] = power + hidden = set(faults.read().get('hideResetTypes', [])) + rai.members[sid]['Parameters'][0]['AllowableValues'] = [v for v in RESET_TYPES if v not in hidden] + + for sid in targets: + if sid not in cs.members or sid not in rai.members: + raise SystemExit('populate did not create lab System ' + sid) + publish(sid, 'Off') + + def authorized(): + header = request.headers.get('Authorization', '') + if not header.startswith('Basic '): + return False + try: + user, _, password = base64.b64decode(header[6:], validate=True).decode().partition(':') + except ValueError: + return False + with open(os.path.join(credentials, 'username')) as f: + want_user = f.read().strip() + with open(os.path.join(credentials, 'password')) as f: + want_password = f.read().strip() + return hmac.compare_digest(user.encode(), want_user.encode()) & hmac.compare_digest(password.encode(), want_password.encode()) + + def take(kind, match=None): + def fn(value): + if kind == 'rejectAuth': + if value.get('rejectAuth', 0) > 0: + value['rejectAuth'] -= 1 + return True + return False + for i, f in enumerate(value.get(kind, [])): + if match(f): + if f.get('skip', 0) > 0: + f['skip'] -= 1 # let this matching request through unfaulted + return None + return value[kind].pop(i) + return None + return faults.update(fn) + + @g.app.before_request + def guard(): + request_context.principal, request_context.detail = 'anonymous', {} + path = request.path.rstrip('/') or '/' + if path in ('/redfish', '/redfish/v1') and request.method == 'GET': + return None # the service root is unauthenticated (Redfish specification) + if not path.startswith('/redfish/v1/') or path == '/redfish/v1/reset': + return error(404, 'not served by this lab BMC') + if not authorized(): + request_context.principal = 'rejected' + return challenge() + if take('rejectAuth'): + request_context.principal, request_context.detail = 'rejected', {'fault': 'reject-auth'} + return challenge() + request_context.principal = 'authenticated' + m = re.fullmatch(r'/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?', path) + if not m: + return None + sid, sub = m.group(1), m.group(2) + if sid not in targets: + return None + try: + with LOCK: + lab.ensure(sid) + publish(sid, lab.power(sid)) + except LibvirtError as e: + return error(503, 'lab hardware unavailable: %s' % e) + if sub is None and request.method == 'PATCH': + body = request.get_json(force=True, silent=True) + if not isinstance(body, dict) or 'Boot' not in body: + return None # upstream handles its own patchable properties + return patch_boot(sid, body) + if sub == '/Actions/ComputerSystem.Reset' and request.method == 'POST': + return reset(sid) + return None + + def patch_boot(sid, body): + boot = body['Boot'] + if set(body) != {'Boot'} or not isinstance(boot, dict) or not set(boot) <= {'BootSourceOverrideTarget', 'BootSourceOverrideEnabled', 'BootSourceOverrideMode'}: + return error(400, 'only Boot source override properties are patchable with Boot') + current = dict(lab.nvram[sid]) + current.update({k: v for k, v in boot.items() if k != 'BootSourceOverrideMode'}) + if boot.get('BootSourceOverrideMode', 'Legacy') != 'Legacy' or current['BootSourceOverrideTarget'] not in BOOT_TARGETS or current['BootSourceOverrideEnabled'] not in BOOT_ENABLED: + return error(400, 'unsupported boot override value') + if current['BootSourceOverrideTarget'] == 'None': + current['BootSourceOverrideEnabled'] = 'Disabled' + with LOCK: + lab.nvram[sid] = current + lab.save() + publish(sid) + request_context.detail = {'boot': current} + return cs.members[sid], 200 + + def reset(sid): + body = request.get_json(force=True, silent=True) + kind = body.get('ResetType') if isinstance(body, dict) and set(body) == {'ResetType'} else None + allowed = [v for v in RESET_TYPES if v not in set(faults.read().get('hideResetTypes', []))] + if kind not in allowed: + return error(400, 'unsupported ResetType') + domain = targets[sid]['domain'] + try: + with LOCK: + power = lab.power(sid) + effect = 'none' + if kind in ('ForceOff', 'ForceRestart') and power != 'Off': + virsh('destroy', domain) + effect = 'destroyed' + if kind in ('On', 'ForceRestart') and (kind == 'ForceRestart' or power == 'Off'): + effect = 'started:' + lab.power_on(sid) + publish(sid, lab.power(sid)) + except LibvirtError as e: + return error(503, 'lab hardware unavailable: %s' % e) + request_context.detail = {'resetType': kind, 'effect': effect} + drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect.startswith('started') else None + if drop: + # Lab fault: the effect is applied, the response is withheld past the client timeout. + request_context.detail['fault'] = 'drop-response-after-effect' + time.sleep(min(int(drop.get('seconds', 45)), 120)) + return '', 204 + + @g.app.after_request + def audit(response): + entry = {'at': now(), 'method': request.method, 'path': request.path, 'status': response.status_code, + 'principal': getattr(request_context, 'principal', 'anonymous')} + entry.update(getattr(request_context, 'detail', {})) + with LOCK, open(audit_path, 'a') as f: + f.write(json.dumps(entry, sort_keys=True) + '\n') + f.flush() + os.fsync(f.fileno()) + return response + + return g.app + + +def load_targets(): + with open(os.path.join(CONFIG_DIR, 'targets.json')) as f: + return {t['system']: t for t in json.load(f)} + + +def fault_cli(args): + faults = FaultFile(STATE) + if args[:1] == ['drop-response'] and len(args) in (4, 5): + skip = int(args[4]) if len(args) == 5 else 0 + faults.update(lambda v: v.setdefault('dropResponse', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip})) + elif args[:1] == ['reject-auth'] and len(args) == 2: + faults.update(lambda v: v.__setitem__('rejectAuth', int(args[1]))) + elif args[:1] == ['hide-reset'] and len(args) == 2: + faults.update(lambda v: v.setdefault('hideResetTypes', []).append(args[1])) + elif args == ['clear']: + faults.update(lambda v: v.clear()) + elif args == ['show']: + pass + else: + raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | reject-auth COUNT | hide-reset TYPE | clear | show') + print(json.dumps(faults.read(), sort_keys=True)) + + +def main(): + if sys.argv[1:2] == ['serve']: + boot_ip = os.environ.get('FLEET_BOOT_IP', '') + if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', boot_ip): + raise SystemExit('FLEET_BOOT_IP must be the boot Service IPv4 address') + create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True) + elif sys.argv[1:2] == ['fault']: + fault_cli(sys.argv[2:]) + else: + raise SystemExit('usage: fleet_lab_adapter.py serve | fault ...') + + +if __name__ == '__main__': + main() diff --git a/hack/redfish-lab/populate-config.json b/hack/redfish-lab/populate-config.json new file mode 100644 index 00000000..a643ce4a --- /dev/null +++ b/hack/redfish-lab/populate-config.json @@ -0,0 +1,24 @@ +{ + "POPULATE": { + "Chassis": [ + { + "Name": "Fleet lab chassis", + "Id": "Chassis-{0}", + "Count": 1, + "Links": { + "ComputerSystems": [ + { + "Name": "Fleet lab target", + "Id": "System-{0}", + "Count": 2, + "Processors": [{"Id": "CPU{0}", "TotalCores": 2, "MaxSpeedMHz": 2000, "Count": 1}], + "Memory": [{"Id": "DRAM{0}", "CapacityMiB": 2048, "MemoryType": "DRAM", "Count": 1}], + "SimpleStorage": [{"Id": "VirtIO-{0}", "Count": 1, "Devices": {"CapacityBytes": 2147483648, "Count": 1}}], + "EthernetInterfaces": [{"Id": "NIC-{0}", "SpeedMbps": 1000, "Count": 1}] + } + ] + } + } + ] + } +} diff --git a/hack/redfish-lab/requirements.lock b/hack/redfish-lab/requirements.lock new file mode 100644 index 00000000..fbfc6321 --- /dev/null +++ b/hack/redfish-lab/requirements.lock @@ -0,0 +1,203 @@ +# Exact Python dependencies of DMTF Redfish-Interface-Emulator 1.2.2 (its requirements.txt +# lists names only). Installed with pip --require-hashes; hashes are every PyPI file of each version. +Flask==2.3.3 \ + --hash=sha256:09c347a92aa7ff4a8e7f3206795f30d826654baf38b873d0744cd571ca609efc \ + --hash=sha256:f69fcd559dc907ed196ab9df0e48471709175e696d6e698dd4dbe940f96ce66b +Werkzeug==2.3.8 \ + --hash=sha256:554b257c74bbeb7a0d254160a4f8ffe185243f52a52035060b761ca62d977f03 \ + --hash=sha256:bba1f19f8ec89d4d607a3bd62f1904bd2e609472d93cd85e9d4e178f472c3748 +Jinja2==3.1.6 \ + --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ + --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 +MarkupSafe==2.1.5 \ + --hash=sha256:00e046b6dd71aa03a41079792f8473dc494d564611a8f89bbbd7cb93295ebdcf \ + --hash=sha256:075202fa5b72c86ad32dc7d0b56024ebdbcf2048c0ba09f1cde31bfdd57bcfff \ + --hash=sha256:0e397ac966fdf721b2c528cf028494e86172b4feba51d65f81ffd65c63798f3f \ + --hash=sha256:17b950fccb810b3293638215058e432159d2b71005c74371d784862b7e4683f3 \ + --hash=sha256:1f3fbcb7ef1f16e48246f704ab79d79da8a46891e2da03f8783a5b6fa41a9532 \ + --hash=sha256:2174c595a0d73a3080ca3257b40096db99799265e1c27cc5a610743acd86d62f \ + --hash=sha256:2b7c57a4dfc4f16f7142221afe5ba4e093e09e728ca65c51f5620c9aaeb9a617 \ + --hash=sha256:2d2d793e36e230fd32babe143b04cec8a8b3eb8a3122d2aceb4a371e6b09b8df \ + --hash=sha256:30b600cf0a7ac9234b2638fbc0fb6158ba5bdcdf46aeb631ead21248b9affbc4 \ + --hash=sha256:397081c1a0bfb5124355710fe79478cdbeb39626492b15d399526ae53422b906 \ + --hash=sha256:3a57fdd7ce31c7ff06cdfbf31dafa96cc533c21e443d57f5b1ecc6cdc668ec7f \ + --hash=sha256:3c6b973f22eb18a789b1460b4b91bf04ae3f0c4234a0a6aa6b0a92f6f7b951d4 \ + --hash=sha256:3e53af139f8579a6d5f7b76549125f0d94d7e630761a2111bc431fd820e163b8 \ + --hash=sha256:4096e9de5c6fdf43fb4f04c26fb114f61ef0bf2e5604b6ee3019d51b69e8c371 \ + --hash=sha256:4275d846e41ecefa46e2015117a9f491e57a71ddd59bbead77e904dc02b1bed2 \ + --hash=sha256:4c31f53cdae6ecfa91a77820e8b151dba54ab528ba65dfd235c80b086d68a465 \ + --hash=sha256:4f11aa001c540f62c6166c7726f71f7573b52c68c31f014c25cc7901deea0b52 \ + --hash=sha256:5049256f536511ee3f7e1b3f87d1d1209d327e818e6ae1365e8653d7e3abb6a6 \ + --hash=sha256:58c98fee265677f63a4385256a6d7683ab1832f3ddd1e66fe948d5880c21a169 \ + --hash=sha256:598e3276b64aff0e7b3451b72e94fa3c238d452e7ddcd893c3ab324717456bad \ + --hash=sha256:5b7b716f97b52c5a14bffdf688f971b2d5ef4029127f1ad7a513973cfd818df2 \ + --hash=sha256:5dedb4db619ba5a2787a94d877bc8ffc0566f92a01c0ef214865e54ecc9ee5e0 \ + --hash=sha256:619bc166c4f2de5caa5a633b8b7326fbe98e0ccbfacabd87268a2b15ff73a029 \ + --hash=sha256:629ddd2ca402ae6dbedfceeba9c46d5f7b2a61d9749597d4307f943ef198fc1f \ + --hash=sha256:656f7526c69fac7f600bd1f400991cc282b417d17539a1b228617081106feb4a \ + --hash=sha256:6ec585f69cec0aa07d945b20805be741395e28ac1627333b1c5b0105962ffced \ + --hash=sha256:72b6be590cc35924b02c78ef34b467da4ba07e4e0f0454a2c5907f473fc50ce5 \ + --hash=sha256:7502934a33b54030eaf1194c21c692a534196063db72176b0c4028e140f8f32c \ + --hash=sha256:7a68b554d356a91cce1236aa7682dc01df0edba8d043fd1ce607c49dd3c1edcf \ + --hash=sha256:7b2e5a267c855eea6b4283940daa6e88a285f5f2a67f2220203786dfa59b37e9 \ + --hash=sha256:823b65d8706e32ad2df51ed89496147a42a2a6e01c13cfb6ffb8b1e92bc910bb \ + --hash=sha256:8590b4ae07a35970728874632fed7bd57b26b0102df2d2b233b6d9d82f6c62ad \ + --hash=sha256:8dd717634f5a044f860435c1d8c16a270ddf0ef8588d4887037c5028b859b0c3 \ + --hash=sha256:8dec4936e9c3100156f8a2dc89c4b88d5c435175ff03413b443469c7c8c5f4d1 \ + --hash=sha256:97cafb1f3cbcd3fd2b6fbfb99ae11cdb14deea0736fc2b0952ee177f2b813a46 \ + --hash=sha256:a17a92de5231666cfbe003f0e4b9b3a7ae3afb1ec2845aadc2bacc93ff85febc \ + --hash=sha256:a549b9c31bec33820e885335b451286e2969a2d9e24879f83fe904a5ce59d70a \ + --hash=sha256:ac07bad82163452a6884fe8fa0963fb98c2346ba78d779ec06bd7a6262132aee \ + --hash=sha256:ae2ad8ae6ebee9d2d94b17fb62763125f3f374c25618198f40cbb8b525411900 \ + --hash=sha256:b91c037585eba9095565a3556f611e3cbfaa42ca1e865f7b8015fe5c7336d5a5 \ + --hash=sha256:bc1667f8b83f48511b94671e0e441401371dfd0f0a795c7daa4a3cd1dde55bea \ + --hash=sha256:bec0a414d016ac1a18862a519e54b2fd0fc8bbfd6890376898a6c0891dd82e9f \ + --hash=sha256:bf50cd79a75d181c9181df03572cdce0fbb75cc353bc350712073108cba98de5 \ + --hash=sha256:bff1b4290a66b490a2f4719358c0cdcd9bafb6b8f061e45c7a2460866bf50c2e \ + --hash=sha256:c061bb86a71b42465156a3ee7bd58c8c2ceacdbeb95d05a99893e08b8467359a \ + --hash=sha256:c8b29db45f8fe46ad280a7294f5c3ec36dbac9491f2d1c17345be8e69cc5928f \ + --hash=sha256:ce409136744f6521e39fd8e2a24c53fa18ad67aa5bc7c2cf83645cce5b5c4e50 \ + --hash=sha256:d050b3361367a06d752db6ead6e7edeb0009be66bc3bae0ee9d97fb326badc2a \ + --hash=sha256:d283d37a890ba4c1ae73ffadf8046435c76e7bc2247bbb63c00bd1a709c6544b \ + --hash=sha256:d9fad5155d72433c921b782e58892377c44bd6252b5af2f67f16b194987338a4 \ + --hash=sha256:daa4ee5a243f0f20d528d939d06670a298dd39b1ad5f8a72a4275124a7819eff \ + --hash=sha256:db0b55e0f3cc0be60c1f19efdde9a637c32740486004f20d1cff53c3c0ece4d2 \ + --hash=sha256:e61659ba32cf2cf1481e575d0462554625196a1f2fc06a1c777d3f48e8865d46 \ + --hash=sha256:ea3d8a3d18833cf4304cd2fc9cbb1efe188ca9b5efef2bdac7adc20594a0e46b \ + --hash=sha256:ec6a563cff360b50eed26f13adc43e61bc0c04d94b8be985e6fb24b81f6dcfdf \ + --hash=sha256:f5dfb42c4604dddc8e4305050aa6deb084540643ed5804d7455b5df8fe16f5e5 \ + --hash=sha256:fa173ec60341d6bb97a89f5ea19c85c5643c1e7dedebc22f5181eb73573142c5 \ + --hash=sha256:fa9db3f79de01457b03d4f01b34cf91bc0048eb2c3846ff26f66687c2f6d16ab \ + --hash=sha256:fce659a462a1be54d2ffcacea5e3ba2d74daa74f30f5f143fe0c58636e355fdd \ + --hash=sha256:ffee1f21e5ef0d712f9033568f8344d5da8cc2869dbd08d87c84656e6a2d2f68 +itsdangerous==2.2.0 \ + --hash=sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef \ + --hash=sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173 +click==8.1.8 \ + --hash=sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2 \ + --hash=sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a +blinker==1.9.0 \ + --hash=sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf \ + --hash=sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc +Flask-RESTful==0.3.10 \ + --hash=sha256:1cf93c535172f112e080b0d4503a8d15f93a48c88bdd36dd87269bdaf405051b \ + --hash=sha256:fe4af2ef0027df8f9b4f797aba20c5566801b6ade995ac63b588abf1a59cec37 +aniso8601==9.0.1 \ + --hash=sha256:1d2b7ef82963909e93c4f24ce48d4de9e66009a21bf1c1e1c85bdd0812fe412f \ + --hash=sha256:72e3117667eedf66951bb2d93f4296a56b94b078a8a95905a052611fb3f1b973 +pytz==2025.2 \ + --hash=sha256:360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3 \ + --hash=sha256:5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00 +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 +StringGenerator==0.4.4 \ + --hash=sha256:35f86752460b25b2ccf936f6c8b0ed330cf49b01a34a5400cbf3fa6693dea609 +requests==2.32.3 \ + --hash=sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760 \ + --hash=sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6 +urllib3==2.2.3 \ + --hash=sha256:ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac \ + --hash=sha256:e7d814a81dad81e6caf2ec9fdedb284ecc9c73076b62654547cc64ccdcae26e9 +certifi==2025.1.31 \ + --hash=sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651 \ + --hash=sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe +idna==3.10 \ + --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \ + --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3 +charset-normalizer==3.4.1 \ + --hash=sha256:0167ddc8ab6508fe81860a57dd472b2ef4060e8d378f0cc555707126830f2537 \ + --hash=sha256:01732659ba9b5b873fc117534143e4feefecf3b2078b0a6a2e925271bb6f4cfa \ + --hash=sha256:01ad647cdd609225c5350561d084b42ddf732f4eeefe6e678765636791e78b9a \ + --hash=sha256:04432ad9479fa40ec0f387795ddad4437a2b50417c69fa275e212933519ff294 \ + --hash=sha256:0907f11d019260cdc3f94fbdb23ff9125f6b5d1039b76003b5b0ac9d6a6c9d5b \ + --hash=sha256:0924e81d3d5e70f8126529951dac65c1010cdf117bb75eb02dd12339b57749dd \ + --hash=sha256:09b26ae6b1abf0d27570633b2b078a2a20419c99d66fb2823173d73f188ce601 \ + --hash=sha256:09b5e6733cbd160dcc09589227187e242a30a49ca5cefa5a7edd3f9d19ed53fd \ + --hash=sha256:0af291f4fe114be0280cdd29d533696a77b5b49cfde5467176ecab32353395c4 \ + --hash=sha256:0f55e69f030f7163dffe9fd0752b32f070566451afe180f99dbeeb81f511ad8d \ + --hash=sha256:1a2bc9f351a75ef49d664206d51f8e5ede9da246602dc2d2726837620ea034b2 \ + --hash=sha256:22e14b5d70560b8dd51ec22863f370d1e595ac3d024cb8ad7d308b4cd95f8313 \ + --hash=sha256:234ac59ea147c59ee4da87a0c0f098e9c8d169f4dc2a159ef720f1a61bbe27cd \ + --hash=sha256:2369eea1ee4a7610a860d88f268eb39b95cb588acd7235e02fd5a5601773d4fa \ + --hash=sha256:237bdbe6159cff53b4f24f397d43c6336c6b0b42affbe857970cefbb620911c8 \ + --hash=sha256:28bf57629c75e810b6ae989f03c0828d64d6b26a5e205535585f96093e405ed1 \ + --hash=sha256:2967f74ad52c3b98de4c3b32e1a44e32975e008a9cd2a8cc8966d6a5218c5cb2 \ + --hash=sha256:2a75d49014d118e4198bcee5ee0a6f25856b29b12dbf7cd012791f8a6cc5c496 \ + --hash=sha256:2bdfe3ac2e1bbe5b59a1a63721eb3b95fc9b6817ae4a46debbb4e11f6232428d \ + --hash=sha256:2d074908e1aecee37a7635990b2c6d504cd4766c7bc9fc86d63f9c09af3fa11b \ + --hash=sha256:2fb9bd477fdea8684f78791a6de97a953c51831ee2981f8e4f583ff3b9d9687e \ + --hash=sha256:311f30128d7d333eebd7896965bfcfbd0065f1716ec92bd5638d7748eb6f936a \ + --hash=sha256:329ce159e82018d646c7ac45b01a430369d526569ec08516081727a20e9e4af4 \ + --hash=sha256:345b0426edd4e18138d6528aed636de7a9ed169b4aaf9d61a8c19e39d26838ca \ + --hash=sha256:363e2f92b0f0174b2f8238240a1a30142e3db7b957a5dd5689b0e75fb717cc78 \ + --hash=sha256:3a3bd0dcd373514dcec91c411ddb9632c0d7d92aed7093b8c3bbb6d69ca74408 \ + --hash=sha256:3bed14e9c89dcb10e8f3a29f9ccac4955aebe93c71ae803af79265c9ca5644c5 \ + --hash=sha256:44251f18cd68a75b56585dd00dae26183e102cd5e0f9f1466e6df5da2ed64ea3 \ + --hash=sha256:44ecbf16649486d4aebafeaa7ec4c9fed8b88101f4dd612dcaf65d5e815f837f \ + --hash=sha256:4532bff1b8421fd0a320463030c7520f56a79c9024a4e88f01c537316019005a \ + --hash=sha256:49402233c892a461407c512a19435d1ce275543138294f7ef013f0b63d5d3765 \ + --hash=sha256:4c0907b1928a36d5a998d72d64d8eaa7244989f7aaaf947500d3a800c83a3fd6 \ + --hash=sha256:4d86f7aff21ee58f26dcf5ae81a9addbd914115cdebcbb2217e4f0ed8982e146 \ + --hash=sha256:5777ee0881f9499ed0f71cc82cf873d9a0ca8af166dfa0af8ec4e675b7df48e6 \ + --hash=sha256:5df196eb874dae23dcfb968c83d4f8fdccb333330fe1fc278ac5ceeb101003a9 \ + --hash=sha256:619a609aa74ae43d90ed2e89bdd784765de0a25ca761b93e196d938b8fd1dbbd \ + --hash=sha256:6e27f48bcd0957c6d4cb9d6fa6b61d192d0b13d5ef563e5f2ae35feafc0d179c \ + --hash=sha256:6ff8a4a60c227ad87030d76e99cd1698345d4491638dfa6673027c48b3cd395f \ + --hash=sha256:73d94b58ec7fecbc7366247d3b0b10a21681004153238750bb67bd9012414545 \ + --hash=sha256:7461baadb4dc00fd9e0acbe254e3d7d2112e7f92ced2adc96e54ef6501c5f176 \ + --hash=sha256:75832c08354f595c760a804588b9357d34ec00ba1c940c15e31e96d902093770 \ + --hash=sha256:7709f51f5f7c853f0fb938bcd3bc59cdfdc5203635ffd18bf354f6967ea0f824 \ + --hash=sha256:78baa6d91634dfb69ec52a463534bc0df05dbd546209b79a3880a34487f4b84f \ + --hash=sha256:7974a0b5ecd505609e3b19742b60cee7aa2aa2fb3151bc917e6e2646d7667dcf \ + --hash=sha256:7a4f97a081603d2050bfaffdefa5b02a9ec823f8348a572e39032caa8404a487 \ + --hash=sha256:7b1bef6280950ee6c177b326508f86cad7ad4dff12454483b51d8b7d673a2c5d \ + --hash=sha256:7d053096f67cd1241601111b698f5cad775f97ab25d81567d3f59219b5f1adbd \ + --hash=sha256:804a4d582ba6e5b747c625bf1255e6b1507465494a40a2130978bda7b932c90b \ + --hash=sha256:807f52c1f798eef6cf26beb819eeb8819b1622ddfeef9d0977a8502d4db6d534 \ + --hash=sha256:80ed5e856eb7f30115aaf94e4a08114ccc8813e6ed1b5efa74f9f82e8509858f \ + --hash=sha256:8417cb1f36cc0bc7eaba8ccb0e04d55f0ee52df06df3ad55259b9a323555fc8b \ + --hash=sha256:8436c508b408b82d87dc5f62496973a1805cd46727c34440b0d29d8a2f50a6c9 \ + --hash=sha256:89149166622f4db9b4b6a449256291dc87a99ee53151c74cbd82a53c8c2f6ccd \ + --hash=sha256:8bfa33f4f2672964266e940dd22a195989ba31669bd84629f05fab3ef4e2d125 \ + --hash=sha256:8c60ca7339acd497a55b0ea5d506b2a2612afb2826560416f6894e8b5770d4a9 \ + --hash=sha256:91b36a978b5ae0ee86c394f5a54d6ef44db1de0815eb43de826d41d21e4af3de \ + --hash=sha256:955f8851919303c92343d2f66165294848d57e9bba6cf6e3625485a70a038d11 \ + --hash=sha256:97f68b8d6831127e4787ad15e6757232e14e12060bec17091b85eb1486b91d8d \ + --hash=sha256:9b23ca7ef998bc739bf6ffc077c2116917eabcc901f88da1b9856b210ef63f35 \ + --hash=sha256:9f0b8b1c6d84c8034a44893aba5e767bf9c7a211e313a9605d9c617d7083829f \ + --hash=sha256:aabfa34badd18f1da5ec1bc2715cadc8dca465868a4e73a0173466b688f29dda \ + --hash=sha256:ab36c8eb7e454e34e60eb55ca5d241a5d18b2c6244f6827a30e451c42410b5f7 \ + --hash=sha256:b010a7a4fd316c3c484d482922d13044979e78d1861f0e0650423144c616a46a \ + --hash=sha256:b1ac5992a838106edb89654e0aebfc24f5848ae2547d22c2c3f66454daa11971 \ + --hash=sha256:b7b2d86dd06bfc2ade3312a83a5c364c7ec2e3498f8734282c6c3d4b07b346b8 \ + --hash=sha256:b97e690a2118911e39b4042088092771b4ae3fc3aa86518f84b8cf6888dbdb41 \ + --hash=sha256:bc2722592d8998c870fa4e290c2eec2c1569b87fe58618e67d38b4665dfa680d \ + --hash=sha256:c0429126cf75e16c4f0ad00ee0eae4242dc652290f940152ca8c75c3a4b6ee8f \ + --hash=sha256:c30197aa96e8eed02200a83fba2657b4c3acd0f0aa4bdc9f6c1af8e8962e0757 \ + --hash=sha256:c4c3e6da02df6fa1410a7680bd3f63d4f710232d3139089536310d027950696a \ + --hash=sha256:c75cb2a3e389853835e84a2d8fb2b81a10645b503eca9bcb98df6b5a43eb8886 \ + --hash=sha256:c96836c97b1238e9c9e3fe90844c947d5afbf4f4c92762679acfe19927d81d77 \ + --hash=sha256:d7f50a1f8c450f3925cb367d011448c39239bb3eb4117c36a6d354794de4ce76 \ + --hash=sha256:d973f03c0cb71c5ed99037b870f2be986c3c05e63622c017ea9816881d2dd247 \ + --hash=sha256:d98b1668f06378c6dbefec3b92299716b931cd4e6061f3c875a71ced1780ab85 \ + --hash=sha256:d9c3cdf5390dcd29aa8056d13e8e99526cda0305acc038b96b30352aff5ff2bb \ + --hash=sha256:dad3e487649f498dd991eeb901125411559b22e8d7ab25d3aeb1af367df5efd7 \ + --hash=sha256:dccbe65bd2f7f7ec22c4ff99ed56faa1e9f785482b9bbd7c717e26fd723a1d1e \ + --hash=sha256:dd78cfcda14a1ef52584dbb008f7ac81c1328c0f58184bf9a84c49c605002da6 \ + --hash=sha256:e218488cd232553829be0664c2292d3af2eeeb94b32bea483cf79ac6a694e037 \ + --hash=sha256:e358e64305fe12299a08e08978f51fc21fac060dcfcddd95453eabe5b93ed0e1 \ + --hash=sha256:ea0d8d539afa5eb2728aa1932a988a9a7af94f18582ffae4bc10b3fbdad0626e \ + --hash=sha256:eab677309cdb30d047996b36d34caeda1dc91149e4fdca0b1a039b3f79d9a807 \ + --hash=sha256:eb8178fe3dba6450a3e024e95ac49ed3400e506fd4e9e5c32d30adda88cbd407 \ + --hash=sha256:ecddf25bee22fe4fe3737a399d0d177d72bc22be6913acfab364b40bce1ba83c \ + --hash=sha256:eea6ee1db730b3483adf394ea72f808b6e18cf3cb6454b4d86e04fa8c4327a12 \ + --hash=sha256:f08ff5e948271dc7e18a35641d2f11a4cd8dfd5634f55228b691e62b37125eb3 \ + --hash=sha256:f30bf9fd9be89ecb2360c7d94a711f00c09b976258846efe40db3d05828e8089 \ + --hash=sha256:fa88b843d6e211393a37219e6a1c1df99d35e8fd90446f1118f4216e307e48cd \ + --hash=sha256:fc54db6c8593ef7d4b2a331b58653356cf04f67c960f584edb7c3d8c97e8f39e \ + --hash=sha256:fd4ec41f914fa74ad1b8304bbc634b3de73d2a0889bd32076342a573e0779e00 \ + --hash=sha256:ffc9202a29ab3920fa812879e95a9e78b2465fd10be7fcbd042899695d75e616 +Flask-HTTPAuth==4.8.0 \ + --hash=sha256:66568a05bc73942c65f1e2201ae746295816dc009edd84b482c44c758d75097a \ + --hash=sha256:a58fedd09989b9975448eef04806b096a3964a7feeebc0a78831ff55685b62b0 diff --git a/hack/redfish-lab/targets.json b/hack/redfish-lab/targets.json new file mode 100644 index 00000000..23e256b0 --- /dev/null +++ b/hack/redfish-lab/targets.json @@ -0,0 +1,8 @@ +[ + {"system": "System-1", "name": "fleet-lab-target-a", "domain": "fleet-lab-target-a", + "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a", "mac": "52:54:00:77:01:0a", "ip": "192.168.77.10", + "disk": "/var/lib/fleet-lab/disks/target-a.raw", "console": "/var/lib/fleet-lab-console/target-a.log"}, + {"system": "System-2", "name": "fleet-lab-target-b", "domain": "fleet-lab-target-b", + "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b", "mac": "52:54:00:77:01:0b", "ip": "192.168.77.11", + "disk": "/var/lib/fleet-lab/disks/target-b.raw", "console": "/var/lib/fleet-lab-console/target-b.log"} +] diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py new file mode 100644 index 00000000..e44926a6 --- /dev/null +++ b/hack/redfish-lab/test_adapter.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Self-test of the unmodified upstream emulator plus the lab adapter. + +Runs inside the built BMC image (it needs the pinned upstream emulator and its +Python dependencies) with fake_virsh.py in place of libvirt. The harness runs +it before creating any cluster; see docs/operations/redfish-lab.md. +""" +import base64 +import json +import os +import pathlib +import sys +import tempfile +import unittest + +HERE = pathlib.Path(__file__).resolve().parent +WORK = pathlib.Path(tempfile.mkdtemp()) +(WORK / 'creds').mkdir() +(WORK / 'creds' / 'username').write_text('lab-operator\n') +(WORK / 'creds' / 'password').write_text('synthetic-test-password\n') +os.environ.update(FLEET_VIRSH=str(HERE / 'fake_virsh.py'), FAKE_VIRSH_STATE=str(WORK / 'virsh.json'), FLEET_BMC_STATE=str(WORK / 'state')) +sys.path.insert(0, str(HERE)) +import fleet_lab_adapter as adapter # noqa: E402 + +AUTH = {'Authorization': 'Basic ' + base64.b64encode(b'lab-operator:synthetic-test-password').decode()} +BAD = {'Authorization': 'Basic ' + base64.b64encode(b'lab-operator:wrong').decode()} + + +def virsh_state(): + return json.loads((WORK / 'virsh.json').read_text()) + + +class AdapterTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = adapter.create_app(adapter.load_targets(), str(WORK / 'state'), str(WORK / 'creds'), '10.96.0.80').test_client() + + def audit(self): + return [json.loads(l) for l in (WORK / 'state' / 'audit.log').read_text().splitlines()] + + def test_1_service_root_is_upstream_and_unauthenticated(self): + r = self.app.get('/redfish/v1/') + self.assertEqual(r.status_code, 200) + self.assertEqual(r.json['Systems'], {'@odata.id': '/redfish/v1/Systems'}) + self.assertEqual(self.app.delete('/redfish/v1/reset/').status_code, 404) + + def test_2_authentication_is_enforced(self): + self.assertEqual(self.app.get('/redfish/v1/Systems').status_code, 401) + self.assertEqual(self.app.get('/redfish/v1/Systems', headers=BAD).status_code, 401) + members = self.app.get('/redfish/v1/Systems', headers=AUTH).json['Members'] + self.assertEqual(sorted(m['@odata.id'] for m in members), ['/redfish/v1/Systems/System-1', '/redfish/v1/Systems/System-2']) + + def test_3_system_identity_and_capabilities(self): + s = self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json + self.assertEqual(s['UUID'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') + self.assertEqual(s['PowerState'], 'Off') + self.assertEqual(s['Boot']['BootSourceOverrideTarget@Redfish.AllowableValues'], ['None', 'Pxe', 'Hdd']) + info = self.app.get(s['Actions']['#ComputerSystem.Reset']['@Redfish.ActionInfo'], headers=AUTH).json + self.assertEqual(info['Parameters'][0]['AllowableValues'], ['On', 'ForceOff', 'ForceRestart']) + + def test_4_boot_once_is_consumed_by_power_on(self): + r = self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Pxe', 'BootSourceOverrideEnabled': 'Once'}}) + self.assertEqual(r.status_code, 200) + self.assertEqual(self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd'}}).status_code, 400) + r = self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertEqual(r.status_code, 204) + d = virsh_state()['domains'] + self.assertEqual(d['fleet-lab-target-a']['starts'], ['network']) + self.assertFalse(d['fleet-lab-target-b']['running'] if 'fleet-lab-target-b' in d else False) + s = self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json + self.assertEqual((s['PowerState'], s['Boot']['BootSourceOverrideEnabled']), ('On', 'Disabled')) + # On while on is a no-op, never a second start. + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'], ['network']) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json['PowerState'], 'Off') + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'Nmi'}).status_code, 400) + + def test_5_faults_are_bounded_and_audited(self): + adapter.fault_cli(['reject-auth', '1']) + self.assertEqual(self.app.get('/redfish/v1/Systems', headers=AUTH).status_code, 401) + self.assertEqual(self.app.get('/redfish/v1/Systems', headers=AUTH).status_code, 200) + adapter.fault_cli(['hide-reset', 'On']) + info = self.app.get('/redfish/v1/Systems/System-1/ResetActionInfo', headers=AUTH).json + self.assertNotIn('On', info['Parameters'][0]['AllowableValues']) + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 400) + adapter.fault_cli(['clear']) + # Skip one effective On, then withhold the response of the next one. + adapter.fault_cli(['drop-response', 'System-1', 'On', '1', '1']) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertNotIn('fault', self.audit()[-1]) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + entries = self.audit() + self.assertEqual(entries[-1]['fault'], 'drop-response-after-effect') + self.assertEqual(entries[-1]['effect'], 'started:hd') + self.assertEqual(adapter.FaultFile(str(WORK / 'state')).read().get('dropResponse'), []) + text = (WORK / 'state' / 'audit.log').read_text() + self.assertNotIn('synthetic-test-password', text) + self.assertNotIn('Authorization', text) + + def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): + s = virsh_state() + s['domains'].pop('fleet-lab-target-a') + s['networks'].clear() + (WORK / 'virsh.json').write_text(json.dumps(s)) + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 200) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['uuid'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') + os.environ['FAKE_VIRSH_DOWN'] = '1' + try: + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + finally: + del os.environ['FAKE_VIRSH_DOWN'] + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/hack/redfish-lab/upstream.sh b/hack/redfish-lab/upstream.sh new file mode 100755 index 00000000..99845e85 --- /dev/null +++ b/hack/redfish-lab/upstream.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Fetch the pinned DMTF Redfish Interface Emulator release into DEST, verified +# before extraction. Prints the provenance record as JSON. +set -euo pipefail +umask 077 +dest=${1:?destination directory} +version=1.2.2 +commit=5f51d8ac48e46665a2a85242434f125aa7b25172 +url=https://github.com/DMTF/Redfish-Interface-Emulator/archive/refs/tags/$version.tar.gz +sha256=acee609abaedaf123b56e7ca5b2534da94bdee6fc1183dde72699c30d63de79f +mkdir -p "$dest" +archive="$dest/redfish-interface-emulator-$version.tar.gz" +[[ -f $archive ]] || curl -fsSL --max-time 120 -o "$archive" "$url" +got=$(shasum -a 256 "$archive" | cut -d' ' -f1) +[[ $got == "$sha256" ]] || { echo "upstream archive digest $got, expected $sha256" >&2; exit 1; } +rm -rf "$dest/src" +mkdir "$dest/src" +python3 - "$archive" "$dest/src" <<'PY' +import sys, tarfile +with tarfile.open(sys.argv[1]) as t: + t.extractall(sys.argv[2], filter='data') +PY +[[ -f $dest/src/Redfish-Interface-Emulator-$version/emulator.py ]] || { echo 'unexpected archive layout' >&2; exit 1; } +printf '{"project":"DMTF Redfish-Interface-Emulator","version":"%s","commit":"%s","archive":"%s","archiveSHA256":"%s","license":"BSD-3-Clause"}\n' "$version" "$commit" "$url" "$sha256" diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 8f62f34f..869cb956 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -371,6 +371,10 @@ func (r *Runner) Allocate(ctx context.Context) error { } func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } +// InstallSecond installs consumer B's Installation after it reused the +// capacity, through the same lifecycle and federation path. +func (r *Runner) InstallSecond(ctx context.Context) error { return r.InstallIndex(ctx, 1) } + func (r *Runner) InstallIndex(ctx context.Context, index int) error { request, err := r.request(ctx, index) if err != nil { diff --git a/internal/redfish/boot.go b/internal/redfish/boot.go new file mode 100644 index 00000000..7dd7d1e2 --- /dev/null +++ b/internal/redfish/boot.go @@ -0,0 +1,217 @@ +package redfish + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +// The provisioning network is site infrastructure: its DHCP hands every +// enrolled NIC the same static script, which chains to a per-MAC URL. The MAC +// is routing information, not authentication. Only a retained operation whose +// enrolled target has that MAC and whose boot admission is open receives a +// script, and that script carries the operation's scoped capability. +const chainScript = "#!ipxe\nchain %s/pxe/${net0/mac:hexhyp}/boot.ipxe\n" + +func (p *Provider) admissionOpen(j journal, r *record) bool { + if j.Closed || j.Image != p.image || r.BootClosed || len(r.BootToken) != 64 || !p.clock().Before(r.BootExpires) { + return false + } + if r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence { + return false + } + for _, ph := range phases[r.Request.Kind] { + if ph.mode != "" && (r.Stage == ph.name+"-requested" || r.Stage == ph.name+"-started") { + return true + } + } + return false +} + +func mode(r *record) string { + if r.Request.Kind == "cleanup" { + return "wipe" + } + return "install" +} + +// BootHandler never serves a caller-selected path. It reads the atomically +// replaced journal on every request and writes only delivery evidence. +func (p *Provider) BootHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(q.URL.Path, "/") + if q.Method != http.MethodGet || q.URL.RawQuery != "" { + deny() + return + } + if q.URL.Path == "/pxe/boot.ipxe" { + fmt.Fprintf(w, chainScript, p.origin) + return + } + j, err := p.read() + if err != nil || len(parts) != 4 { + deny() + return + } + var r *record + var name string + if parts[1] == "pxe" && parts[3] == "boot.ipxe" { + mac, ok := normalizeMAC(parts[2]) + for _, c := range j.Operations { + if ok && c.Target.MAC == mac && p.admissionOpen(j, c) { + r, name = c, "boot.ipxe" + } + } + } else { + for _, c := range j.Operations { + if key(c.Request.ID)[:16] == parts[1] && len(c.BootToken) == 64 && subtle.ConstantTimeCompare([]byte(parts[2]), []byte(c.BootToken)) == 1 && p.admissionOpen(j, c) { + r, name = c, parts[3] + } + } + } + if r == nil || (name != "boot.ipxe" && name != "kernel" && name != "installer.gz") || (name == "boot.ipxe" && parts[1] != "pxe") { + deny() + return + } + var data []byte + var artifact *os.File + var size int64 + if name == "boot.ipxe" { + base := p.origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, mode(r), base)) + size = int64(len(data)) + } else { + // Hash the pinned artifact, then serve the same open file. + if artifact, err = os.Open(p.artifacts + "/" + name); err != nil { + deny() + return + } + defer artifact.Close() + manifest, e := os.ReadFile(p.artifacts + "/SHA256SUMS") + sum := sha256.Sum256(manifest) + h := sha256.New() + size, err = io.Copy(h, artifact) + if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + } + if err := p.evidence(r, "admitted", name, size); err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var n int64 + var werr error + if artifact != nil { + n, werr = io.Copy(w, artifact) + } else { + var written int + written, werr = w.Write(data) + n = int64(written) + } + // A completed server write is not proof of client receipt or boot. + if werr == nil && n == size { + _ = p.evidence(r, "write-complete", name, n) + } + }) +} + +// evidence appends one line without URLs, headers, receipts or capabilities. +func (p *Provider) evidence(r *record, event, name string, size int64) error { + dir := p.bootDirectory(r) + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(dir, "boot-delivery.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = fmt.Fprintf(f, "%s %s %s bytes=%d\n", p.clock().Format(time.RFC3339), event, name, size) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = syncDir(dir) + } + return err +} + +// ServeBoot listens on :8080. The write bound covers an emulated firmware +// fetching the initrd through the site's NAT path. +func (p *Provider) ServeBoot() error { + s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} + return s.ListenAndServe() +} + +// CheckClosedBoot probes a live boot listener after every admission closed: +// each retained operation's MAC script and capability URLs, an unsupported +// artifact, an unguarded artifact and an unknown identity must be denied. +func (p *Provider) CheckClosedBoot(origin string, extraMACs []string) (string, error) { + origin, err := ParseBootOrigin(origin) + if err != nil { + return "", err + } + j, err := p.read() + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + probe := func(u string) error { + resp, err := client.Get(u) + if err != nil { + return fmt.Errorf("boot denial probe unavailable") + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + return fmt.Errorf("closed or unknown boot access allowed") + } + count++ + return nil + } + for _, r := range j.Operations { + if !r.BootClosed { + return "", fmt.Errorf("boot admission not closed") + } + base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + macPath := strings.ReplaceAll(r.Target.MAC, ":", "-") + for _, u := range []string{origin + "/pxe/" + macPath + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", base + "/boot.ipxe"} { + if err := probe(u); err != nil { + return "", err + } + } + } + for _, mac := range extraMACs { + if err := probe(origin + "/pxe/" + strings.ReplaceAll(mac, ":", "-") + "/boot.ipxe"); err != nil { + return "", err + } + } + for _, u := range []string{origin + "/kernel", origin + "/unknown/unknown/kernel", origin + "/pxe/not-a-mac/boot.ipxe"} { + if err := probe(u); err != nil { + return "", err + } + } + if len(j.Operations) == 0 { + return "", fmt.Errorf("no retained admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed per-MAC scripts and capabilities of %d operations, other enrolled MACs, unsupported and unguarded artifacts, unknown identity", count, len(j.Operations)), nil +} diff --git a/internal/redfish/client.go b/internal/redfish/client.go new file mode 100644 index 00000000..c9c0d1b4 --- /dev/null +++ b/internal/redfish/client.go @@ -0,0 +1,413 @@ +// Package redfish implements a Redfish provisioning executor for one site. +// +// It drives exact enrolled ComputerSystems through standard Redfish requests: +// service-root discovery, ComputerSystem.Reset and a one-time boot source +// override. It holds no hypervisor credential and never shells out. The local +// acceptance runs it against the DMTF Redfish Interface Emulator with a +// lab-only libvirt adapter (hack/redfish-lab); that adapter is not part of +// this package. See docs/operations/redfish-lab.md for what is verified and +// what remains hardware-unqualified. +// +// Redfish requests, schema decoding and collection paging use gofish. Fleet +// issues every mutation itself as one request: gofish's SetBoot (a second +// PATCH to the Settings resource on failure) and Reset (a resend without +// If-Match on 412) are deliberately not used. +package redfish + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" +) + +const maxBody = 1 << 20 + +var ( + // ErrUnauthorized means the BMC rejected the enrolled credential. + ErrUnauthorized = errors.New("redfish: credential rejected") + // ErrUnsupported means a required action or value is not advertised. + ErrUnsupported = errors.New("redfish: required capability not advertised") + // ErrIdentity means the enrolled System is not exactly present. + ErrIdentity = errors.New("redfish: enrolled system identity not matched exactly") + // ErrPrecondition means the BMC refused a mutation's If-Match. It is not + // retried without the precondition; the caller observes and decides. + ErrPrecondition = errors.New("redfish: System changed since it was observed") +) + +// Client is a minimal Redfish client over gofish. Its transport admits only +// /redfish/v1 paths on the configured endpoint, never follows redirects or an +// environment proxy, and bounds every response body. +type Client struct { + config gofish.ClientConfig + mu sync.Mutex + api *gofish.APIClient +} + +// NewClient accepts only an http(s)://IP:port endpoint without path or query. +// It performs no request until first use. +func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { + u, err := url.Parse(endpoint) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" { + return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + } + port, err := strconv.Atoi(u.Port()) + if ip := net.ParseIP(u.Hostname()); ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + } + if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { + return nil, errors.New("redfish credential must be a nonempty single-line username and password") + } + if timeout <= 0 { + return nil, errors.New("redfish client requires a positive timeout") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + return &Client{config: gofish.ClientConfig{ + Endpoint: u.Scheme + "://" + u.Host, Username: user, Password: password, + // Basic authentication: creating a session would itself be a BMC + // mutation with its own lifetime and cleanup. + BasicAuth: true, NoModifyTransport: true, + HTTPClient: &http.Client{Timeout: timeout, Transport: guard{scheme: u.Scheme, host: u.Host, next: transport}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + }}, nil +} + +func cleanPath(p string) (string, error) { + if (p != "/redfish/v1" && !strings.HasPrefix(p, "/redfish/v1/")) || strings.Contains(p, "..") || strings.ContainsAny(p, "?#\\ ") { + return "", fmt.Errorf("%w: unexpected resource path", ErrIdentity) + } + return strings.TrimSuffix(p, "/"), nil +} + +// guard is the only path from gofish to the network. A link the BMC returns +// cannot direct a request to another host or outside /redfish/v1, and a +// mutation cannot carry a query. +type guard struct { + scheme, host string + next http.RoundTripper +} + +func (g guard) RoundTrip(r *http.Request) (*http.Response, error) { + u := r.URL + if _, err := cleanPath(u.Path); err != nil || u.Scheme != g.scheme || u.Host != g.host || u.User != nil || u.Fragment != "" || (u.RawQuery != "" && r.Method != http.MethodGet) { + if r.Body != nil { + r.Body.Close() + } + return nil, fmt.Errorf("%w: unexpected resource path", ErrIdentity) + } + r = r.Clone(r.Context()) + r.Header.Set("OData-Version", "4.0") + resp, err := g.next.RoundTrip(r) + if err != nil { + return nil, err + } + resp.Body = &bounded{ReadCloser: resp.Body, left: maxBody} + return resp, nil +} + +type bounded struct { + io.ReadCloser + left int64 +} + +func (b *bounded) Read(p []byte) (int, error) { + if b.left <= 0 { + return 0, errors.New("redfish: response exceeds size bound") + } + if int64(len(p)) > b.left { + p = p[:b.left] + } + n, err := b.ReadCloser.Read(p) + b.left -= int64(n) + return n, err +} + +// Status is a non-2xx Redfish response other than an authentication failure. +type Status struct{ Code int } + +func (s Status) Error() string { return "redfish: HTTP " + strconv.Itoa(s.Code) } + +// classify reduces a gofish error to Fleet's outcome classes. The result +// never carries a URL, header or response body. +func classify(err error) error { + var coll *schemas.CollectionError + if errors.As(err, &coll) { + var worst error + for _, e := range coll.Failures { + e = classify(e) + if worst == nil || errors.Is(e, ErrIdentity) || (errors.Is(e, ErrUnauthorized) && !errors.Is(worst, ErrIdentity)) { + worst = e + } + } + return worst + } + var rf *schemas.Error + switch { + case err == nil: + return nil + case errors.Is(err, ErrIdentity): + return fmt.Errorf("%w: unexpected resource path", ErrIdentity) + case errors.As(err, &rf) && (rf.HTTPReturnedStatusCode == http.StatusUnauthorized || rf.HTTPReturnedStatusCode == http.StatusForbidden): + return ErrUnauthorized + case errors.As(err, &rf) && rf.HTTPReturnedStatusCode == http.StatusPreconditionFailed: + return ErrPrecondition + case errors.As(err, &rf) && rf.HTTPReturnedStatusCode != 0: + return Status{rf.HTTPReturnedStatusCode} + } + // Transport failure, unreadable or oversized response, or a body gofish + // cannot decode as the expected schema. + return errors.New("redfish: transport failure or unreadable response") +} + +// connect reads the unauthenticated service root once and binds the +// stateless basic-auth client to each call's context. +func (c *Client) connect(ctx context.Context) (*gofish.APIClient, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.api == nil { + api, err := gofish.ConnectContext(ctx, c.config) + if err != nil { + return nil, classify(err) + } + c.api = api + } + return c.api.WithContext(ctx), nil +} + +func contains[T ~string](list []T, v string) bool { + for _, x := range list { + if string(x) == v { + return true + } + } + return false +} + +// System is the discovered, retained identity and capability of one target. +type System struct { + Path string `json:"path"` + ID string `json:"id"` + UUID string `json:"uuid"` + ResetTarget string `json:"resetTarget"` + ResetTypes []string `json:"resetTypes"` + BootTargets []string `json:"bootTargets"` +} + +// Power is one observation of a System's power and boot override state. +type Power struct { + State string `json:"state"` + OverrideEnabled string `json:"overrideEnabled"` + OverrideTarget string `json:"overrideTarget"` + etag string +} + +// resetAction holds the annotations gofish decodes into unexported fields. +type resetAction struct { + Actions struct { + Reset struct { + Target string `json:"target"` + Info string `json:"@Redfish.ActionInfo"` + Allowed []string `json:"ResetType@Redfish.AllowableValues"` + } `json:"#ComputerSystem.Reset"` + } + Boot struct { + Enabled *[]string `json:"BootSourceOverrideEnabled@Redfish.AllowableValues"` + } +} + +// Discover walks the service root to the enrolled System. Every member of the +// Systems collection, across all pages, must be read: exactly one must carry +// the enrolled UUID, and it must have the enrolled Id; a member with the +// enrolled Id but another UUID is a renumbered or swapped target. The reset +// target and ActionInfo must belong to that System, and On, ForceOff, Pxe and +// Hdd must be advertised. Discovery issues GETs only. +func (c *Client) Discover(ctx context.Context, t Target) (System, error) { + api, err := c.connect(ctx) + if err != nil { + return System{}, err + } + // gofish keeps the Systems link unexported; read the root once more to + // validate it, then walk exactly that collection. + resp, err := api.Get(schemas.DefaultServiceRoot) + var root struct { + Systems struct { + ID string `json:"@odata.id"` + } + } + if err == nil { + err = json.NewDecoder(resp.Body).Decode(&root) + } + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return System{}, classify(err) + } + if root.Systems.ID == "" { + return System{}, fmt.Errorf("%w: service root has no Systems collection", ErrUnsupported) + } + collection, err := cleanPath(root.Systems.ID) + if err != nil { + return System{}, err + } + members, err := schemas.GetCollectionObjects[schemas.ComputerSystem](api, collection) + if err != nil { + // A partially read collection cannot prove the UUID is unique. + return System{}, classify(err) + } + var found []*schemas.ComputerSystem + for _, s := range members { + p, err := cleanPath(s.ODataID) + if err != nil || !strings.HasPrefix(p, collection+"/") { + return System{}, fmt.Errorf("%w: system member outside the collection", ErrIdentity) + } + if strings.EqualFold(s.UUID, t.SystemUUID) { + found = append(found, s) + } else if s.ID == t.SystemID { + return System{}, fmt.Errorf("%w: enrolled Id reports another UUID", ErrIdentity) + } + } + if len(found) != 1 || found[0].ID != t.SystemID { + return System{}, fmt.Errorf("%w: %d members carry the enrolled UUID", ErrIdentity, len(found)) + } + s := found[0] + sys := System{ID: t.SystemID, UUID: t.SystemUUID} + sys.Path, _ = cleanPath(s.ODataID) + var raw resetAction + if err := json.Unmarshal(s.RawData, &raw); err != nil { + return System{}, classify(err) + } + reset := raw.Actions.Reset + target, err := cleanPath(reset.Target) + if err != nil || !strings.HasPrefix(target, sys.Path+"/") { + return System{}, fmt.Errorf("%w: ComputerSystem.Reset target not on the enrolled System", ErrUnsupported) + } + sys.ResetTarget = target + sys.ResetTypes = reset.Allowed + if len(sys.ResetTypes) == 0 && reset.Info != "" { + info, err := cleanPath(reset.Info) + if err != nil || !strings.HasPrefix(info, sys.Path+"/") { + return System{}, fmt.Errorf("%w: ActionInfo not on the enrolled System", ErrUnsupported) + } + // Not schemas.ActionInfo: its typed decode rejects the whole document + // for one off-schema property, as the DMTF emulator's string + // "Required": "true". Only the ResetType values are read. + resp, err := api.Get(info) + var ai struct { + Parameters []struct { + Name, DataType string + AllowableValues []string + } + } + if err == nil { + err = json.NewDecoder(resp.Body).Decode(&ai) + } + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return System{}, classify(err) + } + for _, p := range ai.Parameters { + if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { + sys.ResetTypes = p.AllowableValues + } + } + } + for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { + sys.BootTargets = append(sys.BootTargets, string(b)) + } + for _, need := range []string{"On", "ForceOff"} { + if !contains(sys.ResetTypes, need) { + return System{}, fmt.Errorf("%w: ResetType %s", ErrUnsupported, need) + } + } + for _, need := range []string{"Pxe", "Hdd"} { + if !contains(sys.BootTargets, need) { + return System{}, fmt.Errorf("%w: boot override target %s", ErrUnsupported, need) + } + } + if raw.Boot.Enabled != nil && !contains(*raw.Boot.Enabled, "Once") { + return System{}, fmt.Errorf("%w: one-time boot override", ErrUnsupported) + } + return sys, nil +} + +func observe(api *gofish.APIClient, sys System) (Power, error) { + s, err := schemas.GetObject[schemas.ComputerSystem](api, sys.Path) + if err != nil { + return Power{}, classify(err) + } + if s.ID != sys.ID || !strings.EqualFold(s.UUID, sys.UUID) { + return Power{}, fmt.Errorf("%w: retained System path changed identity", ErrIdentity) + } + return Power{State: string(s.PowerState), OverrideEnabled: string(s.Boot.BootSourceOverrideEnabled), + OverrideTarget: string(s.Boot.BootSourceOverrideTarget), etag: s.ODataEtag}, nil +} + +// Observe reads the retained System again and re-checks its identity. +func (c *Client) Observe(ctx context.Context, sys System) (Power, error) { + api, err := c.connect(ctx) + if err != nil { + return Power{}, err + } + return observe(api, sys) +} + +// SetBootOnce observes the System, sends exactly one PATCH of the one-time +// boot override (conditional on the observed ETag when the BMC provides one), +// and reads it back. A refused precondition is returned, not retried. +func (c *Client) SetBootOnce(ctx context.Context, sys System, target string) error { + if !contains(sys.BootTargets, target) { + return fmt.Errorf("%w: boot override target %s", ErrUnsupported, target) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + before, err := observe(api, sys) + if err != nil { + return err + } + headers := map[string]string{} + if before.etag != "" { + headers["If-Match"] = before.etag + } + resp, err := api.PatchWithHeaders(sys.Path, map[string]any{"Boot": map[string]string{"BootSourceOverrideTarget": target, "BootSourceOverrideEnabled": "Once"}}, headers) + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return classify(err) + } + p, err := observe(api, sys) + if err != nil { + return err + } + if p.OverrideTarget != target || p.OverrideEnabled != "Once" { + return errors.New("redfish: boot override not observed after PATCH") + } + return nil +} + +// Reset posts exactly one ComputerSystem.Reset to the discovered action +// target. HTTP success, including 202 with a task monitor, is not evidence of +// the effect; callers observe the System. +func (c *Client) Reset(ctx context.Context, sys System, kind string) error { + if !contains(sys.ResetTypes, kind) { + return fmt.Errorf("%w: ResetType %s", ErrUnsupported, kind) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + resp, err := api.PostWithHeaders(sys.ResetTarget, map[string]string{"ResetType": kind}, nil) + schemas.DeferredCleanupHTTPResponse(resp) + return classify(err) +} diff --git a/internal/redfish/client_test.go b/internal/redfish/client_test.go new file mode 100644 index 00000000..cf720a44 --- /dev/null +++ b/internal/redfish/client_test.go @@ -0,0 +1,247 @@ +package redfish + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// bmcStub serves fixed Redfish documents and records every request. +type bmcStub struct { + mu sync.Mutex + docs map[string]any + headers map[string]http.Header + status map[string]int // "METHOD path" -> status + hold map[string]time.Duration + requests []string + ifMatch []string +} + +func newStub() *bmcStub { + sys := func(id, uuid string) map[string]any { + p := "/redfish/v1/Systems/" + id + return map[string]any{"@odata.id": p, "Id": id, "UUID": uuid, "PowerState": "Off", + "Boot": map[string]any{"BootSourceOverrideEnabled": "Disabled", "BootSourceOverrideTarget": "None", + "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, + "@Redfish.Settings": map[string]any{"SettingsObject": map[string]string{"@odata.id": p + "/Settings"}}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": p + "/Actions/ComputerSystem.Reset", + "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}} + } + return &bmcStub{docs: map[string]any{ + "/redfish/v1/": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/A"}}, "Members@odata.nextLink": "/redfish/v1/Systems?$skip=1"}, + "/redfish/v1/Systems?$skip=1": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/B"}}}, + "/redfish/v1/Systems/A": sys("A", uuidA), + "/redfish/v1/Systems/B": sys("B", uuidB), + "/redfish/v1/Systems/Settings": map[string]any{}, + }, headers: map[string]http.Header{}, status: map[string]int{}, hold: map[string]time.Duration{}} +} + +func (b *bmcStub) ServeHTTP(w http.ResponseWriter, r *http.Request) { + key := r.URL.Path + if r.URL.RawQuery != "" { + key += "?" + r.URL.RawQuery + } + b.mu.Lock() + b.requests = append(b.requests, r.Method+" "+key) + if r.Method != http.MethodGet { + b.ifMatch = append(b.ifMatch, r.Header.Get("If-Match")) + } + doc, ok := b.docs[key] + code, coded := b.status[r.Method+" "+key] + hold := b.hold[r.Method+" "+key] + for k, v := range b.headers[key] { + w.Header()[k] = v + } + b.mu.Unlock() + time.Sleep(hold) + if user, pass, _ := r.BasicAuth(); key != "/redfish/v1/" && (user != "operator" || pass != "synthetic-secret" || r.Header.Get("OData-Version") != "4.0") { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch { + case coded: + w.WriteHeader(code) + w.Write([]byte(`{"error":{"message":"echo synthetic-secret"}}`)) + case r.Method != http.MethodGet: + w.WriteHeader(http.StatusNoContent) + case !ok: + w.WriteHeader(http.StatusNotFound) + default: + json.NewEncoder(w).Encode(doc) + } +} + +func (b *bmcStub) count(prefix string) int { + b.mu.Lock() + defer b.mu.Unlock() + n := 0 + for _, r := range b.requests { + if strings.HasPrefix(r, prefix) { + n++ + } + } + return n +} + +func stubClient(t *testing.T, b *bmcStub, timeout time.Duration) *Client { + t.Helper() + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "operator", "synthetic-secret", timeout) + if err != nil { + t.Fatal(err) + } + return c +} + +func noSecret(t *testing.T, err error) { + t.Helper() + if err != nil && (strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString([]byte("operator:synthetic-secret"))) || strings.Contains(err.Error(), "127.0.0.1")) { + t.Fatalf("error exposes a credential, body or endpoint: %v", err) + } +} + +func TestDiscoveryWalksEveryPageOfTheSystemsCollection(t *testing.T) { + b := newStub() + c := stubClient(t, b, time.Second) + s, err := c.Discover(context.Background(), Target{SystemID: "B", SystemUUID: strings.ToUpper(uuidB)}) + if err != nil || s.Path != "/redfish/v1/Systems/B" || s.ResetTarget != s.Path+"/Actions/ComputerSystem.Reset" || strings.Join(s.BootTargets, ",") != "Pxe,Hdd" { + t.Fatalf("paged discovery: %+v %v", s, err) + } + // The enrolled UUID also on a later page is ambiguous, never first-match. + b.docs["/redfish/v1/Systems/B"].(map[string]any)["UUID"] = uuidA + if _, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}); !errors.Is(err, ErrIdentity) { + t.Fatalf("duplicate UUID on a later page: %v", err) + } + if n := b.count("POST") + b.count("PATCH"); n != 0 { + t.Fatalf("discovery mutated: %d", n) + } +} + +func TestDiscoveryRefusesPartialOrForeignCollections(t *testing.T) { + for name, tc := range map[string]struct { + mutate func(*bmcStub) + want error + }{ + "unreadable member": {func(b *bmcStub) { b.status["GET /redfish/v1/Systems/B"] = http.StatusInternalServerError }, Status{}}, + "rejected member": {func(b *bmcStub) { b.status["GET /redfish/v1/Systems/B"] = http.StatusForbidden }, ErrUnauthorized}, + "member under another collection": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/B"].(map[string]any)["@odata.id"] = "/redfish/v1/Managers/B" + }, ErrIdentity}, + "absolute Systems link to another host": {func(b *bmcStub) { + b.docs["/redfish/v1/"] = map[string]any{"Systems": map[string]string{"@odata.id": "http://198.51.100.1/redfish/v1/Systems"}} + }, ErrIdentity}, + "reset target off the System": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{"target": "/redfish/v1/Systems/B/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}} + }, ErrUnsupported}, + "ActionInfo off the System": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{"target": "/redfish/v1/Systems/A/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/B/ResetActionInfo"}} + }, ErrUnsupported}, + "one-time override not advertised": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Boot"].(map[string]any)["BootSourceOverrideEnabled@Redfish.AllowableValues"] = []string{"Continuous"} + }, ErrUnsupported}, + "oversized response": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/B"].(map[string]any)["Pad"] = strings.Repeat("x", maxBody) + }, nil}, + } { + t.Run(name, func(t *testing.T) { + b := newStub() + tc.mutate(b) + _, err := stubClient(t, b, time.Second).Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err == nil || (tc.want != nil && !errors.Is(err, tc.want) && !errors.As(err, new(Status))) || (tc.want == nil && errors.Is(err, ErrIdentity)) { + t.Fatalf("got %v, want %v", err, tc.want) + } + if _, isStatus := tc.want.(Status); isStatus && !errors.As(err, new(Status)) { + t.Fatalf("got %v, want an HTTP status", err) + } + noSecret(t, err) + if n := b.count("POST") + b.count("PATCH"); n != 0 { + t.Fatalf("discovery mutated: %d", n) + } + }) + } +} + +func TestBootOverrideIsOneConditionalPatchWithoutFallback(t *testing.T) { + b := newStub() + b.headers["/redfish/v1/Systems/A"] = http.Header{"Etag": {`W/"7"`}} + c := stubClient(t, b, time.Second) + sys, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil { + t.Fatal(err) + } + b.status["PATCH /redfish/v1/Systems/A"] = http.StatusPreconditionFailed + err = c.SetBootOnce(context.Background(), sys, "Pxe") + if !errors.Is(err, ErrPrecondition) || b.count("PATCH") != 1 || b.ifMatch[0] != `W/"7"` || b.count("GET /redfish/v1/Systems/A/Settings")+b.count("PATCH /redfish/v1/Systems/A/Settings") != 0 { + t.Fatalf("412 must be one conditional PATCH, no retry or Settings fallback: %v %v %v", err, b.requests, b.ifMatch) + } + noSecret(t, err) + delete(b.status, "PATCH /redfish/v1/Systems/A") + b.status["PATCH /redfish/v1/Systems/A"] = http.StatusInternalServerError + if err := c.SetBootOnce(context.Background(), sys, "Pxe"); !errors.As(err, new(Status)) || b.count("PATCH") != 2 { + t.Fatalf("a failed PATCH must not fall back to the Settings resource: %v %v", err, b.requests) + } + if err := c.SetBootOnce(context.Background(), sys, "Cd"); !errors.Is(err, ErrUnsupported) || b.count("PATCH") != 2 { + t.Fatal("unadvertised boot target was sent") + } +} + +func TestResetIsOnePostOnFailureOrLostResponse(t *testing.T) { + b := newStub() + b.headers["/redfish/v1/Systems/A"] = http.Header{"Etag": {`"7"`}} + c := stubClient(t, b, 200*time.Millisecond) + sys, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil { + t.Fatal(err) + } + reset := "POST /redfish/v1/Systems/A/Actions/ComputerSystem.Reset" + for i, inject := range []func(){ + func() { b.status[reset] = http.StatusPreconditionFailed }, + func() { b.status[reset] = http.StatusServiceUnavailable }, + func() { delete(b.status, reset); b.hold[reset] = time.Second }, + } { + inject() + err := c.Reset(context.Background(), sys, "On") + if err == nil || b.count(reset) != i+1 { + t.Fatalf("case %d: a failed or lost Reset must be sent exactly once and reported: %v %v", i, err, b.requests) + } + noSecret(t, err) + } + for _, m := range b.ifMatch { + if m != "" { + t.Fatalf("Reset carried the System ETag as If-Match: %v", b.ifMatch) + } + } + if err := c.Reset(context.Background(), sys, "GracefulRestart"); !errors.Is(err, ErrUnsupported) || b.count(reset) != 3 { + t.Fatal("unadvertised ResetType was sent") + } + if b.count("POST /redfish/v1/SessionService") != 0 { + t.Fatal("client created a session") + } +} + +func TestClientRejectsUntrustedTLSAndEnvironmentProxy(t *testing.T) { + reached := false + srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })) + defer srv.Close() + c, err := NewClient(srv.URL, "operator", "synthetic-secret", time.Second) + if err != nil { + t.Fatal(err) + } + _, err = c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err == nil || reached { + t.Fatalf("untrusted certificate accepted: %v", err) + } + noSecret(t, err) + if c.config.HTTPClient.Transport.(guard).next.(*http.Transport).Proxy != nil { + t.Fatal("BMC requests may be sent through an environment proxy") + } +} diff --git a/internal/redfish/provider.go b/internal/redfish/provider.go new file mode 100644 index 00000000..f6327e67 --- /dev/null +++ b/internal/redfish/provider.go @@ -0,0 +1,814 @@ +package redfish + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "golang.org/x/sys/unix" +) + +const ( + // Root holds the journal; the site mounts its journal subpath here. + Root = "/var/lib/fleet-local" + artifacts = "/opt/fleet-local/artifacts" + // LibvirtSocketDir is the hypervisor socket path of the libvirt mode. Its + // presence in a Redfish worker is a configuration error, never a fallback. + LibvirtSocketDir = "/run/fleet-libvirt" + bootWindow = 20 * time.Minute + maxPowerOn = 3 +) + +// Target is one enrolled physical asset and its exact Redfish System. Console +// names the serial-console capture file for the target (a lab seam; see the +// operations guide). Enrollment is retained before effects and never inferred. +type Target struct { + AssetID string `json:"assetID"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + MAC string `json:"mac"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` +} + +// Enrollment is the site's explicit asset to BMC mapping. +type Enrollment struct { + Endpoint string `json:"endpoint"` + Targets []Target `json:"targets"` +} + +func (e Enrollment) target(asset string) (Target, bool) { + for _, t := range e.Targets { + if t.AssetID == asset { + return t, true + } + } + return Target{}, false +} + +func normalizeMAC(v string) (string, bool) { + hw, err := net.ParseMAC(strings.ReplaceAll(v, "-", ":")) + if err != nil || len(hw) != 6 { + return "", false + } + return hw.String(), true +} + +func ParseEnrollment(b []byte) (Enrollment, error) { + var e Enrollment + d := json.NewDecoder(strings.NewReader(string(b))) + d.DisallowUnknownFields() + if err := d.Decode(&e); err != nil || len(e.Targets) == 0 { + return Enrollment{}, errors.New("invalid Redfish enrollment") + } + seen := map[string]bool{} + for i, t := range e.Targets { + mac, ok := normalizeMAC(t.MAC) + if !ok || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.AssetID] || seen["s"+t.SystemID] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") + } + seen["a"+t.AssetID], seen["s"+t.SystemID], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true + e.Targets[i].MAC = mac + } + return e, nil +} + +// phase is one boot of the target: a one-time boot override, power on, and an +// exact console receipt followed by power off. +type phase struct{ name, boot, marker, mode string } + +var phases = map[string][]phase{ + "install": {{"installer", "Pxe", "FLEET-INSTALLED:", "install"}, {"disk", "Hdd", "FLEET-DISK-BOOT:", ""}}, + "cleanup": {{"wipe", "Pxe", "FLEET-WIPED:", "wipe"}}, +} + +type record struct { + Request simulator.Request `json:"request"` + Result simulator.OperationResult `json:"result"` + Receipt string `json:"receipt"` + Stage string `json:"stage"` + BootToken string `json:"bootToken,omitempty"` + BootExpires time.Time `json:"bootExpires"` + BootClosed bool `json:"bootClosed"` + Target Target `json:"target"` + System *System `json:"system,omitempty"` + PowerOn map[string]int `json:"powerOnRequests,omitempty"` + RequestedAt map[string]time.Time `json:"requestedAt,omitempty"` +} + +type journal struct { + Provider string `json:"provider"` + Image string `json:"image"` + Epoch int64 `json:"epoch"` + Binding string `json:"binding"` + Fence string `json:"fence"` + Closed bool `json:"closed"` + Operations map[string]*record `json:"operations"` +} + +// Provider is the Redfish executor. The effectful provider runs only in a +// per-operation worker; read-only providers serve the boot and observer roles. +type Provider struct { + root, bootRoot, consoleRoot, artifacts string + origin, image string + enrollment Enrollment + client *Client + readOnly bool + now func() time.Time + poll, settle, offGrace, outage time.Duration +} + +func (p *Provider) clock() time.Time { + if p.now != nil { + return p.now().UTC() + } + return time.Now().UTC() +} + +// Open builds the effectful worker provider from its environment. It refuses +// any libvirt configuration: Redfish workers have no hypervisor fallback. +func Open() (*Provider, error) { + if os.Getenv("FLEET_LIBVIRT_URI") != "" { + return nil, errors.New("redfish provider refuses a libvirt URI") + } + if _, err := os.Stat(LibvirtSocketDir); err == nil { + return nil, errors.New("redfish provider refuses a mounted libvirt socket") + } + p, err := open() + if err != nil { + return nil, err + } + enrollment, err := ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return nil, err + } + credentials := os.Getenv("FLEET_REDFISH_CREDENTIALS") + user, err1 := os.ReadFile(filepath.Join(credentials, "username")) + password, err2 := os.ReadFile(filepath.Join(credentials, "password")) + if credentials == "" || err1 != nil || err2 != nil { + return nil, errors.New("redfish credentials are unavailable") + } + client, err := NewClient(enrollment.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) + if err != nil { + return nil, err + } + p.consoleRoot = os.Getenv("FLEET_REDFISH_CONSOLE") + if !filepath.IsAbs(p.consoleRoot) { + return nil, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") + } + p.client, p.enrollment = client, enrollment + return p, p.retainEnrollment() +} + +// OpenReadOnly serves the boot service and observer. It holds no credential, +// cannot lock the journal and cannot execute. +func OpenReadOnly() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + p.readOnly = true + return p, nil +} + +func open() (*Provider, error) { + if os.Getenv("FLEET_SITE_PROVIDER") != "redfish" { + return nil, errors.New("redfish provider requires FLEET_SITE_PROVIDER=redfish") + } + origin, err := ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return nil, err + } + bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") + if !filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot { + return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + p := &Provider{root: Root, bootRoot: bootRoot, origin: origin, artifacts: artifacts} + if p.image, err = verifyArtifacts(p.artifacts); err != nil { + return nil, err + } + return p, nil +} + +// ParseBootOrigin accepts only a literal http://IPv4:port origin. +func ParseBootOrigin(value string) (string, error) { + u, err := url.Parse(value) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + ip := net.ParseIP(u.Hostname()) + port, err := strconv.Atoi(u.Port()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// verifyArtifacts derives the admitted image from the exact two-artifact manifest. +func verifyArtifacts(dir string) (string, error) { + b, err := os.ReadFile(dir + "/SHA256SUMS") + if err != nil { + return "", err + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + seen := map[string]bool{} + for _, line := range lines { + f := strings.Fields(line) + if len(lines) != 2 || len(f) != 2 || (f[1] != "kernel" && f[1] != "installer.gz") || seen[f[1]] { + return "", errors.New("invalid artifact manifest") + } + seen[f[1]] = true + if sum, err := fileSHA256(dir + "/" + f[1]); err != nil || sum != f[0] { + return "", errors.New("artifact digest mismatch") + } + } + sum := sha256.Sum256(b) + return "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]), nil +} + +func fileSHA256(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +func (p *Provider) lock() (*os.File, error) { + f, err := os.OpenFile(p.root+"/lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return nil, err + } + if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + f.Close() + return nil, err + } + return f, nil +} + +func syncDir(path string) error { + d, err := os.Open(path) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} + +// retainEnrollment records the enrollment once; a changed enrollment for a +// retained journal is a re-mapping that requires an explicit migration. +func (p *Provider) retainEnrollment() error { + // No journal lock: a worker that only opens must never contend with an + // executing worker or a concurrently delivered one. The first writer + // creates the record atomically (link of a synced file); every other + // worker compares it. + if err := os.MkdirAll(p.root, 0700); err != nil { + return err + } + want, _ := json.Marshal(p.enrollment) + path := p.root + "/enrollment.json" + got, err := os.ReadFile(path) + if os.IsNotExist(err) { + tmp, cerr := os.CreateTemp(p.root, ".enrollment-") + if cerr != nil { + return cerr + } + defer os.Remove(tmp.Name()) + _, werr := tmp.Write(want) + if werr == nil { + werr = tmp.Sync() + } + if cerr := tmp.Close(); werr == nil { + werr = cerr + } + if werr != nil { + return werr + } + if lerr := os.Link(tmp.Name(), path); lerr == nil { + return syncDir(p.root) + } else if !os.IsExist(lerr) { + return lerr + } + got, err = os.ReadFile(path) + } + if err != nil { + return err + } + if string(got) != string(want) { + return errors.New("redfish enrollment differs from the retained enrollment; re-mapping is not authorized") + } + return nil +} + +var stages = func() map[string]bool { + m := map[string]bool{"admitted": true, "discovered": true} + for _, list := range phases { + for _, ph := range list { + for _, s := range []string{"armed", "requested", "started", "verified"} { + m[ph.name+"-"+s] = true + } + } + } + return m +}() + +func (p *Provider) read() (journal, error) { + var j journal + b, err := os.ReadFile(p.root + "/journal.json") + if os.IsNotExist(err) { + return journal{Provider: "redfish", Operations: map[string]*record{}}, nil + } + if err != nil { + return j, err + } + if err = json.Unmarshal(b, &j); err != nil || j.Provider != "redfish" || j.Operations == nil { + return j, errors.New("invalid redfish journal") + } + for id, r := range j.Operations { + if r == nil || len(r.Receipt) != 64 { + return j, errors.New("invalid retained operation") + } + if _, err := hex.DecodeString(r.Receipt); err != nil { + return j, errors.New("invalid receipt") + } + if r.Stage == "done" { + if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { + return j, errors.New("invalid terminal result") + } + } else if !stages[r.Stage] || r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { + return j, errors.New("invalid pending result") + } + d, err := simulator.RequestDigest(r.Request) + if err != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Target.AssetID != r.Request.AssetID { + return j, errors.New("invalid retained request") + } + } + return j, nil +} + +func (p *Provider) save(j journal) error { + b, err := json.MarshalIndent(j, "", " ") + if err != nil { + return err + } + f, err := os.OpenFile(p.root+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = f.Write(b) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + return err + } + if err = os.Rename(p.root+"/journal.tmp", p.root+"/journal.json"); err != nil { + return err + } + return syncDir(p.root) +} + +func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } + +// Lookup reports only terminal retained results; a retained unfinished +// operation is not found with Unknown, which authorizes exact replay. +func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if !p.readOnly { + f, err := p.lock() + if err != nil { + return simulator.OperationResult{}, false, err + } + defer f.Close() + } + j, err := p.read() + if err != nil { + return simulator.OperationResult{}, false, err + } + r := j.Operations[id] + if r == nil { + return simulator.OperationResult{}, false, nil + } + if r.Stage != "done" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return r.Result, true, nil +} + +func (p *Provider) validate(q simulator.Request) (Target, error) { + if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { + return Target{}, executor.ErrInvalid + } + t, ok := p.enrollment.target(q.AssetID) + if !ok || (q.Kind != "install" && q.Kind != "cleanup") { + return Target{}, executor.ErrInvalid + } + if q.Kind == "install" { + var in struct { + Image string `json:"image"` + } + d := json.NewDecoder(strings.NewReader(string(q.Inputs))) + d.DisallowUnknownFields() + if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { + return Target{}, executor.ErrInvalid + } + } + if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { + return Target{}, executor.ErrInvalid + } + return t, nil +} + +// Execute runs or resumes exactly one retained operation. The exact request, +// enrolled target, receipt and boot capability are durable before any +// Redfish request; replay under the same ID never repeats an effect that may +// have happened. HTTP success is never success: only observed power state and +// the exact console receipt complete a phase. +func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + if p.readOnly || p.client == nil { + return simulator.OperationResult{}, executor.ErrInvalid + } + ctx, cancel := context.WithTimeout(ctx, 40*time.Minute) + defer cancel() + f, err := p.lock() + if err != nil { + return simulator.OperationResult{}, err + } + defer f.Close() + target, err := p.validate(q) + if err != nil { + return simulator.OperationResult{}, err + } + digest, err := simulator.RequestDigest(q) + if err != nil { + return simulator.OperationResult{}, err + } + j, err := p.read() + if err != nil { + return simulator.OperationResult{}, err + } + if j.Image != "" && j.Image != p.image { + return simulator.OperationResult{}, executor.ErrConflict + } + j.Image = p.image + r := j.Operations[q.ID] + if r != nil { + if r.Result.InputDigest != digest || r.Target != target { + return simulator.OperationResult{}, executor.ErrConflict + } + if r.Stage == "done" { + return r.Result, nil + } + } else { + for _, old := range j.Operations { + if old.Stage != "done" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + } + if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { + return simulator.OperationResult{}, executor.ErrFenced + } + j.Epoch, j.Binding, j.Fence, j.Closed = q.Epoch, q.BindingID, q.FenceToken, false + receipt, token := make([]byte, 32), make([]byte, 32) + if _, err = rand.Read(receipt); err == nil { + _, err = rand.Read(token) + } + if err != nil { + return simulator.OperationResult{}, err + } + r = &record{Request: q, Receipt: hex.EncodeToString(receipt), Stage: "admitted", Target: target, + BootToken: hex.EncodeToString(token), BootExpires: p.clock().Add(bootWindow), PowerOn: map[string]int{}, RequestedAt: map[string]time.Time{}, + Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: p.clock()}} + j.Operations[q.ID] = r + if err = p.save(j); err != nil { + return simulator.OperationResult{}, err + } + } + if err = p.run(ctx, &j, r); err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) + } + now := p.clock() + r.Stage, r.Result.Phase, r.Result.CompletedAt, r.Result.Result = "done", "Succeeded", &now, "installed" + if q.Kind == "cleanup" { + r.Result.Result = "clean" + j.Closed = true + } + if err = p.save(j); err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) + } + return r.Result, nil +} + +func (p *Provider) durations() (poll, settle, offGrace, outage time.Duration) { + poll, settle, offGrace, outage = p.poll, p.settle, p.offGrace, p.outage + if poll == 0 { + poll = 2 * time.Second + } + if settle == 0 { + settle = 45 * time.Second + } + if offGrace == 0 { + offGrace = 30 * time.Second + } + if outage == 0 { + outage = 5 * time.Minute + } + return +} + +func sleep(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func (p *Provider) run(ctx context.Context, j *journal, r *record) error { + poll, _, _, _ := p.durations() + if r.Stage == "admitted" { + // GETs only: a rejected credential, a missing capability or a + // mismatched identity leaves the operation admitted with no effect. + sys, err := p.client.Discover(ctx, r.Target) + if err != nil { + return fmt.Errorf("discovery: %w", err) + } + r.System, r.Stage = &sys, "discovered" + if err := p.save(*j); err != nil { + return err + } + } + if r.System == nil { + return errors.New("retained operation lacks its discovered System") + } + before := "discovered" + for _, ph := range phases[r.Request.Kind] { + if r.Stage == before { + // Pre-boot: power off and arm the one-time override. Both are + // idempotent here because no boot of this phase was requested. + if err := p.powerOff(ctx, *r.System); err != nil { + return err + } + if ph.mode != "" && (r.BootClosed || !p.clock().Before(r.BootExpires)) { + return errors.New("boot admission expired or closed before network boot") + } + if err := p.client.SetBootOnce(ctx, *r.System, ph.boot); err != nil { + return fmt.Errorf("arm %s boot: %w", ph.boot, err) + } + r.Stage = ph.name + "-armed" + if err := p.save(*j); err != nil { + return err + } + } + if r.Stage == ph.name+"-armed" { + if err := p.requestPowerOn(ctx, j, r, ph); err != nil { + return err + } + } + for r.Stage == ph.name+"-requested" { + started, err := p.started(ctx, j, r, ph) + if err != nil { + return err + } + if started { + r.Stage = ph.name + "-started" + if err := p.save(*j); err != nil { + return err + } + break + } + if err := sleep(ctx, poll); err != nil { + return err + } + } + if r.Stage == ph.name+"-started" { + if err := p.complete(ctx, r, ph); err != nil { + return err + } + if ph.mode != "" { + r.BootClosed = true + } + r.Stage = ph.name + "-verified" + if err := p.save(*j); err != nil { + return err + } + } + before = ph.name + "-verified" + } + if r.Stage != before { + return errors.New("unexpected operation stage " + r.Stage) + } + return nil +} + +func (p *Provider) powerOff(ctx context.Context, sys System) error { + poll, _, _, _ := p.durations() + deadline := p.clock().Add(5 * time.Minute) + requested := false + for { + pw, err := p.client.Observe(ctx, sys) + if err != nil { + return fmt.Errorf("observe before boot: %w", err) + } + if pw.State == "Off" { + return nil + } + if !requested { + // A slow or lost ForceOff response is observed, not trusted: + // power-off before this phase's boot is idempotent. + if err := p.client.Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { + return fmt.Errorf("power off: %w", err) + } + requested = true + } + if p.clock().After(deadline) { + return errors.New("target did not power off") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// requestPowerOn retains the request, then posts On. A lost or failed +// response leaves the phase requested; recovery observes before any repeat. +func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph phase) error { + if r.PowerOn == nil { + r.PowerOn, r.RequestedAt = map[string]int{}, map[string]time.Time{} + } + if r.PowerOn[ph.name] >= maxPowerOn { + return errors.New("power-on request budget exhausted; outcome requires inspection") + } + r.PowerOn[ph.name]++ + r.RequestedAt[ph.name] = p.clock() + r.Stage = ph.name + "-requested" + if err := p.save(*j); err != nil { + return err + } + if err := p.client.Reset(ctx, *r.System, "On"); err != nil { + return fmt.Errorf("power on (%s) response: %w", ph.name, err) + } + return nil +} + +// started reports whether a requested boot may have begun. Any sign of a boot +// (power not Off, the one-time override consumed, a boot delivery or receipt) +// means it may have run, and it is never requested again. Only a target that +// is still Off, still armed and silent after the settle window gets a repeated +// On, within a small retained budget. +func (p *Provider) started(ctx context.Context, j *journal, r *record, ph phase) (bool, error) { + _, settle, _, _ := p.durations() + pw, err := p.client.Observe(ctx, *r.System) + if err != nil { + if errors.Is(err, ErrIdentity) { + return false, err + } + return false, fmt.Errorf("observe requested boot: %w", err) + } + seen, err := p.receipts(r, ph) + if err != nil { + return false, err + } + delivered := ph.mode != "" && p.deliveryStarted(r) + if pw.State != "Off" || pw.OverrideEnabled != "Once" || pw.OverrideTarget != ph.boot || seen > 0 || delivered { + return true, nil + } + if p.clock().Sub(r.RequestedAt[ph.name]) < settle { + return false, nil + } + return false, p.requestPowerOn(ctx, j, r, ph) +} + +// complete waits for exactly one console receipt for this operation and the +// target powered off. BMC outages are tolerated for a bounded period. +func (p *Provider) complete(ctx context.Context, r *record, ph phase) error { + poll, _, offGrace, outage := p.durations() + var offSince, failingSince time.Time + for { + pw, err := p.client.Observe(ctx, *r.System) + switch { + case errors.Is(err, ErrIdentity): + return err + case err != nil: + if failingSince.IsZero() { + failingSince = p.clock() + } + if p.clock().Sub(failingSince) > outage { + return fmt.Errorf("BMC unavailable while observing %s: %w", ph.name, err) + } + default: + failingSince = time.Time{} + seen, err := p.receipts(r, ph) + if err != nil { + return err + } + if pw.State == "Off" { + if seen == 1 { + if ph.mode != "" { + return p.verifyDelivery(r) + } + return nil + } + if offSince.IsZero() { + offSince = p.clock() + } + if p.clock().Sub(offSince) > offGrace { + return fmt.Errorf("target powered off without the exact %s receipt", ph.name) + } + } else { + offSince = time.Time{} + } + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// receipts counts exact receipt lines for this operation on the target's +// console. More than one is a duplicate execution and never succeeds. +func (p *Provider) receipts(r *record, ph phase) (int, error) { + b, err := os.ReadFile(filepath.Join(p.consoleRoot, r.Target.Console)) + if os.IsNotExist(err) { + return 0, nil + } + if err != nil { + return 0, err + } + want := ph.marker + r.Receipt + if ph.name == "wipe" { + want += ":" + strconv.FormatInt(r.Target.DiskBytes, 10) + } + n := 0 + for _, line := range strings.Split(string(b), "\n") { + if strings.TrimSpace(line) == want { + n++ + } + } + if ph.name == "disk" { + installed, _ := p.receipts(r, phases["install"][0]) + if installed != 1 { + return 0, errors.New("disk receipt without exactly one installer receipt") + } + } + if n > 1 { + return 0, fmt.Errorf("duplicate %s receipt: the phase ran more than once", ph.name) + } + return n, nil +} + +func (p *Provider) bootDirectory(r *record) string { + return filepath.Join(p.bootRoot, key(r.Request.ID)) +} + +func (p *Provider) deliveries(r *record) map[string]bool { + b, _ := os.ReadFile(filepath.Join(p.bootDirectory(r), "boot-delivery.log")) + done := map[string]bool{} + for _, line := range strings.Split(string(b), "\n") { + f := strings.Fields(line) + if len(f) == 4 && (f[1] == "write-complete" || f[1] == "admitted") && strings.HasPrefix(f[3], "bytes=") { + done[f[1]+" "+f[2]] = true + } + } + return done +} + +func (p *Provider) deliveryStarted(r *record) bool { return p.deliveries(r)["admitted boot.ipxe"] } + +func (p *Provider) verifyDelivery(r *record) error { + d := p.deliveries(r) + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !d["write-complete "+name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + return nil +} + +// ImageReference is the locally verified artifact manifest identity. +func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/redfish/provider_test.go b/internal/redfish/provider_test.go new file mode 100644 index 00000000..c19dad39 --- /dev/null +++ b/internal/redfish/provider_test.go @@ -0,0 +1,629 @@ +package redfish + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "go/parser" + "go/token" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +const ( + assetA = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" + assetB = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02" + uuidA = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a" + uuidB = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b" +) + +// fakeSystem is BMC state plus a fake guest that behaves like the lab +// installer: it fetches its script and artifacts from the boot handler, +// prints exactly one receipt on its console, and powers off. +type fakeSystem struct { + id, uuid, mac, console string + power, enabled, target string + disk string // receipt of the installed OS, "" when blank + boots []string +} + +type fakeBMC struct { + t *testing.T + mu sync.Mutex + systems map[string]*fakeSystem + mutations []string + rejectAuth, hideOn, dropOnce, ignoreOnce bool + dropSkip int + hold time.Duration + boot string // boot handler origin + wg sync.WaitGroup +} + +func (b *fakeBMC) handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + write := func(v any) { _ = json.NewEncoder(w).Encode(v) } + if r.URL.Path == "/redfish/v1/" { + write(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) + return + } + user, pass, ok := r.BasicAuth() + b.mu.Lock() + reject := b.rejectAuth + b.mu.Unlock() + if !ok || user != "operator" || pass != "synthetic" || reject { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.URL.Path == "/redfish/v1/Systems" { + write(map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/System-1"}, map[string]string{"@odata.id": "/redfish/v1/Systems/System-2"}}}) + return + } + m := regexp.MustCompile(`^/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?$`).FindStringSubmatch(r.URL.Path) + if m == nil { + w.WriteHeader(http.StatusNotFound) + return + } + b.mu.Lock() + s := b.systems[m[1]] + types := []string{"On", "ForceOff", "ForceRestart"} + if b.hideOn { + types = types[1:] + } + switch { + case r.Method == http.MethodGet && m[2] == "": + v := map[string]any{"@odata.id": r.URL.Path, "Id": s.id, "UUID": s.uuid, "PowerState": s.power, + "Boot": map[string]any{"BootSourceOverrideEnabled": s.enabled, "BootSourceOverrideTarget": s.target, + "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"None", "Pxe", "Hdd"}, "BootSourceOverrideEnabled@Redfish.AllowableValues": []string{"Disabled", "Once"}}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]string{"target": r.URL.Path + "/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": r.URL.Path + "/ResetActionInfo"}}} + b.mu.Unlock() + write(v) + case r.Method == http.MethodGet && m[2] == "/ResetActionInfo": + b.mu.Unlock() + // Shaped like the DMTF emulator 1.2.2 template, including its + // off-schema string "Required". + write(map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "Required": "true", "DataType": "String", "AllowableValues": types}}}) + case r.Method == http.MethodPatch && m[2] == "": + var body struct{ Boot map[string]string } + _ = json.NewDecoder(r.Body).Decode(&body) + s.enabled, s.target = body.Boot["BootSourceOverrideEnabled"], body.Boot["BootSourceOverrideTarget"] + b.mutations = append(b.mutations, s.id+" PATCH "+s.target) + b.mu.Unlock() + w.WriteHeader(http.StatusOK) + write(map[string]any{}) + case r.Method == http.MethodPost && m[2] != "": + var body struct{ ResetType string } + _ = json.NewDecoder(r.Body).Decode(&body) + b.mutations = append(b.mutations, s.id+" POST "+body.ResetType) + allowed := false + for _, t := range types { + allowed = allowed || t == body.ResetType + } + if !allowed { + b.mu.Unlock() + w.WriteHeader(http.StatusBadRequest) + return + } + if body.ResetType == "On" && b.ignoreOnce { + b.ignoreOnce = false + b.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + } + drop := false + if body.ResetType == "On" && s.power == "Off" { + boot := "Hdd" + if s.enabled == "Once" { + boot = s.target + } + s.enabled, s.target, s.power = "Disabled", "None", "On" + s.boots = append(s.boots, boot) + if b.dropOnce && b.dropSkip > 0 { + b.dropSkip-- + } else { + drop, b.dropOnce = b.dropOnce, false + } + b.wg.Add(1) + go b.guest(s, boot) + } + if body.ResetType == "ForceOff" { + s.power = "Off" + } + b.mu.Unlock() + if drop { + time.Sleep(b.hold) + } + w.WriteHeader(http.StatusNoContent) + default: + b.mu.Unlock() + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +func (b *fakeBMC) console(s *fakeSystem, line string) { + f, err := os.OpenFile(s.console, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err == nil { + fmt.Fprintln(f, line) + f.Close() + } +} + +func (b *fakeBMC) guest(s *fakeSystem, boot string) { + defer b.wg.Done() + time.Sleep(20 * time.Millisecond) + line := "" + if boot == "Pxe" { + mac := strings.ReplaceAll(s.mac, ":", "-") + script := get(b.boot + "/pxe/" + mac + "/boot.ipxe") + f := regexp.MustCompile(`kernel (\S+) .*fleet\.receipt=([0-9a-f]{64}) fleet\.mode=(\w+)\ninitrd (\S+)`).FindStringSubmatch(script) + if f != nil && get(f[1]) != "" && get(f[4]) != "" { + b.mu.Lock() + if f[3] == "wipe" { + s.disk = "" + line = "FLEET-WIPED:" + f[2] + ":2147483648" + } else { + s.disk = f[2] + line = "FLEET-INSTALLED:" + f[2] + } + b.mu.Unlock() + } + } else if s.disk != "" { + line = "FLEET-DISK-BOOT:" + s.disk + } + if line != "" { + b.console(s, line) + } + time.Sleep(20 * time.Millisecond) + b.mu.Lock() + s.power = "Off" + b.mu.Unlock() +} + +func get(u string) string { + resp, err := http.Get(u) + if err != nil { + return "" + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + return "" + } + return string(b) +} + +func (b *fakeBMC) mutationsFor(id string) []string { + b.mu.Lock() + defer b.mu.Unlock() + var out []string + for _, m := range b.mutations { + if strings.HasPrefix(m, id+" ") { + out = append(out, strings.TrimPrefix(m, id+" ")) + } + } + return out +} + +type fixture struct { + p *Provider + bmc *fakeBMC + dir string +} + +func newFixture(t *testing.T, timeout time.Duration) *fixture { + t.Helper() + dir := t.TempDir() + for _, d := range []string{"journal", "boot", "console", "artifacts"} { + if err := os.Mkdir(filepath.Join(dir, d), 0700); err != nil { + t.Fatal(err) + } + } + os.WriteFile(filepath.Join(dir, "artifacts/kernel"), []byte("kernel"), 0600) + os.WriteFile(filepath.Join(dir, "artifacts/installer.gz"), []byte("initrd"), 0600) + sums := "" + for _, n := range []string{"kernel", "installer.gz"} { + s, _ := fileSHA256(filepath.Join(dir, "artifacts", n)) + sums += s + " " + n + "\n" + } + os.WriteFile(filepath.Join(dir, "artifacts/SHA256SUMS"), []byte(sums), 0600) + image, err := verifyArtifacts(filepath.Join(dir, "artifacts")) + if err != nil { + t.Fatal(err) + } + bmc := &fakeBMC{t: t, hold: 3 * timeout, systems: map[string]*fakeSystem{ + "System-1": {id: "System-1", uuid: uuidA, mac: "52:54:00:77:01:0a", console: filepath.Join(dir, "console/target-a.log"), power: "On", enabled: "Disabled", target: "None"}, + "System-2": {id: "System-2", uuid: uuidB, mac: "52:54:00:77:01:0b", console: filepath.Join(dir, "console/target-b.log"), power: "Off", enabled: "Disabled", target: "None"}}} + rf := httptest.NewServer(bmc.handler()) + t.Cleanup(rf.Close) + enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"endpoint":%q,"targets":[ + {"assetID":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}, + {"assetID":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}`, rf.URL, assetA, uuidA, assetB, uuidB))) + if err != nil { + t.Fatal(err) + } + client, err := NewClient(rf.URL, "operator", "synthetic", timeout) + if err != nil { + t.Fatal(err) + } + p := &Provider{root: filepath.Join(dir, "journal"), bootRoot: filepath.Join(dir, "boot"), consoleRoot: filepath.Join(dir, "console"), artifacts: filepath.Join(dir, "artifacts"), + image: image, enrollment: enrollment, client: client, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} + boot := httptest.NewServer(p.BootHandler()) + t.Cleanup(boot.Close) + p.origin, bmc.boot = boot.URL, boot.URL + t.Cleanup(bmc.wg.Wait) + return &fixture{p: p, bmc: bmc, dir: dir} +} + +func (f *fixture) install(epoch int64) simulator.Request { + return simulator.Request{ID: fmt.Sprintf("install-%d", epoch), Kind: "install", AssetID: assetA, BindingID: fmt.Sprintf("binding-%d", epoch), Epoch: epoch, + FenceToken: fmt.Sprintf("fence-%d", epoch), Inputs: json.RawMessage(`{"image":"` + f.p.image + `"}`)} +} + +func cleanup(q simulator.Request) simulator.Request { + q.ID, q.Kind, q.Inputs = strings.Replace(q.ID, "install", "cleanup", 1), "cleanup", nil + return q +} + +func (f *fixture) stage(t *testing.T, id string) string { + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + return j.Operations[id].Stage +} + +func TestInstallDiskBootCleanupAndReuseThroughRedfish(t *testing.T) { + f := newFixture(t, time.Second) + ctx := context.Background() + q := f.install(1) + r, err := f.p.Execute(ctx, q) + if err != nil || r.Result != "installed" { + t.Fatalf("install: %v %+v", err, r) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { + t.Fatalf("unexpected Redfish effects: %v", got) + } + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { + t.Fatalf("expected one network install and one disk boot, got %v", got) + } + // Exact replay is a verified no-op. + same := func(a, b simulator.OperationResult) bool { + return a.ID == b.ID && a.InputDigest == b.InputDigest && a.Result == b.Result && a.CompletedAt.Equal(*b.CompletedAt) + } + if again, err := f.p.Execute(ctx, q); err != nil || !same(again, r) || len(f.bmc.mutationsFor("System-1")) != 5 { + t.Fatalf("replay repeated effects: %v", err) + } + if got, found, err := f.p.Lookup(ctx, q.ID); !found || err != nil || !same(got, r) { + t.Fatalf("lookup: %v %v", found, err) + } + c := cleanup(q) + if r, err := f.p.Execute(ctx, c); err != nil || r.Result != "clean" { + t.Fatalf("cleanup: %v %+v", err, r) + } + f.bmc.wg.Wait() + if f.bmc.systems["System-1"].disk != "" { + t.Fatal("cleanup did not boot the wipe environment") + } + // Stale authority after the closed epoch is fenced before any request. + stale := q + stale.ID = "install-replay" + if _, err := f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("stale epoch replay: %v", err) + } + // Reuse in a new epoch installs again with a distinct receipt. + if r, err := f.p.Execute(ctx, f.install(2)); err != nil || r.Result != "installed" { + t.Fatalf("reuse install: %v", err) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-2"); len(got) != 0 { + t.Fatalf("the other enrolled target received effects: %v", got) + } + if b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-b.log")); len(b) != 0 { + t.Fatal("the other enrolled target booted") + } +} + +func TestDiscoveryFailuresIssueNoEffects(t *testing.T) { + for name, inject := range map[string]func(*fixture){ + "rejected credential": func(f *fixture) { f.bmc.rejectAuth = true }, + "unsupported reset": func(f *fixture) { f.bmc.hideOn = true }, + "renumbered system": func(f *fixture) { f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" }, + "swapped system UUIDs": func(f *fixture) { f.bmc.systems["System-1"].uuid, f.bmc.systems["System-2"].uuid = uuidB, uuidA }, + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t, time.Second) + inject(f) + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("expected Unknown, got %v", err) + } + if got := f.bmc.mutations; len(got) != 0 { + t.Fatalf("effects issued before verified discovery: %v", got) + } + if s := f.stage(t, q.ID); s != "admitted" { + t.Fatalf("stage %s", s) + } + if _, found, err := f.p.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal("unfinished operation must look up as not found and Unknown") + } + }) + } + f := newFixture(t, time.Second) + f.bmc.rejectAuth = true + q := f.install(1) + f.p.Execute(context.Background(), q) + f.bmc.rejectAuth = false + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("repaired credential did not resume: %v", err) + } +} + +func TestLostResponseAfterEffectRecoversWithoutRepeat(t *testing.T) { + f := newFixture(t, 100*time.Millisecond) + f.bmc.dropOnce = true + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost response must be Unknown: %v", err) + } + if s := f.stage(t, q.ID); s != "installer-requested" { + t.Fatalf("stage after lost response %s", s) + } + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("recovery: %v", err) + } + f.bmc.wg.Wait() + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { + t.Fatalf("lost response caused a repeated boot: %v", got) + } + ons := 0 + for _, m := range f.bmc.mutationsFor("System-1") { + if m == "POST On" { + ons++ + } + } + if ons != 2 { + t.Fatalf("expected one On per phase, got %d", ons) + } +} + +func TestLostDiskBootResponseRecoversWithoutRepeat(t *testing.T) { + f := newFixture(t, 100*time.Millisecond) + f.bmc.dropOnce, f.bmc.dropSkip = true, 1 + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost disk-boot response must be Unknown: %v", err) + } + if s := f.stage(t, q.ID); s != "disk-requested" { + t.Fatalf("stage after lost response %s", s) + } + f.bmc.wg.Wait() + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("recovery: %v", err) + } + j, _ := f.p.read() + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" || j.Operations[q.ID].PowerOn["disk"] != 1 { + t.Fatalf("lost disk-boot response caused a repeat: %v %v", got, j.Operations[q.ID].PowerOn) + } +} + +func TestLostRequestIsRepeatedOnlyWhileArmedAndSilent(t *testing.T) { + f := newFixture(t, time.Second) + f.bmc.ignoreOnce = true + q := f.install(1) + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("install: %v", err) + } + f.bmc.wg.Wait() + j, _ := f.p.read() + if j.Operations[q.ID].PowerOn["installer"] != 2 || strings.Join(f.bmc.systems["System-1"].boots, ",") != "Pxe,Hdd" { + t.Fatalf("expected one repeated On and one boot: %+v %v", j.Operations[q.ID].PowerOn, f.bmc.systems["System-1"].boots) + } +} + +func TestDuplicateReceiptAndIdentityChangeNeverSucceed(t *testing.T) { + f := newFixture(t, time.Second) + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); err != nil { + t.Fatal(err) + } + f.bmc.wg.Wait() + b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-a.log")) + f.bmc.console(f.bmc.systems["System-1"], strings.Split(string(b), "\n")[0]) + c := cleanup(q) + j, _ := f.p.read() + r := j.Operations[q.ID] + if _, err := f.p.receipts(r, phases["install"][0]); err == nil { + t.Fatal("duplicate installer receipt accepted") + } + f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" + if _, err := f.p.Execute(context.Background(), c); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.bmc.mutationsFor("System-1")) != 5 { + t.Fatalf("identity change: %v %v", err, f.bmc.mutationsFor("System-1")) + } +} + +func TestChangedRetryConflictsAndConcurrentWorkerIsExcluded(t *testing.T) { + f := newFixture(t, time.Second) + f.bmc.rejectAuth = true + q := f.install(1) + f.p.Execute(context.Background(), q) + changed := q + changed.FenceToken = "other" + if _, err := f.p.Execute(context.Background(), changed); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("changed retry: %v", err) + } + other := cleanup(f.install(1)) + other.ID = "unrelated" + if _, err := f.p.Execute(context.Background(), other); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("an unfinished operation must block later ones: %v", err) + } + guard, err := f.p.lock() + if err != nil { + t.Fatal(err) + } + if _, err := f.p.Execute(context.Background(), q); err == nil || errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("second worker was not excluded by the journal lock: %v", err) + } + guard.Close() + ro := &Provider{root: f.p.root, readOnly: true} + if _, err := ro.Execute(context.Background(), q); !errors.Is(err, executor.ErrInvalid) { + t.Fatal("read-only provider executed") + } + bad := q + bad.AssetID = "fleet-provider/fleet.datumapis.com/Device/not-enrolled" + if _, err := f.p.Execute(context.Background(), bad); !errors.Is(err, executor.ErrInvalid) { + t.Fatal("unenrolled asset accepted") + } +} + +func TestEnrollmentIsRetainedOnceWithoutContendingForTheJournalLock(t *testing.T) { + f := newFixture(t, time.Second) + guard, err := f.p.lock() // an executing worker holds the journal lock + if err != nil { + t.Fatal(err) + } + defer guard.Close() + var wg sync.WaitGroup + errs := make(chan error, 8) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { defer wg.Done(); errs <- f.p.retainEnrollment() }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("concurrent open failed: %v", err) + } + } + changed := *f.p + changed.enrollment = Enrollment{Endpoint: f.p.enrollment.Endpoint, Targets: f.p.enrollment.Targets[:1]} + if err := changed.retainEnrollment(); err == nil { + t.Fatal("a changed enrollment was accepted for the retained journal") + } +} + +func TestBootHandlerScopesByMACCapabilityAndAdmission(t *testing.T) { + f := newFixture(t, time.Second) + q := f.install(1) + j := journal{Provider: "redfish", Image: f.p.image, Epoch: 1, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{}} + digest, _ := simulator.RequestDigest(q) + target, _ := f.p.enrollment.target(assetA) + r := &record{Request: q, Receipt: strings.Repeat("a", 64), Stage: "installer-requested", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute), Target: target, + Result: simulator.OperationResult{ID: q.ID, Kind: "install", InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now()}} + j.Operations[q.ID] = r + save := func() { + if err := f.p.save(j); err != nil { + t.Fatal(err) + } + } + save() + base := f.p.origin + "/" + key(q.ID)[:16] + "/" + if s := get(f.p.origin + "/pxe/52-54-00-77-01-0a/boot.ipxe"); !strings.Contains(s, "fleet.mode=install") || !strings.Contains(s, base+r.BootToken+"/kernel") { + t.Fatalf("admitted MAC not served: %q", s) + } + if get(f.p.origin+"/pxe/boot.ipxe") == "" || get(base+r.BootToken+"/kernel") != "kernel" { + t.Fatal("chain script or admitted artifact not served") + } + for _, u := range []string{f.p.origin + "/pxe/52-54-00-77-01-0b/boot.ipxe", base + strings.Repeat("c", 64) + "/kernel", base + r.BootToken + "/SHA256SUMS", base + r.BootToken + "/boot.ipxe"} { + if get(u) != "" { + t.Fatalf("served %s", u) + } + } + for _, mutate := range []func(){func() { r.BootClosed = true }, func() { r.BootExpires = time.Now().Add(-time.Second) }, func() { r.Stage = "disk-requested" }, func() { j.Fence = "superseded" }} { + saved := *r + fence := j.Fence + mutate() + save() + if get(f.p.origin+"/pxe/52-54-00-77-01-0a/boot.ipxe") != "" || get(base+r.BootToken+"/kernel") != "" { + t.Fatal("closed, expired, non-boot or fenced admission served") + } + *r, j.Fence = saved, fence + } + if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, key(q.ID), "boot-delivery.log")); strings.Contains(string(b), r.BootToken) || strings.Contains(string(b), r.Receipt) { + t.Fatal("delivery evidence contains a capability or receipt") + } +} + +func TestWorkerRefusesHypervisorConfiguration(t *testing.T) { + t.Setenv("FLEET_LIBVIRT_URI", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock") + if _, err := Open(); err == nil || !strings.Contains(err.Error(), "libvirt") { + t.Fatalf("Open accepted a libvirt URI: %v", err) + } + t.Setenv("FLEET_LIBVIRT_URI", "") + t.Setenv("FLEET_SITE_PROVIDER", "libvirt") + if _, err := OpenReadOnly(); err == nil { + t.Fatal("redfish provider opened outside Redfish mode") + } +} + +// The executor package must have no direct hypervisor path: no process +// execution, no libvirt client and no dependency on the lab VM provider. +func TestPackageHasNoHypervisorPath(t *testing.T) { + files, _ := filepath.Glob("*.go") + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + src, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + parsed, err := parser.ParseFile(token.NewFileSet(), name, src, parser.ImportsOnly) + if err != nil { + t.Fatal(err) + } + for _, imp := range parsed.Imports { + path := strings.Trim(imp.Path.Value, `"`) + if path == "os/exec" || path == "syscall" || strings.Contains(path, "libvirt") || strings.HasSuffix(path, "/internal/localvm") { + t.Fatalf("%s imports %s", name, path) + } + } + if strings.Contains(string(src), "virsh") || strings.Contains(string(src), "qemu:///") { + t.Fatalf("%s references a hypervisor control path", name) + } + } +} + +func TestClientNeverLeaksCredentialOrFollowsForeignPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redfish/v1/": + json.NewEncoder(w).Encode(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) + case "/redfish/v1/Systems": + json.NewEncoder(w).Encode(map[string]any{"Members": []any{map[string]string{"@odata.id": "/other/../redfish/v1/Systems/x"}}}) + default: + http.Redirect(w, r, "http://198.51.100.1/", http.StatusFound) + } + })) + defer srv.Close() + c, err := NewClient(srv.URL, "operator", "synthetic-secret", time.Second) + if err != nil { + t.Fatal(err) + } + _, err = c.Discover(context.Background(), Target{SystemID: "x", SystemUUID: uuidA}) + if !errors.Is(err, ErrIdentity) || strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString([]byte("operator:synthetic-secret"))) { + t.Fatalf("foreign member path: %v", err) + } + if _, err := c.Observe(context.Background(), System{Path: "/redfish/v1/Managers", ID: "x", UUID: uuidA}); !errors.As(err, new(Status)) { + t.Fatalf("followed a redirect: %v", err) + } + for _, bad := range []string{"ftp://10.0.0.1:1", "http://bmc.example:80", "http://10.0.0.1:80/path", "http://user@10.0.0.1:80"} { + if _, err := NewClient(bad, "u", "p", time.Second); err == nil { + t.Fatalf("accepted endpoint %s", bad) + } + } +} From db99e2cc297f0d750b77dfceacc58440464f74b1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 13:12:11 -0600 Subject: [PATCH 11/12] feat(bootnet): DHCP boot reservations with served and withdrawn evidence A network boot needs an address, but DHCP configured outside Fleet answers every reboot and cannot prove provisioning access ended. Fleet now publishes a reservation for a boot NIC only while its network boot is admitted, and treats the DHCP owner's applied reports as evidence: no network boot before a report shows the reservation served, and no completion until every instance that served it reports it withdrawn. - Enrollment records per-target BMC endpoints, endpoint-scoped System identity, and a static or synced DHCP mode with validated provisioning attachments. - The site's dhcp-feed role serves the canonical feed and accepts authenticated, self-verifying applied reports on its own listener. - fleet-dhcp-sync applies the feed to Kea through its control socket and reports only what Kea accepted. - The boot network enhancement proposes the design; the operations guide records the implemented contract and what remains proposed. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- build/manager.Dockerfile | 4 +- cmd/fleet-dhcp-sync/main.go | 58 ++++ cmd/fleet-multiplane/main.go | 12 +- config/site/redfish/graph/kustomization.yaml | 8 +- docs/enhancements/boot-network/README.md | 348 +++++++++++++++++++ docs/enhancements/pxe-installation/README.md | 9 + docs/operations/README.md | 1 + docs/operations/boot-network.md | 148 ++++++++ docs/operations/redfish-lab.md | 16 +- docs/operations/site-execution.md | 1 + hack/multiplane/test-redfish.py | 3 +- internal/bootnet/feed.go | 150 ++++++++ internal/bootnet/feed_test.go | 55 +++ internal/dhcpsync/sync.go | 195 +++++++++++ internal/dhcpsync/sync_test.go | 206 +++++++++++ internal/redfish/client.go | 24 +- internal/redfish/dhcp.go | 221 ++++++++++++ internal/redfish/dhcp_test.go | 317 +++++++++++++++++ internal/redfish/provider.go | 128 +++++-- internal/redfish/provider_test.go | 23 +- 21 files changed, 1870 insertions(+), 61 deletions(-) create mode 100644 cmd/fleet-dhcp-sync/main.go create mode 100644 docs/enhancements/boot-network/README.md create mode 100644 docs/operations/boot-network.md create mode 100644 internal/bootnet/feed.go create mode 100644 internal/bootnet/feed_test.go create mode 100644 internal/dhcpsync/sync.go create mode 100644 internal/dhcpsync/sync_test.go create mode 100644 internal/redfish/dhcp.go create mode 100644 internal/redfish/dhcp_test.go diff --git a/README.md b/README.md index bf883dd0..345fddbf 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,9 @@ 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. +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 diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 568e18a9..626e0127 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -6,9 +6,11 @@ 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-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 FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager COPY --from=build /out/fleet-simulator /fleet-simulator +COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-dhcp-sync/main.go b/cmd/fleet-dhcp-sync/main.go new file mode 100644 index 00000000..74a7a69a --- /dev/null +++ b/cmd/fleet-dhcp-sync/main.go @@ -0,0 +1,58 @@ +// 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" + "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, instance, socket, base string + var interval 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(&instance, "instance", os.Getenv("POD_NAME"), "stable name of this Kea instance") + flag.StringVar(&socket, "kea-socket", "/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket") + 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.Parse() + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + if err := run(logger, feed, tokenPath, instance, socket, base, interval); err != nil && !errors.Is(err, context.Canceled) { + logger.Error("dhcp sync stopped", "error", err) + os.Exit(1) + } +} + +func run(logger *slog.Logger, feed, tokenPath, instance, socket, base string, interval 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 + s := &dhcpsync.Syncer{ + Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, + 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-multiplane/main.go b/cmd/fleet-multiplane/main.go index d63f851a..0a547a1b 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -31,7 +31,7 @@ func main() { } func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one reconcile attempt for fault injection") @@ -47,6 +47,7 @@ func run() error { 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)") + syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -114,7 +115,7 @@ func run() error { } if redfishMode() { switch os.Args[1] { - case "boot-service", "boot-denials": + case "boot-service", "boot-denials", "dhcp-feed": p, err := redfish.OpenReadOnly() if err != nil { return err @@ -122,6 +123,13 @@ func run() error { if os.Args[1] == "boot-service" { return p.ServeBoot() } + if os.Args[1] == "dhcp-feed" { + token, err := os.ReadFile(*syncToken) + if err != nil { + return fmt.Errorf("DHCP synchronizer token: %w", err) + } + return p.ServeDHCP(strings.TrimSpace(string(token))) + } var extra []string if *extraMAC != "" { extra = append(extra, *extraMAC) diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index 437677c4..d171e202 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -22,10 +22,12 @@ patches: - {name: FLEET_REDFISH_CREDENTIALS, value: /etc/fleet-redfish} - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} # Explicit site enrollment: each physical asset ID maps to exactly one - # Redfish System (Id and UUID), NIC and console capture. Only target A - # is published as capacity; target B is enrolled to prove isolation. + # BMC endpoint, Redfish System (Id and UUID), NIC and console capture. + # The lab's dnsmasq hands out static leases, so DHCP is "static" and + # targets carry no provisioning attachment. Only target A is + # published as capacity; target B is enrolled to prove isolation. - name: FLEET_REDFISH_ENROLLMENT - value: '{"endpoint":"http://10.96.0.81:8000","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + value: '{"dhcp":"static","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","endpoint":"http://10.96.0.81:8000","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","endpoint":"http://10.96.0.81:8000","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' - {name: HOME, value: /tmp} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts diff --git a/docs/enhancements/boot-network/README.md b/docs/enhancements/boot-network/README.md new file mode 100644 index 00000000..2df4f364 --- /dev/null +++ b/docs/enhancements/boot-network/README.md @@ -0,0 +1,348 @@ +--- +status: provisional +stage: alpha +--- + +# Boot network reservations + +- [Summary](#summary) +- [Motivation](#motivation) + - [Goals](#goals) + - [Non-goals](#non-goals) +- [Proposal](#proposal) + - [User stories](#user-stories) + - [Physical and consumer addresses](#physical-and-consumer-addresses) + - [Reservation lifecycle](#reservation-lifecycle) +- [Design details](#design-details) + - [Ownership](#ownership) + - [Physical asset records](#physical-asset-records) + - [Reservation feed and applied reports](#reservation-feed-and-applied-reports) + - [Evidence gates](#evidence-gates) + - [DHCP synchronizer](#dhcp-synchronizer) + - [What firmware boots](#what-firmware-boots) + - [Release and recovery](#release-and-recovery) + - [Security boundaries](#security-boundaries) + - [Acceptance tests](#acceptance-tests) +- [Production readiness review questionnaire](#production-readiness-review-questionnaire) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) +- [Open design questions](#open-design-questions) +- [Infrastructure needed](#infrastructure-needed) + +## Summary + +A physical machine that network-boots needs an address before Fleet can serve it +an installer. This proposal makes that address a short-lived, physical-side +reservation. Fleet publishes a reservation for a machine's boot NIC only while +that machine's network boot is admitted. The network owner's DHCP applies it and +reports what it applied. Fleet starts a network boot only after DHCP reports the +reservation served. It completes the operation only after every DHCP instance +that served it reports it withdrawn. + +The [PXE installation enhancement](../pxe-installation/README.md) assumes +"provider DHCP directs eligible firmware to that service" and requires release +to fence provisioning networking. This proposal defines how both happen without +moving DHCP ownership into Fleet. + +## Motivation + +A DHCP server configured independently of Fleet answers a machine on every boot. +It cannot tell an admitted installation from a stray reboot, and Fleet cannot +prove that a machine's provisioning access ended. Running DHCP at every location +also adds a stateful service per site. + +The opposite extreme also fails. If Fleet writes DHCP configuration directly, it +becomes a second writer of another owner's system and needs that owner's +credentials. If DHCP asks Fleet on every request, every boot depends on Fleet's +availability and latency, and a failure looks like a DHCP timeout. + +The provisioning address also differs from the addresses a consumer receives. +Release must withdraw provisioning access without touching anything a tenant +uses. That is impossible when firmware and the running OS share one address. + +### Goals + +- Answer DHCP for a machine's boot NIC only while its network boot is admitted. +- Keep DHCP, IPAM and relay configuration with the network owner, with one + writer for DHCP configuration. +- Treat DHCP state as evidence: a network boot requires proof the reservation is + served, and completion requires proof it was withdrawn. +- Separate physical-side provisioning addresses from consumer Machine addresses. +- Let a location use central DHCP through relays, with no DHCP server at the site. +- Keep a location that configures DHCP independently working, explicitly marked. + +### Non-goals + +- Running a DHCP server as part of Fleet. +- Allocating consumer Machine addresses; Networking/IPAM does that through the + Machine. +- Configuring relays, VLANs or switch ports. +- Authenticating firmware by MAC. A MAC routes a request; it never authorizes one. +- Permanently network-booted workloads. + +## Proposal + +### User stories + +- A provider runs central DHCP for several locations. Site routers relay to it, + and no location runs a DHCP server. +- An operator reboots an installed machine. DHCP does not answer its boot NIC, so + it boots from disk and is never reinstalled by accident. +- A release completes only after the machine's provisioning access is proven + gone, so capacity returns to supply with no lingering boot path. +- A DHCP instance restarts or a report is lost. Fleet treats the boot as not yet + ready, or the withdrawal as unproven, and never as success. + +### Physical and consumer addresses + +| | Address | Belongs to | Lifetime | Owner | +| --- | --- | --- | --- | --- | +| Physical | BMC endpoint | Physical asset | The hardware's life | Networking/IPAM (out-of-band) | +| | Provisioning attachment (address and gateway) | Physical asset, during an admitted network boot | The boot window | Networking/IPAM allocates; Fleet publishes | +| | Underlay (loopback, routing peers) | Physical host on the fabric | The host's life at the location | Galactic and IPAM | +| Consumer | Machine interfaces | Allocation | Allocation to release | Networking/IPAM, through the Machine | + +A location must give the install NIC a provisioning network whose addresses are +never consumer addresses. A location where firmware boots on the same untagged +network and address as the running OS does not qualify for synchronized DHCP. + +### Reservation lifecycle + +```mermaid +sequenceDiagram + participant W as Site worker + participant J as Journal + participant F as Reservation feed + participant S as DHCP synchronizer + participant D as DHCP server + participant M as Machine firmware + participant B as Boot service + W->>J: admit operation, open boot window + S->>F: fetch feed + F->>J: derive reservations + F-->>S: boot NIC → provisioning address + S->>D: apply configuration + S->>F: report applied feed + W->>F: wait for a report that serves the reservation + W->>M: arm one-time network boot, power on + M->>D: DHCP (through the location's relay) + D-->>M: provisioning address + M->>B: fetch boot program and installer + W->>J: verify receipt, close boot admission + S->>F: fetch feed (reservation gone) + S->>D: apply configuration + S->>F: report applied feed + W->>F: wait until every serving instance reports withdrawal + W->>J: complete operation +``` + +## Design details + +### Ownership + +| Surface | Single writer | +| --- | --- | +| Which boot NICs hold a reservation, and when | Fleet, derived from the site journal | +| DHCP server configuration | The network owner's synchronizer | +| Provisioning attachments (address, gateway, prefix) | Networking/IPAM | +| Relays, VLANs, switch ports | The network owner | +| Boot program and installer delivery | Fleet's boot service | + +Fleet never connects to the DHCP server. The synchronizer pulls Fleet's feed and +pushes reports, so Fleet needs no credential for the network owner's systems. + +### Physical asset records + +The site enrollment is the retained, explicit record of each physical asset. Per +target it holds the BMC endpoint, the Redfish System (Id and UUID), the boot NIC +MAC and, for synchronized DHCP, the provisioning attachment. A Redfish System Id +is unique only within its BMC; physical BMCs commonly expose one System named +`Self`. System identity is therefore the endpoint plus Id, and the UUID. + +A location declares one DHCP mode: + +- **static:** DHCP is configured independently of Fleet. Targets carry no + provisioning attachment, and no DHCP evidence is required. +- **synced:** every target carries a provisioning attachment, addresses are + unique, and the evidence gates below apply. + +The enrollment is retained once and a changed enrollment is refused for a +retained journal. In the target design, provisioning attachments are allocated +by Networking/IPAM per physical asset and referenced from inventory, and NIC MACs +and BMC endpoints are recorded as inventory observations. Until then the +enrollment carries them as explicit values. + +### Reservation feed and applied reports + +The site exposes an authenticated feed, separate from the firmware-facing boot +listener. It reads the journal read-only and writes only retained reports. + +- **Feed.** The complete desired set of reservations: boot NIC MAC, provisioning + address in prefix form, gateway and expiry. A reservation exists while its + operation holds the journal's current epoch, binding and fence, is not done, + has not closed boot admission and is inside its boot window. That starts at + admission, before power-on, so DHCP is ready when firmware asks. Reservations + are sorted canonically and the revision is a digest of them, so any copy of a + feed is self-verifying. +- **Applied report.** A named DHCP instance reports the exact feed it now + serves. The site accepts only a canonical feed with a matching revision and + retains the report durably before acknowledging it. + +### Evidence gates + +1. **Before arming a network boot**, the worker waits, with no effect, for a + report accepted after admission that serves the boot NIC at its exact + provisioning address. A report from an earlier operation is not evidence. If + the boot window expires first, the operation stays Unknown and effect-free. +2. **Before reporting success**, the worker requires that every instance which + served the reservation during the operation has since reported a feed + without it. A silent instance may still be serving, so the outcome stays + Unknown and replay waits again. + +Report and admission times come from different roles, so they must run on +synchronized clocks. + +### DHCP synchronizer + +The synchronizer runs beside one DHCP server instance and is owned and deployed +by the network owner. Each cycle it verifies the fetched feed, adds each +reservation to the base subnet with exactly its prefix, applies the configuration +when the revision changed or the server restarted, and reports only after the +server accepted it. A reservation with no matching base subnet fails the cycle; +it is never dropped. A restarted server loses its reservations, which fails +closed. + +Instance names must survive restarts, for example StatefulSet pod names. A +restarted instance then reports under the same name, which is its withdrawal +evidence. Before scaling down, drain an instance until it reports an empty feed; +a removed instance that served a reservation never reports again and keeps that +operation Unknown. + +The first synchronizer targets Kea DHCPv4 through its control socket. + +### What firmware boots + +A reservation supplies an address and gateway only. Firmware must also learn +what to boot. The proposed path for UEFI hardware is UEFI HTTP Boot: before +arming the one-time boot, the worker sets the System's `HttpBootUri` through +Redfish to the boot service, scoped to the operation, and arms `UefiHttp`. DHCP +then carries no boot URL. Firmware that cannot accept a Redfish boot URI needs +a DHCP boot-file option, which would extend the reservation; that is deferred. + +Boot URLs and capabilities are never DHCP options in the proposed path. + +### Release and recovery + +Release "fences provisioning networking" by requiring withdrawal evidence for +the cleanup operation, exactly as for installation. Missing, corrupt or +conflicting evidence keeps the operation Unknown and the capacity occupied. An +unreadable retained report is corruption, never evidence in either direction. +Recovery replays the same operation, which resumes at its retained stage and +waits for evidence again; it never repeats an effect that may have happened. + +### Security boundaries + +- The feed and reports require a bearer credential of at least 32 characters + and must be reached over TLS. The feed is never served on the boot listener. +- A report can only claim a canonical, self-consistent feed. The synchronizer is + trusted to report what its server serves; a compromised synchronizer can + falsify withdrawal, so its credential is scoped to one location's feed. +- DHCP is unauthenticated and unencrypted. The central server accepts relayed + traffic only from the location's relay addresses and answers only reserved + MACs, with no pool. Nothing secret is placed in DHCP. +- A MAC is routing information. Boot artifacts remain protected by the boot + service's operation-scoped admission. +- Retained reports hold MACs, addresses, revisions and instance names, never a + credential, receipt or capability. + +### Acceptance tests + +- No reservation is published without an admitted boot, and none outlives it. +- A network boot is never armed before a served report for the same operation. +- A report from before admission does not satisfy the served gate. +- Completion waits while any serving instance has not reported withdrawal, and + proceeds once all have. +- Unauthenticated, non-canonical, mismatched or unknown-field reports are + rejected and not retained. +- A synchronizer reports nothing the server rejected and never drops a + reservation with no matching subnet; a server restart re-applies without a + new report. +- Two BMCs exposing the same System Id enroll as distinct targets; a shared + provisioning address is refused. +- End to end at a location: a relayed DHCP exchange, a UEFI HTTP Boot, release + with withdrawal, and a reboot of an installed machine that DHCP ignores. + +## Production readiness review questionnaire + +### How is the feature enabled or disabled? + +Per location, through the enrollment's DHCP mode. Moving a location from static +to synced changes the retained enrollment and requires an explicit migration +with no operation in flight. Rollback to static stops new reservations; retained +operations still require their withdrawal evidence. + +### What must operators monitor? + +Feed and report latency per instance, operations waiting on the served or +withdrawn gate, instances that served and went silent, rejected reports, +synchronizer cycle failures, and DHCP servers receiving traffic from unexpected +relays. + +### How are failures recovered? + +Restore the synchronizer or server and let it report; the waiting operation +resumes. An instance that is permanently gone after serving requires an operator +decision with evidence that it no longer serves; there is no automatic override. + +### What must upgrades preserve? + +The retained enrollment, journal and report log, feed canonicalization and +revision derivation, and stable instance names. + +## Drawbacks + +- Every network boot depends on the network owner's DHCP and synchronizer being + reachable and reporting, which adds latency and a failure mode to installation. +- Withdrawal evidence can strand an operation as Unknown when an instance + disappears, by design, and operators must resolve it. +- The location must expose an authenticated feed endpoint to the DHCP owner. + +## Alternatives + +- **Static reservations configured outside Fleet.** Kept as the static mode, + but it answers every reboot and cannot prove revocation. +- **Fleet writes DHCP configuration.** Rejected: a second writer of the network + owner's system, with its credentials held by Fleet. +- **DHCP queries Fleet per request.** Rejected: couples every boot to Fleet's + availability and latency. +- **Fleet pushes reservations to DHCP.** Rejected: the location would need to + reach into the network owner's environment; with a pull, the DHCP side starts + every connection. +- **Route reservations and reports through the management plane.** Avoids a + location endpoint and reuses existing coordination, but every gate becomes a + management round trip and management holds evidence only the site uses. + Remains an option if exposing the site feed is impractical. +- **A DHCP server at every location.** Possible behind the same feed, but it adds + a stateful service per site; central DHCP through relays is preferred. + +## Open design questions + +- Provisioning attachments from Networking/IPAM: the claim type, per-asset + lifetime and how inventory references it. +- NIC MACs and BMC endpoints as inventory observations instead of enrollment + values. +- Redfish `HttpBootUri` support across qualified BMCs, and the fallback for + firmware without it. +- Feed transport: a TLS endpoint at the location versus the management-plane + route. +- Resolving a permanently lost instance with evidence instead of an operator + decision alone. +- DHCPv6 reservations and an IPv6 provisioning network. +- Per-location synchronizer credentials, rotation and revocation. + +## Infrastructure needed + +A location with a provisioning network on the install NIC and a relay to the +central DHCP service, the network owner's DHCP service with one synchronizer per +instance and stable instance names, a TLS endpoint for the location's feed, and +disposable UEFI hardware whose BMC accepts a one-time UEFI HTTP Boot target. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index 97a26a28..b3e1b46d 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -351,6 +351,15 @@ eligible firmware to that service. With no active admitted boot session, the service returns local boot. With a valid session, it serves the Fleet installer or chains through an allocation-scoped proxy to the admitted customer endpoint. +Provisioning addresses are physical-side attachments, distinct from consumer +Machine addresses. Where the location's DHCP is synchronized, the boot service +publishes a reservation for the asset's boot NIC only while its boot is admitted. +The network owner's DHCP reports what it applied. A network boot requires a +report that the reservation is served, and completion requires reports that +every instance which served it has withdrawn it. The +[boot network enhancement](../boot-network/README.md) proposes this design; the +implemented contract is in [Boot network](../../operations/boot-network.md). + The proxy validates the endpoint and TLS policy, prevents unapproved redirects, keeps endpoint credentials away from the machine, and records the response digest. Customer artifacts referenced by the returned script must use approved HTTPS diff --git a/docs/operations/README.md b/docs/operations/README.md index d6a1fb64..ed23e838 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -16,6 +16,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | +| Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md new file mode 100644 index 00000000..e5f7fd4b --- /dev/null +++ b/docs/operations/boot-network.md @@ -0,0 +1,148 @@ +# Boot network: physical addresses and DHCP reservations + +A physical host has addresses that belong to the asset, separate from the +addresses a consumer's Machine receives. Fleet records the physical ones in the +site enrollment and, for network boot, publishes a DHCP reservation only while an +operation's boot is admitted. The network owner's DHCP applies it and reports +back; those reports are the evidence that the boot was reachable and that +provisioning networking was later revoked. + +This page describes the implemented contract. The design and its alternatives +are in the [boot network enhancement](../enhancements/boot-network/README.md). +What is still proposed is listed under +[Implemented versus proposed](#implemented-versus-proposed). + +## Two kinds of address + +| | Address | Belongs to | Lifetime | Owner | +| --- | --- | --- | --- | --- | +| Physical | BMC endpoint | Physical asset | The hardware's life | Networking/IPAM (out-of-band) | +| | Provisioning attachment (address and gateway) | Physical asset, during an admitted network boot | The boot window | Networking/IPAM allocates; Fleet publishes | +| | Underlay (loopback, routing peers) | Physical host on the fabric | The host's life on the site | Galactic and IPAM | +| Consumer | Machine interfaces (`Machine.spec.networkInterfaces`) | Allocation | Allocation to release | Networking/IPAM, through the Machine | + +A provisioning address must not be a consumer address. Release fences +provisioning networking, so Fleet must be able to withdraw the provisioning +address without touching anything a tenant uses. A site whose firmware boots on +the same untagged network and address as the running OS cannot meet that, and +needs a dedicated provisioning network on the install NIC. + +## Enrollment + +The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit, retained +mapping of physical assets. It sets a site DHCP mode and, per target, the BMC +endpoint, the Redfish System, the boot NIC and, in synchronized mode, the +provisioning attachment: + +```json +{ + "dhcp": "synced", + "targets": [{ + "assetID": "fleet-provider/fleet.datumapis.com/Device/example-01", + "endpoint": "https://192.0.2.20:443", + "systemID": "Self", + "systemUUID": "00000000-0000-4000-8000-000000000001", + "mac": "00:00:5e:00:53:01", + "provisioning": {"address": "198.51.100.10/24", "gateway": "198.51.100.1"}, + "diskBytes": 960197124096, + "console": "example-01.log" + }] +} +``` + +- **`endpoint`** is per target. Physical BMCs each expose one System, often with + the same Id (`Self`), so a System is identified by its endpoint plus Id, and by + its UUID. +- **`dhcp: static`** means the site's DHCP is configured independently of Fleet. + Targets must not carry a provisioning attachment. The Redfish lab uses this + mode: its dnsmasq hands out fixed leases. +- **`dhcp: synced`** requires a provisioning attachment on every target: a host + address in prefix form and a different host in the same prefix as gateway. + Provisioning addresses are unique within the enrollment. + +The executor retains the enrollment once and refuses a changed enrollment for +the retained journal. + +## Reservation lifecycle + +In synchronized mode the site serves a reservation feed derived only from the +journal. A target's boot NIC holds its provisioning address while its operation: + +- is the journal's current epoch, binding and fence, and is not done; +- has a boot capability whose window has not expired; and +- has not closed boot admission. + +That window opens at admission, before power-on, so DHCP is ready when firmware +asks. The boot handler's narrower rule still decides which scripts and artifacts +are served. + +The worker gates its effects on reports: + +1. **Before arming a network boot** it waits, with no effect, until some DHCP + instance reports a feed that serves the boot NIC at its exact provisioning + address, accepted after this operation was admitted. A report from an earlier + operation is not evidence. If the boot window expires first, the operation + stays Unknown and effect-free. +2. **Before reporting success** it waits until every DHCP instance that served + the reservation during this operation reports a later feed without it. A + silent instance may still be serving, so the outcome stays Unknown and replay + waits again. Completion therefore includes verified withdrawal. + +Report times are the boot service's clock and admission times the worker's, so +both roles must run on synchronized clocks. + +A reservation carries an address and gateway only. It does not tell firmware +what to boot; see the boot-program row below. + +## Feed and reports + +The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file …`) +listens on `:8081`, never on the firmware-facing boot listener. It reads the +journal read-only and writes only `dhcp-applied.log` in the boot-evidence +directory. Every request needs `Authorization: Bearer `; the token is at +least 32 characters. + +- `GET /dhcp/v1/reservations` returns the canonical feed: + `{"revision": "", "reservations": [{"mac", "address", "gateway", "expires"}]}`. + Reservations are sorted by MAC; the revision is the SHA-256 of their canonical + JSON, so a feed is self-verifying. +- `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`. The + feed must be canonical with a matching revision; anything else is rejected and + not retained. An accepted report is synced to disk before `204`. + +The retained log holds MACs, addresses, revisions and instance names. It holds +no token, receipt or boot capability. An unreadable line is treated as +corruption, never as evidence. + +## Kea synchronizer + +`fleet-dhcp-sync` (in the manager image) runs beside one Kea DHCPv4 instance, +with a stable instance name such as a StatefulSet pod name. Each cycle it: + +1. fetches and verifies the feed over HTTPS; +2. reads Kea's PID with `status-get`; +3. when the revision changed or Kea restarted, adds each reservation to the base + configuration's subnet with exactly its prefix, sets the gateway as the + host's `routers` option, and sends `config-set` over Kea's control socket; +4. reports the feed only after Kea accepted it, once per revision. + +A reservation with no matching base subnet fails the cycle; it is never +dropped. A restarted Kea loses its reservations and fails closed until the next +cycle re-applies them. An instance that disappears after serving never reports +withdrawal, which keeps that operation Unknown until an operator resolves it, +so instance names must survive restarts. Before scaling down, drain the +instance being removed until it reports an empty feed. + +## Implemented versus proposed + +| Behavior | Status | +| --- | --- | +| Per-target BMC endpoints, endpoint-scoped System identity, static and synced DHCP modes, validated provisioning attachments | Implemented; unit tested | +| Reservation feed, authenticated applied reports, served and withdrawn gates, multi-instance withdrawal | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | +| Kea synchronizer: exact-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | +| Provisioning attachments allocated by Networking/IPAM instead of enrollment values | Proposed | +| NIC MACs and BMC endpoints recorded as Fleet inventory observations | Proposed; the enrollment is the only record | +| Deployment of `dhcp-feed` and the synchronizer, TLS to the feed, relay and provisioning VLAN at a site | Proposed; not exercised end to end | +| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the executor still arms `Pxe`, which relies on site DHCP for the boot file | +| DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer rejects it | +| Lab acceptance in synced mode | Not run; the lab uses static DHCP | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 08446eb4..2fff15d7 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -120,9 +120,12 @@ ownership audit covers the BMC Deployment, Service and ServiceAccount. The disks, domain UUIDs and MACs exist before any allocation. Each installation or cleanup reuses target A's single persistent disk. The site enrollment is an -explicit asset-to-System mapping in the worker template, with the endpoint, -System Id, UUID, MAC, disk size and console capture name. The executor writes it -once into the journal directory and refuses a changed enrollment later. +explicit asset-to-System mapping in the worker template, with each target's BMC +endpoint, System Id, UUID, MAC, disk size and console capture name. The lab sets +`"dhcp": "static"` because its dnsmasq leases are fixed; see +[Boot network](boot-network.md) for synchronized DHCP. The executor writes the +enrollment once into the journal directory and refuses a changed enrollment +later. ## Redfish executor contract @@ -600,8 +603,11 @@ MVP. They are listed as an explicit qualification checklist: 4. **Credentials and transport.** TLS with pinned CA or certificate, per-BMC accounts, a credential broker so workers never hold a long-lived password, and rotation and revocation. -5. **Provisioning network.** Integrate with the networking/IPAM owner: per-host - DHCP or a dedicated provisioning VLAN, and authentication beyond MAC. +5. **Provisioning network.** Synchronized DHCP reservations with served and + withdrawn evidence are implemented and unit tested + ([Boot network](boot-network.md)) but not exercised at a site. Still open: + attachments allocated by Networking/IPAM, a dedicated provisioning VLAN, + and authentication beyond MAC. 6. **Cleanup assurance.** Use vendor or NIST SP 800-88 sanitization (secure erase, crypto-erase, sanitize commands) with verifiable device evidence. Distinguish it from this logical overwrite. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 440a417d..fec814ef 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -360,6 +360,7 @@ container and is unchanged. | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | | Redfish execution Jobs with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md) for its run record | +| Synchronized DHCP boot reservations with served and withdrawn evidence | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | | Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | ## Independent review of the recorded run diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 317dcf0d..d8bd1f38 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -67,7 +67,8 @@ def build(path): enrollment = json.loads(env.get('FLEET_REDFISH_ENROLLMENT', '{}')) targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) by_system = {t['system']: t for t in targets} -check('enrollment endpoint is the fixed BMC Service', enrollment.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP) +check('every enrolled BMC endpoint is the fixed BMC Service', enrollment.get('targets') and all(t.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP for t in enrollment['targets'])) +check('lab DHCP is static: no provisioning attachment published', enrollment.get('dhcp') == 'static' and not any('provisioning' in t for t in enrollment.get('targets', []))) check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['mac'] == t['mac'] and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) diff --git a/internal/bootnet/feed.go b/internal/bootnet/feed.go new file mode 100644 index 00000000..02b4e285 --- /dev/null +++ b/internal/bootnet/feed.go @@ -0,0 +1,150 @@ +// Package bootnet is the boot-reservation contract between a site's boot +// service and the DHCP owner's synchronizer. A reservation maps one enrolled +// boot NIC to the provisioning address the network owner assigned to that +// physical asset, and exists only while an operation's network boot is +// admitted. The synchronizer reports what each DHCP instance applied; those +// reports are the evidence that a reservation was served and later withdrawn. +package bootnet + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net" + "net/netip" + "regexp" + "sort" + "time" +) + +// Reservation is one boot NIC's provisioning address. Address is in prefix +// form (address/prefix length) so the DHCP side never infers the subnet. +type Reservation struct { + MAC string `json:"mac"` + Address string `json:"address"` + Gateway string `json:"gateway"` + Expires time.Time `json:"expires"` +} + +// Feed is the complete desired reservation set. Revision is derived from the +// reservations, so a report of an applied Feed is self-verifying. +type Feed struct { + Revision string `json:"revision"` + Reservations []Reservation `json:"reservations"` +} + +// Applied reports that one DHCP instance now serves exactly Feed. +type Applied struct { + Instance string `json:"instance"` + Feed Feed `json:"feed"` +} + +var instanceName = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$`) + +// NormalizeMAC returns the canonical lower-case colon form of a 48-bit MAC. +func NormalizeMAC(v string) (string, bool) { + hw, err := net.ParseMAC(v) + if err != nil || len(hw) != 6 { + return "", false + } + return hw.String(), true +} + +// ValidAttachment checks a provisioning address and its gateway: the address +// is a host in its prefix and the gateway is a different host in the same one. +func ValidAttachment(address, gateway string) error { + p, err := netip.ParsePrefix(address) + if err != nil || p.Addr().Zone() != "" || p.Addr() == p.Masked().Addr() || p.Bits() == p.Addr().BitLen() { + return errors.New("provisioning address must be a host address in prefix form") + } + g, err := netip.ParseAddr(gateway) + if err != nil || g.Zone() != "" || g == p.Addr() || g == p.Masked().Addr() || !p.Masked().Contains(g) { + return errors.New("provisioning gateway must be another host in the address prefix") + } + return nil +} + +func canonical(r Reservation) (Reservation, error) { + mac, ok := NormalizeMAC(r.MAC) + if !ok || r.Expires.IsZero() { + return Reservation{}, errors.New("invalid reservation") + } + if err := ValidAttachment(r.Address, r.Gateway); err != nil { + return Reservation{}, err + } + p, _ := netip.ParsePrefix(r.Address) + g, _ := netip.ParseAddr(r.Gateway) + return Reservation{MAC: mac, Address: p.String(), Gateway: g.String(), Expires: r.Expires.UTC().Truncate(time.Second)}, nil +} + +func revision(rs []Reservation) string { + b, _ := json.Marshal(rs) + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} + +// NewFeed canonicalizes, orders and checks reservations, and derives the +// revision. A MAC or an address may appear only once. +func NewFeed(rs []Reservation) (Feed, error) { + out := make([]Reservation, 0, len(rs)) + for _, r := range rs { + c, err := canonical(r) + if err != nil { + return Feed{}, err + } + out = append(out, c) + } + sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC }) + addresses := map[string]bool{} + for i, r := range out { + a, _ := netip.ParsePrefix(r.Address) + if (i > 0 && out[i-1].MAC == r.MAC) || addresses[a.Addr().String()] { + return Feed{}, errors.New("duplicate reservation") + } + addresses[a.Addr().String()] = true + } + return Feed{Revision: revision(out), Reservations: out}, nil +} + +// Verify accepts only a feed already in canonical form whose revision matches. +func (f Feed) Verify() error { + want, err := NewFeed(f.Reservations) + if err != nil { + return err + } + got, _ := json.Marshal(f) + exact, _ := json.Marshal(want) + if string(got) != string(exact) { + return errors.New("feed is not canonical or its revision does not match") + } + return nil +} + +// Verify checks the instance name and the applied feed. +func (a Applied) Verify() error { + if !instanceName.MatchString(a.Instance) { + return errors.New("invalid DHCP instance name") + } + return a.Feed.Verify() +} + +// Has reports whether the feed serves mac at exactly address. +func (f Feed) Has(mac, address string) bool { + for _, r := range f.Reservations { + if r.MAC == mac && r.Address == address { + return true + } + } + return false +} + +// Serves reports whether the feed serves mac at any address. +func (f Feed) Serves(mac string) bool { + for _, r := range f.Reservations { + if r.MAC == mac { + return true + } + } + return false +} diff --git a/internal/bootnet/feed_test.go b/internal/bootnet/feed_test.go new file mode 100644 index 00000000..985483a4 --- /dev/null +++ b/internal/bootnet/feed_test.go @@ -0,0 +1,55 @@ +package bootnet + +import ( + "testing" + "time" +) + +func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { + exp := time.Date(2030, 1, 2, 3, 4, 5, 999, time.FixedZone("x", 3600)) + a := Reservation{MAC: "52-54-00-77-01-0B", Address: "192.0.2.11/24", Gateway: "192.0.2.1", Expires: exp} + b := Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: exp} + f1, err := NewFeed([]Reservation{a, b}) + if err != nil { + t.Fatal(err) + } + f2, _ := NewFeed([]Reservation{b, a}) + if f1.Revision != f2.Revision || f1.Reservations[0].MAC != "52:54:00:77:01:0a" || !f1.Reservations[0].Expires.Equal(exp.Truncate(time.Second)) { + t.Fatalf("feed not canonical: %+v", f1) + } + if err := f1.Verify(); err != nil { + t.Fatal(err) + } + if !f1.Has("52:54:00:77:01:0a", "192.0.2.10/24") || f1.Has("52:54:00:77:01:0a", "192.0.2.11/24") || !f1.Serves("52:54:00:77:01:0b") || f1.Serves("52:54:00:77:01:0c") { + t.Fatal("membership is not exact") + } + empty, _ := NewFeed(nil) + for name, f := range map[string]Feed{ + "other revision": {Revision: empty.Revision, Reservations: f1.Reservations}, + "unordered": {Revision: f1.Revision, Reservations: []Reservation{f1.Reservations[1], f1.Reservations[0]}}, + "null reservation": {Revision: empty.Revision}, + } { + if f.Verify() == nil { + t.Errorf("%s: verified", name) + } + } + for name, rs := range map[string][]Reservation{ + "duplicate MAC": {b, {MAC: b.MAC, Address: "192.0.2.12/24", Gateway: "192.0.2.1", Expires: exp}}, + "duplicate address": {b, {MAC: "52:54:00:77:01:0c", Address: "192.0.2.10/25", Gateway: "192.0.2.1", Expires: exp}}, + "no expiry": {{MAC: b.MAC, Address: b.Address, Gateway: b.Gateway}}, + "bare address": {{MAC: b.MAC, Address: "192.0.2.10", Gateway: b.Gateway, Expires: exp}}, + "gateway is host": {{MAC: b.MAC, Address: b.Address, Gateway: "192.0.2.10", Expires: exp}}, + "host route": {{MAC: b.MAC, Address: "192.0.2.10/32", Gateway: "192.0.2.1", Expires: exp}}, + "long MAC": {{MAC: "02:00:5e:10:00:00:00:01", Address: b.Address, Gateway: b.Gateway, Expires: exp}}, + } { + if _, err := NewFeed(rs); err == nil { + t.Errorf("%s: accepted", name) + } + } + if _, err := NewFeed([]Reservation{{MAC: b.MAC, Address: "2001:db8::10/64", Gateway: "2001:db8::1", Expires: exp}}); err != nil { + t.Fatalf("IPv6 attachment: %v", err) + } + if (Applied{Instance: "kea-0", Feed: empty}).Verify() != nil || (Applied{Instance: "-kea", Feed: empty}).Verify() == nil { + t.Fatal("instance names not checked") + } +} diff --git a/internal/dhcpsync/sync.go b/internal/dhcpsync/sync.go new file mode 100644 index 00000000..15f0c596 --- /dev/null +++ b/internal/dhcpsync/sync.go @@ -0,0 +1,195 @@ +// Package dhcpsync applies a site's boot-reservation feed to a Kea DHCPv4 +// server and reports each applied revision back to the site. It runs beside +// one Kea instance, owned with DHCP by the network owner; Fleet only decides +// which reservations exist. A report is sent only after Kea accepted the +// configuration that serves exactly the reported feed. +package dhcpsync + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "os" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +// Syncer is one synchronizer for one Kea instance. +type Syncer struct { + Feed string // the site's https DHCP feed origin + Token string + Instance string + Socket string // Kea's unix control socket + Base string // Kea configuration without Fleet reservations + HTTP *http.Client + + applied, reported string + pid float64 +} + +// Cycle fetches the feed, applies it when it changed or Kea restarted, and +// reports a newly applied revision. Any failure leaves the last report as the +// site's evidence; nothing is reported that Kea did not accept. +func (s *Syncer) Cycle(ctx context.Context) error { + feed, err := s.fetch(ctx) + if err != nil { + return err + } + status, err := s.command("status-get", nil) + if err != nil { + return err + } + pid, _ := status["pid"].(float64) + if pid == 0 { + return errors.New("kea status has no pid") + } + if feed.Revision != s.applied || pid != s.pid { + cfg, err := s.config(feed) + if err != nil { + return err + } + if _, err := s.command("config-set", cfg); err != nil { + return err + } + s.applied, s.pid = feed.Revision, pid + } + if s.reported == s.applied { + return nil + } + if err := s.report(ctx, feed); err != nil { + return err + } + s.reported = feed.Revision + return nil +} + +func (s *Syncer) request(ctx context.Context, method, path string, body []byte) (*http.Response, error) { + q, err := http.NewRequestWithContext(ctx, method, s.Feed+path, bytes.NewReader(body)) + if err != nil { + return nil, err + } + q.Header.Set("Authorization", "Bearer "+s.Token) + if body != nil { + q.Header.Set("Content-Type", "application/json") + } + return s.HTTP.Do(q) +} + +func (s *Syncer) fetch(ctx context.Context) (bootnet.Feed, error) { + resp, err := s.request(ctx, http.MethodGet, "/dhcp/v1/reservations", nil) + if err != nil { + return bootnet.Feed{}, err + } + defer resp.Body.Close() + var feed bootnet.Feed + d := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)) + d.DisallowUnknownFields() + if resp.StatusCode != http.StatusOK || d.Decode(&feed) != nil || feed.Verify() != nil { + return bootnet.Feed{}, fmt.Errorf("invalid reservation feed (HTTP %d)", resp.StatusCode) + } + return feed, nil +} + +func (s *Syncer) report(ctx context.Context, feed bootnet.Feed) error { + b, _ := json.Marshal(bootnet.Applied{Instance: s.Instance, Feed: feed}) + resp, err := s.request(ctx, http.MethodPost, "/dhcp/v1/applied", b) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + return fmt.Errorf("applied report rejected (HTTP %d)", resp.StatusCode) + } + return nil +} + +// config adds each reservation to the base subnet with exactly its prefix. +// A reservation with no such subnet is an error: it is never dropped silently. +func (s *Syncer) config(feed bootnet.Feed) (map[string]any, error) { + b, err := os.ReadFile(s.Base) + if err != nil { + return nil, err + } + var cfg map[string]any + if err := json.Unmarshal(b, &cfg); err != nil { + return nil, fmt.Errorf("base Kea configuration: %w", err) + } + dhcp, _ := cfg["Dhcp4"].(map[string]any) + subnets, _ := dhcp["subnet4"].([]any) + if subnets == nil { + return nil, errors.New("base Kea configuration has no Dhcp4 subnet4 list") + } + for _, r := range feed.Reservations { + p := netip.MustParsePrefix(r.Address) + if !p.Addr().Is4() { + return nil, fmt.Errorf("reservation %s is not IPv4", r.MAC) + } + var subnet map[string]any + for _, v := range subnets { + m, _ := v.(map[string]any) + text, _ := m["subnet"].(string) + if sp, err := netip.ParsePrefix(text); err == nil && sp == p.Masked() { + subnet = m + } + } + if subnet == nil { + return nil, fmt.Errorf("no base subnet %s for reservation %s", p.Masked(), r.MAC) + } + hosts, _ := subnet["reservations"].([]any) + subnet["reservations"] = append(hosts, map[string]any{ + "hw-address": r.MAC, "ip-address": p.Addr().String(), + "option-data": []any{map[string]any{"name": "routers", "data": r.Gateway}}, + }) + } + return cfg, nil +} + +// command sends one Kea control command and requires result 0. +func (s *Syncer) command(name string, arguments map[string]any) (map[string]any, error) { + c, err := net.DialTimeout("unix", s.Socket, 5*time.Second) + if err != nil { + return nil, err + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(30 * time.Second)) + q := map[string]any{"command": name} + if arguments != nil { + q["arguments"] = arguments + } + if err := json.NewEncoder(c).Encode(q); err != nil { + return nil, err + } + var resp struct { + Result int `json:"result"` + Text string `json:"text"` + Arguments map[string]any `json:"arguments"` + } + if err := json.NewDecoder(io.LimitReader(c, 4<<20)).Decode(&resp); err != nil { + return nil, fmt.Errorf("kea %s: %w", name, err) + } + if resp.Result != 0 { + return nil, fmt.Errorf("kea %s failed: %s", name, resp.Text) + } + return resp.Arguments, nil +} + +// Run cycles until the context ends, reporting each failed cycle. +func (s *Syncer) Run(ctx context.Context, interval time.Duration, failed func(error)) error { + for { + if err := s.Cycle(ctx); err != nil { + failed(err) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(interval): + } + } +} diff --git a/internal/dhcpsync/sync_test.go b/internal/dhcpsync/sync_test.go new file mode 100644 index 00000000..3121a534 --- /dev/null +++ b/internal/dhcpsync/sync_test.go @@ -0,0 +1,206 @@ +package dhcpsync + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +const token = "synthetic-dhcp-synchronizer-token-0123456789" + +// fakeKea answers status-get with its pid and records each config-set. +type fakeKea struct { + mu sync.Mutex + pid float64 + fail bool + configs []map[string]any +} + +func (k *fakeKea) serve(t *testing.T) string { + dir, err := os.MkdirTemp("", "kea") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + path := filepath.Join(dir, "ctrl") + l, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + var q struct { + Command string `json:"command"` + Arguments map[string]any `json:"arguments"` + } + _ = json.NewDecoder(c).Decode(&q) + k.mu.Lock() + resp := map[string]any{"result": 0} + switch { + case q.Command == "status-get": + resp["arguments"] = map[string]any{"pid": k.pid} + case q.Command == "config-set" && k.fail: + resp = map[string]any{"result": 1, "text": "synthetic rejection"} + case q.Command == "config-set": + k.configs = append(k.configs, q.Arguments) + } + k.mu.Unlock() + _ = json.NewEncoder(c).Encode(resp) + c.Close() + } + }() + return path +} + +func (k *fakeKea) applied() int { + k.mu.Lock() + defer k.mu.Unlock() + return len(k.configs) +} + +// fakeSite serves a feed and records applied reports. +type fakeSite struct { + mu sync.Mutex + feed bootnet.Feed + reports []bootnet.Applied +} + +func (f *fakeSite) handler(t *testing.T) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + if q.Header.Get("Authorization") != "Bearer "+token { + w.WriteHeader(http.StatusUnauthorized) + return + } + f.mu.Lock() + defer f.mu.Unlock() + switch q.URL.Path { + case "/dhcp/v1/reservations": + _ = json.NewEncoder(w).Encode(f.feed) + case "/dhcp/v1/applied": + var a bootnet.Applied + b, _ := io.ReadAll(q.Body) + if json.Unmarshal(b, &a) != nil || a.Verify() != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + f.reports = append(f.reports, a) + w.WriteHeader(http.StatusNoContent) + } + }) +} + +func (f *fakeSite) set(t *testing.T, rs ...bootnet.Reservation) { + feed, err := bootnet.NewFeed(rs) + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.feed = feed + f.mu.Unlock() +} + +func (f *fakeSite) reported() []bootnet.Applied { + f.mu.Lock() + defer f.mu.Unlock() + return append([]bootnet.Applied(nil), f.reports...) +} + +func newSyncer(t *testing.T) (*Syncer, *fakeKea, *fakeSite) { + kea := &fakeKea{pid: 100} + site := &fakeSite{} + site.set(t) + srv := httptest.NewTLSServer(site.handler(t)) + t.Cleanup(srv.Close) + base := filepath.Join(t.TempDir(), "kea-dhcp4.conf") + os.WriteFile(base, []byte(`{"Dhcp4":{"subnet4":[{"id":1,"subnet":"192.0.2.0/24","relay":{"ip-addresses":["192.0.2.1"]}},{"id":2,"subnet":"198.51.100.0/24"}]}}`), 0600) + return &Syncer{Feed: srv.URL, Token: token, Instance: "kea-0", Socket: kea.serve(t), Base: base, HTTP: srv.Client()}, kea, site +} + +var reservation = bootnet.Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Hour)} + +func TestAppliesReservationIntoItsExactSubnetThenReports(t *testing.T) { + s, kea, site := newSyncer(t) + ctx := context.Background() + if err := s.Cycle(ctx); err != nil || kea.applied() != 1 || len(site.reported()) != 1 { + t.Fatalf("empty feed not applied and reported: %v", err) + } + site.set(t, reservation) + if err := s.Cycle(ctx); err != nil { + t.Fatal(err) + } + kea.mu.Lock() + subnets := kea.configs[1]["Dhcp4"].(map[string]any)["subnet4"].([]any) + kea.mu.Unlock() + hosts, _ := json.Marshal(subnets[0].(map[string]any)["reservations"]) + if string(hosts) != `[{"hw-address":"52:54:00:77:01:0a","ip-address":"192.0.2.10","option-data":[{"data":"192.0.2.1","name":"routers"}]}]` || subnets[1].(map[string]any)["reservations"] != nil { + t.Fatalf("reservation not placed in exactly its subnet: %s", hosts) + } + reports := site.reported() + if len(reports) != 2 || !reports[1].Feed.Has(reservation.MAC, reservation.Address) || reports[1].Instance != "kea-0" { + t.Fatalf("applied revision not reported: %+v", reports) + } + // An unchanged feed is neither re-applied nor re-reported; a restarted + // Kea (new pid) lost its reservations and is re-applied without a report. + if err := s.Cycle(ctx); err != nil || kea.applied() != 2 || len(site.reported()) != 2 { + t.Fatalf("unchanged feed churned: %v", err) + } + kea.mu.Lock() + kea.pid = 101 + kea.mu.Unlock() + if err := s.Cycle(ctx); err != nil || kea.applied() != 3 || len(site.reported()) != 2 { + t.Fatalf("restarted Kea not re-applied: %v", err) + } + site.set(t) + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 3 || site.reported()[2].Feed.Serves(reservation.MAC) { + t.Fatalf("withdrawal not applied and reported: %v", err) + } +} + +func TestNothingIsReportedThatKeaDidNotAccept(t *testing.T) { + s, kea, site := newSyncer(t) + ctx := context.Background() + kea.mu.Lock() + kea.fail = true + kea.mu.Unlock() + site.set(t, reservation) + if err := s.Cycle(ctx); err == nil || len(site.reported()) != 0 { + t.Fatal("a rejected configuration was reported as applied") + } + kea.mu.Lock() + kea.fail = false + kea.mu.Unlock() + site.set(t, bootnet.Reservation{MAC: reservation.MAC, Address: "203.0.113.10/24", Gateway: "203.0.113.1", Expires: reservation.Expires}) + if err := s.Cycle(ctx); err == nil || kea.applied() != 0 || len(site.reported()) != 0 { + t.Fatal("a reservation without a base subnet was dropped or applied") + } + s.Token = "wrong-token-wrong-token-wrong-token-0000" + if err := s.Cycle(ctx); err == nil { + t.Fatal("an unauthenticated feed was accepted") + } +} + +func TestForgedFeedIsRejectedBeforeKea(t *testing.T) { + s, kea, site := newSyncer(t) + site.set(t, reservation) + site.mu.Lock() + site.feed.Reservations[0].Address = "192.0.2.99/24" + site.mu.Unlock() + if err := s.Cycle(context.Background()); err == nil || kea.applied() != 0 { + t.Fatal("a feed whose revision does not match its reservations was applied") + } +} diff --git a/internal/redfish/client.go b/internal/redfish/client.go index c9c0d1b4..3109d62f 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -55,17 +55,29 @@ type Client struct { api *gofish.APIClient } -// NewClient accepts only an http(s)://IP:port endpoint without path or query. -// It performs no request until first use. -func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { +// ParseEndpoint accepts only an http(s)://IPv4:port BMC endpoint without path +// or query, and returns its canonical form. +func ParseEndpoint(endpoint string) (string, error) { u, err := url.Parse(endpoint) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" { - return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + return "", errors.New("redfish endpoint must be http(s)://IPv4:port") } port, err := strconv.Atoi(u.Port()) - if ip := net.ParseIP(u.Hostname()); ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { - return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + ip := net.ParseIP(u.Hostname()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("redfish endpoint must be http(s)://IPv4:port") + } + return u.Scheme + "://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// NewClient accepts only an endpoint ParseEndpoint accepts. It performs no +// request until first use. +func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { + endpoint, err := ParseEndpoint(endpoint) + if err != nil { + return nil, err } + u, _ := url.Parse(endpoint) if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { return nil, errors.New("redfish credential must be a nonempty single-line username and password") } diff --git a/internal/redfish/dhcp.go b/internal/redfish/dhcp.go new file mode 100644 index 00000000..b9af3f8c --- /dev/null +++ b/internal/redfish/dhcp.go @@ -0,0 +1,221 @@ +package redfish + +import ( + "bufio" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +// withdrawalWindow bounds how long a worker waits, after the network boot +// closed, for every DHCP instance that served the reservation to report it +// withdrawn. Past it the outcome stays unknown and replay waits again. +const withdrawalWindow = 10 * time.Minute + +const dhcpLog = "dhcp-applied.log" + +// report is one retained applied report: when the boot service accepted it, +// which DHCP instance applied which exact feed. +type report struct { + At time.Time `json:"at"` + Instance string `json:"instance"` + Feed bootnet.Feed `json:"feed"` +} + +// reserved reports whether the operation's boot NIC should hold its +// provisioning address now: the same admission the boot handler serves, +// widened to the stages before power-on so DHCP is ready when firmware asks. +func (p *Provider) reserved(j journal, r *record, now time.Time) bool { + return r.Target.Provisioning != (Provisioning{}) && !j.Closed && j.Image == p.image && r.Stage != "done" && !r.BootClosed && len(r.BootToken) == 64 && now.Before(r.BootExpires) && + r.Request.BindingID == j.Binding && r.Request.Epoch == j.Epoch && r.Request.FenceToken == j.Fence +} + +// Reservations is the complete desired reservation set derived from the +// journal. It is empty when no network boot is admitted. +func (p *Provider) Reservations() (bootnet.Feed, error) { + j, err := p.read() + if err != nil { + return bootnet.Feed{}, err + } + now := p.clock() + rs := []bootnet.Reservation{} + for _, r := range j.Operations { + if p.reserved(j, r, now) { + rs = append(rs, bootnet.Reservation{MAC: r.Target.MAC, Address: r.Target.Provisioning.Address, Gateway: r.Target.Provisioning.Gateway, Expires: r.BootExpires}) + } + } + return bootnet.NewFeed(rs) +} + +// DHCPHandler serves the reservation feed and accepts applied reports from +// the DHCP owner's synchronizer, authenticated by a shared bearer token. It +// is never served on the firmware-facing boot listener. +func (p *Provider) DHCPHandler(token string) (http.Handler, error) { + if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { + return nil, errors.New("DHCP synchronizer token must be at least 32 characters without whitespace") + } + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + got, ok := strings.CutPrefix(q.Header.Get("Authorization"), "Bearer ") + if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + switch { + case q.Method == http.MethodGet && q.URL.Path == "/dhcp/v1/reservations" && q.URL.RawQuery == "": + feed, err := p.Reservations() + if err != nil { + http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(feed) + case q.Method == http.MethodPost && q.URL.Path == "/dhcp/v1/applied" && q.URL.RawQuery == "": + var a bootnet.Applied + d := json.NewDecoder(io.LimitReader(q.Body, 64<<10)) + d.DisallowUnknownFields() + if d.Decode(&a) != nil || d.Decode(&struct{}{}) != io.EOF || a.Verify() != nil { + http.Error(w, "invalid applied report", http.StatusBadRequest) + return + } + if err := p.retainReport(a); err != nil { + http.Error(w, "applied report not retained", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "not found", http.StatusNotFound) + } + }), nil +} + +// ServeDHCP listens on :8081, separate from the boot listener. +func (p *Provider) ServeDHCP(token string) error { + h, err := p.DHCPHandler(token) + if err != nil { + return err + } + s := &http.Server{Addr: ":8081", Handler: h, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + return s.ListenAndServe() +} + +// retainReport appends one report and syncs it before acknowledging. +func (p *Provider) retainReport(a bootnet.Applied) error { + b, err := json.Marshal(report{At: p.clock(), Instance: a.Instance, Feed: a.Feed}) + if err != nil { + return err + } + if err := os.MkdirAll(p.bootRoot, 0700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(p.bootRoot, dhcpLog), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = f.Write(append(b, '\n')) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = syncDir(p.bootRoot) + } + return err +} + +// reports reads every retained report in order. An unreadable line is +// corruption, never evidence in either direction. +func (p *Provider) reports() ([]report, error) { + f, err := os.Open(filepath.Join(p.bootRoot, dhcpLog)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + defer f.Close() + var out []report + s := bufio.NewScanner(f) + s.Buffer(make([]byte, 0, 64<<10), 1<<20) + for s.Scan() { + var r report + if json.Unmarshal(s.Bytes(), &r) != nil || r.At.IsZero() || (bootnet.Applied{Instance: r.Instance, Feed: r.Feed}).Verify() != nil { + return nil, errors.New("invalid retained DHCP report") + } + out = append(out, r) + } + return out, s.Err() +} + +// awaitReservation waits, without any effect, until some DHCP instance reports +// serving the target's exact provisioning address for this operation. +func (p *Provider) awaitReservation(ctx context.Context, r *record) error { + poll, _, _, _ := p.durations() + for { + reports, err := p.reports() + if err != nil { + return err + } + for _, a := range reports { + if a.At.After(r.Result.CreatedAt) && a.Feed.Has(r.Target.MAC, r.Target.Provisioning.Address) { + return nil + } + } + if !p.clock().Before(r.BootExpires) { + return errors.New("DHCP did not apply the boot reservation before boot admission expired") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// awaitWithdrawal requires that every DHCP instance which served the boot NIC +// during this operation now reports a feed without it. A silent instance +// keeps the outcome unknown: its reservation may still be served. +func (p *Provider) awaitWithdrawal(ctx context.Context, r *record) error { + poll, _, _, _ := p.durations() + deadline := p.clock().Add(withdrawalWindow) + for { + reports, err := p.reports() + if err != nil { + return err + } + served, latest := map[string]bool{}, map[string]bootnet.Feed{} + for _, a := range reports { + if !a.At.After(r.Result.CreatedAt) { + continue + } + if a.Feed.Serves(r.Target.MAC) { + served[a.Instance] = true + } + latest[a.Instance] = a.Feed + } + withdrawn := len(served) > 0 + for instance := range served { + if latest[instance].Serves(r.Target.MAC) { + withdrawn = false + } + } + if withdrawn { + return nil + } + if p.clock().After(deadline) { + return errors.New("DHCP has not reported the boot reservation withdrawn") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} diff --git a/internal/redfish/dhcp_test.go b/internal/redfish/dhcp_test.go new file mode 100644 index 00000000..9e60e1cc --- /dev/null +++ b/internal/redfish/dhcp_test.go @@ -0,0 +1,317 @@ +package redfish + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/executor" +) + +const syncToken = "synthetic-dhcp-synchronizer-token-0123456789" + +// fakeSync stands in for the DHCP owner's synchronizer: each instance applies +// the current feed and reports it whenever its revision changes. Withholding +// an instance's reports models a DHCP instance that may still serve. +type fakeSync struct { + t *testing.T + h http.Handler + mu sync.Mutex + silent map[string]bool + applied map[string]string + stop chan struct{} + done sync.WaitGroup +} + +func startSync(t *testing.T, p *Provider, instances ...string) *fakeSync { + t.Helper() + h, err := p.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) + } + s := &fakeSync{t: t, h: h, silent: map[string]bool{}, applied: map[string]string{}, stop: make(chan struct{})} + s.done.Add(1) + go func() { + defer s.done.Done() + for { + select { + case <-s.stop: + return + case <-time.After(2 * time.Millisecond): + } + for _, instance := range instances { + s.cycle(instance) + } + } + }() + t.Cleanup(s.close) + return s +} + +func (s *fakeSync) close() { + select { + case <-s.stop: + default: + close(s.stop) + } + s.done.Wait() +} + +func (s *fakeSync) silence(instance string, v bool) { + s.mu.Lock() + s.silent[instance] = v + s.mu.Unlock() +} + +func (s *fakeSync) cycle(instance string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.silent[instance] { + return + } + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) + q.Header.Set("Authorization", "Bearer "+syncToken) + s.h.ServeHTTP(w, q) + var feed bootnet.Feed + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &feed) != nil || s.applied[instance] == feed.Revision { + return + } + if code := post(s.h, syncToken, bootnet.Applied{Instance: instance, Feed: feed}); code != http.StatusNoContent { + return + } + s.applied[instance] = feed.Revision +} + +func post(h http.Handler, token string, a any) int { + b, _ := json.Marshal(a) + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodPost, "/dhcp/v1/applied", bytes.NewReader(b)) + q.Header.Set("Authorization", "Bearer "+token) + h.ServeHTTP(w, q) + return w.Code +} + +func TestEnrollmentRecordsPhysicalAttachments(t *testing.T) { + target := func(asset, endpoint, system, uuid, mac, prov string) string { + return fmt.Sprintf(`{"assetID":%q,"endpoint":%q,"systemID":%q,"systemUUID":%q,"mac":%q%s,"diskBytes":1,"console":"c.log"}`, asset, endpoint, system, uuid, mac, prov) + } + prov := func(address string) string { + return `,"provisioning":{"address":"` + address + `","gateway":"198.51.100.1"}` + } + // Physical BMCs each expose one System with the same ID: identity is the + // endpoint plus System, so two "Self" systems on two BMCs are distinct. + e, err := ParseEnrollment([]byte(`{"dhcp":"synced","targets":[` + + target("a", "https://192.0.2.20:443", "Self", uuidA, "00-00-5E-00-53-20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`)) + if err != nil { + t.Fatal(err) + } + if got := e.Targets[0]; got.Endpoint != "https://192.0.2.20:443" || got.MAC != "00:00:5e:00:53:20" || got.Provisioning != (Provisioning{Address: "198.51.100.21/24", Gateway: "198.51.100.1"}) { + t.Fatalf("enrollment not canonical: %+v", got) + } + for name, body := range map[string]string{ + "same System on one BMC": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.20:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`, + "shared provisioning address": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.21/24")) + `]}`, + "synced without attachment": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "static with attachment": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `]}`, + "gateway outside prefix": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", `,"provisioning":{"address":"198.51.100.21/24","gateway":"203.0.113.1"}`) + `]}`, + "network address as host": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.0/24")) + `]}`, + "BMC endpoint with a path": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443/redfish", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "missing DHCP mode": `{"targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "retired site-wide BMC endpoint": `{"dhcp":"static","endpoint":"https://192.0.2.20:443","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + } { + if _, err := ParseEnrollment([]byte(body)); err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestSyncedInstallServesAndWithdrawsTheReservation(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + ctx := context.Background() + if feed, err := f.p.Reservations(); err != nil || len(feed.Reservations) != 0 { + t.Fatalf("reservations published with no admitted boot: %+v %v", feed, err) + } + s := startSync(t, f.p, "kea-0") + q := f.install(1) + if r, err := f.p.Execute(ctx, q); err != nil || r.Result != "installed" { + t.Fatalf("install: %v %+v", err, r) + } + f.bmc.wg.Wait() + s.close() + reports, err := f.p.reports() + if err != nil { + t.Fatal(err) + } + var served, withdrawn bool + for _, a := range reports { + if a.Feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { + served = true + } else if served { + withdrawn = true + } + if a.Feed.Serves("52:54:00:77:01:0b") { + t.Fatal("the other enrolled target's attachment was published") + } + } + if !served || !withdrawn { + t.Fatalf("reports do not show the reservation served then withdrawn: %+v", reports) + } + if feed, _ := f.p.Reservations(); len(feed.Reservations) != 0 { + t.Fatalf("reservation outlived the operation: %+v", feed) + } + if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, dhcpLog)); strings.Contains(string(b), syncToken) { + t.Fatal("DHCP evidence contains the synchronizer token") + } +} + +func TestSyncedBootWaitsForDHCPWithoutEffects(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + q := f.install(1) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("network boot proceeded without DHCP evidence: %v", err) + } + if got := strings.Join(f.bmc.mutationsFor("System-1"), ","); strings.Contains(got, "Pxe") || strings.Contains(got, "On") { + t.Fatalf("boot effects before DHCP applied the reservation: %s", got) + } + // A report from before this operation is not evidence for it. + feed, _ := f.p.Reservations() + if len(feed.Reservations) != 1 || !feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { + t.Fatalf("admitted operation not published: %+v", feed) + } + startSync(t, f.p, "kea-0") + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("replay after DHCP applied: %v %+v", err, r) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { + t.Fatalf("unexpected Redfish effects: %v", got) + } +} + +func TestUnwithdrawnReservationKeepsTheOutcomeUnknown(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + s := startSync(t, f.p, "kea-0", "kea-1") + q := f.install(1) + result := make(chan error, 1) + go func() { + r, err := f.p.Execute(context.Background(), q) + if err == nil && r.Result != "installed" { + err = fmt.Errorf("unexpected result %+v", r) + } + result <- err + }() + waitFor := func(what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(5 * time.Second); !ok(); time.Sleep(2 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for " + what) + } + } + } + // Both instances serve the reservation; then kea-1 goes silent, so it + // never reports the withdrawal and may still be serving. + waitFor("both instances to serve", func() bool { + reports, _ := f.p.reports() + served := map[string]bool{} + for _, a := range reports { + if a.Feed.Serves("52:54:00:77:01:0a") { + served[a.Instance] = true + } + } + return len(served) == 2 + }) + s.silence("kea-1", true) + waitFor("the withdrawal gate", func() bool { return f.stage(t, q.ID) == "disk-verified" }) + time.Sleep(50 * time.Millisecond) + observer := *f.p + observer.readOnly = true + if _, found, err := observer.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("completed while one DHCP instance may still serve: %v %v", found, err) + } + s.silence("kea-1", false) + if err := <-result; err != nil { + t.Fatalf("withdrawal by every serving instance did not complete the operation: %v", err) + } + f.bmc.wg.Wait() +} + +func TestDHCPHandlerAuthenticatesAndRejectsForgedReports(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + if _, err := f.p.DHCPHandler("short"); err == nil { + t.Fatal("a weak token was accepted") + } + h, _ := f.p.DHCPHandler(syncToken) + for _, auth := range []string{"", "Bearer wrong-token-wrong-token-wrong-token-0000", "Basic " + syncToken} { + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) + if auth != "" { + q.Header.Set("Authorization", auth) + } + h.ServeHTTP(w, q) + if w.Code != http.StatusUnauthorized { + t.Fatalf("%q: %d", auth, w.Code) + } + } + if code := post(h, "wrong-token-wrong-token-wrong-token-0000", bootnet.Applied{Instance: "kea-0", Feed: bootnet.Feed{Reservations: []bootnet.Reservation{}}}); code != http.StatusUnauthorized { + t.Fatalf("unauthenticated report: %d", code) + } + valid, _ := bootnet.NewFeed([]bootnet.Reservation{{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Minute)}}) + forged := valid + forged.Reservations = []bootnet.Reservation{} + for name, a := range map[string]any{ + "revision of another set": bootnet.Applied{Instance: "kea-0", Feed: forged}, + "bad instance": bootnet.Applied{Instance: "Kea 0", Feed: valid}, + "unknown field": map[string]any{"instance": "kea-0", "feed": valid, "extra": true}, + } { + if code := post(h, syncToken, a); code != http.StatusBadRequest { + t.Fatalf("%s: %d", name, code) + } + } + if reports, _ := f.p.reports(); len(reports) != 0 { + t.Fatalf("rejected reports were retained: %+v", reports) + } + if code := post(h, syncToken, bootnet.Applied{Instance: "kea-0", Feed: valid}); code != http.StatusNoContent { + t.Fatalf("valid report: %d", code) + } + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/pxe/boot.ipxe", nil) + q.Header.Set("Authorization", "Bearer "+syncToken) + h.ServeHTTP(w, q) + if w.Code != http.StatusNotFound { + t.Fatalf("DHCP listener served a boot path: %d", w.Code) + } + os.WriteFile(filepath.Join(f.p.bootRoot, dhcpLog), []byte("not json\n"), 0600) + if _, err := f.p.reports(); err == nil { + t.Fatal("corrupt DHCP evidence was read as evidence") + } +} + +func TestShippedLabEnrollmentIsValidAndStatic(t *testing.T) { + b, err := os.ReadFile("../../config/site/redfish/graph/kustomization.yaml") + if err != nil { + t.Fatal(err) + } + _, value, ok := strings.Cut(string(b), "- name: FLEET_REDFISH_ENROLLMENT\n value: '") + value, _, _ = strings.Cut(value, "'\n") + e, err := ParseEnrollment([]byte(value)) + if !ok || err != nil || e.DHCP != DHCPStatic || len(e.Targets) != 2 { + t.Fatalf("shipped lab enrollment: %v %+v", err, e) + } +} diff --git a/internal/redfish/provider.go b/internal/redfish/provider.go index f6327e67..b97d029e 100644 --- a/internal/redfish/provider.go +++ b/internal/redfish/provider.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "go.datum.net/fleet/internal/bootnet" "go.datum.net/fleet/internal/executor" "go.datum.net/fleet/internal/simulator" "golang.org/x/sys/unix" @@ -33,22 +34,42 @@ const ( maxPowerOn = 3 ) -// Target is one enrolled physical asset and its exact Redfish System. Console -// names the serial-console capture file for the target (a lab seam; see the -// operations guide). Enrollment is retained before effects and never inferred. +// Target is one enrolled physical asset: its BMC endpoint, its exact Redfish +// System, its boot NIC and, when the site's DHCP is synchronized, the +// provisioning attachment the network owner assigned to it. Console names the +// serial-console capture file for the target (a lab seam; see the operations +// guide). Enrollment is retained before effects and never inferred. type Target struct { - AssetID string `json:"assetID"` - SystemID string `json:"systemID"` - SystemUUID string `json:"systemUUID"` - MAC string `json:"mac"` - DiskBytes int64 `json:"diskBytes"` - Console string `json:"console"` -} + AssetID string `json:"assetID"` + Endpoint string `json:"endpoint"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + MAC string `json:"mac"` + Provisioning Provisioning `json:"provisioning,omitzero"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` +} + +// Provisioning is the asset's address on the provisioning network, in prefix +// form, and that network's gateway. Networking/IPAM allocates it; Fleet only +// publishes it while the asset's network boot is admitted. +type Provisioning struct { + Address string `json:"address"` + Gateway string `json:"gateway"` +} + +// DHCP modes. Static: the site's DHCP is configured independently of Fleet. +// Synced: Fleet publishes boot reservations and a network boot requires +// evidence that DHCP applied the reservation and later withdrew it. +const ( + DHCPStatic = "static" + DHCPSynced = "synced" +) // Enrollment is the site's explicit asset to BMC mapping. type Enrollment struct { - Endpoint string `json:"endpoint"` - Targets []Target `json:"targets"` + DHCP string `json:"dhcp"` + Targets []Target `json:"targets"` } func (e Enrollment) target(asset string) (Target, bool) { @@ -61,29 +82,45 @@ func (e Enrollment) target(asset string) (Target, bool) { } func normalizeMAC(v string) (string, bool) { - hw, err := net.ParseMAC(strings.ReplaceAll(v, "-", ":")) - if err != nil || len(hw) != 6 { - return "", false - } - return hw.String(), true + return bootnet.NormalizeMAC(strings.ReplaceAll(v, "-", ":")) } func ParseEnrollment(b []byte) (Enrollment, error) { var e Enrollment d := json.NewDecoder(strings.NewReader(string(b))) d.DisallowUnknownFields() - if err := d.Decode(&e); err != nil || len(e.Targets) == 0 { + if err := d.Decode(&e); err != nil || len(e.Targets) == 0 || (e.DHCP != DHCPStatic && e.DHCP != DHCPSynced) { return Enrollment{}, errors.New("invalid Redfish enrollment") } seen := map[string]bool{} for i, t := range e.Targets { mac, ok := normalizeMAC(t.MAC) - if !ok || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || - seen["a"+t.AssetID] || seen["s"+t.SystemID] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + endpoint, err := ParseEndpoint(t.Endpoint) + // A Redfish System ID is unique only within its BMC. + system := "s" + endpoint + " " + t.SystemID + if !ok || err != nil || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.AssetID] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") } - seen["a"+t.AssetID], seen["s"+t.SystemID], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true - e.Targets[i].MAC = mac + seen["a"+t.AssetID], seen[system], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true + e.Targets[i].MAC, e.Targets[i].Endpoint = mac, endpoint + if e.DHCP == DHCPStatic { + if t.Provisioning != (Provisioning{}) { + return Enrollment{}, errors.New("a static-DHCP enrollment carries no provisioning attachment") + } + continue + } + feed, err := bootnet.NewFeed([]bootnet.Reservation{{MAC: mac, Address: t.Provisioning.Address, Gateway: t.Provisioning.Gateway, Expires: time.Unix(1, 0)}}) + if err != nil { + return Enrollment{}, errors.New("invalid provisioning attachment for enrolled target " + t.AssetID) + } + r := feed.Reservations[0] + address := "p" + strings.SplitN(r.Address, "/", 2)[0] + if seen[address] { + return Enrollment{}, errors.New("duplicate provisioning address") + } + seen[address] = true + e.Targets[i].Provisioning = Provisioning{Address: r.Address, Gateway: r.Gateway} } return e, nil } @@ -127,7 +164,7 @@ type Provider struct { root, bootRoot, consoleRoot, artifacts string origin, image string enrollment Enrollment - client *Client + clients map[string]*Client readOnly bool now func() time.Time poll, settle, offGrace, outage time.Duration @@ -163,15 +200,20 @@ func Open() (*Provider, error) { if credentials == "" || err1 != nil || err2 != nil { return nil, errors.New("redfish credentials are unavailable") } - client, err := NewClient(enrollment.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) - if err != nil { - return nil, err + p.clients = map[string]*Client{} + for _, t := range enrollment.Targets { + if p.clients[t.Endpoint] != nil { + continue + } + if p.clients[t.Endpoint], err = NewClient(t.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second); err != nil { + return nil, err + } } p.consoleRoot = os.Getenv("FLEET_REDFISH_CONSOLE") if !filepath.IsAbs(p.consoleRoot) { return nil, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") } - p.client, p.enrollment = client, enrollment + p.enrollment = enrollment return p, p.retainEnrollment() } @@ -447,7 +489,7 @@ func (p *Provider) validate(q simulator.Request) (Target, error) { // have happened. HTTP success is never success: only observed power state and // the exact console receipt complete a phase. func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { - if p.readOnly || p.client == nil { + if p.readOnly || len(p.clients) == 0 { return simulator.OperationResult{}, executor.ErrInvalid } ctx, cancel := context.WithTimeout(ctx, 40*time.Minute) @@ -554,7 +596,7 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage == "admitted" { // GETs only: a rejected credential, a missing capability or a // mismatched identity leaves the operation admitted with no effect. - sys, err := p.client.Discover(ctx, r.Target) + sys, err := p.bmc(r).Discover(ctx, r.Target) if err != nil { return fmt.Errorf("discovery: %w", err) } @@ -571,13 +613,18 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage == before { // Pre-boot: power off and arm the one-time override. Both are // idempotent here because no boot of this phase was requested. - if err := p.powerOff(ctx, *r.System); err != nil { + if err := p.powerOff(ctx, r); err != nil { return err } if ph.mode != "" && (r.BootClosed || !p.clock().Before(r.BootExpires)) { return errors.New("boot admission expired or closed before network boot") } - if err := p.client.SetBootOnce(ctx, *r.System, ph.boot); err != nil { + if ph.mode != "" && p.enrollment.DHCP == DHCPSynced { + if err := p.awaitReservation(ctx, r); err != nil { + return err + } + } + if err := p.bmc(r).SetBootOnce(ctx, *r.System, ph.boot); err != nil { return fmt.Errorf("arm %s boot: %w", ph.boot, err) } r.Stage = ph.name + "-armed" @@ -623,15 +670,22 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage != before { return errors.New("unexpected operation stage " + r.Stage) } + if p.enrollment.DHCP == DHCPSynced { + return p.awaitWithdrawal(ctx, r) + } return nil } -func (p *Provider) powerOff(ctx context.Context, sys System) error { +// bmc is the client of the target's own enrolled BMC. +func (p *Provider) bmc(r *record) *Client { return p.clients[r.Target.Endpoint] } + +func (p *Provider) powerOff(ctx context.Context, r *record) error { + sys := *r.System poll, _, _, _ := p.durations() deadline := p.clock().Add(5 * time.Minute) requested := false for { - pw, err := p.client.Observe(ctx, sys) + pw, err := p.bmc(r).Observe(ctx, sys) if err != nil { return fmt.Errorf("observe before boot: %w", err) } @@ -641,7 +695,7 @@ func (p *Provider) powerOff(ctx context.Context, sys System) error { if !requested { // A slow or lost ForceOff response is observed, not trusted: // power-off before this phase's boot is idempotent. - if err := p.client.Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { + if err := p.bmc(r).Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { return fmt.Errorf("power off: %w", err) } requested = true @@ -670,7 +724,7 @@ func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph if err := p.save(*j); err != nil { return err } - if err := p.client.Reset(ctx, *r.System, "On"); err != nil { + if err := p.bmc(r).Reset(ctx, *r.System, "On"); err != nil { return fmt.Errorf("power on (%s) response: %w", ph.name, err) } return nil @@ -683,7 +737,7 @@ func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph // On, within a small retained budget. func (p *Provider) started(ctx context.Context, j *journal, r *record, ph phase) (bool, error) { _, settle, _, _ := p.durations() - pw, err := p.client.Observe(ctx, *r.System) + pw, err := p.bmc(r).Observe(ctx, *r.System) if err != nil { if errors.Is(err, ErrIdentity) { return false, err @@ -710,7 +764,7 @@ func (p *Provider) complete(ctx context.Context, r *record, ph phase) error { poll, _, offGrace, outage := p.durations() var offSince, failingSince time.Time for { - pw, err := p.client.Observe(ctx, *r.System) + pw, err := p.bmc(r).Observe(ctx, *r.System) switch { case errors.Is(err, ErrIdentity): return err diff --git a/internal/redfish/provider_test.go b/internal/redfish/provider_test.go index c19dad39..2d2f643f 100644 --- a/internal/redfish/provider_test.go +++ b/internal/redfish/provider_test.go @@ -224,6 +224,13 @@ type fixture struct { } func newFixture(t *testing.T, timeout time.Duration) *fixture { + t.Helper() + return newDHCPFixture(t, timeout, DHCPStatic) +} + +// newDHCPFixture builds the fixture with the given site DHCP mode. Synced +// targets carry documentation-range provisioning attachments. +func newDHCPFixture(t *testing.T, timeout time.Duration, dhcp string) *fixture { t.Helper() dir := t.TempDir() for _, d := range []string{"journal", "boot", "console", "artifacts"} { @@ -248,9 +255,15 @@ func newFixture(t *testing.T, timeout time.Duration) *fixture { "System-2": {id: "System-2", uuid: uuidB, mac: "52:54:00:77:01:0b", console: filepath.Join(dir, "console/target-b.log"), power: "Off", enabled: "Disabled", target: "None"}}} rf := httptest.NewServer(bmc.handler()) t.Cleanup(rf.Close) - enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"endpoint":%q,"targets":[ - {"assetID":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}, - {"assetID":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}`, rf.URL, assetA, uuidA, assetB, uuidB))) + provA, provB := "", "" + if dhcp == DHCPSynced { + provA = `,"provisioning":{"address":"192.0.2.10/24","gateway":"192.0.2.1"}` + provB = `,"provisioning":{"address":"192.0.2.11/24","gateway":"192.0.2.1"}` + } + enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"dhcp":%q,"targets":[ + {"assetID":%q,"endpoint":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a"%s,"diskBytes":2147483648,"console":"target-a.log"}, + {"assetID":%q,"endpoint":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b"%s,"diskBytes":2147483648,"console":"target-b.log"}]}`, + dhcp, assetA, rf.URL, uuidA, provA, assetB, rf.URL, uuidB, provB))) if err != nil { t.Fatal(err) } @@ -259,7 +272,7 @@ func newFixture(t *testing.T, timeout time.Duration) *fixture { t.Fatal(err) } p := &Provider{root: filepath.Join(dir, "journal"), bootRoot: filepath.Join(dir, "boot"), consoleRoot: filepath.Join(dir, "console"), artifacts: filepath.Join(dir, "artifacts"), - image: image, enrollment: enrollment, client: client, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} + image: image, enrollment: enrollment, clients: map[string]*Client{enrollment.Targets[0].Endpoint: client}, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} boot := httptest.NewServer(p.BootHandler()) t.Cleanup(boot.Close) p.origin, bmc.boot = boot.URL, boot.URL @@ -510,7 +523,7 @@ func TestEnrollmentIsRetainedOnceWithoutContendingForTheJournalLock(t *testing.T } } changed := *f.p - changed.enrollment = Enrollment{Endpoint: f.p.enrollment.Endpoint, Targets: f.p.enrollment.Targets[:1]} + changed.enrollment = Enrollment{DHCP: f.p.enrollment.DHCP, Targets: f.p.enrollment.Targets[:1]} if err := changed.retainEnrollment(); err == nil { t.Fatal("a changed enrollment was accepted for the retained journal") } From f735b9cca967dc45f0caa49aa4c94d081a0fbda0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 15:05:51 -0600 Subject: [PATCH 12/12] feat(inventory): add operator-written DeviceClaim and Device Add a minimal subset of the proposed physical inventory API in fleet.datumapis.com/v1alpha1. A DeviceClaim is the plan for one rack slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. A Device is the actual asset, bound to exactly one claim when an operator registers detected hardware. It records serial, SMBIOS system UUID, model, optional BMC endpoint, interfaces, and Manual provenance. Both kinds are operator-written and have no controller. Registration authorizes no hardware effect and creates or changes no MachineCapacity. Status is a reserved subresource with no fields and no writer. CEL keeps the records attributable and their identities stable: - every edit must advance provenance.recordedAt - a Device's claimRef and identity are immutable, so a hardware swap is a new Device bound to the same claim - names are unique, MACs are lowercase and recorded once, and BMC endpoints are https without credentials config/inventory packages only the CRDs as an opt-in root. Trust, enrollment, reservations, and the Facility, Rack, and Cable kinds stay deferred to the inventory proposal. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + config/README.md | 5 + config/inventory/fleet.datumapis.com.yaml | 178 ++++++++++ config/inventory/kustomization.yaml | 4 + docs/architecture/README.md | 2 +- docs/development/README.md | 16 +- docs/operations/README.md | 1 + docs/operations/physical-inventory.md | 174 ++++++++++ internal/api/inventory/v1alpha1/crd_test.go | 357 ++++++++++++++++++++ internal/api/inventory/v1alpha1/types.go | 179 ++++++++++ 10 files changed, 915 insertions(+), 2 deletions(-) create mode 100644 config/inventory/fleet.datumapis.com.yaml create mode 100644 config/inventory/kustomization.yaml create mode 100644 docs/operations/physical-inventory.md create mode 100644 internal/api/inventory/v1alpha1/crd_test.go create mode 100644 internal/api/inventory/v1alpha1/types.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83fdfdb0..16d25a42 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: kustomize build config/milo >/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 diff --git a/config/README.md b/config/README.md index 07e34cda..c7bca057 100644 --- a/config/README.md +++ b/config/README.md @@ -18,6 +18,11 @@ API servers and must be reconciled independently. | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | +`config/inventory` is an opt-in root for the Fleet management cluster. It holds +only the CRDs for the operator-written `DeviceClaim` and `Device` subset of the +physical inventory API. Neither production root references it. See +[Planning and registering physical devices](../docs/operations/physical-inventory.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/inventory/fleet.datumapis.com.yaml b/config/inventory/fleet.datumapis.com.yaml new file mode 100644 index 00000000..3033e41c --- /dev/null +++ b/config/inventory/fleet.datumapis.com.yaml @@ -0,0 +1,178 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceclaims.fleet.datumapis.com +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: Facility, type: string, jsonPath: .spec.placement.facility} + - {name: Rack, type: string, jsonPath: .spec.placement.rack} + - {name: Position, type: integer, jsonPath: .spec.placement.position} + - {name: Model, type: string, jsonPath: .spec.expectedIdentity.model} + - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [provenance, expectedIdentity, placement] + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every change to a claim must advance provenance.recordedAt + properties: + provenance: + type: object + required: [method, recordedBy, recordedAt] + properties: + method: {type: string, enum: [Manual]} + recordedBy: {type: string, minLength: 1, maxLength: 253} + recordedAt: {type: string, format: date-time} + reference: {type: string, minLength: 1, maxLength: 1024} + 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: [facility, rack, position, face] + properties: + facility: {type: string, minLength: 1, maxLength: 253} + rack: {type: string, minLength: 1, maxLength: 253} + position: {type: integer, format: int32, minimum: 1, maximum: 100} + height: {type: integer, format: int32, minimum: 1, maximum: 100, default: 1} + face: {type: string, enum: [front, rear]} + ports: + type: array + maxItems: 128 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 63} + type: {type: string, maxLength: 253} + speedMbps: {type: integer, format: int64, minimum: 1} + expectedPeer: + type: object + required: [device, port] + properties: + device: {type: string, minLength: 1, maxLength: 253} + port: {type: string, minLength: 1, maxLength: 253} + status: {type: object} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devices.fleet.datumapis.com +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: System UUID, type: string, priority: 1, jsonPath: .spec.identity.systemUUID} + - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [claimRef, provenance, identity] + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every change to a device must advance provenance.recordedAt + - 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.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 + properties: + claimRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 253} + provenance: + type: object + required: [method, recordedBy, recordedAt] + properties: + method: {type: string, enum: [Manual]} + recordedBy: {type: string, minLength: 1, maxLength: 253} + recordedAt: {type: string, format: date-time} + reference: {type: string, minLength: 1, maxLength: 1024} + identity: + type: object + required: [model] + x-kubernetes-validations: + - rule: has(self.serial) || has(self.systemUUID) + message: a device needs a serial or a system UUID + 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}$'} + 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}$'} + peer: + type: object + required: [device, port] + properties: + device: {type: string, minLength: 1, maxLength: 253} + port: {type: string, minLength: 1, maxLength: 253} + 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}$'} + status: {type: object} diff --git a/config/inventory/kustomization.yaml b/config/inventory/kustomization.yaml new file mode 100644 index 00000000..9ce565ec --- /dev/null +++ b/config/inventory/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - fleet.datumapis.com.yaml diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 4d305dfe..57c04fa4 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -59,7 +59,7 @@ processes or service-catalog entries. | --- | --- | --- | | `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. | | `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; no physical inventory CRDs or real provider executor are implemented here. | +| `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, as alpha CRDs in the opt-in [inventory root](../operations/physical-inventory.md), outside the production roots; 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 diff --git a/docs/development/README.md b/docs/development/README.md index 3eb2fe48..f81cbf2b 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -45,7 +45,8 @@ Milo IAM, service, and quota boundaries; packaging is not runtime readiness. 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. @@ -587,6 +588,19 @@ 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. +## Physical inventory subset + +`internal/api/inventory/v1alpha1` defines `DeviceClaim`, the plan for one rack +slot, and `Device`, the asset bound to one claim. Operators write both by hand. +`config/inventory` packages only their CRDs. CEL requires `Manual` provenance on +both and requires every edit to advance `recordedAt`. It 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 production root includes the +package, and nothing reads it. Unit tests run the API server's schema, +list-type, defaulting, and CEL validation offline. See +[Planning and registering physical devices](../operations/physical-inventory.md). + ## Build, test, and run Run the implemented checks from the repository root: diff --git a/docs/operations/README.md b/docs/operations/README.md index ed23e838..746774d5 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -17,6 +17,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | +| Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records with attributable provenance and immutable identity and binding; no capacity or hardware effect; unit tested | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md new file mode 100644 index 00000000..ddfdfe83 --- /dev/null +++ b/docs/operations/physical-inventory.md @@ -0,0 +1,174 @@ +# Planning and registering physical devices + +[Operations guide](README.md) · [Architecture](../architecture/README.md) · +[Implementation status](../development/README.md) + +Before Fleet can enroll or offer real hardware, operators need to record two +things: where a server is meant to go, and which physical server is actually +there. Recording either must not provision the server, publish capacity, or +take ownership of it. + +This package implements a minimal subset of the +[inventory lifecycle and trust proposal (#63)](https://github.com/datum-cloud/fleet/pull/63). +It has two operator-written kinds in `fleet.datumapis.com/v1alpha1`: + +| Kind | What it is | Writer | +| --- | --- | --- | +| `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | +| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | The registrar (an operator, for now) | + +## Status + +| Aspect | State | +| --- | --- | +| CRDs and Go types | Implemented in `config/inventory` and `internal/api/inventory/v1alpha1`. | +| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. | +| Production roots | Not included. `config/milo`, `config/overlays/management-plane`, and `config/overlays/synthetic-staging` do not reference it. An environment opts in by applying `config/inventory`. | +| Controllers | None. No Fleet code reads or writes these kinds. | +| Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | + +## What registration does and does not do + +Creating a Device is the explicit, manual binding step. It records that the +registrar saw this hardware in this planned slot. It does not: + +- authorize power, boot, wipe, BMC credential, or network changes; +- create, change, or enable any `MachineCapacity`, or make anything + allocatable; or +- verify identity, placement, cabling, or power. + +Detection is manual too. The registrar records what the BMC (for example +Redfish) and the rack showed them. MachineCapacity is unchanged by this +package. Its `spec.deviceRef` already names a Device by name, and the +allocator forms the asset key +`/fleet.datumapis.com/Device/`. Device names are +Kubernetes object names in the same group and kind, so a later supply step can +reference a Device without renaming it. That step must place the Device and its +MachineCapacity in the same namespace. + +## Writers and validation + +| Rule | Kind | Why | +| --- | --- | --- | +| `provenance` is required: `method: Manual`, `recordedBy`, `recordedAt`, and an optional opaque `reference` | Both | Every plan and registration is attributable to a person and a time. | +| Any spec change must set a later `provenance.recordedAt` | Both | An edit cannot pass off new facts under old provenance. | +| `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | +| `identity` (manufacturer, model, serial, system UUID) is immutable, including adding a missing field; at least one of serial or system UUID is required | Device | Serial and UUID are matching evidence. A hardware swap is a new Device bound to the same claim. | +| Serial is optional | DeviceClaim | It is usually unknown at plan time. | +| Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | +| The system UUID is in lowercase canonical form | Device | One spelling per identity. | +| `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `status` is a separate subresource that declares no fields | Both | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | + +The CRDs cannot check that `claimRef` names an existing DeviceClaim, because +CEL cannot read other objects. Until a registrar enforces it, the operator +creates the claim first. + +Use `unmappedMACAddresses` for MACs detected on the asset that cannot yet be +attributed to a named port. Do not guess a mapping; #63 requires an +authenticated, complete NIC mapping before any network path depends on it. + +## Example + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: rack-01-u12 + namespace: fleet-system +spec: + provenance: + method: Manual + recordedBy: planner@example.com + recordedAt: "2026-01-02T03:04:05Z" + reference: rack plan 1234 + expectedIdentity: + manufacturer: Example Vendor + model: Example 1U + placement: + facility: example-facility + rack: rack-01 + position: 12 + face: front + ports: + - name: eth0 + type: 25gbase-x-sfp28 + speedMbps: 25000 + expectedPeer: {device: switch-01, port: Ethernet1/1} + - name: bmc0 + type: 1000base-t + speedMbps: 1000 + expectedPeer: {device: mgmt-switch-01, port: Ethernet5} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: rack-01-u12-synthetic-0001 + namespace: fleet-system +spec: + claimRef: + name: rack-01-u12 + provenance: + method: Manual + recordedBy: registrar@example.com + recordedAt: "2026-01-09T10:00:00Z" + reference: BMC inventory read during rack turn-up + identity: + manufacturer: Example Vendor + model: Example 1U + serial: SYNTHETIC-0001 + systemUUID: 00000000-0000-4000-8000-000000000001 + bmc: + endpoint: https://192.0.2.100:443 + unmappedMACAddresses: + - 00:00:5e:00:53:01 + - 00:00:5e:00:53:02 +``` + +To replace the hardware, create a new Device with its own name and identity +that names the same claim. Leave the old Device in place until its retirement +is settled. This package does not model retirement. + +## Relationship to the inventory proposal + +The names and writers match #63: + +- DeviceClaim is a physical installation plan written by the installation + planner. +- Device is the canonical asset created only by the registrar. +- Collectors submit observations and never edit Device identity. +- Status is a protected projection. +- Serial and SMBIOS UUID are matching evidence, not authenticators. +- Logical LAGs and VLANs are not ports. + +Deferred to #63, and deliberately absent: + +- `Facility`, `Rack`, `Cable`, and `PowerFeed` kinds. Facility and rack are + names on the claim, and the expected cable peer is inline on each claimed + port, until those kinds replace them. Rack geometry beyond position, height, + and face is also deferred. +- Plan acceptance, revisions, and reservations; canonical-identity + adjudication and duplicate detection; and the protected ledger. +- Trust roots, qualification profiles, enrollment challenges, technician and + collector attestation, and evidence freshness. +- Component incarnations and lineage, maintenance, moves, retirement, and + adopted custody. +- The `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, + `NetworkPathVerified`, and `PowerPathVerified` predicates and any eligibility + publication. +- Separation of planner, approver, registrar, and verifier roles. One operator + can write both kinds today. + +**Divergence to resolve:** this package's convention is that a whole-server +replacement binds a new Device to the same DeviceClaim, because the planned slot +outlives the hardware. #63's current text says whole-server replacement creates a +new DeviceClaim as well. The schema enforces neither convention. Settle this in +#63 before either path is automated. + +## Applying the root + +`config/inventory` contains only the two cluster-scoped CRDs. It needs no +credentials or workload. Apply claims and Devices after the CRDs are +established, claims before the Devices that name them. Keep records with real +serials, UUIDs, MACs, endpoints, or cabling in the environment's private +configuration, not in this repository. diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go new file mode 100644 index 00000000..21150ef1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -0,0 +1,357 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "testing" + "time" + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype" + "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utiljson "k8s.io/apimachinery/pkg/util/json" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apimachinery/pkg/util/yaml" + celconfig "k8s.io/apiserver/pkg/apis/cel" +) + +var inventoryRoot = filepath.Join("..", "..", "..", "..", "config", "inventory") + +func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { + t.Helper() + data, err := os.ReadFile(filepath.Join(inventoryRoot, "fleet.datumapis.com.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + out := map[string]*extensionsv1.CustomResourceDefinition{} + for { + var crd extensionsv1.CustomResourceDefinition + if err := decoder.Decode(&crd); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if crd.Name != "" { + copied := crd + out[crd.Spec.Names.Kind] = &copied + } + } +} + +func TestInventoryCRDContract(t *testing.T) { + crds := loadCRDs(t) + if len(crds) != 2 || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got CRDs %v, want exactly DeviceClaim and Device", crds) + } + for kind, crd := range crds { + if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { + t.Fatalf("%s identity = %s %s", kind, crd.Name, crd.Spec.Scope) + } + version := crd.Spec.Versions[0] + if len(crd.Spec.Versions) != 1 || version.Name != GroupVersion.Version || !version.Served || !version.Storage { + t.Fatalf("%s must serve and store exactly v1alpha1", kind) + } + if version.Subresources == nil || version.Subresources.Status == nil { + t.Fatalf("%s must reserve status as a separate subresource", kind) + } + if status := version.Schema.OpenAPIV3Schema.Properties["status"]; len(status.Properties) != 0 || status.XPreserveUnknownFields != nil { + t.Fatalf("%s status must stay empty until a collector or verifier owns it", kind) + } + if _, ok := crd.Annotations["discovery.miloapis.com/parent-contexts"]; ok { + t.Fatalf("%s must not be exposed through Milo project discovery", kind) + } + defaulted := crd.DeepCopy() + extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) + defaulted.Status.StoredVersions = []string{GroupVersion.Version} + var internal apiextensions.CustomResourceDefinition + if err := extensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(defaulted, &internal, nil); err != nil { + t.Fatal(err) + } + if errs := crdvalidation.ValidateCustomResourceDefinition(context.Background(), &internal); len(errs) > 0 { + t.Fatalf("%s: %v", kind, errs.ToAggregate()) + } + } +} + +// admit applies schema defaults to both objects, as stored objects already +// carry them, then the OpenAPI, list-type, and CEL +// validation the API server runs on create (old == nil) or update. Objects are +// decoded with integer-preserving JSON, as the API server decodes them. +func admit(t *testing.T, kind string, object, old map[string]any) field.ErrorList { + t.Helper() + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)[kind].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + structuraldefaulting.Default(object, structural) + validator, _, err := validation.NewSchemaValidator(&schema) + if err != nil { + t.Fatal(err) + } + errs := validation.ValidateCustomResource(nil, object, validator) + errs = append(errs, listtype.ValidateListSetsAndMaps(nil, structural, object)...) + var oldObject any + if old != nil { + structuraldefaulting.Default(old, structural) + oldObject = old + } + celErrs, _ := cel.NewValidator(structural, true, celconfig.PerCallLimit).Validate(context.Background(), nil, structural, object, oldObject, celconfig.RuntimeCELCostBudget) + return append(errs, celErrs...) +} + +func object(t *testing.T, value any) map[string]any { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + var out map[string]any + if err := utiljson.Unmarshal(data, &out); err != nil { + t.Fatal(err) + } + return out +} + +var recordedAt = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + +func provenance(at time.Time) Provenance { + return Provenance{Method: ProvenanceManual, RecordedBy: "operator@example.com", RecordedAt: metav1.NewTime(at), Reference: "rack plan 1234"} +} + +func syntheticClaim() DeviceClaim { + return DeviceClaim{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceClaim"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12", Namespace: "fleet-system"}, + Spec: DeviceClaimSpec{ + Provenance: provenance(recordedAt), + ExpectedIdentity: ExpectedIdentity{Manufacturer: "Example Vendor", Model: "Example 1U"}, + Placement: Placement{Facility: "example-facility", Rack: "rack-01", Position: 12, Face: "front"}, + Ports: []ExpectedPort{ + {Name: "eth0", Type: "25gbase-x-sfp28", SpeedMbps: 25000, ExpectedPeer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", Type: "1000base-t", SpeedMbps: 1000, ExpectedPeer: &PortPeer{Device: "mgmt-switch-01", Port: "Ethernet5"}}, + }, + }, + } +} + +func syntheticDevice() Device { + return Device{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Device"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12-synthetic-0001", Namespace: "fleet-system"}, + Spec: DeviceSpec{ + ClaimRef: LocalReference{Name: "rack-01-u12"}, + Provenance: provenance(recordedAt), + Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, + BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, + Interfaces: []Interface{ + {Name: "eth0", MACAddress: "00:00:5e:00:53:01", Peer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", MACAddress: "00:00:5e:00:53:02"}, + }, + UnmappedMACAddresses: []string{"00:00:5e:00:53:03"}, + }, + } +} + +func later(d time.Duration) metav1.Time { return metav1.NewTime(recordedAt.Add(d)) } + +func TestValidRecordsAreAccepted(t *testing.T) { + if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), nil); len(errs) > 0 { + t.Fatalf("claim rejected: %v", errs) + } + if errs := admit(t, "Device", object(t, syntheticDevice()), nil); len(errs) > 0 { + t.Fatalf("device rejected: %v", errs) + } + minimal := syntheticDevice() + minimal.Spec.Identity.Serial = "" + minimal.Spec.BMC, minimal.Spec.Interfaces = nil, nil + if errs := admit(t, "Device", object(t, minimal), nil); len(errs) > 0 { + t.Fatalf("device with only a system UUID rejected: %v", errs) + } +} + +func TestClaimDoesNotRequireSerialAndDefaultsHeight(t *testing.T) { + claim := object(t, syntheticClaim()) + if errs := admit(t, "DeviceClaim", claim, nil); len(errs) > 0 { + t.Fatal(errs) + } + if height := claim["spec"].(map[string]any)["placement"].(map[string]any)["height"]; height != int64(1) { + t.Fatalf("height defaulted to %v", height) + } +} + +func TestInvalidClaimsAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*DeviceClaim){ + "unknown method": func(c *DeviceClaim) { c.Spec.Provenance.Method = "Discovered" }, + "missing recorder": func(c *DeviceClaim) { c.Spec.Provenance.RecordedBy = "" }, + "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, + "missing facility": func(c *DeviceClaim) { c.Spec.Placement.Facility = "" }, + "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, + "unknown face": func(c *DeviceClaim) { c.Spec.Placement.Face = "side" }, + "duplicate port": func(c *DeviceClaim) { c.Spec.Ports[1].Name = c.Spec.Ports[0].Name }, + "peer without port": func(c *DeviceClaim) { + c.Spec.Ports[0].ExpectedPeer = &PortPeer{Device: "switch-01"} + }, + } { + claim := syntheticClaim() + mutate(&claim) + if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } +} + +func TestInvalidDevicesAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*Device){ + "missing claim": func(d *Device) { d.Spec.ClaimRef.Name = "" }, + "no identity key": func(d *Device) { d.Spec.Identity.Serial, d.Spec.Identity.SystemUUID = "", "" }, + "uppercase system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-00000000000A" }, + "malformed system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "not-a-uuid" }, + "uppercase MAC": func(d *Device) { d.Spec.Interfaces[0].MACAddress = "00:00:5E:00:53:01" }, + "malformed MAC": func(d *Device) { d.Spec.UnmappedMACAddresses = []string{"not-a-mac"} }, + "duplicate interface": func(d *Device) { d.Spec.Interfaces[1].Name = d.Spec.Interfaces[0].Name }, + "MAC on two interfaces": func(d *Device) { d.Spec.Interfaces[1].MACAddress = d.Spec.Interfaces[0].MACAddress }, + "MAC mapped and unmapped": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{d.Spec.Interfaces[0].MACAddress} + }, + "duplicate unmapped MAC": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{"00:00:5e:00:53:03", "00:00:5e:00:53:03"} + }, + "plain-http BMC": func(d *Device) { d.Spec.BMC.Endpoint = "http://192.0.2.100" }, + "BMC with credentials": func(d *Device) { d.Spec.BMC.Endpoint = "https://admin:secret@192.0.2.100" }, + "BMC not a URL": func(d *Device) { d.Spec.BMC.Endpoint = "192.0.2.100" }, + } { + device := syntheticDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + withoutClaim := object(t, syntheticDevice()) + delete(withoutClaim["spec"].(map[string]any), "claimRef") + if errs := admit(t, "Device", withoutClaim, nil); len(errs) == 0 { + t.Error("device without a claim reference accepted") + } +} + +func TestEveryEditMustAdvanceRecordedAt(t *testing.T) { + oldClaim := object(t, syntheticClaim()) + if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), oldClaim); len(errs) > 0 { + t.Fatalf("unchanged claim update rejected: %v", errs) + } + for name, at := range map[string]metav1.Time{"same time": metav1.NewTime(recordedAt), "backdated": later(-time.Hour)} { + claim := syntheticClaim() + claim.Spec.Placement.Position = 14 + claim.Spec.Provenance.RecordedAt = at + if errs := admit(t, "DeviceClaim", object(t, claim), oldClaim); len(errs) == 0 { + t.Errorf("claim edit with %s accepted", name) + } + } + replanned := syntheticClaim() + replanned.Spec.Placement.Position = 14 + replanned.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "DeviceClaim", object(t, replanned), oldClaim); len(errs) > 0 { + t.Fatalf("re-recorded claim edit rejected: %v", errs) + } + + oldDevice := object(t, syntheticDevice()) + stale := syntheticDevice() + stale.Spec.BMC.Endpoint = "https://192.0.2.101" + if errs := admit(t, "Device", object(t, stale), oldDevice); len(errs) == 0 { + t.Error("device edit without a newer recordedAt accepted") + } + updated := syntheticDevice() + updated.Spec.BMC.Endpoint = "https://192.0.2.101" + updated.Spec.UnmappedMACAddresses = nil + updated.Spec.Interfaces = append(updated.Spec.Interfaces, Interface{Name: "eth1", MACAddress: "00:00:5e:00:53:03"}) + updated.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, updated), oldDevice); len(errs) > 0 { + t.Fatalf("re-recorded device edit rejected: %v", errs) + } +} + +func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { + old := object(t, syntheticDevice()) + for name, mutate := range map[string]func(*Device){ + "retarget claim": func(d *Device) { d.Spec.ClaimRef.Name = "rack-01-u14" }, + "change serial": func(d *Device) { d.Spec.Identity.Serial = "SYNTHETIC-0002" }, + "remove serial": func(d *Device) { d.Spec.Identity.Serial = "" }, + "change system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" }, + "change model": func(d *Device) { d.Spec.Identity.Model = "Example 2U" }, + } { + device := syntheticDevice() + mutate(&device) + device.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, device), old); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + unserialed := syntheticDevice() + unserialed.Spec.Identity.Serial = "" + added := syntheticDevice() + added.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, added), object(t, unserialed)); len(errs) == 0 { + t.Error("adding a serial to a registered device accepted; a new identity needs a new Device") + } +} + +func TestReplacementBindsANewDeviceToTheSameClaim(t *testing.T) { + replacement := syntheticDevice() + replacement.Name = "rack-01-u12-synthetic-0002" + replacement.Spec.Identity.Serial = "SYNTHETIC-0002" + replacement.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" + replacement.Spec.Provenance.RecordedAt = later(24 * time.Hour) + if errs := admit(t, "Device", object(t, replacement), nil); len(errs) > 0 { + t.Fatalf("replacement device for the same claim rejected: %v", errs) + } +} + +func TestStatusAcceptsNoFieldsYet(t *testing.T) { + device := object(t, syntheticDevice()) + device["status"] = map[string]any{"identity": map[string]any{"serial": "SYNTHETIC-0009"}} + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + if structural.Properties["status"].Properties != nil { + t.Fatal("status declares fields") + } +} + +func TestSchemeRegistersBothKinds(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + claim, device := syntheticClaim(), syntheticDevice() + for _, obj := range []runtime.Object{claim.DeepCopyObject(), device.DeepCopyObject(), &DeviceClaimList{}, &DeviceList{}} { + if _, _, err := scheme.ObjectKinds(obj); err != nil { + t.Fatal(err) + } + } + if copied := device.DeepCopyObject().(*Device); copied.Spec.Identity != device.Spec.Identity || &copied.Spec.Interfaces[0] == &device.Spec.Interfaces[0] { + t.Fatal("deep copy did not copy the device") + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go new file mode 100644 index 00000000..66351684 --- /dev/null +++ b/internal/api/inventory/v1alpha1/types.go @@ -0,0 +1,179 @@ +// Package v1alpha1 holds a minimal subset of the proposed physical inventory +// API in fleet.datumapis.com: DeviceClaim, the installation plan for one slot, +// and Device, the actual asset bound to a claim. +// +// Both are operator-written records. Neither has a controller. Registering a +// Device authorizes no hardware effect and creates or changes no +// MachineCapacity. Status is reserved for future collectors and verifiers and +// has no writer. +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +// ProvenanceManual marks a record an operator entered by hand. +const ProvenanceManual = "Manual" + +// Provenance says how, by whom, and when a record's spec was written. Every +// change to a spec must advance RecordedAt. +type Provenance struct { + Method string `json:"method"` + RecordedBy string `json:"recordedBy"` + RecordedAt metav1.Time `json:"recordedAt"` + // Reference is an optional, opaque pointer to where the facts came from. + // Fleet does not interpret it. + Reference string `json:"reference,omitempty"` +} + +// DeviceClaim is the plan for one physical slot, written by the installation +// planner before hardware arrives. The slot outlives any one Device. +type DeviceClaim struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceClaimSpec `json:"spec"` + Status DeviceClaimStatus `json:"status,omitempty"` +} + +type DeviceClaimSpec struct { + Provenance Provenance `json:"provenance"` + ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` + Placement Placement `json:"placement"` + Ports []ExpectedPort `json:"ports,omitempty"` +} + +// ExpectedIdentity is the planned equipment. Serial is usually unknown at plan +// time and is optional. +type ExpectedIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` +} + +// Placement is the planned mount: the lowest occupied rack unit, the number of +// units, and the face. Facility and Rack are names until those kinds exist. +type Placement struct { + Facility string `json:"facility"` + Rack string `json:"rack"` + Position int32 `json:"position"` + Height int32 `json:"height,omitempty"` + Face string `json:"face"` +} + +// ExpectedPort is a planned physical port and the cable peer it should reach. +// Logical LAGs and VLANs are not ports. +type ExpectedPort struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + SpeedMbps int64 `json:"speedMbps,omitempty"` + ExpectedPeer *PortPeer `json:"expectedPeer,omitempty"` +} + +// PortPeer names the far end of a cable by device name and port. +type PortPeer struct { + Device string `json:"device"` + Port string `json:"port"` +} + +// DeviceClaimStatus is reserved for verifiers. Nothing writes it yet. +type DeviceClaimStatus struct{} + +// Device is one actual asset, created by the registrar when detected hardware +// is bound to a claim. Its identity and claim binding are immutable: a hardware +// swap is a new Device. +type Device struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceSpec `json:"spec"` + Status DeviceStatus `json:"status,omitempty"` +} + +type DeviceSpec struct { + ClaimRef LocalReference `json:"claimRef"` + Provenance Provenance `json:"provenance"` + Identity DeviceIdentity `json:"identity"` + BMC *BMC `json:"bmc,omitempty"` + Interfaces []Interface `json:"interfaces,omitempty"` + // UnmappedMACAddresses are MACs detected on the asset that the registrar + // could not attribute to a named interface. + UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` +} + +type LocalReference struct { + Name string `json:"name"` +} + +// DeviceIdentity is the detected chassis identity. Serial and SystemUUID are +// matching evidence, not authenticators. At least one is required. +type DeviceIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` + // SystemUUID is the SMBIOS system UUID in lowercase canonical form. + SystemUUID string `json:"systemUUID,omitempty"` +} + +// BMC records where the management controller was reached. Credentials never +// belong here. +type BMC struct { + Endpoint string `json:"endpoint"` +} + +type Interface struct { + Name string `json:"name"` + MACAddress string `json:"macAddress,omitempty"` + Peer *PortPeer `json:"peer,omitempty"` +} + +// DeviceStatus is reserved for collectors and verifiers to report drift and +// mismatch. It never carries identity. Nothing writes it yet. +type DeviceStatus struct{} + +type DeviceClaimList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceClaim `json:"items"` +} + +type DeviceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Device `json:"items"` +} + +func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +var AddToScheme = addKnown + +func (in *DeviceClaim) DeepCopyObject() runtime.Object { + out := new(DeviceClaim) + deepCopy(in, out) + return out +} +func (in *DeviceClaimList) DeepCopyObject() runtime.Object { + out := new(DeviceClaimList) + deepCopy(in, out) + return out +} +func (in *Device) DeepCopyObject() runtime.Object { + out := new(Device) + deepCopy(in, out) + return out +} +func (in *DeviceList) DeepCopyObject() runtime.Object { + out := new(DeviceList) + deepCopy(in, out) + return out +} + +func deepCopy[T any](in *T, out *T) { b, _ := json.Marshal(in); _ = json.Unmarshal(b, out) }