diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index 3a3033da..ffcf86d2 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -79,10 +79,7 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi return nil, nil, nil, err } namespace := flags.syntheticDeviceNamespace - // The simulator's installs and wipes are simulated, so its declaration - // keeps the lifecycle it always had: it starts no DHCP, claims no boot - // address and attaches no boot NIC, and offers no virtual media. - sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{syntheticSite: custody.NetworkBootOnly}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}} for device := range enrollment { deviceNamespace, name, _ := strings.Cut(device, "/") if deviceNamespace != namespace { @@ -112,7 +109,7 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: cleaning}, // The synthetic site enrolls one boot NIC and one disk per Device. BootInterface: "primary", TargetDisks: []string{"disk-0"}, - DeliveryMethods: custody.NetworkBootOnly, + Sites: sites, } // Synthetic staging has no BMC discovery. The manager writes fixture // discovery for the synthetic site's Devices instead. diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 83014060..48c272f1 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -19,6 +19,7 @@ import ( "k8s.io/client-go/tools/clientcmd" "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/multiplane" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" @@ -40,6 +41,7 @@ func run() error { handoff := fs.String("handoff", "", "exact delivered handoff name (site-worker)") origin := fs.String("origin", "", "boot listener origin to probe, http://IPv4:port (boot-denials; required)") interval := fs.Duration("interval", 10*time.Second, "observation refresh interval (site-observer)") + deliveryFile := fs.String("delivery-methods", "", "the site enrollment's delivery declaration, a JSON list of offers (site-observer, dhcp-feed)") configPath := fs.String("config", "", "private acceptance config JSON") kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") cell := fs.String("cell", "", "exact Karmada member name") @@ -79,7 +81,7 @@ func run() error { return multiplane.Coordinate(ctx, config, multiplane.CoordinatorOptions{InstallationDeadline: *installationDeadline, SkewMargin: *skewMargin}, func(err error) { fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) }) - case "seed", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation", "media-not-offered", "media-unpinned", "media-install-held", "media-install-download", "media-install-lost", "media-install": + case "seed", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation", "media-not-offered", "media-offered", "media-unpinned", "media-install-held", "media-install-download", "media-install-lost", "media-install": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin, *clientID) @@ -91,7 +93,7 @@ func run() error { fmt.Println(image) return nil case "boot-service", "boot-denials", "dhcp-feed": - return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey) + return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey, *deliveryFile) case "boot-withhold": return armWithhold(fs.Arg(0)) case "media-stale": @@ -165,7 +167,15 @@ func run() error { } cellView := &coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell} if os.Args[1] == "site-observer" { - // The observer never runs work: it reports what the store holds. + // The observer never runs work: it reports what the store holds and + // the enrollment's delivery declaration, read again on every pass. + cellView.Delivery = func() ([]custody.OfferedMethod, error) { + data, err := os.ReadFile(*deliveryFile) + if err != nil { + return nil, err + } + return custody.ParseOffered(data) + } return cellView.Observe(ctx, *interval, store, site.NewResults(store), func(name string, err error) { fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) }) @@ -210,7 +220,7 @@ func phase(name, configPath string, once bool) error { "commission": r.Commission, "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "release": r.Release, "release-b": r.ReleaseSecond, "reuse": r.Reuse, "admit-install-b": r.AdmitInstallSecond, "recovery-mismatch": r.RecoveryMismatch, "probe-unallocatable": r.ProbeUnallocatable, "tenant-isolation": r.TenantIsolation, - "media-not-offered": r.MediaNotOffered, "media-unpinned": r.MediaUnpinned, "media-install-held": r.MediaInstallHeld, "media-install-download": r.MediaInstallDownload, "media-install-lost": r.MediaInstallLost, "media-install": r.MediaInstall, + "media-not-offered": r.MediaNotOffered, "media-offered": r.MediaOffered, "media-unpinned": r.MediaUnpinned, "media-install-held": r.MediaInstallHeld, "media-install-download": r.MediaInstallDownload, "media-install-lost": r.MediaInstallLost, "media-install": r.MediaInstall, }[name] last := "" for { diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 8582c29a..fb7f69db 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -16,6 +16,7 @@ import ( "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" "go.datum.net/fleet/internal/site/fixture" @@ -267,7 +268,7 @@ func redfishKinds(work redfishwork.Config, burnIn string) map[string]site.Kind { // boot serves network boots, the DHCP reservation feed, or probes that // every closed admission is denied. -func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { +func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey, deliveryFile string) error { store, err := openStore() if err != nil { return err @@ -305,7 +306,11 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { if err != nil { return err } - enrollment, err := feedEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + declaration, err := os.ReadFile(deliveryFile) + if err != nil { + return fmt.Errorf("the site enrollment's delivery declaration: %w", err) + } + enrollment, err := feedEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT")), declaration) if err != nil { return err } @@ -334,9 +339,11 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { } // feedEnrollment is the enrollment the DHCP reservation feed serves. Only a -// site whose enrollment has synced DHCP has a feed; the default, static, -// leaves DHCP to the site and starts no feed. -func feedEnrollment(raw []byte) (redfish.Enrollment, error) { +// site whose enrollment has synced DHCP and declares network boot has a +// feed. The defaults, static DHCP and no declaration, leave DHCP to the site +// and start no feed, and a site that declares only virtual media never +// network-boots, so it starts none either. +func feedEnrollment(raw, declaration []byte) (redfish.Enrollment, error) { enrollment, err := redfish.ParseEnrollment(raw) if err != nil { return redfish.Enrollment{}, err @@ -344,6 +351,13 @@ func feedEnrollment(raw []byte) (redfish.Enrollment, error) { if enrollment.DHCP != redfish.DHCPSynced { return redfish.Enrollment{}, errors.New("the DHCP reservation feed serves only a site whose enrollment has synced DHCP") } + offered, err := custody.ParseOffered(declaration) + if err != nil { + return redfish.Enrollment{}, fmt.Errorf("the site enrollment's delivery declaration: %w", err) + } + if !custody.NetworkBootOffered(offered) { + return redfish.Enrollment{}, errors.New("the DHCP reservation feed serves only a site whose enrollment declares network boot") + } return enrollment, nil } diff --git a/cmd/fleet-multiplane/site_test.go b/cmd/fleet-multiplane/site_test.go index d0b8d065..4b0b0ff9 100644 --- a/cmd/fleet-multiplane/site_test.go +++ b/cmd/fleet-multiplane/site_test.go @@ -55,14 +55,43 @@ func syntheticEnrollment(dhcp string) []byte { // feed for an enrollment that leaves DHCP to the site, or names no DHCP // mode. func TestTheDHCPFeedStartsOnlyForSyncedDHCP(t *testing.T) { - if _, err := feedEnrollment(syntheticEnrollment(`"dhcp":"static",`)); err == nil || !strings.Contains(err.Error(), "synced DHCP") { + networkBoot := []byte(`[{"method":"NetworkBoot"}]`) + if _, err := feedEnrollment(syntheticEnrollment(`"dhcp":"static",`), networkBoot); err == nil || !strings.Contains(err.Error(), "synced DHCP") { t.Errorf("static DHCP: the feed started: %v", err) } - if _, err := feedEnrollment(syntheticEnrollment(``)); err == nil { + if _, err := feedEnrollment(syntheticEnrollment(``), networkBoot); err == nil { t.Error("no DHCP mode: the feed started") } - enrollment, err := feedEnrollment(syntheticEnrollment(`"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0"],`)) + enrollment, err := feedEnrollment(syntheticEnrollment(synced), networkBoot) if err != nil || len(enrollment.DHCPInstances) != 1 { t.Fatalf("synced DHCP: %+v, %v", enrollment, err) } } + +// synced is the DHCP fields of a synced enrollment with one instance. +const synced = `"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0"],` + +// TestTheDHCPFeedStartsOnlyWhereTheEnrollmentDeclaresNetworkBoot refuses +// to start the feed, even with synced DHCP, for a site whose enrollment +// declares only virtual media, declares nothing, or names no valid +// declaration. +func TestTheDHCPFeedStartsOnlyWhereTheEnrollmentDeclaresNetworkBoot(t *testing.T) { + for name, declaration := range map[string]string{ + "only virtual media": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443"}]`, + "nothing": `[]`, + "no declaration": ``, + "not a declaration": `{"method":"NetworkBoot"}`, + } { + if _, err := feedEnrollment(syntheticEnrollment(synced), []byte(declaration)); err == nil { + t.Errorf("%s: the feed started", name) + } + } + for name, declaration := range map[string]string{ + "network boot": `[{"method":"NetworkBoot"}]`, + "virtual media then network boot": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443"},{"method":"NetworkBoot"}]`, + } { + if _, err := feedEnrollment(syntheticEnrollment(synced), []byte(declaration)); err != nil { + t.Errorf("%s: the feed did not start: %v", name, err) + } + } +} diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index 517dc89f..017cdc87 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -22,6 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" "go.datum.net/fleet/internal/site/fixture" "go.datum.net/fleet/internal/site/simwork" @@ -76,7 +77,10 @@ func main() { Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}} runner.Kinds["DevicePowerOperation"] = simwork.Power{} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} - server := newServer(address, siteapi.Handler(dispatcher, store, results, func() (string, error) { return readToken(tokenPath) }), logger) + // The simulator's installs and wipes are simulated, so its declaration + // keeps the lifecycle it always had: it starts no DHCP, claims no boot + // address and attaches no boot NIC, and offers no virtual media. + server := newServer(address, siteapi.Handler(dispatcher, store, results, custody.NetworkBootOnly, func() (string, error) { return readToken(tokenPath) }), logger) if discover { api, err := discoveryClient() if err != nil { diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index d3340ce7..8e5c1db5 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -91,8 +91,7 @@ func main() { Capacity: offers, // The fixture Device's boot NIC and the simulator's one enrolled disk. BootInterface: "primary", TargetDisks: []string{"disk-0"}, - // The simulator site offers only network boot. - DeliveryMethods: custody.NetworkBootOnly, + Sites: simulatorOffer{site: siteName}, } runner := standalone.Runner{Client: provider, Allocator: allocator, Options: options} if phase == standalone.PhaseCommission { @@ -103,6 +102,22 @@ func main() { fmt.Printf("standalone synthetic smoke phase %s completed\n", phase) } +// simulatorOffer is the phases' view of the simulator site, which declares +// only network boot. The phases hold no site credential, so they do not +// read the declaration; the coordinator reads it from the site's API and +// refuses an installation recording any other method. +type simulatorOffer struct{ site string } + +func (s simulatorOffer) Serving(*inventory.Device) []string { return []string{s.site} } + +func (s simulatorOffer) Fence(context.Context, string, *inventory.Device) (custody.SiteFence, bool, error) { + return custody.SiteFence{}, false, nil +} + +func (s simulatorOffer) DeliveryMethods(context.Context, string, *inventory.Device) ([]custody.OfferedMethod, bool, error) { + return custody.NetworkBootOnly, true, nil +} + // coordinate is the coordinator process: the custody loop with the simulator // as the only site. func coordinate(ctx context.Context, config *rest.Config, registry *custody.Registry, namespace, siteName, siteURL, tokenFile, projectorToken string, devices []string) error { @@ -121,7 +136,7 @@ func coordinate(ctx context.Context, config *rest.Config, registry *custody.Regi if err != nil { return err } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} for _, device := range devices { if device = strings.TrimSpace(device); device != "" { sites.Devices[device] = []string{siteName} diff --git a/config/site/dhcp/feed/kustomization.yaml b/config/site/dhcp/feed/kustomization.yaml index b3d7f108..c20b16f7 100644 --- a/config/site/dhcp/feed/kustomization.yaml +++ b/config/site/dhcp/feed/kustomization.yaml @@ -1,12 +1,14 @@ # The reservation feed: a container beside the boot service, which reads the # site store and writes the applied reports beside the boot evidence, and a -# Service. The site's central DHCP instances reach it over TLS only. The environment supplies -# the Secrets fleet-site-dhcp-sync (key token) and fleet-site-dhcp-feed-tls -# (tls.crt, tls.key, ca.crt), never in Git, and the ConfigMap -# fleet-site-redfish-enrollment (key enrollment): the same synced Redfish -# enrollment the site's workers get. The feed serves, and takes reports from, -# only the enrollment's dhcpInstances. The Kea component and the Redfish -# lab's synchronized DHCP both use it. +# Service. The site's central DHCP instances reach it over TLS only. The +# environment supplies the Secrets fleet-site-dhcp-sync (key token) and +# fleet-site-dhcp-feed-tls (tls.crt, tls.key, ca.crt), never in Git, and the +# ConfigMap fleet-site-redfish-enrollment (key enrollment): the same synced +# Redfish enrollment the site's workers get. The feed serves, and takes +# reports from, only the enrollment's dhcpInstances, and starts only while +# the site's delivery declaration, the fleet-site-delivery ConfigMap, offers +# network boot. The Kea component and the Redfish lab's synchronized DHCP +# both use it. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component resources: @@ -22,7 +24,7 @@ patches: name: dhcp-feed image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key] + command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key, -delivery-methods, /etc/fleet-site-delivery/methods] env: - {name: FLEET_SITE_PROVIDER, value: redfish} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} @@ -46,9 +48,15 @@ patches: - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} - {name: dhcp-feed-tls, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - {name: dhcp-feed-delivery, mountPath: /etc/fleet-site-delivery, readOnly: true} - op: add path: /spec/template/spec/volumes/- value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} - op: add path: /spec/template/spec/volumes/- value: {name: dhcp-feed-tls, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400}} + # The site enrollment's delivery declaration: the feed starts only + # while it declares network boot. + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-delivery, configMap: {name: fleet-site-delivery}} diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml index 49f24515..268ee5b0 100644 --- a/config/site/services/services.yaml +++ b/config/site/services/services.yaml @@ -21,6 +21,20 @@ spec: ports: - {name: http, port: 8080, targetPort: 8080, protocol: TCP} --- +# The site enrollment's boot delivery declaration: the methods this site +# offers, in its order of preference. The observer publishes it on every +# report handoff; the coordinator and the Metal provider read it there and +# keep no copy. The environment gives the JSON list base64-encoded, because +# Flux's substitution would drop the quotes around JSON text; the mounted +# file holds the JSON. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-delivery + namespace: fleet-site +binaryData: + methods: ${FLEET_SITE_DELIVERY_METHODS} +--- # Admission parameter for kro-created worker Jobs: they must run the same # digest-pinned image as these services. apiVersion: v1 @@ -148,7 +162,7 @@ spec: - name: observer image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --interval, 10s] + command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --interval, 10s, --delivery-methods, /etc/fleet-site-delivery/methods] env: - {name: FLEET_LOCAL_VM_ACCEL, value: "${FLEET_LOCAL_VM_ACCEL}"} securityContext: @@ -161,6 +175,9 @@ spec: limits: {memory: 128Mi} volumeMounts: - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: delivery, mountPath: /etc/fleet-site-delivery, readOnly: true} volumes: - name: state persistentVolumeClaim: {claimName: fleet-site-state} + - name: delivery + configMap: {name: fleet-site-delivery} diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9c3e0d2b..bbc8ad67 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -327,10 +327,14 @@ operations guide describes how it runs in the [Redfish lab](../operations/redfis it is still bound to the operation's own claim. The media service takes the first-boot report only from it. A virtual media installation's deadline is the sum of its windows. -- **Sites declare their methods.** `custody.Sites` gains `DeliveryMethods`, - the site's methods in its order of preference. Admission sees the methods - every serving site offers. The Metal provider selects from the same - declaration. +- **Sites declare their methods in their enrollment.** Each site's + enrollment lists its methods in its order of preference. The site reports + that declaration with its fence report, and `custody.Sites` returns it + through `DeliveryMethods`. The coordinator keeps no copy. Admission sees + the methods every serving site offers, and the Metal provider selects from + the same report. A site that has not reported a current, valid + declaration decides nothing: admission leaves the operation `Pending`, and + the provider creates no installation until the site reports one. - **Admission checks the method** under the custody update: offered, qualified, consistent with the other inputs, and every installer download pinned by digest. The admission snapshot records the method, so a diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index e21498a5..c244b3dc 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -528,13 +528,23 @@ CI. ISC builds the Kea image for `linux/amd64` only. Synchronized DHCP is off by default. Outside the opt-in roots below, no overlay or site base includes either component, a site enrollment must name -its `dhcp` mode, and the feed refuses to start for a `static` enrollment. In -CI, +its `dhcp` mode, and the feed refuses to start for a `static` enrollment. It +also refuses to start unless the site's delivery declaration, which it reads +from the `fleet-site-delivery` ConfigMap at start, offers network boot. No +packaged root declares any method, so a site offers nothing until its +environment declares one. A site that declares only virtual media never +starts the feed, and admission refuses every network boot there, including +wipes and commissionings. Including the DHCP component is itself a site's +choice of network boot: without a feed, its Kea instances hold no +reservation and answer no server. A site that stops declaring network boot +admits no new network boot, while the operations already admitted finish, +so a running feed keeps serving them until its next restart. In CI, `hack/validate-network-boot-inactive.sh` renders every kustomization root under `config/`. It checks that only the DHCP components, their example and the Redfish lab's synchronized mode render a Kea server, the synchronizer, the -feed, a UDP 67 listener, or a synced enrollment or lab switch, and that only -the boot address roles grant IPAM permissions. +feed, a UDP 67 listener, or a synced enrollment or lab switch, that only the +boot address roles grant IPAM permissions, and that no root declares +delivery methods. ## Network operations requirements diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md index f36fc484..00375d56 100644 --- a/docs/operations/gitops.md +++ b/docs/operations/gitops.md @@ -52,7 +52,7 @@ from its own OCIRepository). See | Handoff CRD, management role, interpreter, member `Cluster`, `PropagationPolicy` on the Karmada API | hub kustomize-controller through the chart's `karmada-kubeconfig` | — | | kro controller | cell helm-controller (`HelmRelease kro`) | — | | Site namespace, StorageClass, site store 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) | +| Shared runtime, boot and observer Deployments, boot Service, worker-policy parameter, delivery declaration | 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) | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 0babb37d..3202712f 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -589,7 +589,7 @@ a CI runner's KVM guests. Each held installation waits out both windows. | Part | In the prototype | | --- | --- | | Delivery inputs | Real. Each installation records its method and the method's inputs before admission; the input digest pins them. | -| Site declaration | Real, with one simplification: the coordinator's site configuration declares each site's methods in preference order. The Metal provider selects from the same declaration. | +| Site declaration | Real. The site enrollment's `fleet-site-delivery` ConfigMap declares the site's methods in preference order. The observer publishes it on each report handoff, and the coordinator and the Metal provider read it there. A change is a source revision, with no coordinator restart. | | Admission | Real for the site and qualification checks, the settling-hold rule, input consistency and digest-pinned downloads. A machine class cannot restrict methods yet. | | Qualification | Stubbed. Staff set the `fleet.datumapis.com/qualified-delivery-methods` annotation on the Device. A Device without it is qualified for network boot only. Commissioning will replace it. | | Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods reach through the runtime's host gateway. Guests reach it through the report relay. | @@ -617,7 +617,7 @@ it pulled that reference, installed, and booted the installed disk. | --- | --- | | `commission-dispatch` to `commission-settle` | As in the Redfish suite, target A passes a commissioning, whose burn-in boots it once over the network, so the projector offers its capacity. | | `media-not-offered` | While the cell declares network boot only, a virtual media installation is refused with `DeliveryMethodNotOffered`. The fence does not change and nothing is delivered. | -| `media-central`, `media-offer` | The central media service starts with the image's pinned artifacts. The operator adds virtual media after network boot; staff record target A as qualified for virtual media only. | +| `media-central`, `media-offer`, `media-offered` | The central media service starts with the image's pinned artifacts. A source revision adds virtual media after network boot to the site enrollment, and the coordinator reads it from the cell's report without a restart. Staff record target A as qualified for virtual media only. | | `media-unpinned` | An installation whose installer downloads an image by tag is refused with `InstallDownloadUnpinned`. | | `media-arm-corrupt-token`, `media-install-held`, `media-held-report` | The lab BMC's config medium carries another report token. The installed OS's report, from its IPAM address, is refused for its token. Reports posted straight to the service, over IPv4 and IPv6 loopback, come from outside the site's report ranges and are refused for their source. No report is taken, and the installation ends `OutcomeUnknown` at its report deadline with a hold that records virtual media. | | `media-arm-add-download`, `media-install-download`, `media-held-download` | The next installation settles that hold with the held method. The lab BMC adds a download the operation never pinned to its config medium; the first-boot report names it, so the report is never verified and the installation is held. | diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 439868af..194dc22d 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -64,8 +64,9 @@ observer Deployment (site store read-only; only handoff status writer) | `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 each Device's stored fences, and the stored result of each assignment, every 10 seconds | +| `fleet-site-observer` Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem | `journal` **ro** | Publishes each Device's stored fences and the site's delivery declaration, and the stored result of each assignment, every 10 seconds | | `fleet-site-worker-policy` ConfigMap | Flux `fleet-site-services` | — | — | Admission parameter: the image worker Jobs must run | +| `fleet-site-delivery` ConfigMap | Flux `fleet-site-services`, from the environment's base64-encoded `FLEET_SITE_DELIVERY_METHODS` | — | — | The site enrollment's boot delivery declaration. The observer mounts it read only and publishes it on each report handoff; the coordinator keeps no copy | | `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 | Runs or resumes that one assignment | diff --git a/hack/multiplane/acceptance-media.sh b/hack/multiplane/acceptance-media.sh index 24ed5f3e..a5f452f9 100755 --- a/hack/multiplane/acceptance-media.sh +++ b/hack/multiplane/acceptance-media.sh @@ -31,7 +31,10 @@ run allocate 900 # refused at admission and nothing is delivered. run media-not-offered 600 ph media-central 300 bash hack/multiplane/media-central.sh start "$state" -md offer 300 +# The operator adds virtual media to the site enrollment as a revision; the +# coordinator reads it from the cell's report, with no restart. +md offer 900 +run media-offered 600 # An installer download by tag, not digest, is refused at admission. run media-unpinned 600 # Dispatch is a source revision the cell's Flux reconciles, as in the diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 5d377039..94aec576 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -21,6 +21,7 @@ Nothing here stores credentials in a source revision. """ import argparse +import base64 import datetime import hashlib import json @@ -81,7 +82,7 @@ # 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', + ('configmaps', SITE, 'fleet-site-worker-policy'): 'fleet-site-services', ('configmaps', SITE, 'fleet-site-delivery'): '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', @@ -136,7 +137,7 @@ } if LAB_IPAM else {} EXPECTED['platform'] += list(PLATFORM_LAYER_INVENTORY) LAYER_INVENTORY = { - 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', + 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', 'fleet-site_fleet-site-delivery__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-bmc__Service', 'fleet-site_fleet-site-bmc_apps_Deployment'] if PROVIDER == 'redfish' else []) + SYNCED_OBJECTS), @@ -269,6 +270,20 @@ def config_map(name, namespace, data): return '\n'.join(lines) + '\n' +def delivery_methods(state, given): + """The site enrollment's delivery declaration for this revision, base64 + encoded for the ConfigMap's binaryData: the one given, kept for later + revisions, else the last one given, else network boot only.""" + path = pathlib.Path(state) / 'site-delivery.json' + if given: + methods = json.loads(given) + if not isinstance(methods, list): + raise SystemExit('--delivery-methods must be a JSON list of offers') + path.write_text(json.dumps(methods, separators=(',', ':'))) + declared = path.read_text() if path.exists() else '[{"method":"NetworkBoot"}]' + return base64.b64encode(declared.encode()).decode() + + def stage(args): s = pathlib.Path(args.state).resolve() root = pathlib.Path(args.root).resolve() @@ -321,7 +336,10 @@ def stage(args): # Redfish workers verify it; empty where none runs. FLEET_MEDIA_CA=env.get('mediaCA', ''), # Where lab Pods reach the central media service. - FLEET_MEDIA_HOST=(s / 'media-host').read_text().strip() if (s / 'media-host').exists() else '192.168.5.2') + FLEET_MEDIA_HOST=(s / 'media-host').read_text().strip() if (s / 'media-host').exists() else '192.168.5.2', + # The site enrollment's delivery declaration, which + # the observer publishes to the coordinator. + FLEET_SITE_DELIVERY_METHODS=delivery_methods(s, args.delivery_methods)) 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}], @@ -1104,7 +1122,7 @@ def fail_closed(args): 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, + bad = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 1, site='dispatch', bad_kro_chart=True, drop_site_volume=False, delivery_methods='', purpose='fail-closed: kro chart pinned to an absent digest', cluster=[], timeout=0) stage(bad) push(bad) @@ -1142,7 +1160,7 @@ def blocked(): '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, + fixed = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, delivery_methods='', 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]) @@ -1161,7 +1179,7 @@ def retention(args): 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, + drop = argparse.Namespace(state=str(s), root=args.root, revision=base + 1, site='dispatch', bad_kro_chart=False, drop_site_volume=True, delivery_methods='', purpose='retention: site volume claim removed from the source', cluster=['cell'], timeout=600) publish(drop) inv = kustomizations(s, 'cell')['flux-system/fleet-site-base'] @@ -1172,7 +1190,7 @@ def retention(args): 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, + restore = argparse.Namespace(state=str(s), root=args.root, revision=base + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, delivery_methods='', 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'] @@ -1205,6 +1223,7 @@ def staging(s): s.add_argument('--bad-kro-chart', action='store_true') s.add_argument('--drop-site-volume', action='store_true') s.add_argument('--purpose', default='') + s.add_argument('--delivery-methods', default='', help='the site enrollment\'s delivery declaration, a JSON list of offers; kept for later revisions') def clusters(s): s.add_argument('--cluster', action='append', default=[], choices=CLUSTERS) diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index fd37d77c..bed7e686 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -7,11 +7,13 @@ paths, outcome classes, fences and digests; never a media URL, a URL capability or a report token. - offer the operator adds virtual media after network boot, with - the central media service and the lab's short phases, and - restarts the coordinator; staff record target A as - qualified for virtual media only (the lab stand-in for - delivery qualification by commissioning) + offer the operator adds virtual media after network boot to the + site enrollment, with the central media service and the + lab's short phases, as a source revision the cell's Flux + reconciles; the coordinator is not restarted. Staff + record target A as qualified for virtual media only (the + lab stand-in for delivery qualification by + commissioning) arm-corrupt-token one-shot: the lab BMC's next config medium carries another report token than the one the media service served held-report the first install booted from media and its OS posted a @@ -180,14 +182,20 @@ def steps_of(s, operation): def offer(s): config = json.loads((s / 'acceptance.json').read_text()) - config['DeliveryMethods'] = [{'method': 'NetworkBoot'}, - {'method': 'VirtualMedia', 'addresses': 'DataNetwork', 'mediaService': config['MediaService'], 'fetchWindow': FETCH, 'reportWindow': REPORT}] - (s / 'acceptance.json').write_text(json.dumps(config)) + methods = [{'method': 'NetworkBoot'}, + {'method': 'VirtualMedia', 'addresses': 'DataNetwork', 'mediaService': config['MediaService'], 'fetchWindow': FETCH, 'reportWindow': REPORT}] provider(s, '-n', 'fleet-provider', 'annotate', '--overwrite', 'device', DEVICE_NAME, QUALIFIED + '=VirtualMedia') - subprocess.run(['bash', 'hack/multiplane/coordinator.sh', 'restart', str(s)], check=True, capture_output=True, text=True) - rf.write(s / 'evidence' / 'media-offer.json', {'observedAt': now(), 'deliveryMethods': config['DeliveryMethods'], + # The declaration is site enrollment: a source revision changes it, and + # the cell's observer publishes it to the coordinator, which keeps none. + revision = max(r['revision'] for r in json.loads((s / 'flux-revisions.json').read_text())) + 1 + subprocess.run(['python3', 'hack/multiplane/flux.py', 'publish', str(s), '--revision', str(revision), '--site', 'off', '--purpose', 'offer virtual media', + '--delivery-methods', json.dumps(methods), '--cluster', 'cell', '--timeout', '600'], check=True, capture_output=True, text=True) + rendered = base64.b64decode(rf.kget(s, '-n', 'fleet-site', 'get', 'configmap', 'fleet-site-delivery')['binaryData']['methods']).decode() + if json.loads(rendered) != methods: + die('the reconciled site declaration differs from the revision: %s' % rendered) + rf.write(s / 'evidence' / 'media-offer.json', {'observedAt': now(), 'deliveryMethods': methods, 'source': 'site enrollment, revision r%d' % revision, 'qualified': {'device': harness.DEVICE, 'methods': ['VirtualMedia'], 'source': 'lab-set annotation; commissioning does not qualify delivery methods yet'}}) - print('media-offer: the cell declares NetworkBoot then VirtualMedia (central media service, %s fetch and %s report phases); target A is qualified for VirtualMedia only; coordinator restarted' % (FETCH, REPORT)) + print('media-offer: revision r%d declares NetworkBoot then VirtualMedia in the site enrollment (central media service, %s fetch and %s report phases); target A is qualified for VirtualMedia only' % (revision, FETCH, REPORT)) def arm(s, *fault): diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 7a5ba2d3..935e7664 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -162,9 +162,6 @@ import json,pathlib,sys s=pathlib.Path(sys.argv[1]).resolve() enrollment=json.loads((s/'redfish'/'fixture-enrollment.json').read_text() if sys.argv[2]=='redfish' else pathlib.Path('config/site/base/enrollment.json').read_text()) c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment, - # The cell's declared boot delivery methods: network boot only. The - # virtual media suite adds virtual media as an operator would. - 'DeliveryMethods':[{'method':'NetworkBoot'}], # The central media service, as lab Pods and guests reach the workstation. 'MediaService':'https://%s:28443'%(s/'media-host').read_text().strip()} if sys.argv[3]=='1':c['BootAddressClass']='lab-provisioning' diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index 7c0091e5..f84743d2 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -2,6 +2,7 @@ """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 base64 import importlib.util import json import os @@ -100,7 +101,7 @@ def meta(name, **kw): (s / 'gitops-environment.json').write_text(json.dumps(env)) 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 = dict(state=str(s), root=str(root), revision=1, site='absent', bad_kro_chart=False, drop_site_volume=False, delivery_methods='', purpose='test', cluster=[], timeout=5) base.update(kw) return argparse.Namespace(**base) @@ -137,6 +138,15 @@ def render(rev, cluster): check('site accelerator is the run parameter, TCG by default', 'FLEET_LOCAL_VM_ACCEL: tcg\n' in cell3.replace('"', '')) check('graph uses no Flux variables', not re.findall(r'\$\{FLEET_', (root / 'config/site/graph/rgd.yaml').read_text())) check('stage off revision', flux.stage(ns(revision=2, site='off')) == 0 and 'FLEET_SITE_DISPATCH: "false"' in render(2, 'cell')) + def declared(rev): + found = re.search(r'^ FLEET_SITE_DELIVERY_METHODS: "?([A-Za-z0-9+/=]+)"?$', render(rev, 'cell'), re.M) + return found and base64.b64decode(found.group(1)).decode() + check('the site declares network boot by default', declared(2) == '[{"method":"NetworkBoot"}]') + media = '[{"method":"NetworkBoot"},{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443"}]' + flux.stage(ns(revision=7, site='off', delivery_methods=media)) + flux.stage(ns(revision=8, site='dispatch')) + check('a declaration is kept by later revisions', declared(7) == media and declared(8) == media) + expect_exit('a declaration must be a list', lambda: flux.stage(ns(revision=10, site='off', delivery_methods='{"method":"NetworkBoot"}')), '--delivery-methods must be a JSON list of offers') flux.stage(ns(revision=4, site='dispatch', bad_kro_chart=True)) check('bad chart revision patches only kro', flux.MISSING_DIGEST in render(4, 'cell') and flux.KRO_CHART_DIGEST not in render(4, 'cell')) def kro_timeout(revision): diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 2276a430..5136aadd 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -473,6 +473,12 @@ with tempfile.TemporaryDirectory() as tmp: clients = re.search(r'--clients "?(\S+?)"? ', central) check('the central media service admits the site\'s report range as clients', report_from is not None and clients is not None and report_from.group(1) in clients.group(1).split(',')) + media = (root / 'hack/multiplane/media_steps.py').read_text() + observer = (root / 'config/site/services/services.yaml').read_text() + check('the delivery declaration is site enrollment, changed by a source revision', + "'--delivery-methods'" in media and 'coordinator.sh' not in media and 'DeliveryMethods' not in run_sh + and 'name: fleet-site-delivery' in observer and 'binaryData:\n methods: ${FLEET_SITE_DELIVERY_METHODS}' in observer + and '--delivery-methods, /etc/fleet-site-delivery/methods' in observer) 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', diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index e9522591..e753268d 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -257,7 +257,7 @@ def build(path): (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})) - 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) + args = argparse.Namespace(state=str(s), root=str(root), revision=2, site='off', bad_kro_chart=False, drop_site_volume=True, delivery_methods='', 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'): diff --git a/hack/validate-network-boot-inactive.sh b/hack/validate-network-boot-inactive.sh index ae0de758..9e3df217 100755 --- a/hack/validate-network-boot-inactive.sh +++ b/hack/validate-network-boot-inactive.sh @@ -6,7 +6,10 @@ # enrollment or lab switch with synced DHCP, or a grant of IPAM permissions # for boot address claims. Every other root, including every overlay an # environment deploys, renders none of them. Each opt-in root must render one, -# so the list stays exact. +# so the list stays exact. No root declares a site's delivery methods: the +# fleet-site-delivery ConfigMap carries only the environment's substitution, +# so a site offers nothing, network boot included, until its environment +# declares it. set -euo pipefail cd "$(dirname "$0")/.." opt_in=( @@ -107,13 +110,18 @@ for root in roots: continue parts = set() for doc in yaml.safe_load_all(render.stdout): - if doc: - parts |= found(doc) + if not doc: + continue + parts |= found(doc) + if doc.get('kind') == 'ConfigMap' and (doc.get('metadata') or {}).get('name') == 'fleet-site-delivery': + methods = {**(doc.get('data') or {}), **(doc.get('binaryData') or {})} + if methods != {'methods': '${FLEET_SITE_DELIVERY_METHODS}'}: + failures.append('%s declares delivery methods %s; only the environment may' % (root, methods)) if root in opt_in and not parts: failures.append('%s is listed as opt in but renders no synchronized DHCP' % root) if root not in opt_in and parts: failures.append('%s renders %s, which only an opt-in root may' % (root, ', '.join(sorted(parts)))) if failures: sys.exit('FAIL network boot inactive by default:\n ' + '\n '.join(failures)) -print('PASS network boot inactive by default: %d roots render no synchronized DHCP or IPAM grant; only the %d opt-in roots do' % (len(roots) - len(opt_in), len(opt_in))) +print('PASS network boot inactive by default: %d roots render no synchronized DHCP or IPAM grant; only the %d opt-in roots do; no root declares delivery methods' % (len(roots) - len(opt_in), len(opt_in))) PY diff --git a/hack/validate-site-dhcp-render.sh b/hack/validate-site-dhcp-render.sh index c89e39ea..5e591663 100755 --- a/hack/validate-site-dhcp-render.sh +++ b/hack/validate-site-dhcp-render.sh @@ -16,6 +16,10 @@ boot = one("Deployment", "fleet-site-boot")["spec"]["template"]["spec"] feed = next(c for c in boot["containers"] if c["name"] == "dhcp-feed") assert feed["command"][:2] == ["fleet-multiplane", "dhcp-feed"] and "-tls-cert" in feed["command"] and "-tls-key" in feed["command"], feed["command"] assert {"name": "state", "mountPath": "/var/lib/fleet-local", "subPath": "journal", "readOnly": True} in feed["volumeMounts"], "the feed reads the store read-only" +assert feed["command"][feed["command"].index("-delivery-methods") + 1] == "/etc/fleet-site-delivery/methods", "the feed reads the site delivery declaration" +declared = next(m for m in feed["volumeMounts"] if m["mountPath"] == "/etc/fleet-site-delivery") +assert declared.get("readOnly") and {"name": declared["name"], "configMap": {"name": "fleet-site-delivery"}} in boot["volumes"], "the feed mounts the declaration read-only" +one("ConfigMap", "fleet-site-delivery") ref = next(e["valueFrom"]["configMapKeyRef"] for e in feed["env"] if e["name"] == "FLEET_REDFISH_ENROLLMENT") enrollment = json.loads(one("ConfigMap", ref["name"])["data"][ref["key"]]) service = one("Service", "fleet-site-dhcp-feed") diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index ef3a61b7..43d83cd6 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -166,11 +166,10 @@ type Allocator struct { // through them, by claim kind, until no operation names their kind. // IPAM's claimer always takes part as the default. PreviousBootAddresses []bootaddress.Source - // DeliveryMethods is the site's declared boot delivery methods, in its - // order of preference. It is the same declaration the coordinator - // admits against. Each installation records the method selected from - // it. - DeliveryMethods []custody.OfferedMethod + // Sites reads the boot delivery methods each serving site's enrollment + // declares, the same declaration the coordinator admits against. Each + // installation records the method selected from it. + Sites custody.Sites } // ErrNoReportAddress means the site has no address source that claims a @@ -186,6 +185,10 @@ var ErrNoDeliveryMethod = errors.New("allocation: the site offers no delivery me // wipe uses, so a release cannot wipe the server there. var ErrNoWipeMethod = errors.New("allocation: the site offers no network boot, the only method a wipe uses") +// ErrDeliveryUnknown means a serving site has not reported a current +// delivery declaration, so no method is selected yet. +var ErrDeliveryUnknown = errors.New("allocation: a serving site has not reported its delivery methods") + // selectDelivery reads the Device and its custody and selects the method an // installation records. func (a *Allocator) selectDelivery(ctx context.Context, allocation *fleetv1.MachineAllocation) (ops.DeliveryInput, error) { @@ -197,7 +200,14 @@ func (a *Allocator) selectDelivery(ctx context.Context, allocation *fleetv1.Mach if err := a.Provider.Get(ctx, key, state); err != nil { return ops.DeliveryInput{}, err } - input, ok := custody.SelectMethod(a.DeliveryMethods, custody.QualifiedMethods(device), state) + offered, known, err := custody.Offered(ctx, a.Sites, device) + if err != nil { + return ops.DeliveryInput{}, err + } + if !known { + return ops.DeliveryInput{}, ErrDeliveryUnknown + } + input, ok := custody.SelectMethod(offered, custody.QualifiedMethods(device), state) if !ok { return ops.DeliveryInput{}, ErrNoDeliveryMethod } diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 41af79d6..792b1183 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -160,7 +160,7 @@ func TestAReleaseWipesOnlyWhereTheSiteOffersNetworkBoot(t *testing.T) { recorder := &ipam{Client: e.admin} e.allocator.Provider, e.allocator.Releaser = writer{recorder, "DeviceInstallation"}, writer{recorder, "DeviceWipe"} e.allocator.BootAddresses = &bootaddress.Claimer{Class: "provisioning"} - e.allocator.DeliveryMethods = []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} + e.allocator.Sites = offering{Sites: e.allocator.Sites, methods: []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}}} e.server(1) allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) if err != nil { @@ -184,6 +184,11 @@ func TestAReleaseWipesOnlyWhereTheSiteOffersNetworkBoot(t *testing.T) { if !errors.Is(last, ErrNoWipeMethod) { t.Fatalf("release = %v, want %v", last, ErrNoWipeMethod) } + // Nor while the site has not reported what it offers. + e.allocator.Sites = undeclared{e.allocator.Sites} + if released, err := e.allocator.Release(e.ctx, allocation, machine(1)); released || !errors.Is(err, ErrDeliveryUnknown) { + t.Fatalf("release with no declaration = %v, %v, want %v", released, err, ErrDeliveryUnknown) + } if allocation.Status.Wipe != nil { t.Fatalf("release recorded wipe %+v", allocation.Status.Wipe) } @@ -349,7 +354,7 @@ func TestAVirtualMediaInstallRecordsTheMachinesAddress(t *testing.T) { e := startEnv(t) recorder := &ipam{Client: e.admin} e.allocator.Provider, e.allocator.Releaser = writer{recorder, "DeviceInstallation"}, writer{recorder, "DeviceWipe"} - e.allocator.DeliveryMethods = []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} + e.allocator.Sites = offering{Sites: e.allocator.Sites, methods: []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}}} device := e.server(1) e.until("staff record the server as qualified for virtual media", func() bool { if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { diff --git a/internal/allocation/delivery_test.go b/internal/allocation/delivery_test.go new file mode 100644 index 00000000..74daa333 --- /dev/null +++ b/internal/allocation/delivery_test.go @@ -0,0 +1,58 @@ +package allocation + +import ( + "context" + "errors" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// undeclared is a site that has not reported its delivery declaration. +type undeclared struct{ custody.Sites } + +func (undeclared) DeliveryMethods(context.Context, string, *inventory.Device) ([]custody.OfferedMethod, bool, error) { + return nil, false, nil +} + +// offering is a site that declares the given methods. +type offering struct { + custody.Sites + methods []custody.OfferedMethod +} + +func (o offering) DeliveryMethods(context.Context, string, *inventory.Device) ([]custody.OfferedMethod, bool, error) { + return o.methods, true, nil +} + +// TestNoInstallationUntilTheSiteDeclaresItsMethods creates no installation +// while the serving site has not reported its delivery declaration, and +// the same request installs once it has. +func TestNoInstallationUntilTheSiteDeclaresItsMethods(t *testing.T) { + e := startEnv(t) + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + declared := e.allocator.Sites + e.allocator.Sites = undeclared{declared} + request := Installation{Installation: e.installation(1, "debian-12", "")} + if _, err := e.allocator.Install(e.ctx, allocation, request); !errors.Is(err, ErrDeliveryUnknown) { + t.Fatalf("install err = %v", err) + } + name := custody.InstallationName(allocation.Name, uid(701)) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: name}, &ops.DeviceInstallation{}); !apierrors.IsNotFound(err) { + t.Fatalf("an installation was created without a declaration: %v", err) + } + e.allocator.Sites = declared + operation, err := e.allocator.Install(e.ctx, allocation, request) + if err != nil || operation.Spec.Delivery.Method != ops.DeliveryNetworkBoot { + t.Fatalf("install = %v, %v", operation, err) + } +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index c349242f..540b4f34 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -120,7 +120,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Poll: 20 * time.Millisecond} e.runner = runner dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} - server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, func() (string, error) { return siteToken, nil })) + server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, custody.NetworkBootOnly, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) if err != nil { @@ -130,7 +130,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -144,7 +144,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio Cleaning: func(string) (string, error) { return policyDigest, nil }, Capacity: e.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, - DeliveryMethods: custody.NetworkBootOnly, + Sites: sites, } // One qualified plan covers every fixture server: one person writes it // and another approves it. diff --git a/internal/allocation/release.go b/internal/allocation/release.go index 8f2e24f5..96bf0f7a 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -10,6 +10,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" @@ -318,9 +319,10 @@ func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocat // two creates the same wipe again. func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocation, reference fleetv1.WipeReference) error { // A wipe network-boots, the only method it has. Where the site offers - // no network boot, nothing claims a boot address and no wipe is made. - if !custody.NetworkBootOffered(a.DeliveryMethods) { - return ErrNoWipeMethod + // no network boot, or has not reported what it offers, nothing claims a + // boot address and no wipe is made. + if err := a.offersNetworkBoot(ctx, allocation); err != nil { + return err } if current := allocation.Status.Wipe; current == nil || *current != reference { allocation.Status.Wipe = &reference @@ -354,3 +356,23 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat wipe.Spec.BootNetwork = network return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) } + +// offersNetworkBoot reports ErrNoWipeMethod unless every site serving the +// allocation's Device offers network boot, and ErrDeliveryUnknown while a +// serving site has no current declaration. +func (a *Allocator) offersNetworkBoot(ctx context.Context, allocation *fleetv1.MachineAllocation) error { + device := &inventory.Device{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, device); err != nil { + return err + } + offered, known, err := custody.Offered(ctx, a.Sites, device) + switch { + case err != nil: + return err + case !known: + return ErrDeliveryUnknown + case !custody.NetworkBootOffered(offered): + return ErrNoWipeMethod + } + return nil +} diff --git a/internal/coordination/cell.go b/internal/coordination/cell.go index 9044c3de..3ff14242 100644 --- a/internal/coordination/cell.go +++ b/internal/coordination/cell.go @@ -10,6 +10,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/client-go/dynamic" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" ) @@ -26,6 +27,9 @@ type Cell struct { Namespace string Name string Now func() time.Time + // Delivery reads the site enrollment's delivery declaration, once per + // observer pass. An error publishes no declaration. + Delivery func() ([]custody.OfferedMethod, error) } func (c *Cell) now() time.Time { @@ -71,10 +75,32 @@ func (c *Cell) Work(ctx context.Context, name string, runner *site.Runner) error return err } -// Publish writes the observation of one handoff: the Device's stored fences -// and, for an assignment, its stored result. It deletes the site's copy of a -// result the coordinator answered. +// declaration reads the delivery declaration for one pass, or nil. +func (c *Cell) declaration() (*DeliveryDeclaration, error) { + if c.Delivery == nil { + return nil, errors.New("coordination: the cell has no delivery declaration") + } + methods, err := c.Delivery() + if err != nil { + return nil, err + } + data, err := json.Marshal(methods) + if err != nil { + return nil, err + } + return &DeliveryDeclaration{Methods: string(data)}, nil +} + +// Publish writes the observation of one handoff: the Device's stored fences, +// the site's delivery declaration on a report, and, for an assignment, its +// stored result. It deletes the site's copy of a result the coordinator +// answered. func (c *Cell) Publish(ctx context.Context, object *unstructured.Unstructured, store *site.Store, results *site.Results) error { + declared, _ := c.declaration() + return c.publish(ctx, object, store, results, declared) +} + +func (c *Cell) publish(ctx context.Context, object *unstructured.Unstructured, store *site.Store, results *site.Results, declared *DeliveryDeclaration) error { observation := Observation{Cell: c.Name, ObservedAt: c.now()} var device string switch object.GetLabels()[RoleLabel] { @@ -100,7 +126,7 @@ func (c *Cell) Publish(ctx context.Context, object *unstructured.Unstructured, s if err != nil || spec.Cell != c.Name || object.GetLabels()[CellLabel] != c.Name || spec.AssignmentJSON != "" || object.GetName() != ReportName(spec.Device) { return ErrNotDelivered } - device = spec.Device + device, observation.Delivery = spec.Device, declared default: return ErrNotDelivered } @@ -131,8 +157,13 @@ func (c *Cell) Observe(ctx context.Context, interval time.Duration, store *site. if err != nil { onError("", err) } else { + // One read per pass, so an invalid declaration is reported once. + declared, err := c.declaration() + if err != nil { + onError("delivery declaration", err) + } for index := range list.Items { - if err := c.Publish(ctx, &list.Items[index], store, results); err != nil { + if err := c.publish(ctx, &list.Items[index], store, results, declared); err != nil { onError(list.Items[index].GetName(), err) } } diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index 42ff7d63..cf5479a5 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -74,6 +74,17 @@ type Observation struct { ObservedAt time.Time `json:"observedAt"` Fence FenceReport `json:"fence"` Result *custody.SiteResult `json:"result,omitempty"` + // Delivery is the site enrollment's delivery declaration, on a report + // handoff. Nil means the site could not read a valid one. + Delivery *DeliveryDeclaration `json:"delivery,omitempty"` +} + +// DeliveryDeclaration is the delivery methods the site's enrollment +// declares, in its order of preference, as the declaration's JSON. A string +// survives Karmada's status aggregation exactly, where an empty list could +// come back as an object or not at all. "[]" offers none. +type DeliveryDeclaration struct { + Methods string `json:"methods"` } // CellStatus is the status the cell writes. @@ -218,6 +229,25 @@ func (h *Hub) Fence(ctx context.Context, device string) (custody.SiteFence, bool return custody.SiteFence{Seen: observation.Fence.Seen, Stopped: observation.Fence.Stopped}, true, nil } +// DeliveryMethods reads the site's delivery declaration from the Device's +// report handoff. A missing, stale or foreign report, or one with no valid +// declaration, is no declaration: the coordinator then decides nothing. +func (h *Hub) DeliveryMethods(ctx context.Context, device string) ([]custody.OfferedMethod, bool, error) { + object, err := h.ensure(ctx, ReportName(device), RoleReport, Spec{Cell: h.Cell, Device: device}) + if err != nil { + return nil, false, err + } + spec, observation, err := h.reflected(object) + if err != nil || spec.Device != device || observation.AssignmentDigest != "" || h.now().Sub(observation.ObservedAt) > h.MaxAge || observation.Delivery == nil { + return nil, false, nil + } + methods, err := custody.ParseOffered([]byte(observation.Delivery.Methods)) + if err != nil { + return nil, false, nil + } + return methods, true, nil +} + // Results returns each unanswered assignment's reflected result. A result // counts only when it is for exactly the assignment the handoff carries. func (h *Hub) Results(ctx context.Context) ([]site.Stored, error) { diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index dd091632..8d65e797 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -3,6 +3,7 @@ package coordination import ( "context" "encoding/json" + "errors" "fmt" "os" "testing" @@ -293,3 +294,49 @@ func TestTheCellRunsOnlyItsOwnAssignments(t *testing.T) { }) } } + +// TestTheHubReadsTheSiteDeliveryDeclaration reads the declaration the +// site's observer publishes on the report handoff, follows its changes, and +// counts a missing, unreadable or stale one as no declaration. +func TestTheHubReadsTheSiteDeliveryDeclaration(t *testing.T) { + f := newFixture(t) + if _, _, err := f.hub.DeliveryMethods(f.ctx, device); err != nil { + t.Fatal(err) + } + f.fed.sync() + f.observe() + if _, known, err := f.hub.DeliveryMethods(f.ctx, device); err != nil || known { + t.Fatalf("a site with no declaration declared one: %v %v", known, err) + } + media := custody.OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"} + declared := []custody.OfferedMethod{{Method: ops.DeliveryNetworkBoot}, media} + var unreadable error + f.cell.Delivery = func() ([]custody.OfferedMethod, error) { return declared, unreadable } + f.observe() + if methods, known, err := f.hub.DeliveryMethods(f.ctx, device); err != nil || !known || len(methods) != 2 || methods[1] != media { + t.Fatalf("declaration = %+v, %v, %v", methods, known, err) + } + // The site removes network boot; the next report carries only media. + declared = []custody.OfferedMethod{media} + f.observe() + if methods, known, _ := f.hub.DeliveryMethods(f.ctx, device); !known || len(methods) != 1 || methods[0] != media { + t.Fatalf("a removed method is still declared: %+v", methods) + } + // A site may offer nothing: that is a declaration, not a missing one. + declared = []custody.OfferedMethod{} + f.observe() + if methods, known, _ := f.hub.DeliveryMethods(f.ctx, device); !known || len(methods) != 0 { + t.Fatalf("an empty declaration = %+v, %v", methods, known) + } + unreadable = errors.New("unreadable") + f.observe() + if _, known, _ := f.hub.DeliveryMethods(f.ctx, device); known { + t.Fatal("an unreadable declaration keeps the last one") + } + unreadable = nil + f.observe() + f.hub.Now = func() time.Time { return time.Now().Add(2 * time.Minute) } + if _, known, _ := f.hub.DeliveryMethods(f.ctx, device); known { + t.Fatal("a stale declaration counts") + } +} diff --git a/internal/custody/commissioning_test.go b/internal/custody/commissioning_test.go index cc23f6c7..81c8e6b6 100644 --- a/internal/custody/commissioning_test.go +++ b/internal/custody/commissioning_test.go @@ -297,6 +297,27 @@ func TestCommissioning(t *testing.T) { } }) + t.Run("a commissioning waits while a serving site has not reported its methods", func(t *testing.T) { + e, device := next(t, "undeclared") + plan := e.plan("undeclared-v1", "undeclared", planAuthor) + e.approve(plan, planApprover) + e.sites.mu.Lock() + e.sites.unknown = true + e.sites.mu.Unlock() + defer func() { + e.sites.mu.Lock() + e.sites.unknown = false + e.sites.mu.Unlock() + }() + before := e.custody(device.Name).Spec.Fence + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDeliveryNotOffered) + if custody := e.custody(device.Name); custody.Spec.Fence != before || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("a waiting commissioning changed custody: %+v", custody.Spec) + } + }) + t.Run("an inactive Device is refused", func(t *testing.T) { e, device := next(t, "inactive") plan := e.plan("inactive-v1", "inactive", planAuthor) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 4e4e69bc..4c0e7aec 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -29,9 +29,11 @@ type Sites interface { // Fence returns the site's fence report for the Device, and false if // the site has not reported one. Fence(ctx context.Context, site string, device *inventory.Device) (SiteFence, bool, error) - // DeliveryMethods returns the boot delivery methods the site declares, - // in its order of preference. A site that declares none offers none. - DeliveryMethods(site string) []OfferedMethod + // DeliveryMethods returns the boot delivery methods the site's + // enrollment declares, in its order of preference, as the site reports + // them for the Device. It returns false when the site has not reported + // a current declaration: the coordinator then decides nothing on it. + DeliveryMethods(ctx context.Context, site string, device *inventory.Device) ([]OfferedMethod, bool, error) } // SiteFence is one site's fence report for one Device. @@ -810,7 +812,12 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonOperationInProgress, "another operation is running, and staff operations never wait") } - admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval, Offered: offered(c.Sites, device)} + admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} + // A declaration that cannot be read counts as not current: a check that + // needs it waits instead of deciding. + if offers, known, err := Offered(ctx, c.Sites, device); err == nil { + admission.Offered, admission.OfferedKnown = offers, known + } // Rule 7, the kind's own checks, runs before the shared identity and // key checks, so a kind's more specific reason, such as a system UUID // that is not recorded, is the one reported. diff --git a/internal/custody/delivery.go b/internal/custody/delivery.go index 5d49bb55..1b259c79 100644 --- a/internal/custody/delivery.go +++ b/internal/custody/delivery.go @@ -1,9 +1,12 @@ package custody import ( + "bytes" "context" + "encoding/json" "fmt" "net/netip" + "net/url" "regexp" "slices" "strings" @@ -47,6 +50,49 @@ func (o OfferedMethod) Input() ops.DeliveryInput { return ops.DeliveryInput{Method: o.Method, Addresses: o.Addresses, MediaService: o.MediaService, FetchWindow: fetch, ReportWindow: report} } +// ParseOffered reads a site enrollment's delivery declaration: a JSON list +// of offers in the site's order of preference. Each method appears once, +// network boot carries nothing else, and virtual media names its address +// mode and an https media service. +func ParseOffered(data []byte) ([]OfferedMethod, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + var offered []OfferedMethod + if err := decoder.Decode(&offered); err != nil { + return nil, fmt.Errorf("custody: the delivery declaration is not a list of offers: %w", err) + } + if decoder.More() { + return nil, fmt.Errorf("custody: the delivery declaration has trailing data") + } + if offered == nil { + return nil, fmt.Errorf("custody: the delivery declaration is null, not a list") + } + seen := map[ops.DeliveryMethod]bool{} + for _, offer := range offered { + if !slices.Contains(ops.DeliveryMethods, offer.Method) || seen[offer.Method] { + return nil, fmt.Errorf("custody: the delivery declaration offers %q not exactly once as a known method", offer.Method) + } + seen[offer.Method] = true + if offer.Method == ops.DeliveryNetworkBoot { + if offer != (OfferedMethod{Method: ops.DeliveryNetworkBoot}) { + return nil, fmt.Errorf("custody: the delivery declaration gives network boot virtual media settings") + } + continue + } + service, err := url.Parse(offer.MediaService) + if offer.Addresses != ops.AddressesDataNetwork || err != nil || service.Scheme != "https" || service.Host == "" || service.User != nil || + service.Path != "" || service.RawQuery != "" || service.Fragment != "" || service.Opaque != "" { + return nil, fmt.Errorf("custody: the delivery declaration's virtual media needs DataNetwork addresses and an https media service") + } + for _, window := range []*metav1.Duration{offer.FetchWindow, offer.ReportWindow} { + if window != nil && window.Duration <= 0 { + return nil, fmt.Errorf("custody: the delivery declaration's virtual media windows must be positive") + } + } + } + return offered, nil +} + // DeliveryDeadline is how long an installation may run: the sum of its // virtual media phases, or zero for the kind's own deadline. func DeliveryDeadline(delivery ops.DeliveryInput) time.Duration { @@ -182,28 +228,37 @@ func SelectMethod(offered []OfferedMethod, qualified []ops.DeliveryMethod, custo return ops.DeliveryInput{}, false } -// offered returns the methods every site serving the Device offers, in the -// first site's order. A Device no site serves is offered nothing. -func offered(sites Sites, device *inventory.Device) []OfferedMethod { +// Offered returns the methods every site serving the Device declares, in +// the first site's order, and whether every serving site reported a current +// declaration. A Device no site serves is offered nothing. +func Offered(ctx context.Context, sites Sites, device *inventory.Device) ([]OfferedMethod, bool, error) { if sites == nil || device == nil { - return nil + return nil, true, nil } serving := sites.Serving(device) if len(serving) == 0 { - return nil + return nil, true, nil + } + declared := make([][]OfferedMethod, len(serving)) + for index, site := range serving { + methods, known, err := sites.DeliveryMethods(ctx, site, device) + if err != nil || !known { + return nil, false, err + } + declared[index] = methods } var out []OfferedMethod - for _, offer := range sites.DeliveryMethods(serving[0]) { + for _, offer := range declared[0] { everywhere := true - for _, other := range serving[1:] { + for _, other := range declared[1:] { // Offers hold window pointers, so they compare by value. - everywhere = everywhere && slices.ContainsFunc(sites.DeliveryMethods(other), func(o OfferedMethod) bool { return equalInput(o.Input(), offer.Input()) }) + everywhere = everywhere && slices.ContainsFunc(other, func(o OfferedMethod) bool { return equalInput(o.Input(), offer.Input()) }) } if everywhere { out = append(out, offer) } } - return out + return out, true, nil } // checkDelivery is the installation's delivery check. An installation that @@ -247,6 +302,12 @@ func checkDelivery(admission *Admission, spec *ops.DeviceInstallationSpec) *Refu // A settling installation still takes its inputs from the site's offer; // only the qualification check, which the held operation passed, is // skipped. + if !admission.OfferedKnown { + // Undecided, not refused: the site's declaration is not current. + refusal := refuse(ReasonDeliveryNotOffered, "waiting: a site serving the Device has not reported its delivery methods") + refusal.Retry = true + return refusal + } index := slices.IndexFunc(admission.Offered, func(offer OfferedMethod) bool { return offer.Method == method }) if index < 0 { return refuse(ReasonDeliveryNotOffered, "no site serving the Device offers %s", method) @@ -277,6 +338,12 @@ func checkWipeDelivery(admission *Admission) *Refusal { // network-boots a server, so its DHCP, boot addresses and boot NIC // attachments are never used. func requireNetworkBoot(admission *Admission, what string) *Refusal { + if !admission.OfferedKnown { + // Undecided, not refused: the site's declaration is not current. + refusal := refuse(ReasonDeliveryNotOffered, "waiting: a site serving the Device has not reported its delivery methods") + refusal.Retry = true + return refusal + } if NetworkBootOffered(admission.Offered) { return nil } @@ -335,7 +402,12 @@ func (c *Coordinator) holdWaiting(ctx context.Context, custody *ops.DeviceCustod } var want *ops.HoldWaiting if method, held := HeldMethod(custody, "DeviceInstallation"); held { - if !slices.ContainsFunc(offered(c.Sites, device), func(offer OfferedMethod) bool { return offer.Method == method }) { + offers, known, err := Offered(ctx, c.Sites, device) + if err != nil || !known { + // Without a current declaration nothing changes. + return Outcome{}, err + } + if !slices.ContainsFunc(offers, func(offer OfferedMethod) bool { return offer.Method == method }) { want = &ops.HoldWaiting{Reason: ReasonHoldMethodNotOffered, Message: fmt.Sprintf("waits for a site serving the Device to offer %s again", method)} } } diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index 4b6e9200..c6ee1c85 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -149,12 +149,13 @@ func TestDeliveryMethodAdmission(t *testing.T) { fence := e.custody(device.Name).Spec.Fence notURL := virtualMedia notURL.MediaService = "http://media.example" - if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{Delivery: notURL}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { + offers, _, _ := e.sites.DeliveryMethods(e.ctx, "", device) + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: offers, OfferedKnown: true}, &ops.DeviceInstallationSpec{Delivery: notURL}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { t.Fatalf("a media service that is not https://IPv4:port: %+v", refusal) } // The schema leaves delivery optional for installations stored // before it existed; admission refuses one that records no method. - if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: offers, OfferedKnown: true}, &ops.DeviceInstallationSpec{}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { t.Fatalf("an installation with no delivery method: %+v", refusal) } network := &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "ipam.miloapis.com", Kind: "IPAddressClaim", Name: "claim-example"}, Address: "198.51.100.30"} @@ -168,7 +169,8 @@ func TestDeliveryMethodAdmission(t *testing.T) { e := e.sub(t) device := held(e, "VirtualMedia") fence := e.custody(device.Name).Spec.Fence - if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{Delivery: virtualMedia}); refusal == nil || refusal.Reason != ReasonReportAddressRequired { + offers, _, _ := e.sites.DeliveryMethods(e.ctx, "", device) + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: offers, OfferedKnown: true}, &ops.DeviceInstallationSpec{Delivery: virtualMedia}); refusal == nil || refusal.Reason != ReasonReportAddressRequired { t.Fatalf("virtual media with no report address: %+v", refusal) } // Another operation's claim does not hold this one's address. @@ -259,6 +261,26 @@ func TestDeliveryMethodAdmission(t *testing.T) { } }) + t.Run("an install waits while a serving site has not reported its methods", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + fence := e.custody(device.Name).Spec.Fence + e.sites.mu.Lock() + e.sites.unknown = true + e.sites.mu.Unlock() + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDeliveryNotOffered) + e.requireUntouched(device.Name, fence) + e.sites.mu.Lock() + e.sites.unknown = false + e.sites.mu.Unlock() + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != operation.Name { + t.Fatalf("the install was not admitted once the site reported its methods: %+v", active) + } + }) + t.Run("a wipe cannot settle a held virtual media install", func(t *testing.T) { e := e.sub(t) device := held(e, "VirtualMedia") @@ -312,6 +334,31 @@ func TestDeliveryMethodAdmission(t *testing.T) { } }) + t.Run("a wipe waits while a serving site has not reported its methods", func(t *testing.T) { + e := e.sub(t) + device := held(e, "") + allocation := "alloc-d-" + device.Name + if err := e.coord.BeginRelease(e.ctx, device.Name, allocation); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + fence := e.custody(device.Name).Spec.Fence + e.sites.mu.Lock() + e.sites.unknown = true + e.sites.mu.Unlock() + wipe := e.wipe(device, allocation, 1) + e.settle(device.Name) + e.requirePhase(wipe, ops.PhasePending, ReasonDeliveryNotOffered) + e.requireUntouched(device.Name, fence) + e.sites.mu.Lock() + e.sites.unknown = false + e.sites.mu.Unlock() + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != wipe.Name { + t.Fatalf("the wipe was not admitted once the site reported its methods: %+v", active) + } + }) + t.Run("an unpinned installer download is refused", func(t *testing.T) { e := e.sub(t) device := held(e, "VirtualMedia") @@ -364,7 +411,10 @@ func (t twoSites) Serving(*inventory.Device) []string { return []string{"site-a" func (t twoSites) Fence(context.Context, string, *inventory.Device) (SiteFence, bool, error) { return SiteFence{}, false, nil } -func (t twoSites) DeliveryMethods(site string) []OfferedMethod { return t[site] } +func (t twoSites) DeliveryMethods(_ context.Context, site string, _ *inventory.Device) ([]OfferedMethod, bool, error) { + methods, known := t[site] + return methods, known, nil +} func TestOfferedIsWhatEveryServingSiteOffers(t *testing.T) { window := func(d time.Duration) *metav1.Duration { return &metav1.Duration{Duration: d} } @@ -372,15 +422,18 @@ func TestOfferedIsWhatEveryServingSiteOffers(t *testing.T) { // Each site's declaration holds its own window values. return OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: mediaService, FetchWindow: window(time.Minute), ReportWindow: window(time.Hour)} } - got := offered(twoSites{"site-a": {{Method: ops.DeliveryNetworkBoot}, media()}, "site-b": {media()}}, &inventory.Device{}) - if len(got) != 1 || got[0].Method != ops.DeliveryVirtualMedia { + got, known, _ := Offered(context.Background(), twoSites{"site-a": {{Method: ops.DeliveryNetworkBoot}, media()}, "site-b": {media()}}, &inventory.Device{}) + if !known || len(got) != 1 || got[0].Method != ops.DeliveryVirtualMedia { t.Fatalf("offered = %+v, want virtual media alone", got) } other := media() other.ReportWindow = window(time.Minute) - if got := offered(twoSites{"site-a": {media()}, "site-b": {other}}, &inventory.Device{}); len(got) != 0 { + if got, _, _ := Offered(context.Background(), twoSites{"site-a": {media()}, "site-b": {other}}, &inventory.Device{}); len(got) != 0 { t.Fatalf("sites with different windows offered %+v", got) } + if _, known, _ := Offered(context.Background(), twoSites{"site-a": {media()}}, &inventory.Device{}); known { + t.Fatal("a site that has reported no declaration counted as known") + } } func TestCheckDownloads(t *testing.T) { @@ -399,3 +452,32 @@ func TestCheckDownloads(t *testing.T) { t.Fatalf("a pinned download was refused: %+v", refusal) } } + +func TestParseOffered(t *testing.T) { + got, err := ParseOffered([]byte(`[{"method":"NetworkBoot"},{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443","fetchWindow":"5m"}]`)) + if err != nil || len(got) != 2 || got[0].Method != ops.DeliveryNetworkBoot || got[1].FetchWindow.Duration != 5*time.Minute { + t.Fatalf("declaration = %+v, %v", got, err) + } + if got, err := ParseOffered([]byte(`[]`)); err != nil || len(got) != 0 { + t.Fatalf("an empty declaration offers none: %+v, %v", got, err) + } + for name, data := range map[string]string{ + "not a list": `{"method":"NetworkBoot"}`, + "unknown method": `[{"method":"Floppy"}]`, + "repeated method": `[{"method":"NetworkBoot"},{"method":"NetworkBoot"}]`, + "unknown field": `[{"method":"NetworkBoot","priority":1}]`, + "network boot settings": `[{"method":"NetworkBoot","mediaService":"https://192.0.2.10:8443"}]`, + "no address mode": `[{"method":"VirtualMedia","mediaService":"https://192.0.2.10:8443"}]`, + "plain http service": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"http://192.0.2.10:8080"}]`, + "service with a path": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443/media"}]`, + "zero report window": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443","reportWindow":"0s"}]`, + "trailing data": `[{"method":"NetworkBoot"}] []`, + "null": `null`, + "service with a user": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://user:secret@192.0.2.10:8443"}]`, + "service with a query": `[{"method":"VirtualMedia","addresses":"DataNetwork","mediaService":"https://192.0.2.10:8443?x=1"}]`, + } { + if _, err := ParseOffered([]byte(data)); err == nil { + t.Errorf("%s: accepted", name) + } + } +} diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 81af0b9c..ff77e192 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -75,15 +75,20 @@ type fakeSites struct { // methods, when set, replaces the site's declared delivery methods, // which default to network boot then virtual media. methods []OfferedMethod + // unknown makes the site report no current declaration. + unknown bool } -func (s *fakeSites) DeliveryMethods(string) []OfferedMethod { +func (s *fakeSites) DeliveryMethods(context.Context, string, *inventory.Device) ([]OfferedMethod, bool, error) { s.mu.Lock() defer s.mu.Unlock() + if s.unknown { + return nil, false, nil + } if s.methods != nil { - return s.methods + return s.methods, true, nil } - return []OfferedMethod{{Method: ops.DeliveryNetworkBoot}, {Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} + return []OfferedMethod{{Method: ops.DeliveryNetworkBoot}, {Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}}, true, nil } func newFakeSites() *fakeSites { diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 8c0a2984..d8eaabb5 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -187,8 +187,10 @@ type Admission struct { // DiscoveryInterval is how often BMC discovery reads each BMC. DiscoveryInterval time.Duration // Offered is the boot delivery methods every site serving the Device - // offers, in the first site's order of preference. - Offered []OfferedMethod + // offers, in the first site's order of preference. OfferedKnown is + // false while a serving site has not reported a current declaration. + Offered []OfferedMethod + OfferedKnown bool } // RecoverySettleContext is what a held kind's settle hook sees. Hold carries diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index 0b42a6c6..bc256675 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -33,6 +33,10 @@ type Site interface { Results(ctx context.Context) ([]site.Stored, error) // Forget tells the site the coordinator answered a result. Forget(ctx context.Context, stored site.Stored) error + // DeliveryMethods returns the delivery methods the site's enrollment + // declares, as the site reports them for a "/" + // Device, and false if it has reported no current declaration. + DeliveryMethods(ctx context.Context, device string) ([]custody.OfferedMethod, bool, error) } // Sites is the coordinator's explicit site configuration: which sites serve @@ -42,13 +46,16 @@ type Sites struct { Sites map[string]Site // Devices maps a Device name to the names of the sites serving it. Devices map[string][]string - // Methods is each site's declared boot delivery methods, in its order - // of preference. A site with none offers none. - Methods map[string][]custody.OfferedMethod } -func (s *Sites) DeliveryMethods(name string) []custody.OfferedMethod { - return slices.Clone(s.Methods[name]) +// DeliveryMethods reads the site's own declaration, from its enrollment, as +// the site reports it. The coordinator keeps no copy. +func (s *Sites) DeliveryMethods(ctx context.Context, name string, device *inventory.Device) ([]custody.OfferedMethod, bool, error) { + remote, ok := s.Sites[name] + if !ok { + return nil, false, nil + } + return remote.DeliveryMethods(ctx, device.Namespace+"/"+device.Name) } var _ custody.Sites = (*Sites)(nil) diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go index 4bcf3e1f..669c28ed 100644 --- a/internal/manager/customer_power_envtest_test.go +++ b/internal/manager/customer_power_envtest_test.go @@ -110,7 +110,7 @@ func startEnv(t *testing.T) *env { runner := &site.Runner{Site: siteName, Store: e.store, Results: site.NewResults(e.store), Access: fixture.Access{Enrollment: e.enrollment}, Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DevicePowerOperation": simwork.Power{}}, Poll: 20 * time.Millisecond} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} - server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, func() (string, error) { return siteToken, nil })) + server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, custody.NetworkBootOnly, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) if err != nil { @@ -120,7 +120,7 @@ func startEnv(t *testing.T) *env { if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -129,7 +129,7 @@ func startEnv(t *testing.T) *env { e.allocator = &allocation.Allocator{ Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, - Custody: coordinator, DeliveryMethods: custody.NetworkBootOnly, Namespace: namespace, + Custody: coordinator, Sites: sites, Namespace: namespace, Cleaning: func(string) (string, error) { return policyDigest, nil }, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Capacity: fixtureOffers{}, diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go index 1f3bad7e..29dc39ea 100644 --- a/internal/multiplane/media.go +++ b/internal/multiplane/media.go @@ -39,7 +39,11 @@ import ( // provider that skipped selection would. Admission refuses it before // anything is delivered, with custody's fence unchanged. func (r *Runner) MediaNotOffered(ctx context.Context) error { - for _, offer := range r.Config.DeliveryMethods { + declared, err := r.declared(ctx) + if err != nil { + return err + } + for _, offer := range declared { if offer.Method == ops.DeliveryVirtualMedia { return fmt.Errorf("%w: the cell already offers virtual media", errTerminal) } @@ -48,13 +52,34 @@ func (r *Runner) MediaNotOffered(ctx context.Context) error { return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000227", delivery, nil, custody.ReasonDeliveryNotOffered) } +// MediaOffered waits until the coordinator reads, from the cell's report, +// a site enrollment that offers virtual media through the acceptance's +// central media service. The coordinator keeps no copy and is not +// restarted. +func (r *Runner) MediaOffered(ctx context.Context) error { + declared, err := r.declared(ctx) + if err != nil { + return err + } + for _, offer := range declared { + if offer.Method == ops.DeliveryVirtualMedia && offer.MediaService == r.Config.MediaService { + return nil + } + } + return fmt.Errorf("%w: the cell declares %d methods, none of them virtual media", errPending, len(declared)) +} + // MediaUnpinned creates, once the cell offers virtual media, a virtual // media installation whose installer would download an image by tag, as an // image like Talos's would without a digest. Admission refuses it before // anything is delivered. func (r *Runner) MediaUnpinned(ctx context.Context) error { + declared, err := r.declared(ctx) + if err != nil { + return err + } index := -1 - for i, offer := range r.Config.DeliveryMethods { + for i, offer := range declared { if offer.Method == ops.DeliveryVirtualMedia { index = i } @@ -63,7 +88,20 @@ func (r *Runner) MediaUnpinned(ctx context.Context) error { return fmt.Errorf("%w: the cell does not offer virtual media", errTerminal) } downloads := []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}} - return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000228", r.Config.DeliveryMethods[index].Input(), downloads, custody.ReasonDownloadUnpinned) + return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000228", declared[index].Input(), downloads, custody.ReasonDownloadUnpinned) +} + +// declared reads the cell's delivery declaration as the coordinator does, +// from target A's report handoff. +func (r *Runner) declared(ctx context.Context) ([]custody.OfferedMethod, error) { + methods, known, err := r.Hub.DeliveryMethods(ctx, DeviceNamespace+"/"+Device) + if err != nil { + return nil, err + } + if !known { + return nil, fmt.Errorf("%w: the cell has not reported its delivery declaration", errPending) + } + return methods, nil } // unclaimedReportAddress gives a refused installation the report address diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 6f55ad46..19895ba2 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -69,10 +69,6 @@ type Config struct { // Fleet synchronizes. Empty means the site's DHCP is configured // independently, as in the lab. BootAddressClass string `json:",omitempty"` - // DeliveryMethods is the cell's declared boot delivery methods, in its - // order of preference. The coordinator admits against it and the Metal - // provider selects from it. A cell that declares none offers none. - DeliveryMethods []custody.OfferedMethod `json:",omitempty"` // MediaService is the central media service's endpoint, as BMCs and // installed servers reach it, when the acceptance runs one. MediaService string `json:",omitempty"` @@ -159,7 +155,7 @@ func coordinator(ctx context.Context, c Config, registry *custody.Registry) (*cu return nil, nil, nil, nil, err } hub := &coordination.Hub{API: dynamicHub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} - sites := &delivery.Sites{Sites: map[string]delivery.Site{c.Cell: hub}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{c.Cell: c.DeliveryMethods}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{c.Cell: hub}, Devices: map[string][]string{}} for key := range c.Enrollment { namespace, name, _ := strings.Cut(key, "/") if namespace == DeviceNamespace { @@ -224,7 +220,7 @@ func New(ctx context.Context, c Config) (*Runner, error) { if err != nil { return nil, err } - coord, hub, _, _, err := coordinator(ctx, c, registry) + coord, hub, sites, _, err := coordinator(ctx, c, registry) if err != nil { return nil, err } @@ -269,7 +265,7 @@ func New(ctx context.Context, c Config) (*Runner, error) { }, Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: cleaningResolver}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, - DeliveryMethods: c.DeliveryMethods, + Sites: sites, } if c.BootAddressClass != "" { // IPAM, aggregated by the provider project's Milo API, binds each claim diff --git a/internal/site/config.go b/internal/site/config.go index b01272e3..8c1f9b15 100644 --- a/internal/site/config.go +++ b/internal/site/config.go @@ -5,7 +5,6 @@ import ( "crypto/sha256" "crypto/tls" "encoding/hex" - "slices" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" "go.datum.net/fleet/internal/bmcdiscovery" @@ -57,24 +56,19 @@ func (t StaticTargets) Target(device string) (redfish.Target, bool) { } // Report is the site's fence report for the coordinator. Targets is the -// explicit list of Devices this site serves, and Methods the boot delivery -// methods it declares, in its order of preference. +// explicit list of Devices this site serves. type Report struct { Site string Store *Store Targets StaticTargets - Methods []custody.OfferedMethod } var _ custody.Sites = Report{} -// DeliveryMethods returns the site's declared methods. A site that declares -// none offers none. -func (r Report) DeliveryMethods(site string) []custody.OfferedMethod { - if site != r.Site { - return nil - } - return slices.Clone(r.Methods) +// DeliveryMethods reports no declaration: the site's declaration reaches the +// coordinator only through the cell's report handoff. +func (r Report) DeliveryMethods(context.Context, string, *inventory.Device) ([]custody.OfferedMethod, bool, error) { + return nil, false, nil } func (r Report) Serving(device *inventory.Device) []string { diff --git a/internal/site/siteapi/api_test.go b/internal/site/siteapi/api_test.go index 090a18ec..f9807055 100644 --- a/internal/site/siteapi/api_test.go +++ b/internal/site/siteapi/api_test.go @@ -66,7 +66,7 @@ func TestTheSiteAPI(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() dispatcher := &Dispatcher{Runner: runner, Context: ctx} - server := httptest.NewServer(Handler(dispatcher, store, results, func() (string, error) { return token, nil })) + server := httptest.NewServer(Handler(dispatcher, store, results, custody.NetworkBootOnly, func() (string, error) { return token, nil })) defer server.Close() for name, header := range map[string]string{"no token": "", "wrong token": "Bearer other"} { request, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/results", nil) @@ -86,6 +86,14 @@ func TestTheSiteAPI(t *testing.T) { if err != nil { t.Fatal(err) } + // The site reports its enrollment's delivery declaration, and only to + // an authenticated caller. + if response, err := server.Client().Get(server.URL + "/v1/delivery-methods"); err != nil || response.StatusCode != http.StatusUnauthorized { + t.Fatalf("unauthenticated delivery methods = %v, %v", response, err) + } + if methods, known, err := remote.DeliveryMethods(ctx, device); err != nil || !known || len(methods) != 1 || methods[0].Method != ops.DeliveryNetworkBoot { + t.Fatalf("delivery methods = %+v, %v, %v", methods, known, err) + } a := assignment(t) for range 3 { if err := remote.Deliver(ctx, a); err != nil { diff --git a/internal/site/siteapi/client.go b/internal/site/siteapi/client.go index f9e3f53f..50a52946 100644 --- a/internal/site/siteapi/client.go +++ b/internal/site/siteapi/client.go @@ -88,6 +88,18 @@ func (c *Client) Fence(ctx context.Context, device string) (custody.SiteFence, b return custody.SiteFence{Seen: report.Seen, Stopped: report.Stopped}, true, nil } +// DeliveryMethods reads the site's declared delivery methods. The simulator +// site declares one set for every Device it serves. +func (c *Client) DeliveryMethods(ctx context.Context, _ string) ([]custody.OfferedMethod, bool, error) { + var declared struct { + Methods []custody.OfferedMethod `json:"methods"` + } + if err := c.do(ctx, http.MethodGet, "/v1/delivery-methods", nil, &declared); err != nil { + return nil, false, err + } + return declared.Methods, true, nil +} + func (c *Client) Results(ctx context.Context) ([]site.Stored, error) { var held []site.Stored return held, c.do(ctx, http.MethodGet, "/v1/results", nil, &held) diff --git a/internal/site/siteapi/server.go b/internal/site/siteapi/server.go index 39393a30..2a7d0797 100644 --- a/internal/site/siteapi/server.go +++ b/internal/site/siteapi/server.go @@ -88,9 +88,15 @@ type FenceReport struct { Stopped int64 `json:"stopped"` } -// Handler serves the site API behind a bearer token. -func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, token func() (string, error)) http.Handler { +// Handler serves the site API behind a bearer token. methods is the site's +// enrollment of delivery methods, in its order of preference. +func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, methods []custody.OfferedMethod, token func() (string, error)) http.Handler { mux := http.NewServeMux() + mux.HandleFunc("GET /v1/delivery-methods", func(w http.ResponseWriter, _ *http.Request) { + write(w, struct { + Methods []custody.OfferedMethod `json:"methods"` + }{methods}) + }) mux.HandleFunc("PUT /v1/assignments", func(w http.ResponseWriter, r *http.Request) { var assignment site.Assignment if err := decode(r, &assignment); err != nil { diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index b4d03d2b..587b43ef 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -115,7 +115,7 @@ func startStack(t *testing.T) *stack { runner := &site.Runner{Site: siteName, Store: store, Results: site.NewResults(store), Access: fixture.Access{Enrollment: enrollment}, Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Poll: 20 * time.Millisecond} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} - server := httptest.NewServer(siteapi.Handler(dispatcher, store, runner.Results, func() (string, error) { return siteToken, nil })) + server := httptest.NewServer(siteapi.Handler(dispatcher, store, runner.Results, custody.NetworkBootOnly, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) if err != nil { @@ -125,7 +125,7 @@ func startStack(t *testing.T) *stack { if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: providerNamespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -139,7 +139,7 @@ func startStack(t *testing.T) *stack { Cleaning: func(string) (string, error) { return policyDigest, nil }, Capacity: s.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, - DeliveryMethods: custody.NetworkBootOnly, + Sites: sites, } // One qualified plan covers every fixture server. s.plan = &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan", Namespace: providerNamespace}, Spec: ops.DeviceCommissioningPlanSpec{