diff --git a/cmd/fleet-manager/main.go b/cmd/fleet-manager/main.go index 9108516e..c56b3337 100644 --- a/cmd/fleet-manager/main.go +++ b/cmd/fleet-manager/main.go @@ -43,6 +43,7 @@ type managerFlags struct { syntheticProviderProjectName, syntheticPublishedClassName string syntheticPublishedProfileName string syntheticCoordinatorCertDir, syntheticReleaseCertDir string + syntheticProjectorCertDir string syntheticEnrollmentFile, syntheticDeviceNamespace string } @@ -55,6 +56,7 @@ func bindFlags(flags *flag.FlagSet) *managerFlags { flags.StringVar(&f.syntheticTokenFile, "synthetic-provider-token-file", "", "file containing the synthetic provider site's bearer token") flags.StringVar(&f.syntheticCoordinatorCertDir, "synthetic-coordinator-client-cert-dir", "", "directory holding the custody coordinator's Milo client certificate as tls.crt and tls.key") flags.StringVar(&f.syntheticReleaseCertDir, "synthetic-release-client-cert-dir", "", "directory holding the release controller's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticProjectorCertDir, "synthetic-projector-client-cert-dir", "", "directory holding the capacity projector's Milo client certificate as tls.crt and tls.key") flags.StringVar(&f.syntheticEnrollmentFile, "synthetic-site-enrollment-file", "", "JSON enrollment of the Devices the synthetic provider site serves") flags.StringVar(&f.syntheticDeviceNamespace, "synthetic-device-namespace", "default", "namespace of the Devices, capacities and allocations in the provider project") flags.StringVar(&f.syntheticLocation, "synthetic-location", "us-central-1", "only location accepted by synthetic staging") @@ -73,13 +75,13 @@ func (f *managerFlags) validate() error { return errors.Join(errFlags, errors.New("--config and --leader-election-namespace are required")) } if !f.syntheticStaging { - if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" || f.syntheticCoordinatorCertDir != "" || f.syntheticReleaseCertDir != "" || f.syntheticEnrollmentFile != "" { + if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" || f.syntheticCoordinatorCertDir != "" || f.syntheticReleaseCertDir != "" || f.syntheticProjectorCertDir != "" || f.syntheticEnrollmentFile != "" { return errors.Join(errFlags, errors.New("synthetic flags require --synthetic-staging")) } return nil } - if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" || f.syntheticCoordinatorCertDir == "" || f.syntheticReleaseCertDir == "" || f.syntheticEnrollmentFile == "" { - return errors.Join(errFlags, errors.New("--synthetic-staging requires the provider site token, the coordinator and release controller client certificates, the site enrollment, and --synthetic-consumer-project-name")) + if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" || f.syntheticCoordinatorCertDir == "" || f.syntheticReleaseCertDir == "" || f.syntheticProjectorCertDir == "" || f.syntheticEnrollmentFile == "" { + return errors.Join(errFlags, errors.New("--synthetic-staging requires the provider site token, the coordinator, release controller and capacity projector client certificates, the site enrollment, and --synthetic-consumer-project-name")) } if f.syntheticProviderProjectName != "" && (f.syntheticPublishedClassName == "" || f.syntheticPublishedProfileName == "") { return errors.Join(errFlags, errors.New("--synthetic-provider-project-name requires the published class and profile names")) diff --git a/cmd/fleet-manager/main_test.go b/cmd/fleet-manager/main_test.go index a4b3e6d3..04e793f0 100644 --- a/cmd/fleet-manager/main_test.go +++ b/cmd/fleet-manager/main_test.go @@ -52,7 +52,7 @@ func TestSyntheticFlagsRequireAndScopeStaging(t *testing.T) { if err := parse(t, append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t")...); !errors.Is(err, errFlags) { t.Fatalf("staging without a consumer project: %v", err) } - components := []string{"--synthetic-coordinator-client-cert-dir=/c", "--synthetic-release-client-cert-dir=/r", "--synthetic-site-enrollment-file=/e"} + components := []string{"--synthetic-coordinator-client-cert-dir=/c", "--synthetic-release-client-cert-dir=/r", "--synthetic-projector-client-cert-dir=/p", "--synthetic-site-enrollment-file=/e"} staging := append(append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t", "--synthetic-consumer-project-name=consumer"), components...) if err := parse(t, staging...); err != nil { t.Fatal(err) diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index 66d33ec8..8ca09493 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -18,6 +18,7 @@ import ( ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" "go.datum.net/fleet/internal/allocation" + "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/delivery" "go.datum.net/fleet/internal/site/fixture" @@ -49,14 +50,18 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi if err != nil { return nil, nil, nil, fmt.Errorf("release controller credential: %w", err) } - clients := make([]ctrlclient.Client, 3) - for index, config := range []*rest.Config{providerConfig, coordinatorConfig, releaseConfig} { + projectorConfig, err := withClientCert(providerConfig, flags.syntheticProjectorCertDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("capacity projector credential: %w", err) + } + clients := make([]ctrlclient.Client, 4) + for index, config := range []*rest.Config{providerConfig, coordinatorConfig, releaseConfig, projectorConfig} { // Decisions read through to the API server, never a cache. if clients[index], err = ctrlclient.New(config, ctrlclient.Options{Scheme: scheme}); err != nil { return nil, nil, nil, err } } - provider, coordinatorClient, releaseClient := clients[0], clients[1], clients[2] + provider, coordinatorClient, releaseClient, projectorClient := clients[0], clients[1], clients[2], clients[3] providerCreator, err := allocation.Creator(ctx, providerConfig) if err != nil { return nil, nil, nil, fmt.Errorf("identify the Metal provider: %w", err) @@ -91,7 +96,9 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi } coordinator := &custody.Coordinator{Client: coordinatorClient, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals}} log := ctrl.Log.WithName("custody") - loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, + cleaning := func(context.Context, string) (string, error) { return custody.SpecDigest(syntheticCleaningPolicy) } + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: cleaning} + loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: coordinatorClient, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, OnError: func(err error) { log.Info("coordinator pass incomplete", "error", err.Error()) }} allocator := &allocation.Allocator{ @@ -99,6 +106,7 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: coordinator, Namespace: namespace, Cleaning: func(string) (string, error) { return custody.SpecDigest(syntheticCleaningPolicy) }, + 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"}, } diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index fadb2467..c33dbcfd 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -67,7 +67,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", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": + case "seed", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin, *clientID) @@ -146,8 +146,12 @@ func phase(name, configPath string, once bool) error { if err != nil { return err } + // The Redfish lab serves a firmware inventory; the local VM has none. + if redfishMode() { + r.PlanFirmware = multiplane.LabFirmware + } action := map[string]func(context.Context) error{ - "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, + "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, }[name] @@ -164,7 +168,7 @@ func phase(name, configPath string, once bool) error { fmt.Println("Installation admitted and delivered; its result remains Unknown") return nil } - if err == nil && (name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation") { + if err == nil && (name == "commission" || name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation") { return nil } if err == nil { diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 9fce8af2..3c4c1f6c 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -182,7 +182,7 @@ func siteRunner(_ context.Context, config *rest.Config, cell string, store *site return nil, err } runner.Access = fixture.Access{Enrollment: enrollment} - runner.Kinds = map[string]site.Kind{"DeviceInstallation": vmwork.Installation{Config: vm}, "DeviceWipe": vmwork.Wipe{Config: vm}} + runner.Kinds = map[string]site.Kind{"DeviceInstallation": vmwork.Installation{Config: vm}, "DeviceWipe": vmwork.Wipe{Config: vm}, "DeviceCommissioning": vmwork.Commissioning{Config: vm}} return runner, nil } work, enrollment, err := redfishConfig() @@ -206,7 +206,14 @@ func siteRunner(_ context.Context, config *rest.Config, cell string, store *site targets[target.Device] = target } runner.Access = site.RedfishAccess{Credentials: site.SecretCredentials{Reader: reader, Namespace: namespace, Project: project}, Targets: targets} - runner.Kinds = map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work}} + // The site serves one boot image, which also burns in. + image, err := siteImage() + if err != nil { + return nil, err + } + _, burnIn, _ := strings.Cut(image, "@") + runner.Kinds = map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work}, + "DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn}} return runner, nil } diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index c9baa2d0..d4903a4c 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -73,7 +73,7 @@ func main() { defer stop() results := site.NewResults(store) runner := &site.Runner{Site: siteName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, - Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}}} + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} server := newServer(address, siteapi.Handler(dispatcher, store, results, func() (string, error) { return readToken(tokenPath) }), logger) if discover { diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index b4546881..de84a7f3 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -25,6 +25,7 @@ import ( 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/capacity" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/delivery" "go.datum.net/fleet/internal/site/siteapi" @@ -41,8 +42,12 @@ const ( func main() { options := standalone.DefaultOptions() - var phase, coordinatorToken, releaseToken, siteURL, siteToken, siteName, devices string - flag.StringVar(&phase, "phase", "", "required: allocate, install, reinstall, release, or coordinate") + var phase, coordinatorToken, releaseToken, siteURL, siteToken, siteName, devices, projectorToken, authorToken, approverToken, operatorToken string + flag.StringVar(&phase, "phase", "", "required: commission, allocate, install, reinstall, release, or coordinate") + flag.StringVar(&projectorToken, "projector-token-file", "", "the capacity projector's ServiceAccount token (coordinate)") + flag.StringVar(&authorToken, "plan-author-token-file", "", "the plan author's ServiceAccount token (commission)") + flag.StringVar(&approverToken, "plan-approver-token-file", "", "the plan approver's ServiceAccount token (commission)") + flag.StringVar(&operatorToken, "operator-token-file", "", "the commissioning operator's ServiceAccount token (commission)") flag.StringVar(&coordinatorToken, "coordinator-token-file", "", "the custody coordinator's ServiceAccount token (phases)") flag.StringVar(&releaseToken, "release-token-file", "", "the release controller's ServiceAccount token (phases)") flag.StringVar(&siteURL, "site-url", "http://fleet-simulator:8080", "the simulator site's API (coordinate)") @@ -59,7 +64,7 @@ func main() { registry, err := custody.DefaultRegistry() must(err) if phase == "coordinate" { - must(coordinate(ctx, config, registry, options.ProviderNamespace, siteName, siteURL, siteToken, strings.Split(devices, ","))) + must(coordinate(ctx, config, registry, options.ProviderNamespace, siteName, siteURL, siteToken, projectorToken, strings.Split(devices, ","))) return } if coordinatorToken == "" || releaseToken == "" { @@ -76,24 +81,35 @@ func main() { must(err) releaseCreator, err := allocation.Creator(ctx, releaseConfig) must(err) + offers := &capacity.Projector{Reader: provider, Namespace: options.ProviderNamespace, Cleaning: fixtureResolver} allocator := &allocation.Allocator{ Provider: provider, ProviderCreator: providerCreator, Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: &custody.Coordinator{Client: coordinatorClient, Registry: registry, Config: custody.Config{Namespace: options.ProviderNamespace, Principals: principals()}}, Namespace: options.ProviderNamespace, Cleaning: fixtureCleaning, + Capacity: offers, // The fixture Device's boot NIC and the simulator's one enrolled disk. BootInterface: "primary", TargetDisks: []string{"disk-0"}, } - must(standalone.Runner{Client: provider, Allocator: allocator, Options: options}.Run(ctx, phase)) + runner := standalone.Runner{Client: provider, Allocator: allocator, Options: options} + if phase == standalone.PhaseCommission { + runner.Staff, err = staff(ctx, config, authorToken, approverToken, operatorToken) + must(err) + } + must(runner.Run(ctx, phase)) fmt.Printf("standalone synthetic smoke phase %s completed\n", phase) } // 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 string, devices []string) error { - if tokenFile == "" { - return errors.New("coordinate needs the site token file") +func coordinate(ctx context.Context, config *rest.Config, registry *custody.Registry, namespace, siteName, siteURL, tokenFile, projectorToken string, devices []string) error { + if tokenFile == "" || projectorToken == "" { + return errors.New("coordinate needs the site and capacity projector token files") + } + projectorClient, err := newClient(withToken(config, projectorToken)) + if err != nil { + return err } api, err := newClient(config) if err != nil { @@ -111,12 +127,48 @@ func coordinate(ctx context.Context, config *rest.Config, registry *custody.Regi } coordinator := &custody.Coordinator{Client: api, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals()}} logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) - loop := &delivery.Loop{Client: api, Coordinator: coordinator, Namespace: namespace, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: fixtureResolver} + loop := &delivery.Loop{Client: api, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, OnError: func(err error) { logger.Info("coordinator pass incomplete", "error", err.Error()) }} logger.Info("custody coordinator running", "namespace", namespace, "site", siteName) return loop.Run(ctx) } +// staff returns the commissioning phase's three people, each with their own +// token. +func staff(ctx context.Context, config *rest.Config, author, approver, operator string) (*standalone.Staff, error) { + if author == "" || approver == "" || operator == "" { + return nil, errors.New("commission needs the plan author, approver and operator token files") + } + out := &standalone.Staff{} + for _, person := range []struct { + token string + client *client.Client + creator *ops.Creator + }{{author, &out.Author, &out.AuthorCreator}, {approver, &out.Approver, &out.ApproverCreator}, {operator, &out.Operator, &out.OperatorCreator}} { + personConfig := withToken(config, person.token) + api, err := newClient(personConfig) + if err != nil { + return nil, err + } + creator, err := allocation.Creator(ctx, personConfig) + if err != nil { + return nil, err + } + *person.client, *person.creator = api, creator + } + return out, nil +} + +// fixtureResolver is the projector's view of the fixture cleaning policy. +func fixtureResolver(_ context.Context, name string) (string, error) { + digest, err := fixtureCleaning(name) + if err != nil { + return "", capacity.ErrUnresolved + } + return digest, nil +} + func principals() custody.Principals { return custody.Principals{custody.CreatorMetalProvider: {{Username: providerPrincipal}}, custody.CreatorReleaseController: {{Username: releasePrincipal}}} } diff --git a/config/README.md b/config/README.md index 7647a777..afb93075 100644 --- a/config/README.md +++ b/config/README.md @@ -138,11 +138,14 @@ following before the new manager runs: registering physical devices](../docs/operations/physical-inventory.md). Records GitOps already manages stay with it; import by hand only the ones it does not. -3. Create two Milo identities that sign in with client certificates, bind one - to `fleet.datumapis.com-device-coordinator` and the other to - `fleet.datumapis.com-device-wipe-requester` in the provider project, and +3. Create three Milo identities that sign in with client certificates, bind + one to `fleet.datumapis.com-device-coordinator`, one to + `fleet.datumapis.com-device-wipe-requester` and one to + `fleet.datumapis.com-capacity-projector` in the provider project, and issue each a client certificate with a cert-manager Certificate whose - Secret is the one below. + Secret is the one below. Bind each role on the provider project, not on + one namespace: evaluating capacity lists Devices in every namespace to + find a duplicate identity. 4. Give the manager's own identity, the Metal provider, these roles in the provider project: `metal.datumapis.com-controller`, which now deletes an allocation that lost its Device before it held it; @@ -158,9 +161,175 @@ following before the new manager runs: 7. Delete the publisher's copy of the MachineClass in the consumer project. Its source names the old `project` field and is immutable, so the publisher recreates it with `publisherRef`. -8. After rollout, verify both Deployments, Service routing, PVC binding, and a - fresh allocation and verified release. Do not delete the PVC as a recovery - shortcut. +8. After rollout, verify both Deployments, Service routing and PVC binding. + Do not delete the PVC as a recovery shortcut. Do not test an allocation + yet: no capacity is allocatable until its Device is commissioned. + +#### Commissioning the synthetic Devices + +The new manager no longer marks synthetic capacity `Prepared`, `Healthy` and +`Available` by itself. The capacity projector derives them from evidence, so +after rollout every existing capacity reads `Prepared=False` with reason +`NotCommissioned`, and an allocation fails with insufficient capacity. That is +correct: nothing has proven the servers yet. Commission each synthetic Device +before testing an allocation. The examples use the synthetic names this +repository ships; substitute your own Devices, namespace and people. + +1. **Choose three identities.** A plan author, a plan approver and a + commissioning operator. The author and the approver must be two different + people: custody refuses an approval whose creator has the author's + username. Never bind the author and approver roles to the same principal, + or to groups that share a member. The operator may be either person or a + third. Bind each role on the provider project: + + ```yaml + apiVersion: iam.miloapis.com/v1alpha1 + kind: PolicyBinding + metadata: + name: fleet-plan-author-example + namespace: example-provider-project + spec: + roleRef: + name: fleet.datumapis.com-device-commissioning-plan-author + namespace: milo-system # where the environment installs the Fleet roles + subjects: + - kind: User + name: plan-author@example.com + uid: 00000000-0000-4000-8000-0000000000a1 + resourceSelector: + resourceRef: + apiGroup: resourcemanager.miloapis.com + kind: Project + name: example-provider-project + uid: 00000000-0000-4000-8000-0000000000f1 + ``` + + Create the same binding for `plan-approver@example.com` with + `fleet.datumapis.com-device-commissioning-plan-approver`, and for + `operator@example.com` with + `fleet.datumapis.com-device-commissioning-operator`. + +2. **Author the plan.** An inventory editor labels the Devices the plan + covers, and the plan author creates the plan. `creator` must be the author's own username, and + `uid` only if their credential carries one. The content describes the + hardware every covered Device must have. + + ```sh + kubectl label device server-example-001 -n default fleet.datumapis.com/hardware-model=synthetic + ``` + + ```yaml + apiVersion: fleet.datumapis.com/v1alpha1 + kind: DeviceCommissioningPlan + metadata: + name: synthetic-plan-v1 + namespace: default + spec: + creator: + username: plan-author@example.com + deviceSelector: + matchLabels: + fleet.datumapis.com/hardware-model: synthetic + content: + inspection: + cpu: {architecture: amd64, cores: 2} + memory: {capacity: 2Gi} + disks: {count: 1, minCapacity: 2Gi} + interfaces: {count: 1} + firmware: + - {component: BMC, version: 1.0.0} + burnIn: + image: + name: synthetic-burn-in + digest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + duration: 1m + evidenceLifetime: 720h + ``` + +3. **A different person approves it.** The approval's name, and the + generation and digest it names, must match the plan exactly as the API + server stores it, so compute them from the stored plan rather than by + hand. The approver runs, from a checkout: + + ```sh + kubectl get devicecommissioningplan synthetic-plan-v1 -n default -o json > plan.json + go run ./hack/commissioning-request approval --plan plan.json \ + --username plan-approver@example.com | kubectl create -f - + ``` + + The printed approval looks like this; the name's suffix and the digest + are derived from the plan: + + ```yaml + apiVersion: fleet.datumapis.com/v1alpha1 + kind: DeviceCommissioningPlanApproval + metadata: + name: synthetic-plan-v1-<16 hex characters> + namespace: default + spec: + creator: + username: plan-approver@example.com + planRef: + name: synthetic-plan-v1 + generation: 1 + digest: sha256: + ``` + +4. **Add hardware and firmware to the site enrollment.** The synthetic site + inspects what its enrollment says each Device has. Give every Device in + the `fleet-synthetic-site-enrollment` ConfigMap a `hardware` field and a + `firmware` list that meet the plan; a Device without `hardware` cannot be + commissioned. The manager and the synthetic provider read the ConfigMap + only when they start, so this is best done with step 5 above, before the + new manager runs. A change made later takes effect after a rollout of + both; the provider's `Recreate` strategy keeps its store safe: + + ```sh + kubectl rollout restart deployment/fleet-synthetic-provider deployment/fleet-manager -n fleet-system + ``` + + ```json + {"default/server-example-001": { + "bmcEndpoint": "https://[2001:db8::31]", + "systemUUID": "00000000-0000-4000-8000-000000000031", + "bootMACAddress": "02:00:00:00:00:31", + "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", + "disks": ["disk-0"], + "hardware": { + "cpu": {"architecture": "amd64", "cores": 2}, + "memory": "2Gi", + "disks": [{"name": "disk-0", "capacity": "2Gi"}], + "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:31"}] + }, + "firmware": [{"component": "BMC", "version": "1.0.0"}] + }} + ``` + +5. **Create one commissioning per Device.** The operator creates each one + under the plan, with an exact copy of its content and the Device's + incarnation label, again computed from the stored objects. Create, do not + apply: the name is generated. + + ```sh + kubectl get device server-example-001 -n default -o json > device.json + go run ./hack/commissioning-request commission --plan plan.json --device device.json \ + --username operator@example.com --reason "synthetic intake" | kubectl create -f - + ``` + +6. **Wait for `Prepared` and `Available`.** Each commissioning should end + `Succeeded` with result `Passed`, and the capacity projector then sets + `Prepared`, `Healthy` and `Available` to `True`: + + ```sh + kubectl get devicecommissionings -n default + kubectl wait machinecapacity --all -n default --for=condition=Available --timeout=10m + ``` + + A `Failed` result names what did not match the plan in its evidence. Fix + the enrollment or the plan (a changed plan is a new plan, approved again) + and commission again. + +7. **Then verify a fresh allocation** and its verified release. Render the Milo and management-cluster roots before publishing the Kustomize bundle: @@ -254,6 +423,7 @@ manager runs under its leader lease together with fixture discovery: | --- | --- | --- | | Secret `fleet-system/fleet-custody-coordinator-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-coordinator-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-coordinator` role in the provider project, as a cert-manager Certificate writes it. Supplied by the environment. | | Secret `fleet-system/fleet-release-controller-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-release-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-wipe-requester` role in the provider project. Supplied by the environment. | +| Secret `fleet-system/fleet-capacity-projector-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-projector-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-capacity-projector` role in the provider project. Supplied by the environment. | | ConfigMap `fleet-system/fleet-synthetic-site-enrollment`, key `enrollment.json` | `--synthetic-site-enrollment-file` | The Devices the synthetic site serves, keyed `/`, each with its BMC endpoint, system UUID, boot MAC address, key digest and disks. The overlay ships a synthetic placeholder for `server-example-001`, and an environment replaces it with the Devices it imports. | | `--synthetic-device-namespace` | Default `default` | The namespace of the Devices, capacities and allocations in the provider project. Every enrolled Device must be in it. | diff --git a/config/components/device-operations/roles/capacity-projector.yaml b/config/components/device-operations/roles/capacity-projector.yaml new file mode 100644 index 00000000..4cbe39fb --- /dev/null +++ b/config/components/device-operations/roles/capacity-projector.yaml @@ -0,0 +1,29 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-capacity-projector + annotations: + kubernetes.io/display-name: Fleet Capacity Projector + kubernetes.io/description: The only writer of MachineCapacity status. Derives Prepared, Healthy, Available and the hardware from commissioning, discovery and custody evidence. Bound on the provider project, it reads Devices in every namespace, a deliberate widening so a duplicate identity in another namespace withdraws the offer. +spec: + launchStage: Alpha + includedPermissions: + - metal.datumapis.com/machinecapacities.get + - metal.datumapis.com/machinecapacities.list + - metal.datumapis.com/machinecapacities.watch + - metal.datumapis.com/machinecapacities.updateStatus + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml index 1131652a..0c78eeeb 100644 --- a/config/components/device-operations/roles/installation-requester.yaml +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-installation-requester annotations: kubernetes.io/display-name: Fleet Device Installation Requester - kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations and reads custody. + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, and reads custody and the commissioning evidence it evaluates capacity from. spec: launchStage: Alpha includedPermissions: @@ -15,3 +15,15 @@ spec: - fleet.datumapis.com/devicecustodies.get - fleet.datumapis.com/devicecustodies.list - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml index 8885e67a..ca35ee2b 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -9,3 +9,4 @@ resources: - device-commissioning-operator.yaml - device-commissioning-plan-author.yaml - device-commissioning-plan-approver.yaml + - capacity-projector.yaml diff --git a/config/components/iam/roles/controller.yaml b/config/components/iam/roles/controller.yaml index 5739cf1b..0830ec6f 100644 --- a/config/components/iam/roles/controller.yaml +++ b/config/components/iam/roles/controller.yaml @@ -13,7 +13,6 @@ spec: includedPermissions: - metal.datumapis.com/machineclasses.updateStatus - metal.datumapis.com/machineprofiles.updateStatus - - metal.datumapis.com/machinecapacities.updateStatus - metal.datumapis.com/machines.updateStatus - metal.datumapis.com/machineallocations.list - metal.datumapis.com/machineallocations.get diff --git a/config/overlays/synthetic-staging/kustomization.yaml b/config/overlays/synthetic-staging/kustomization.yaml index 48b464ea..f1363d79 100644 --- a/config/overlays/synthetic-staging/kustomization.yaml +++ b/config/overlays/synthetic-staging/kustomization.yaml @@ -39,6 +39,9 @@ patches: - op: add path: /spec/template/spec/containers/0/args/- value: --synthetic-release-client-cert-dir=/var/run/fleet/release + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-projector-client-cert-dir=/var/run/fleet/projector - op: add path: /spec/template/spec/containers/0/args/- value: --synthetic-site-enrollment-file=/etc/fleet/enrollment/enrollment.json @@ -92,6 +95,12 @@ patches: name: release-controller-client-cert mountPath: /var/run/fleet/release readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: capacity-projector-client-cert + mountPath: /var/run/fleet/projector + readOnly: true - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: @@ -126,6 +135,20 @@ patches: path: tls.crt - key: tls.key path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: capacity-projector-client-cert + # A cert-manager Certificate's Secret for the capacity projector's + # Milo identity. + secret: + secretName: fleet-capacity-projector-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key - op: add path: /spec/template/spec/volumes/- value: diff --git a/config/site/base/enrollment.json b/config/site/base/enrollment.json index d02d4f85..9a3508bf 100644 --- a/config/site/base/enrollment.json +++ b/config/site/base/enrollment.json @@ -1 +1 @@ -{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"]}} +{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"], "hardware": {"cpu": {"architecture": "amd64", "cores": 2}, "memory": "2Gi", "disks": [{"name": "disk-0", "capacity": "2Gi"}], "interfaces": [{"name": "primary", "macAddress": "52:54:00:77:00:02"}]}}} diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index d4f0d938..38ee08d5 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -22,7 +22,10 @@ spec: # its fixture discovery writes the Device's status. apiVersion: fleet.datumapis.com/v1alpha1 kind: Device -metadata: {name: synthetic-device-central-01, namespace: fleet-provider} +metadata: + name: synthetic-device-central-01 + namespace: fleet-provider + labels: {fleet.datumapis.com/hardware-model: synthetic} spec: claimRef: {name: synthetic-claim-central-01} identity: {model: synthetic, serial: synthetic-serial-central-01, systemUUID: 00000000-0000-4000-8000-000000000021} diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index ace349f6..d1c89965 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -31,15 +31,12 @@ kind: Role metadata: {name: fleet-synthetic-provider-writer, namespace: fleet-provider} rules: # The Metal provider selects capacity, records allocations and creates - # installations. It reads custody and Devices only to skip taken capacity; + # installations. It evaluates each capacity from its commissioning, + # discovery and custody evidence, and never writes capacity status; # custody decides. - apiGroups: [metal.datumapis.com] resources: [machinecapacities] verbs: [get, list] - - apiGroups: [metal.datumapis.com] - resources: [machinecapacities/status] - resourceNames: [central1-baremetal-01] - verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [machineallocations] verbs: [get, list, create, delete] @@ -50,8 +47,8 @@ rules: resources: [deviceinstallations] verbs: [get, list, create] - apiGroups: [fleet.datumapis.com] - resources: [devices, devicecustodies] - verbs: [get] + resources: [devices, devicecustodies, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -218,3 +215,151 @@ metadata: {name: fleet-simulator-discovery, namespace: fleet-provider} roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-simulator-discovery} subjects: - {kind: ServiceAccount, name: fleet-simulator, namespace: fleet-system} +--- +# The capacity projector is the only writer of capacity status. It derives +# Prepared, Healthy, Available and the hardware from evidence. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-capacity-projector, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-capacity-projector-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-capacity-projector} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-capacity-projector, namespace: fleet-provider} +rules: + - apiGroups: [metal.datumapis.com] + resources: [machinecapacities] + verbs: [get, list] + - apiGroups: [metal.datumapis.com] + resources: [machinecapacities/status] + verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [devices, devicecustodies, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-capacity-projector, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-capacity-projector} +subjects: + - {kind: ServiceAccount, name: fleet-capacity-projector, namespace: fleet-system} +--- +# A duplicate identity anywhere in the project withdraws an offer, so the +# projector reads Devices in every namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-capacity-projector-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} +subjects: + - {kind: ServiceAccount, name: fleet-capacity-projector, namespace: fleet-system} +--- +# The smoke is the Metal provider, and the allocator offers a capacity only +# after evaluating it from live evidence, which includes the duplicate +# identity scan over Devices in every namespace. A namespaced binding would +# fail every offer, so this stays cluster-wide and read-only. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-standalone-smoke-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} +subjects: + - {kind: ServiceAccount, name: fleet-standalone-smoke, namespace: fleet-system} +--- +# Writes commissioning plans. It cannot approve them. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-plan-author, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-plan-author-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-plan-author} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-plan-author, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-plan-author, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-plan-author} +subjects: + - {kind: ServiceAccount, name: fleet-plan-author, namespace: fleet-system} +--- +# Approves another person's commissioning plan. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-plan-approver, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-plan-approver-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-plan-approver} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-plan-approver, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplanapprovals] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-plan-approver, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-plan-approver} +subjects: + - {kind: ServiceAccount, name: fleet-plan-approver, namespace: fleet-system} +--- +# Commissions a Device under its current plan. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-commissioning-operator, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-commissioning-operator-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-commissioning-operator} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-commissioning-operator, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissionings] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-commissioning-operator, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-commissioning-operator} +subjects: + - {kind: ServiceAccount, name: fleet-commissioning-operator, namespace: fleet-system} diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml index bca62a78..156a7c6e 100644 --- a/config/standalone/site.yaml +++ b/config/standalone/site.yaml @@ -6,7 +6,7 @@ kind: ConfigMap metadata: {name: fleet-simulator-enrollment, namespace: fleet-system} data: enrollment.json: | - {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"]}} + {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"], "hardware": {"cpu": {"architecture": "amd64", "model": "synthetic", "sockets": 2, "cores": 24}, "memory": "128Gi", "disks": [{"name": "disk-0", "capacity": "960Gi"}], "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:21"}]}, "firmware": [{"component": "BMC", "version": "synthetic-1.0"}]}} --- # The custody coordinator: the only writer of custody and of operation # status. It delivers admitted operations to the simulator site and reports @@ -29,13 +29,17 @@ spec: - name: coordinator image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=coordinate, --site-token-file=/var/run/fleet/token] + args: [--phase=coordinate, --site-token-file=/var/run/fleet/token, --projector-token-file=/var/run/fleet/projector/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} resources: requests: {cpu: 20m, memory: 32Mi} limits: {cpu: 250m, memory: 128Mi} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: runtime-token, mountPath: /var/run/fleet, readOnly: true} + - {name: projector-token, mountPath: /var/run/fleet/projector, readOnly: true} + volumes: + - {name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}} + - {name: projector-token, secret: {secretName: fleet-capacity-projector-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- # The creator rule. Milo projects ignore admission policies, so Milo uses the # creator webhook; a plain cluster enforces the same rule with this policy: diff --git a/config/standalone/smoke-cronjobs.yaml b/config/standalone/smoke-cronjobs.yaml index 529d5ab2..187eda42 100644 --- a/config/standalone/smoke-cronjobs.yaml +++ b/config/standalone/smoke-cronjobs.yaml @@ -1,3 +1,38 @@ +# The commissioning phase acts as three people: one writes the plan, another +# approves it, and an operator commissions the Device. +apiVersion: batch/v1 +kind: CronJob +metadata: {name: fleet-smoke-commission, namespace: fleet-system} +spec: + schedule: "0 0 1 1 *" + suspend: true + jobTemplate: + spec: + backoffLimit: 0 + template: + spec: + serviceAccountName: fleet-standalone-smoke + restartPolicy: Never + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: smoke + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=commission, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token, --plan-author-token-file=/var/run/fleet/author/token, --plan-approver-token-file=/var/run/fleet/approver/token, --operator-token-file=/var/run/fleet/operator/token] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + - {name: author-token, mountPath: /var/run/fleet/author, readOnly: true} + - {name: approver-token, mountPath: /var/run/fleet/approver, readOnly: true} + - {name: operator-token, mountPath: /var/run/fleet/operator, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: author-token, secret: {secretName: fleet-plan-author-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: approver-token, secret: {secretName: fleet-plan-approver-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: operator-token, secret: {secretName: fleet-commissioning-operator-token, defaultMode: 0440, items: [{key: token, path: token}]}} +--- apiVersion: batch/v1 kind: CronJob metadata: {name: fleet-smoke-allocate, namespace: fleet-system} diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 177de8ed..0201aed4 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -44,8 +44,7 @@ marked **implemented and verified**, **implemented and inert**, or only when `spec.creator` is the authenticated caller's username, plus its UID when the caller has one, and an update only when the creator is unchanged. - **The capacity projector** is a pure function that derives `Prepared`, - `Healthy` and `Available`. Nothing calls it outside tests (**implemented and - inert**; see [Capacity](#other-decisions)). + `Healthy` and `Available`. [Capacity status](#capacity-status) wires it. Creating or importing a Device creates `Unverified` custody. That sends nothing to a BMC and makes no capacity `Available`. @@ -377,8 +376,6 @@ event. ### Unchanged and still open -- The capacity projector stays unwired (O1), so the synthetic fixtures still write - `Prepared`, `Healthy` and `Available`. - Bootstrap stays refused (O10). - `DeviceRecovery` needs no second person. @@ -700,12 +697,8 @@ remains. policy record pinned at allocation. A resolver maps the capacity's cleaning policy reference to that digest when the allocator creates the allocation. The standalone, staging and multi-plane modes supply a fixture resolver. -- **Capacity (O1).** The projector stays a pure function. `Prepared` needs a - succeeded commissioning under the current plan, `Healthy` needs current - commissioning and discovery evidence, and `Available` also needs `Verified` - custody, holder `None`, no hold and an enabled allocation policy. Wiring it - as written would make every server unallocatable, because commissioning is - not built. +- **Capacity (O1).** Settled by commissioning: see [Capacity + status](#capacity-status). ### No object UIDs in spec @@ -871,10 +864,10 @@ which a test pins, because the coordinator lists every registered kind. PolicyBinding grants one subject both. - **Residual window.** Admission reads the plan and its approval before the custody update, which re-checks only the Device. A plan revoked in between - can still be admitted once. No capacity projector reads commissioning yet, - so this increment makes nothing `Prepared`. The projector that does must - check the plan's qualification again when it reads a commissioning, so - that run cannot make a server `Prepared` under a revoked plan (O1). + can still be admitted once. The capacity projector reads the Device's + current plan, and so its qualification, again on every pass, so that run + cannot make a server `Prepared` under a revoked plan (see [Capacity + status](#capacity-status)). - **Current plan.** The qualified plans whose selector matches the Device's labels, minus those another of them supersedes. One left is the current plan. None left with none matching is `NoCurrentPlan`. More than one, or @@ -911,11 +904,11 @@ The boot interface is fixed at `primary`, like the allocator's in every mode. ### The Redfish commissioning worker -The Redfish worker for `DeviceCommissioning` is **implemented and inert**. It -is tested against a TLS BMC stub, and no site registers it yet. The lab -emulator's adapter reports each target's serial, its one disk and a firmware -inventory, which a local read with the worker's Redfish client matched to a -plan's hardware and firmware. +The Redfish worker for `DeviceCommissioning` is **implemented**. It is tested +against a TLS BMC stub, and the multi-plane Redfish site runs it against the +lab emulator in its `commission` phase (see [Capacity +status](#capacity-status)). The lab adapter reports each target's serial, its +one disk and a firmware inventory. No production site registers it yet. - **Preflight.** It reads the system's identity, processors, memory, storage, network interfaces and firmware inventory with GETs only. A serial number @@ -960,15 +953,113 @@ plan's hardware and firmware. component lists are dropped before the verdict if the evidence would pass the kind's limit. +## Capacity status + +The capacity projector is **implemented** in every mode, and verified by tests +against a real API server and by the standalone smoke. It derives +`Prepared`, `Healthy`, `Available` and the hardware of every MachineCapacity +from the [commissioning proposal](https://github.com/datum-cloud/fleet/pull/185)'s +inputs, and nothing else writes them. + +- **Where it runs.** The coordinator loop runs it after each pass, with the + projector's own identity: the `fleet.datumapis.com-capacity-projector` role + in Milo, a `fleet-capacity-projector` ServiceAccount in standalone, the + `--synthetic-projector-client-cert-dir` client certificate in synthetic staging, and a + `projector` token in the multi-plane run. The Metal controller role no + longer holds `machinecapacities.updateStatus`. +- **The allocator does not read conditions.** It asks the projector to + evaluate each candidate from live inputs (`Offer`), matches the profile + against the hardware that evaluation returns, and pins that hardware on the + allocation. Custody still decides. It reads each candidate's Device and + custody first and evaluates only identified, visibly free capacity. One + pass lists the provider project's Devices, plans, approvals and + commissionings once, not once per capacity, and so does each projector + pass. A capacity whose reads or evaluation fail is skipped; the error is + returned only when nothing is offered. +- **Grants.** Every identity that evaluates capacity, the Metal provider and + the projector, lists Devices across the provider project, because a + duplicate in any namespace withdraws an offer. + `TestEveryEvaluatorListsDevicesProjectWide` pins that in every mode. `TestOnlyEvidenceOffersCapacity` edits a + failed server's status to `Available` and shows the allocator refuses it and + the projector restores the derived status. +- **Inputs.** The Device and its lifecycle, custody for the same Device UID, + the Device's current plan, its latest succeeded commissioning for the same + Device UID, discovery currency by the admission rule, the cleaning policy + resolver, and whether another Device in the namespace shares an identity + alias anywhere in the provider project. Registration admission checks the + other provider projects when capacity is registered and enabled; the + projector does not read across projects. Aliases moved from registration to + the inventory API package, so both compute them the same way. +- **Device pin.** Registered capacity counts its Device only while the + Device's UID is the one registration recorded when it created the + capacity. Capacity behind a Device recreated under the same name is not + `Prepared` (`DeviceReplaced`), so the allocator never offers it. +- **Hardware ID.** A Device without a hardware ID never backs capacity + ([#131](https://github.com/datum-cloud/fleet/issues/131)). The projector + calls `inventory.CapacityBackingError` on the Device it reads and, when it + fails, reads nothing else and leaves the capacity not `Prepared` + (`DeviceUnidentified`). The allocator makes the same check on the Device it + reads, whatever the evaluation offered. + `TestAServerWithoutAHardwareIDIsNeverOffered` and + `TestTheAllocatorNeverSelectsAServerWithoutAHardwareID` pin both. +- **Plan pin.** `Prepared` needs the latest commissioning's evidence to name + the current plan's name, generation, digest and approval name. The approval + name is derived from the plan's UID, so evidence under a plan recreated with + the same name and content proves nothing (`PlanChanged`). +- **Cleaning policy.** The projector takes a resolver that returns a digest, + `ErrUnresolved`, or another error, which makes `Available` `Unknown`. Every + mode supplies a fixture resolver for its one fixture policy. No production + resolver exists yet; it belongs to the cleaning policy owner. +- **Simulated commissioning.** The simulator site runs a `DeviceCommissioning` + worker that inspects the hardware and firmware its enrollment records for + the Device. Its burn-in sends nothing and takes no time: it journals one + step named `simulated-burnin` and records the plan's duration, so its + evidence is synthetic and says so. The enrollment gains `hardware` and + `firmware` fields for it. +- **Standalone.** A `commission` phase runs before `allocate`, as three + ServiceAccounts: a plan author, an approver and an operator. The fixture + Device carries a `fleet.datumapis.com/hardware-model` label that the plan + selects. The smoke checks that the provider cannot write capacity status + and that the author cannot approve. +- **Multi-plane.** The provider project gets the projector, the three staff + identities and a capacity operator, and the Metal provider reads + commissioning evidence. The seed no longer writes capacity conditions. A + `commission` phase runs before `allocate` in both runs: the plan author + writes the local plan, another identity approves it, the operator + commissions the Device, and the phase waits until the projector offers the + capacity. The seeded Device carries the `fleet.datumapis.com/hardware-model` + label the plan selects. The plan requires the fixture profile's hardware + and a one-minute burn-in of the site image. In Redfish mode it also requires + the lab's firmware inventory; the local VM reports no firmware, so its plan + has no baseline. + - The site needs a worker before any allocation exists, while the install + must still be delivered before any worker Job for the partition scenario. + So one source revision enables dispatch for the commissioning and the next + disables it again, and kro prunes the finished commissioning's Job. Its + handoff stays delivered and answered, and the install's scenarios count + only the other assignments. When dispatch is enabled again, or the graph + lifecycle recreates the workers, kro recreates the commissioning's Job: + it replays a verified no-op, or the site refuses it at exit 65 once the + install raised the Device's fence. It sends nothing either way. + - The local VM site runs a `DeviceCommissioning` worker. The local VM has + no BMC, so inspection compares the hardware the site enrolls for the + Device, which describes the guest it defines, with the plan. Burn-in is + real: one network boot of the site image in burn-in mode on a scratch + disk, proven by its one console receipt, after which the scratch disk is + removed. + - The Redfish site registers the Redfish worker against the lab emulator. + The `redfish-commission-mark` step requires exactly one effective `On` to + target A, one passed burn-in receipt and no effect on target B, and the + later Redfish counts start after it. + - The harness keeps commissionings out of its install and wipe evidence by + their site key. +- **Synthetic staging.** The staging handler no longer writes capacity + status; the projector does. + ## Points for a person These need a decision before the increment that depends on them. -- **O1: the interim source of `Prepared` and `Healthy`.** Still open after C. - The projector stays unwired, so the synthetic fixtures write `Prepared`, - `Healthy` and `Available` themselves. When the projector reads - commissioning, it must check the plan's qualification again, which closes - the residual window of [Commissioning](#commissioning). - **Who approves commissioning plans.** No team holds the plan approver role in any deployed environment yet, so no plan qualifies there. The roles keep the author and the approver apart by username. @@ -984,14 +1075,17 @@ These need a decision before the increment that depends on them. 2. Make sure each Device, with its BMC endpoint and identity, and each capacity exists in the provider project. Records GitOps already manages stay with it; import by hand only the ones it does not. - 3. Create two Milo identities that sign in with client certificates, bound - to the `fleet.datumapis.com-device-coordinator` and - `fleet.datumapis.com-device-wipe-requester` roles, and issue each a + 3. Create three Milo identities that sign in with client certificates, + bound to the `fleet.datumapis.com-device-coordinator`, + `fleet.datumapis.com-device-wipe-requester` and + `fleet.datumapis.com-capacity-projector` roles, and issue each a cert-manager client certificate. 4. Grant the manager's own identity, the Metal provider, the `metal.datumapis.com-controller`, `fleet.datumapis.com-device-installation-requester` and `fleet.datumapis.com-inventory-discoverer` roles in the provider project. + Bind these roles and the projector's on the project, not on one + namespace: evaluating capacity lists Devices in every namespace. 5. Supply the site's enrollment. 6. Delete the old `fleet-system-private` namespace and its Secrets. 7. Delete the publisher's copy of the MachineClass in the consumer project. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 895895ae..b3b12759 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -197,7 +197,7 @@ gated in full, and updates, deletes and any routed subresource are denied. rule. Stage 1 has no status writer for inventory-backed capacity, but a provider may need one later, and the webhook would then have to be changed first. Status writes are governed by RBAC alone; in the packaged IAM roles -only the controller role holds `machinecapacities.updateStatus`. This is +only the capacity projector role holds `machinecapacities.updateStatus`. This is acceptable because a status write cannot widen what capacity offers: - the CRD's status subresource ignores changes to `metadata` and `spec`, so a diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 4d162455..26f2551e 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -345,7 +345,19 @@ The phases are then: Redfish mode the BMC audit must hold no effect. `staff-access` requires the staff identity to read custody and list recoveries, and to be forbidden Secrets, every other operation, allocations and custody writes. - Staff hold no consumer-project or hub credential. + Staff hold no consumer-project or hub credential. `commission-dispatch` + publishes a source revision that enables dispatch, `commission` then + commissions the Device as three people, a plan author, an approver and an + operator, and waits until the capacity projector offers its capacity, and + `commission-settle` publishes the next revision, which disables dispatch + again so the install is delivered before any worker Job. The site boots + the site image once in burn-in mode. In Redfish mode + `redfish-commission-mark` requires that burn-in to be target A's one + effective `On`, with one passed receipt and no effect on target B. In local + VM mode `commission-mark` records digests of the commissioning's journal + and boot record. kro later recreates the finished commissioning's Job, and + the evidence phase requires both to be unchanged, so that replay sent + nothing. 2. **Contention.** Two consumers request one provider capacity. Custody grants one allocation; `verify-contention` independently reads Bound for A and Pending/InsufficientCapacity for B, and requires custody to name the one diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 59ec1fee..08ac5310 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -195,7 +195,7 @@ or provider host ID in `serial` to avoid it. **What it prevents.** A Device without hardware identity cannot back a MachineCapacity. Nothing can match it to a chassis, so enrollment, wiping and -allocation could reach the wrong machine. Two things enforce this today: +allocation could reach the wrong machine. Three things enforce this today: - Admission rejects a `bmc` endpoint on a marked Device, so it has no management endpoint to enroll through. @@ -205,12 +205,13 @@ allocation could reach the wrong machine. Two things enforce this today: for one with no identity at all. Any resolver of `deviceRef` must call it and treat a non-nil result as ineligible. -Nothing resolves `deviceRef` yet: the allocator uses the name only to form the -asset key and never reads the Device. Admission cannot check the reference -either, because MachineCapacity is a separate API group and CEL cannot read -other objects. Until a resolver exists, operators must not create a -MachineCapacity whose `deviceRef` names a marked Device, just as they must not -name a Device that does not exist. +- The capacity projector and the allocator, the readers of `deviceRef`, both + call it. Capacity behind such a Device is never `Prepared`, so it is never + offered or allocated. + +Admission cannot check the reference, because MachineCapacity is a separate +API group and CEL cannot read other objects, so such capacity can still be +created. It stays ineligible; do not create it. A marked Device still binds to a DeviceClaim through `claimRef`. Do not bind it to a claim whose `expectedIdentity.serial` is set; that claim expects diff --git a/hack/commissioning-request/main.go b/hack/commissioning-request/main.go new file mode 100644 index 00000000..aa832b80 --- /dev/null +++ b/hack/commissioning-request/main.go @@ -0,0 +1,96 @@ +// Command commissioning-request prints the DeviceCommissioningPlanApproval +// or DeviceCommissioning a person creates, from the plan and Device as the +// API server returns them. An approval's name, generation and digest, and a +// commissioning's copy of the plan, must match the plan exactly, so they are +// computed rather than written by hand. It reads files and prints JSON for +// `kubectl create -f -`; it contacts no API server. +// +// commissioning-request approval --plan plan.json --username NAME [--uid UID] +// commissioning-request commission --plan plan.json --device device.json --username NAME [--uid UID] --reason TEXT +package main + +import ( + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "commissioning-request:", err) + os.Exit(2) + } +} + +func run(args []string, out io.Writer) error { + if len(args) == 0 { + return errors.New("want a subcommand: approval or commission") + } + flags := flag.NewFlagSet(args[0], flag.ContinueOnError) + planFile := flags.String("plan", "", "the plan as `kubectl get -o json` prints it") + deviceFile := flags.String("device", "", "the Device as `kubectl get -o json` prints it (commission)") + username := flags.String("username", "", "your username: the creator admission records must be the caller") + uid := flags.String("uid", "", "your UID, if your credential carries one") + reason := flags.String("reason", "", "why the Device is commissioned (commission)") + if err := flags.Parse(args[1:]); err != nil { + return err + } + if *planFile == "" || *username == "" { + return errors.New("--plan and --username are required") + } + plan := &ops.DeviceCommissioningPlan{} + if err := read(*planFile, plan); err != nil { + return err + } + if plan.UID == "" || plan.Generation == 0 { + return errors.New("the plan has no UID or generation: read it from the API server") + } + creator := ops.Creator{Username: *username, UID: *uid} + var object any + switch args[0] { + case "approval": + approval, err := custody.NewApproval(plan, creator) + if err != nil { + return err + } + approval.APIVersion, approval.Kind = ops.GroupVersion.String(), "DeviceCommissioningPlanApproval" + object = approval + case "commission": + if *deviceFile == "" || *reason == "" { + return errors.New("commission needs --device and --reason") + } + device := &inventory.Device{} + if err := read(*deviceFile, device); err != nil { + return err + } + if device.UID == "" { + return errors.New("the Device has no UID: read it from the API server") + } + operation, err := custody.NewCommissioning(device, plan, creator, *reason) + if err != nil { + return err + } + operation.APIVersion, operation.Kind = ops.GroupVersion.String(), "DeviceCommissioning" + object = operation + default: + return fmt.Errorf("unknown subcommand %q", args[0]) + } + encoder := json.NewEncoder(out) + encoder.SetIndent("", " ") + return encoder.Encode(object) +} + +func read(path string, into any) error { + data, err := os.ReadFile(path) + if err != nil { + return err + } + return json.Unmarshal(data, into) +} diff --git a/hack/commissioning-request/main_test.go b/hack/commissioning-request/main_test.go new file mode 100644 index 00000000..71b0ad75 --- /dev/null +++ b/hack/commissioning-request/main_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// The printed approval and commissioning are what custody computes from the +// plan and Device as the API server returns them, so the plan qualifies and +// admission's exact-copy check passes. +func TestItPrintsWhatCustodyComputes(t *testing.T) { + dir := t.TempDir() + plan := &ops.DeviceCommissioningPlan{TypeMeta: metav1.TypeMeta{APIVersion: ops.GroupVersion.String(), Kind: "DeviceCommissioningPlan"}, + ObjectMeta: metav1.ObjectMeta{Name: "example-plan", Namespace: "default", UID: "00000000-0000-4000-8000-000000000a01", Generation: 1}, + Spec: ops.DeviceCommissioningPlanSpec{Creator: ops.Creator{Username: "plan-author@example.com"}, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/hardware-model": "example"}}, + Content: ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "2Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: "sha256:" + string(bytes.Repeat([]byte("b"), 64))}, Duration: metav1.Duration{Duration: time.Minute}}, + }, + EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}}} + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001", Namespace: "default", UID: "00000000-0000-4000-8000-000000000d01"}} + write := func(name string, value any) string { + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, name) + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + return path + } + planFile, deviceFile := write("plan.json", plan), write("device.json", device) + + var out bytes.Buffer + if err := run([]string{"approval", "--plan", planFile, "--username", "plan-approver@example.com"}, &out); err != nil { + t.Fatal(err) + } + var approval ops.DeviceCommissioningPlanApproval + if err := json.Unmarshal(out.Bytes(), &approval); err != nil { + t.Fatal(err) + } + want, err := custody.NewApproval(plan, ops.Creator{Username: "plan-approver@example.com"}) + if err != nil { + t.Fatal(err) + } + if approval.Kind != "DeviceCommissioningPlanApproval" || approval.Name != want.Name || approval.Spec != want.Spec { + t.Fatalf("approval = %+v, want %+v", approval, want) + } + + out.Reset() + if err := run([]string{"commission", "--plan", planFile, "--device", deviceFile, "--username", "operator@example.com", "--reason", "intake"}, &out); err != nil { + t.Fatal(err) + } + var operation ops.DeviceCommissioning + if err := json.Unmarshal(out.Bytes(), &operation); err != nil { + t.Fatal(err) + } + reference, err := custody.PlanReferenceOf(plan) + if err != nil { + t.Fatal(err) + } + if operation.Kind != "DeviceCommissioning" || operation.Labels[ops.LabelDeviceUID] != string(device.UID) || operation.Spec.Plan.PlanReference != reference || + operation.Spec.Plan.Approval != want.Name || operation.Spec.DeviceRef.Name != device.Name || operation.Spec.Creator.Username != "operator@example.com" { + t.Fatalf("commissioning = %+v", operation) + } + + // A plan written by hand, without the server's UID and generation, would + // name an approval that qualifies nothing. + bare := write("bare.json", &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan"}, Spec: plan.Spec}) + if err := run([]string{"approval", "--plan", bare, "--username", "plan-approver@example.com"}, &out); err == nil { + t.Fatal("a plan without a UID was accepted") + } +} diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 54e316d2..eb1088bf 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -24,6 +24,10 @@ step import-inert 300 step staff-access 120 rf baseline 300 rf discovery-faults 600 +step commission-dispatch 900 +ph commission 1500 "$host" commission --config "$state/acceptance.json" +rf commission-mark 120 +step commission-settle 900 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 step tenant-isolation 300 diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index caa69773..36afc7d0 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -19,6 +19,10 @@ ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" step import-inert 300 step staff-access 120 +step commission-dispatch 900 +ph commission 1500 "$host" commission --config "$state/acceptance.json" +ph commission-mark 120 python3 hack/multiplane/harness.py commission-mark --state "$state" +step commission-settle 900 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 step tenant-isolation 300 diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 476cd39f..68ce85a4 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -222,6 +222,16 @@ def libvirt_provider(): installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] + # kro recreated the finished commissioning's Job after the commission + # phase. Its journal and boot record are as the phase left them, so the + # replay sent nothing. + mark = json.loads((s / 'commission.json').read_text()) + current, error = harness.commission_digest(store, lambda operation: boot_record(raw, 'vmboot', harness.key(operation)) or None) + if error or current != mark: + fail('the commissioning changed after its phase: %s' % (error or {'mark': mark, 'now': current})) + if not boot_record(raw, 'vmboot', harness.key(mark['operation'])).get('closed'): + fail('the commissioning did not close its boot admission') + receipts, starts = [], {} for o in installs: uid = o['operation'] @@ -319,6 +329,10 @@ def redfish_provider(): for name in ('boot.ipxe', 'kernel', 'installer.gz'): if 'write-complete ' + name + ' bytes=' not in written: fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) + # The commissioning's one burn-in receipt came before every operation's. + burnin = [i for i, l in enumerate(console) if l.startswith('FLEET-BURNIN:')] + if len(burnin) != 1 or not console[burnin[0]].endswith(':passed') or (expected and burnin[0] > min(expected)): + fail('expected exactly one passed burn-in receipt before the first operation receipt') if expected != sorted(expected) or sum(1 for l in console if l.startswith(('FLEET-INSTALLED:', 'FLEET-DISK-BOOT:', 'FLEET-WIPED:'))) != len(expected): fail('console receipts are out of order or include another operation') installed = [boot_record(raw, 'boot', o['operation'])['receipt'] for o in ops if o['kind'] == 'DeviceInstallation'] @@ -332,10 +346,10 @@ def network(block): order = ['network' if network(b) else 'disk' for b in blocks] starts = {'targetA': order, 'targetB': (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').read_text(errors='replace').count(': starting up ') if (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').exists() else 0} - # A install (network, disk), A wipe, B's held install (its network boot - # was withheld by the lab boot hook), B wipe. - if order != ['network', 'disk', 'network', 'network', 'network'] or starts['targetB']: - fail('expected target A boots network, disk, network, network, network and no target B start; got %s' % starts) + # The commissioning's burn-in, A install (network, disk), A wipe, B's held + # install (its network boot was withheld by the lab boot hook), B wipe. + if order != ['network', 'network', 'disk', 'network', 'network', 'network'] or starts['targetB']: + fail('expected target A boots network (burn-in), network, disk, network, network, network and no target B start; got %s' % starts) # Every lab target start ran the selected accelerator: libvirt logs each # QEMU command line, which names the accelerator it ran. The adapter # defines a target only while the site runtime publishes the same one. @@ -344,7 +358,14 @@ def network(block): fail('lab target accelerator is not %s: QEMU accelerators %s' % (ACCEL, qemu_accels)) starts['accelerator'] = ACCEL audit = [json.loads(l) for l in (ev / 'redfish-audit.jsonl').read_text().splitlines()] - effects = [e for e in audit if e['method'] not in ('GET', 'HEAD')] + # The commission phase's effects were checked at its mark; these are the + # operations' after it. + commission = json.loads((s / 'redfish' / 'commission.json').read_text()) + if commission['onRequestsToTargetA'] != 1: + fail('the commissioning did not boot target A exactly once') + if any('/System-1' not in e['path'] for e in audit if e['method'] not in ('GET', 'HEAD')): + fail('a target other than System-1 received an effect') + effects = [e for e in audit[commission['auditEntries']:] if e['method'] not in ('GET', 'HEAD')] ons = [e for e in effects if e.get('resetType') == 'On'] if len(ons) != 5 or any(not e.get('effect', '').startswith('started') for e in ons) or any('/System-1' not in e['path'] for e in effects): fail('expected exactly five effective On requests, all to System-1, and no other target effect') @@ -428,19 +449,25 @@ def flux_evidence(): for job in jobs: handoff = job['metadata']['labels']['fleet.datumapis.com/handoff'] conditions = sorted([c['type'], c['status'], c.get('reason', '')] for c in job['status'].get('conditions', [])) - if ['Complete', 'True', 'CompletionsReached'] not in conditions: - fail('worker Job not Complete: ' + job['metadata']['name']) job_pods = kget('-n', 'fleet-site', 'get', 'pods', '-l', 'batch.kubernetes.io/controller-uid=' + job['metadata']['uid'])['items'] exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in job_pods] - if exits.count(0) != 1: - fail('worker Job without exactly one successful Pod: ' + job['metadata']['name']) operation = handoffs[handoff]['operation'] + # Dispatch was disabled after the commission phase and enabled again, and + # the graph lifecycle recreates every worker, so kro recreated the + # finished commissioning's Job. It replays a verified no-op, or, once a + # newer operation raised the Device's fence, the site refuses it at exit + # 65 before reading anything, and the Job fails without a retry. + fenced = operation['kind'] == 'DeviceCommissioning' and ['Failed', 'True', 'PodFailurePolicy'] in conditions and exits and set(exits) == {65} + if not fenced and ['Complete', 'True', 'CompletionsReached'] not in conditions: + fail('worker Job not Complete: ' + job['metadata']['name']) + if not fenced and exits.count(0) != 1: + fail('worker Job without exactly one successful Pod: ' + job['metadata']['name']) worker_jobs.append({'job': job['metadata']['name'], 'uid': job['metadata']['uid'], 'operationID': harness.operation_key(operation['kind'], operation['name'], handoffs[handoff]['fence']), 'kind': operation['kind'], 'name': operation['name'], 'fence': handoffs[handoff]['fence'], 'conditions': conditions, 'succeeded': job['status'].get('succeeded', 0), 'failed': job['status'].get('failed', 0), 'pods': [{'uid': p['metadata']['uid'], 'phase': p['status'].get('phase'), 'exitCode': e} for p, e in zip(job_pods, exits)], 'serviceAccount': job['spec']['template']['spec']['serviceAccountName'], 'podReplacementPolicy': job['spec'].get('podReplacementPolicy'), 'podFailurePolicy': job['spec'].get('podFailurePolicy'), 'backoffLimit': job['spec'].get('backoffLimit'), - 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id')}) + 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id'), 'fencedReplay': bool(fenced)}) if REDFISH: # Every Redfish worker that ran: Redfish provider, no hypervisor path. for job in jobs: @@ -451,9 +478,13 @@ def flux_evidence(): if env.get('FLEET_SITE_PROVIDER') != 'redfish' or 'FLEET_LIBVIRT_URI' in env or any('libvirt' in m or 'lab-disks' in m for m in mounts) or any('hostPath' in v for v in pod.get('volumes', [])): fail('a Redfish worker Job had a hypervisor path: ' + job['metadata']['name']) # One kro-created worker Job per admitted operation, at that operation's -# fence, including the installation held at its deadline. +# fence, including the installation held at its deadline, and one for the +# commission phase's commissioning. held_job = (json.loads((s / 'deadline-install.json').read_text())['key'], json.loads((s / 'deadline-hold.json').read_text())['fence']) -if sorted((j['operationID'], j['fence']) for j in worker_jobs) != sorted([(o['operation'], o['fence']) for o in ops] + [held_job]) or any(j['createdBy'] != 'workers' for j in worker_jobs): +if [j['kind'] for j in worker_jobs].count('DeviceCommissioning') != 1: + fail('expected one worker Job for the commissioning, got %s' % [(j['kind'], j['name'], j['fence']) for j in worker_jobs]) +operation_jobs = [j for j in worker_jobs if j['kind'] != 'DeviceCommissioning'] +if sorted((j['operationID'], j['fence']) for j in operation_jobs) != sorted([(o['operation'], o['fence']) for o in ops] + [held_job]) or any(j['createdBy'] != 'workers' for j in worker_jobs): fail('expected one kro-created worker Job per operation at its fence, got %s' % [(j['kind'], j['name'], j['fence'], j['createdBy']) for j in worker_jobs]) pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') pv = kget('get', 'pv', pvc['spec']['volumeName']) diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index f6062f97..c783bfea 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -47,7 +47,7 @@ class Interrupted(Exception): pass DEBIAN = 'debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc' # Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. -REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', +REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'commission', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable', 'tenant-isolation')) + ('multiplane.ErrLocationNotServed',) READINESS_PACKAGES = ('./internal/coordination', './internal/custody', './internal/site/...', './internal/multiplane', './cmd/fleet-multiplane') @@ -402,13 +402,23 @@ def provider_key(item): return operation_key(item['kind'], item['metadata']['name'], item.get('status', {}).get('fence', 0)) +def is_commissioning(operation): + """Whether a site key is a DeviceCommissioning's. The commission phase + runs before any allocation and records its own evidence, so the install + and wipe evidence leaves it out.""" + return operation.startswith('devicecommissioning.') + + def sanitized_operations(store, results=(), redfish=None): - """Each journaled operation in admission order: its site key, fence, kind - (from its step names), steps with their states, and its stored result - phase. Step payloads are never read out.""" + """Each journaled install or wipe in admission order: its site key, fence, + kind (from its step names), steps with their states, and its stored + result phase. Step payloads are never read out. Commissionings are left + out; commissionings() returns them.""" redfish = PROVIDER == 'redfish' if redfish is None else redfish ops = {} for e in (store or {}).get('journal') or []: + if is_commissioning(e['operation']): + continue o = ops.setdefault(e['operation'], {'operation': e['operation'], 'fence': e['fence'], 'steps': []}) o['steps'].append([e['step'], e['state']]) phases = {(operation_key(r['result']['operation']['kind'], r['result']['operation']['name'], r['result']['fence']), r['result']['fence']): r['result'].get('phase') for r in results} @@ -422,6 +432,57 @@ def sanitized_operations(store, results=(), redfish=None): return out +def commissionings(store): + """Each journaled commissioning: its site key, fence and steps.""" + ops = {} + for e in (store or {}).get('journal') or []: + if is_commissioning(e['operation']): + o = ops.setdefault(e['operation'], {'operation': e['operation'], 'fence': e['fence'], 'steps': []}) + o['steps'].append([e['step'], e['state']]) + return list(ops.values()) + + +def commission_digest(store, boot): + """The one finished commissioning in a site store, with digests of its + journal entries (times and payloads included) and of its boot record, + or an error. boot(operation) returns the parsed boot record, or None. A + replay that sent anything would journal a step or touch the record.""" + found = commissionings(store) + if len(found) != 1 or ['burnin-disk-removed', 'Done'] not in found[0]['steps']: + return None, 'expected one finished commissioning, got %s' % found + c = found[0] + entries = [e for e in (store or {}).get('journal') or [] if e['operation'] == c['operation']] + record = boot(c['operation']) + if not record: + return None, 'the commissioning has no boot record' + return dict(c, journalSHA256=hashlib.sha256(json.dumps(entries, sort_keys=True).encode()).hexdigest(), + bootRecordSHA256=hashlib.sha256(json.dumps(record, sort_keys=True).encode()).hexdigest()), None + + +def boot_record_path(operation): + """Where the local VM site stores an operation's boot admission.""" + return device_dir() + '/vmboot/' + key(operation) + '.json' + + +def commission_mark(args): + """After the local VM commission phase: record the commissioning's journal + and boot record, so the evidence phase can prove the Job kro recreates + for it later changed neither.""" + store, _ = site_store(args.state) + + def boot(operation): + code, out, _ = runtime_exec(args.state, 'sh', '-c', "cat '%s' 2>/dev/null || true" % boot_record_path(operation)) + return json.loads(out) if code == 0 and out.strip() else None + mark, error = commission_digest(store, boot) + if error: + print(json.dumps({'error': error})) + return EXIT_FAILED + write_json(pathlib.Path(args.state) / 'commission.json', mark) + write_json(evidence_dir(args.state) / 'commission.json', mark) + print('commission-mark: one finished commissioning; its journal and boot record are recorded') + return 0 + + def past_installer(op): """Whether an install verified its installer phase or began its disk phase.""" return any(n == 'installer-verified' or n.startswith('disk-') for n, _ in op['steps']) @@ -613,6 +674,8 @@ def main(): s.add_argument('--state', required=True) s = sub.add_parser('custody-digest') s.add_argument('--state', required=True) + s = sub.add_parser('commission-mark') + s.add_argument('--state', required=True) s = sub.add_parser('scan') s.add_argument('--state', required=True) s.add_argument('--extra', nargs='*') @@ -629,7 +692,7 @@ def main(): if not a.command or not re.match(r'^[a-z0-9-]+$', a.name): return EXIT_USAGE return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, 'custody-digest': custody_cmd, - 'scan': scan, 'result': result, 'verify': verify}[a.cmd](a) + 'commission-mark': commission_mark, 'scan': scan, 'result': result, 'verify': verify}[a.cmd](a) if __name__ == '__main__': diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 73f8eea4..00e86e1a 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -229,7 +229,10 @@ def record_lifecycle(state, old, new): for key in ('siteStoreSHA256', 'qemuStarts', 'pvcUID', 'pvUID', 'pvReclaimPolicy', 'domains', 'machineA'): if a[key] != b[key]: raise SystemExit('%s changed across Pod/Job lifecycle: %s -> %s' % (key, a[key], b[key])) - if a['machineA'] != {'phase': 'Ready', 'bound': 'True', 'ready': 'True'} or a['qemuStarts'] != 2 or a['domains'] or a['pvReclaimPolicy'] != 'Retain': + # Lab target A carries the commissioning's burn-in boot before the + # install's two; a local VM install has its own domain. + starts = 2 + (json.loads((s / 'redfish' / 'commission.json').read_text())['qemuStartsTargetA'] if REDFISH else 0) + if a['machineA'] != {'phase': 'Ready', 'bound': 'True', 'ready': 'True'} or a['qemuStarts'] != starts or a['domains'] or a['pvReclaimPolicy'] != 'Retain': raise SystemExit('unexpected lifecycle baseline: %s' % a) for d, uids in a['sitePods'].items(): if set(uids) & set(b['sitePods'][d]) or len(b['sitePods'][d]) != 1: diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 75e655ce..4e223e2f 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -39,7 +39,7 @@ def wait(fn,seconds,what): d=root/role;ns='milo-'+role if not d.exists(): d.mkdir(mode=0o700) - who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff') if role=='provider' else ()) + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator') if role=='provider' else ()) tokens={r:secrets.token_hex(32) for r in who} (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k=='bootstrap' else 'fleet-local') for k,v in tokens.items())+'\n') run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) @@ -87,10 +87,12 @@ def wait(fn,seconds,what): # coordinator's namespace. A project API runs no namespace controller, so # the namespace is never deleted. apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'fleet-rules'}}) - # The Metal provider records allocations and creates installations; it - # reads custody and Devices only to skip taken capacity. + # The Metal provider records allocations and creates installations. It + # evaluates capacity from custody and commissioning evidence, and never + # writes capacity status. rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}] # The coordinator rules mirror config/components/device-operations/roles/ # coordinator.yaml: it lists and settles every registered operation kind. components={ @@ -100,6 +102,16 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], + # The capacity projector is the only writer of capacity status. + 'projector':[{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}], + # Three people commission a server: one writes the plan, another approves + # it, and an operator commissions the Device. + 'plan-author':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans'],'verbs':['get','create']}], + 'plan-approver':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','create']}], + 'operator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecommissioningplans'],'verbs':['get']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissionings'],'verbs':['get','list','create']}], + # A capacity operator, not the commissioning operator, enables capacity. + 'capacity-operator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','update']}], 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}], # Staff create recoveries and read inventory and custody, nothing else. # The coordinator treats every unconfigured creator as staff. diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 5d667530..9cde2d8e 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -328,7 +328,8 @@ def lost_response(s): break time.sleep(2) ops = installs(s) - ons = [e for e in mutating(audit(s), TARGET_A['system']) if e.get('resetType') == 'On' and e.get('effect', '').startswith('started')] + # The commissioning's burn-in boot came before this install. + ons = [e for e in mutating(commission_audit(s), TARGET_A['system']) if e.get('resetType') == 'On' and e.get('effect', '').startswith('started')] journaled = power_ons(ops[0]) if len(ops) == 1 else {} if len(ops) != 1 or not done(ops[0], 'disk-power-on') or len(ons) != 2 or journaled != {'installer': 'Done', 'disk': 'Done'}: die('recovery after the lost response repeated or did not observe the boot: %d effective On requests, journaled power-on %s' % (len(ons), journaled)) @@ -405,6 +406,30 @@ def isolation(s): ('target A disk independently hashes as all zeroes after the final cleanup' if released else 'target A stays installed: this group runs no release')) +def commission_mark(s): + """After the commission phase: the commissioning booted lab target A once + over Redfish, its burn-in printed one passed receipt, and no other target + received an effect. Later counts start at this mark.""" + base = json.loads((s / 'redfish-baseline.json').read_text()) + entries = audit(s) + window = mutating(entries[base['auditEntries']:]) + ons = [e for e in window if e.get('resetType') == 'On' and e.get('effect', '').startswith('started')] + other = [e for e in window if not e['path'].rstrip('/').startswith('/redfish/v1/Systems/' + TARGET_A['system'])] + burnin = [l.rsplit(':', 1)[1] for l in console_lines(s, 'target-a.log') if l.startswith('FLEET-BURNIN:')] + record = {'observedAt': now(), 'auditEntries': len(entries), 'onRequestsToTargetA': len(ons), 'otherTargetEffects': len(other), + 'qemuStartsTargetA': qemu_starts(s, TARGET_A['domain']), 'qemuStartsTargetB': qemu_starts(s, TARGET_B['domain']), 'burnInResults': burnin} + if len(ons) != 1 or other or record['qemuStartsTargetA'] != 1 or record['qemuStartsTargetB'] or burnin != ['passed']: + die('the commissioning did not boot target A exactly once with one passed burn-in: %s' % record) + write(s / 'redfish' / 'commission.json', record) + write(s / 'evidence' / 'redfish-commission.json', record) + print('redfish-commission: the commissioning booted lab target A once over the emulator and its burn-in passed; target B untouched') + + +def commission_audit(s): + """The BMC audit after the commission phase.""" + return audit(s)[json.loads((s / 'redfish' / 'commission.json').read_text())['auditEntries']:] + + def audit_mark(s): """Record the BMC audit's length for a later audit-unchanged.""" (s / 'redfish' / 'audit-mark').write_text('%d\n' % len(audit(s))) @@ -422,4 +447,4 @@ def audit_unchanged(s): step, state = sys.argv[1], pathlib.Path(sys.argv[2]) {'enroll': enroll, 'baseline': baseline, 'discovery-faults': discovery_faults, 'arm-lost-response': arm_lost_response, 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation, - 'audit-mark': audit_mark, 'audit-unchanged': audit_unchanged}[step](state) + 'audit-mark': audit_mark, 'audit-unchanged': audit_unchanged, 'commission-mark': commission_mark}[step](state) diff --git a/hack/multiplane/reflection-faults.py b/hack/multiplane/reflection-faults.py index 580b68e7..9facdf6e 100755 --- a/hack/multiplane/reflection-faults.py +++ b/hack/multiplane/reflection-faults.py @@ -16,6 +16,8 @@ def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=20s',*args],input=input,text=True,capture_output=True,check=True).stdout def handoff():return json.loads(k(hub,'-n','fleet-coordination','get','machineallocationhandoff',name,'-o','json')) items=json.loads(k(hub,'-n','fleet-coordination','get','machineallocationhandoffs','-l','coordination.fleet.datumapis.com/role=assignment','-o','json'))['items'] +# The commission phase's commissioning stays delivered; the faults target the install. +items=[i for i in items if json.loads(i['spec']['assignmentJSON'])['operation']['kind']!='DeviceCommissioning'] if len(items)!=1:raise SystemExit('run reflection faults after install and before the release wipe') obj=items[0];original=obj.get('status');name=obj['metadata']['name'] if obj['metadata'].get('labels',{}).get(ANSWERED)!='true':raise SystemExit('the install result is not answered yet') diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index c052d5df..4d33a439 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -37,8 +37,20 @@ wait_api() { echo "API did not recover: $(basename "$1")" >&2; return 1 } assignments=coordination.fleet.datumapis.com/role=assignment +# Delivered assignments other than the commission phase's commissioning, +# which stays delivered for the rest of the run: one "name phase" line each, +# with the result phase the observer published, if any. +operation_handoffs() { + cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o json | python3 -c ' +import json,sys +for h in json.load(sys.stdin)["items"]: + if json.loads(h["spec"]["assignmentJSON"])["operation"]["kind"] != "DeviceCommissioning": + print(h["metadata"]["name"], ((h.get("status") or {}).get("observation") or {}).get("result", {}).get("phase", ""))' +} # The site results the observer publishes: only it writes handoff status. -local_phase() { cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o jsonpath='{.items[*].status.observation.result.phase}'; } +local_phase() { operation_handoffs | awk '{print $2}' | tr -s '\n' ' ' | sed 's/^ *//;s/ *$//'; } +# The next Flux source revision number. +next_revision() { python3 -c 'import json,sys; print(max(r["revision"] for r in json.load(open(sys.argv[1]))) + 1)' "$state/flux-revisions.json"; } # Provider-project custody digest: the spec, phase and fence of every custody # record, operation and allocation; the records never leave memory. custody_digest() { "${harness[@]}" custody-digest --state "$state"; } @@ -112,7 +124,7 @@ case "$step" in audit_mark "$host" tenant-isolation --config "$state/acceptance.json" [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for an unheld tenant' >&2; exit 1; } - [[ -z $(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o name) ]] || { echo 'an assignment was delivered for an unheld tenant' >&2; exit 1; } + [[ -z $(operation_handoffs) ]] || { echo 'an assignment was delivered for an unheld tenant' >&2; exit 1; } audit_unchanged ;; import-inert) @@ -193,9 +205,31 @@ JSON site_restore fleet-site-observer scenario rebuild-verified "$state" ;; + commission-dispatch) + # The commission phase needs a site worker before any allocation exists, so + # one source revision enables dispatch for it and the next disables it + # again: the install below is still delivered before any worker Job. + flux publish "$state" --revision "$(next_revision)" --site dispatch --purpose 'enable dispatch for commissioning' --cluster cell --cluster hub --cluster platform --timeout 600 >/dev/null + [[ $(site get handoffdispatcher dispatcher -o jsonpath='{.spec.dispatch}') == true ]] || { echo 'commissioning dispatch revision not applied' >&2; exit 1; } + printf 'commission-dispatch: cell Flux enabled dispatch for the commissioning before any allocation\n' + ;; + commission-settle) + # Disable dispatch again. kro prunes the commissioning's finished worker + # Job; its delivered handoff stays, answered, for the rest of the run. + flux publish "$state" --revision "$(next_revision)" --site off --purpose 'disable dispatch after commissioning' --cluster cell --cluster hub --cluster platform --timeout 600 >/dev/null + [[ $(site get handoffdispatcher dispatcher -o jsonpath='{.spec.dispatch}') == false ]] || { echo 'dispatch-off revision not applied' >&2; exit 1; } + for _ in $(seq 1 180); do [[ -z $(site get jobs -o name) ]] && break; sleep 1; done + [[ -z $(site get jobs -o name) ]] || { echo 'kro did not prune the commissioning worker Job' >&2; exit 1; } + [[ -z $(operation_handoffs) ]] || { echo 'an assignment other than the commissioning was delivered before any allocation' >&2; exit 1; } + cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o json | python3 -c ' +import json,sys +kinds=[json.loads(h["spec"]["assignmentJSON"])["operation"]["kind"] for h in json.load(sys.stdin)["items"]] +if kinds != ["DeviceCommissioning"]: raise SystemExit("expected the one delivered commissioning, got %s" % kinds)' + printf 'commission-settle: dispatch disabled again; kro pruned the commissioning worker Job; only the commissioning was delivered\n' + ;; await-delivery) for _ in $(seq 1 120); do - names=$(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o jsonpath='{.items[*].metadata.name}') + names=$(operation_handoffs | awk '{print $1}') [[ -z $names ]] || break sleep 1 done @@ -203,7 +237,9 @@ JSON [[ $(wc -w <<<"$names") -eq 1 ]] || { echo 'more than one delivered assignment' >&2; exit 1; } printf '%s\n' "$names" > "$state/install-handoff" [[ -z $(local_phase) ]] || { echo 'cell status existed before any worker started' >&2; exit 1; } - site wait --for=jsonpath='{.status.deliveredHandoffs}'=1 handoffdispatcher/dispatcher --timeout=120s >/dev/null + # kro also counts the commission phase's delivered commissioning. + delivered=$(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o name | wc -l | tr -d ' ') + site wait --for=jsonpath='{.status.deliveredHandoffs}'="$delivered" handoffdispatcher/dispatcher --timeout=120s >/dev/null [[ -z $(site get jobs -o name) ]] || { echo 'worker Job exists before dispatch' >&2; exit 1; } printf 'delivery: Karmada delivered exactly one retained assignment; kro observed it; no worker Job before dispatch\n' ;; @@ -219,7 +255,7 @@ JSON dispatch) # Dispatch is a source revision, reconciled by the cell's own Flux from the # registry while the hub is paused; kro then creates per-operation RBAC and the Job. - flux publish "$state" --revision 3 --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 >/dev/null + flux publish "$state" --revision "$(next_revision)" --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 >/dev/null [[ $(site get handoffdispatcher dispatcher -o jsonpath='{.spec.dispatch}') == true ]] || { echo 'dispatch revision not applied' >&2; exit 1; } name=$(cat "$state/install-handoff") for _ in $(seq 1 120); do site get job "w-$name" >/dev/null 2>&1 && break; sleep 1; done diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 0bae3cd1..8ac5c6b0 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -41,10 +41,18 @@ if tool == 'docker': if tool == 'kubectl' and 'exec' in a and 'deploy/fleet-site-runtime' in a: if a[-1].endswith('/state.json'): stage = os.environ.get('FAKE_STAGE', 'installer-start') + if stage == 'commissioned': + steps = ['burnin-disk', 'burnin-network', 'burnin-start', 'burnin-verified', 'burnin-network-off', 'burnin-disk-removed'] + print(json.dumps({'device': 'fleet-provider/synthetic-device-central-01', 'fence': 1, 'stopped': 1, + 'journal': [{'operation': 'devicecommissioning.commission-1.1', 'fence': 1, 'step': s, 'state': 'Done', 'at': '2026-01-01T00:00:00Z'} for s in steps]})); sys.exit(0) steps = {'prepared': ['prepare-disk'], 'installer-start': ['prepare-disk', 'installer-network', 'installer-start'], 'disk-start': ['prepare-disk', 'installer-network', 'installer-start', 'installer-verified', 'disk-network-off', 'disk-start']}[stage] print(json.dumps({'device': 'fleet-provider/synthetic-device-central-01', 'fence': 3, 'stopped': 3, 'journal': [{'operation': 'install-op-1', 'fence': 3, 'step': s, 'state': 'Done', 'at': '2026-01-01T00:00:00Z', 'payload': {'note': 'R' * 64}} for s in steps]})); sys.exit(0) + if '/vmboot/' in a[-1]: + if os.environ.get('FAKE_BOOT_RECORD', 'present') == 'present': + print(json.dumps({'operation': 'devicecommissioning.commission-1.1', 'fence': 1, 'receipt': 'r' * 64, 'token': 'T' * 64, 'closed': True, 'mode': 'burnin'})) + sys.exit(0) if 'virsh' in a: import hashlib print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:16]); sys.exit(0) @@ -83,7 +91,7 @@ with tempfile.TemporaryDirectory() as tmp: d = pathlib.Path(tempfile.mkdtemp(dir=tmp)); d.chmod(0o700); return d good_root = tmp / 'good'; (good_root / 'cmd/fleet-multiplane').mkdir(parents=True) - markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', + markers = ['seed', 'commission', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable', 'tenant-isolation'] (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed "redfish-probe" redfish.NewPinnedClient') bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) @@ -206,6 +214,26 @@ with tempfile.TemporaryDirectory() as tmp: check('wait-stage bounded', r.returncode == 4, r.stdout) out = run(['journal', '--state', str(obs)]).stdout check('journal sanitized', 'R' * 64 not in out and 'install-op-1' in out, out) + # The commission mark records the one finished commissioning's journal and + # boot record as digests; the evidence phase compares them after replay. + mark = state() + r = run(['commission-mark', '--state', str(mark)]) + check('commission-mark refuses a store without a finished commissioning', r.returncode == 1, r.stdout) + r = run(['commission-mark', '--state', str(mark)], {'FAKE_STAGE': 'commissioned', 'FAKE_BOOT_RECORD': 'missing'}) + check('commission-mark refuses a commissioning without a boot record', r.returncode == 1, r.stdout) + r = run(['commission-mark', '--state', str(mark)], {'FAKE_STAGE': 'commissioned'}) + recorded = json.loads((mark / 'commission.json').read_text()) if r.returncode == 0 else {} + check('commission-mark records the commissioning', recorded.get('operation') == 'devicecommissioning.commission-1.1' and recorded.get('fence') == 1 + and len(recorded.get('journalSHA256', '')) == 64 and len(recorded.get('bootRecordSHA256', '')) == 64, r.stdout + r.stderr) + check('commission-mark evidence holds no boot token', 'T' * 64 not in (mark / 'evidence/commission.json').read_text() if recorded else False) + sys.path.insert(0, str(root / 'hack/multiplane')) + import harness as h + store = {'journal': [{'operation': 'devicecommissioning.c.1', 'fence': 1, 'step': 'burnin-disk-removed', 'state': 'Done', 'at': '2026-01-01T00:00:00Z'}]} + before, _ = h.commission_digest(store, lambda op: {'closed': True}) + replayed = {'journal': [dict(store['journal'][0], at='2026-01-01T00:05:00Z')]} + check('a replayed step changes the commission digest', h.commission_digest(replayed, lambda op: {'closed': True})[0] != before) + check('a touched boot record changes the commission digest', h.commission_digest(store, lambda op: {'closed': True, 'open': True})[0] != before) + check('an unchanged commissioning digests the same', h.commission_digest(store, lambda op: {'closed': True})[0] == before) calls = [json.loads(l) for l in trace.read_text().splitlines()] check('provider observation only through the cell API', not any(c[0] == 'docker' and 'exec' in c for c in calls) and any(c[0] == 'kubectl' and 'exec' in c and 'deploy/fleet-site-runtime' in c for c in calls)) @@ -332,7 +360,7 @@ with tempfile.TemporaryDirectory() as tmp: for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['custody-crd-rules', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'tenant-isolation', 'admit-install', 'await-delivery', 'partition', 'hold-installer', 'dispatch', 'interrupt-pod', 'interrupt-job', 'release-installer', 'resume', + order = ['custody-crd-rules', 'import-inert', 'staff-access', 'commission-dispatch', 'commission', 'commission-settle', 'allocate', 'verify-contention', 'tenant-isolation', 'admit-install', 'await-delivery', 'partition', 'hold-installer', 'dispatch', 'interrupt-pod', 'interrupt-job', 'release-installer', 'resume', 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', 'reflection-faults', 'release', 'release-status-a', 'reuse', 'reuse-status', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', @@ -356,7 +384,7 @@ with tempfile.TemporaryDirectory() as tmp: 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', 'rebuild', 'wrong-location', 'boot-denials'], str(blocks.get('release'))) for name in order: - if name in ('custody-crd-rules', 'allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', + if name in ('custody-crd-rules', 'commission', 'allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'): continue check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index c017cab7..7c6bcbf6 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -106,6 +106,13 @@ run_phase() { kubectl --context "$context" -n fleet-system logs "job/$run" } +# Commissioning, not a fixture, makes the server Prepared, Healthy and +# Available. The projector is the only status writer. +run_phase commission fleet-smoke-commission-run +test "$(kubectl --context "$context" -n fleet-provider get devicecommissionings -o jsonpath='{range .items[*]}{.status.phase}{"\n"}{end}')" = "Succeeded" +test "$(kubectl --context "$context" -n fleet-provider get machinecapacity central1-baremetal-01 -o jsonpath='{.status.conditions[?(@.type=="Available")].status}')" = "True" +test "$(kubectl --context "$context" auth can-i update machinecapacities/status --as=system:serviceaccount:fleet-system:fleet-standalone-smoke -n fleet-provider)" = "no" +test "$(kubectl --context "$context" auth can-i create devicecommissioningplanapprovals --as=system:serviceaccount:fleet-system:fleet-plan-author -n fleet-provider)" = "no" run_phase allocate fleet-smoke-allocate-run kubectl --context "$context" get machines -A test "$(kubectl --context "$context" -n fleet-project-a get machine -o name)" = "machine.metal.datumapis.com/allocation" @@ -151,7 +158,7 @@ for project in fleet-project-a fleet-project-b; do fi done done - for secret in fleet-simulator-runtime fleet-custody-coordinator-token fleet-release-controller-token; do + for secret in fleet-simulator-runtime fleet-custody-coordinator-token fleet-release-controller-token fleet-capacity-projector-token fleet-plan-author-token fleet-plan-approver-token fleet-commissioning-operator-token; do if [ "$(kubectl --context "$context" auth can-i get "secret/$secret" --as="$subject" -n fleet-system)" != "no" ]; then echo "$subject unexpectedly has access to $secret" >&2 exit 1 diff --git a/hack/synthetic-staging-validator.go b/hack/synthetic-staging-validator.go index b0db3a32..09117dd2 100644 --- a/hack/synthetic-staging-validator.go +++ b/hack/synthetic-staging-validator.go @@ -120,6 +120,7 @@ func main() { } require(mountsSecret(manager.Spec.Template.Spec, "/var/run/fleet/coordinator", "fleet-custody-coordinator-client-cert"), "the coordinator's client certificate must resolve to its external Secret") require(mountsSecret(manager.Spec.Template.Spec, "/var/run/fleet/release", "fleet-release-controller-client-cert"), "the release controller's client certificate must resolve to its external Secret") + require(has(m.Args, "--synthetic-projector-client-cert-dir=/var/run/fleet/projector") && mountsSecret(manager.Spec.Template.Spec, "/var/run/fleet/projector", "fleet-capacity-projector-client-cert"), "the capacity projector needs its own Milo client certificate") var enrollment core.ConfigMap read("ConfigMap/fleet-synthetic-site-enrollment", &enrollment) for _, pod := range []core.PodSpec{manager.Spec.Template.Spec, provider.Spec.Template.Spec} { diff --git a/hack/validate-standalone-render.sh b/hack/validate-standalone-render.sh index e61d758c..65a553e2 100755 --- a/hack/validate-standalone-render.sh +++ b/hack/validate-standalone-render.sh @@ -15,14 +15,15 @@ require_count() { fi } -require_count 6 'runAsUser: 65532' -require_count 6 'runAsGroup: 65532' -require_count 6 'fsGroup: 65532' -require_count 11 'defaultMode: 288' -require_count 6 'imagePullPolicy: Never' -require_count 4 'suspend: true' +require_count 7 'runAsUser: 65532' +require_count 7 'runAsGroup: 65532' +require_count 7 'fsGroup: 65532' +require_count 17 'defaultMode: 288' +require_count 7 'imagePullPolicy: Never' +require_count 5 'suspend: true' require_count 1 'name: fleet-smoke-reinstall' require_count 1 '--phase=reinstall' +require_count 1 '--phase=commission' require_count 1 'fsGroupChangePolicy: OnRootMismatch' require_count 1 'mountPath: /var/lib/fleet' require_count 1 'volumeClaimTemplates:' diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 9285255d..deefd850 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -21,7 +21,6 @@ import ( "strings" apierrors "k8s.io/apimachinery/pkg/api/errors" - apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" @@ -104,6 +103,14 @@ type Quota interface { // to the digest of the policy record pinned at allocation. type CleaningPolicies func(name string) (string, error) +// Offers evaluates, from live inputs, whether a capacity may be offered and +// the hardware its latest passed commissioning inspected. The capacity +// projector implements it. The allocator never reads capacity conditions, so +// editing status cannot make a server allocatable. +type Offers interface { + Offer(ctx context.Context, capacity *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) +} + // Request is one Machine's allocation request, already admitted. type Request struct { Machine Machine @@ -129,6 +136,8 @@ type Allocator struct { Namespace string Quota Quota Cleaning CleaningPolicies + // Capacity decides which capacity may be offered. + Capacity Offers // BootInterface and TargetDisks are pinned on each allocation. BootInterface string TargetDisks []string @@ -190,12 +199,12 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac tried[allocation.Spec.MachineCapacityRef.Name] = true continue } - candidate, device, err := a.candidate(ctx, request, tried) + candidate, device, hardware, err := a.candidate(ctx, request, tried) if err != nil { return nil, err } tried[candidate.Name] = true - allocation, err = a.newAllocation(request, candidate, device, claim) + allocation, err = a.newAllocation(request, candidate, device, hardware, claim) if err != nil { return nil, err } @@ -230,58 +239,76 @@ func (a *Allocator) claim(ctx context.Context, allocation *fleetv1.MachineAlloca return false, nil } -// candidate returns the first eligible capacity, by name, whose Device -// custody looks free. Custody decides; this only skips Devices that are -// visibly taken. -func (a *Allocator) candidate(ctx context.Context, request Request, tried map[string]bool) (*fleetv1.MachineCapacity, *inventory.Device, error) { +// candidate returns the first capacity, by name, that the projection offers +// for the profile and whose Device custody looks free, with the hardware its +// commissioning inspected. Custody decides; this only skips Devices that are +// visibly taken. The cheap per-capacity reads, the Device's identity and its +// custody, come before the evaluation, which lists the provider project. A +// capacity whose reads or evaluation fail is skipped; the error is returned +// only when no capacity is offered. +func (a *Allocator) candidate(ctx context.Context, request Request, tried map[string]bool) (*fleetv1.MachineCapacity, *inventory.Device, fleetv1.Hardware, error) { selector, err := metav1.LabelSelectorAsSelector(&request.Class.Spec.Capacity.MachineCapacities.Selector) if err != nil { - return nil, nil, fmt.Errorf("invalid MachineClass selector: %w", err) + return nil, nil, fleetv1.Hardware{}, fmt.Errorf("invalid MachineClass selector: %w", err) } var capacities fleetv1.MachineCapacityList if err := a.Provider.List(ctx, &capacities, client.InNamespace(a.Namespace), client.MatchingLabelsSelector{Selector: selector}); err != nil { - return nil, nil, err + return nil, nil, fleetv1.Hardware{}, err } sort.Slice(capacities.Items, func(i, j int) bool { return capacities.Items[i].Name < capacities.Items[j].Name }) + if a.Capacity == nil { + return nil, nil, fleetv1.Hardware{}, errors.New("allocation: no capacity evaluator") + } + // One pass reads each list the evaluation needs once, when the + // evaluator supports it, instead of once per capacity. + offer := a.Capacity.Offer + if passes, ok := a.Capacity.(interface { + Pass() func(context.Context, *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) + }); ok { + offer = passes.Pass() + } + var failed error for index := range capacities.Items { capacity := &capacities.Items[index] - if tried[capacity.Name] || !Eligible(capacity, request.Profile.Spec) || !selector.Matches(labels.Set(capacity.Labels)) { + if tried[capacity.Name] || capacity.Spec.AllocationPolicy != "Enabled" || !capacity.DeletionTimestamp.IsZero() || !selector.Matches(labels.Set(capacity.Labels)) { continue } device := &inventory.Device{} if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: capacity.Spec.DeviceRef.Name}, device); apierrors.IsNotFound(err) { continue } else if err != nil { - return nil, nil, err + failed = errors.Join(failed, fmt.Errorf("capacity %s: %w", capacity.Name, err)) + continue + } + // A server without a hardware ID never backs capacity, whatever the + // evaluation would say. + if inventory.CapacityBackingError(device) != nil { + continue } state := &ops.DeviceCustody{} if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: device.Name}, state); apierrors.IsNotFound(err) { continue } else if err != nil { - return nil, nil, err + failed = errors.Join(failed, fmt.Errorf("capacity %s: %w", capacity.Name, err)) + continue } if !Free(state, device) { continue } - return capacity, device, nil - } - return nil, nil, ErrInsufficientCapacity -} - -// Eligible reports whether a capacity may be offered for the profile: its -// allocation policy is enabled, its Prepared, Healthy and Available -// conditions are current, and its hardware matches exactly. -func Eligible(capacity *fleetv1.MachineCapacity, profile fleetv1.MachineProfileSpec) bool { - if capacity.Spec.AllocationPolicy != "Enabled" || !capacity.DeletionTimestamp.IsZero() { - return false - } - for _, conditionType := range []string{"Prepared", "Healthy", "Available"} { - condition := apiMeta.FindStatusCondition(capacity.Status.Conditions, conditionType) - if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != capacity.Generation { - return false + offered, hardware, err := offer(ctx, capacity) + if err != nil { + failed = errors.Join(failed, fmt.Errorf("capacity %s: %w", capacity.Name, err)) + continue } + if !offered || !matches(request.Profile.Spec, hardware) { + continue + } + return capacity, device, hardware, nil + } + if failed != nil { + return nil, nil, fleetv1.Hardware{}, failed } - return matches(profile, capacity.Status.Hardware) + return nil, nil, fleetv1.Hardware{}, ErrInsufficientCapacity } // Free reports whether custody shows the Device free: Verified, for this @@ -292,7 +319,7 @@ func Free(state *ops.DeviceCustody, device *inventory.Device) bool { spec.RecoveryHold == nil && spec.ActiveOperation == nil && inventory.LifecycleOf(device) == inventory.DeviceActive } -func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapacity, device *inventory.Device, claim string) (*fleetv1.MachineAllocation, error) { +func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapacity, device *inventory.Device, hardware fleetv1.Hardware, claim string) (*fleetv1.MachineAllocation, error) { if a.Cleaning == nil { return nil, errors.New("allocation: no cleaning policy resolver") } @@ -323,7 +350,7 @@ func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapa CPU: request.Profile.Spec.CPU, Memory: request.Profile.Spec.Memory, }, - Hardware: capacity.Status.Hardware, + Hardware: hardware, Authority: request.Authority, CleaningPolicyDigest: digest, BootInterface: a.BootInterface, diff --git a/internal/allocation/candidate_test.go b/internal/allocation/candidate_test.go new file mode 100644 index 00000000..90ebacfd --- /dev/null +++ b/internal/allocation/candidate_test.go @@ -0,0 +1,99 @@ +package allocation + +import ( + "context" + "errors" + "fmt" + "testing" + + 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" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +// offersExcept offers every capacity but those it fails, and records which +// capacities it evaluated. +type offersExcept struct { + fail map[string]bool + evaluated []string +} + +func (o *offersExcept) Offer(ctx context.Context, capacity *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) { + o.evaluated = append(o.evaluated, capacity.Name) + if o.fail[capacity.Name] { + return false, fleetv1.Hardware{}, errors.New("the evaluation could not read its inputs") + } + return offersAll{}.Offer(ctx, capacity) +} + +// candidates is three capacities, a to c, each backed by its own identified +// Device. held names the Devices whose custody is taken. +func candidates(t *testing.T, held ...string) (client.Client, Request) { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{inventory.AddToScheme, ops.AddToScheme, fleetv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + taken := map[string]bool{} + for _, name := range held { + taken[name] = true + } + var objects []client.Object + for index, name := range []string{"a", "b", "c"} { + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-" + name, Namespace: namespace, UID: types.UID(uid(index + 1))}, + Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-" + name, SystemUUID: uid(100 + index)}}} + holder := ops.Holder{Type: ops.HolderNone} + if taken[device.Name] { + holder = ops.Holder{Type: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: "allocation-example"}} + } + state := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, + Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name}, State: ops.CustodyVerified, Holder: holder}} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, + Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: device.Name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} + objects = append(objects, device, state, capacity) + } + class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class-example"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{ + MachineCapacities: fleetv1.MachineSelector{Namespace: namespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} + profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build(), Request{Class: class, Profile: profile} +} + +// One capacity whose evaluation fails does not stop the allocator from +// selecting the next; the error surfaces only when nothing is offered. +func TestACapacityThatFailsEvaluationIsSkipped(t *testing.T) { + provider, request := candidates(t) + offers := &offersExcept{fail: map[string]bool{"capacity-a": true}} + allocator := &Allocator{Provider: provider, Namespace: namespace, Capacity: offers} + selected, _, _, err := allocator.candidate(context.Background(), request, map[string]bool{}) + if err != nil || selected == nil || selected.Name != "capacity-b" { + t.Fatalf("selected %v, %v; want capacity-b", selected, err) + } + + offers = &offersExcept{fail: map[string]bool{"capacity-a": true, "capacity-b": true, "capacity-c": true}} + allocator.Capacity = offers + if _, _, _, err := allocator.candidate(context.Background(), request, map[string]bool{}); err == nil || errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("every evaluation failed, got %v; want the evaluation error", err) + } +} + +// The evaluation, which lists the provider project, runs only for a +// capacity whose Device is identified and whose custody is free. +func TestTheAllocatorEvaluatesOnlyFreeCapacity(t *testing.T) { + provider, request := candidates(t, "server-a", "server-b") + offers := &offersExcept{} + allocator := &Allocator{Provider: provider, Namespace: namespace, Capacity: offers} + selected, _, _, err := allocator.candidate(context.Background(), request, map[string]bool{}) + if err != nil || selected == nil || selected.Name != "capacity-c" { + t.Fatalf("selected %v, %v; want capacity-c", selected, err) + } + if fmt.Sprint(offers.evaluated) != "[capacity-c]" { + t.Fatalf("evaluated %v; want only the free capacity-c", offers.evaluated) + } +} diff --git a/internal/allocation/capacity_test.go b/internal/allocation/capacity_test.go new file mode 100644 index 00000000..c38a820c --- /dev/null +++ b/internal/allocation/capacity_test.go @@ -0,0 +1,157 @@ +package allocation + +import ( + "errors" + "testing" + + 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/custody" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// TestOnlyEvidenceOffersCapacity commissions a server, fails it on a second +// commissioning, and then edits its status to claim it is Available. The +// projector withdraws the offer and the allocator refuses the server. +func TestOnlyEvidenceOffersCapacity(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + e.until("the projector writes Available", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable) + return available != nil && available.Status == metav1.ConditionTrue && capacity.Status.Hardware.CPU.Cores == 2 + }) + + // The server reports other hardware, so commissioning it again fails. + target := e.enrollment[namespace+"/"+device.Name] + changed := *target.Hardware + changed.CPU.Cores = 4 + target.Hardware = &changed + e.enrollment[namespace+"/"+device.Name] = target + operation, err := custody.NewCommissioning(device, e.plan, ops.Creator{Username: "operator@example.com", UID: uid(805)}, "recommission") + if err != nil { + t.Fatal(err) + } + e.create(operation) + e.until("the capacity is withdrawn", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + prepared := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionPrepared) + return prepared != nil && prepared.Reason == "CommissioningFailed" && capacity.Status.Hardware.CPU.Cores == 0 + }) + + // Nobody can offer it by editing status. + for _, kind := range []string{custody.ConditionPrepared, custody.ConditionHealthy, custody.ConditionAvailable} { + apiMeta.SetStatusCondition(&capacity.Status.Conditions, metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: "Edited", ObservedGeneration: capacity.Generation}) + } + capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}} + if err := e.admin.Status().Update(e.ctx, capacity); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("an edited status offered the server: %v", err) + } + // The projector restores the derived status on its next pass. + if err := e.loop.Pass(e.ctx); err != nil { + t.Logf("pass: %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + if available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable); available == nil || available.Status != metav1.ConditionFalse { + t.Fatalf("the projector kept the edited status: %+v", capacity.Status.Conditions) + } +} + +// TestADuplicateDeviceWithdrawsTheOffer records a second Device with the +// first one's serial number after its capacity is offered. +func TestADuplicateDeviceWithdrawsTheOffer(t *testing.T) { + e := startEnv(t) + device := e.server(1) + copied := *device + copied.ObjectMeta = metav1.ObjectMeta{Name: "server-example-duplicate", Namespace: namespace} + copied.Spec.Identity.SystemUUID = uid(999) + copied.Status = device.Status + copied.Spec.ClaimRef.Name = "claim-duplicate" + e.create(&copied) + offered, _, err := e.projector.Offer(e.ctx, e.capacity(device.Name)) + if err != nil || offered { + t.Fatalf("a duplicate serial left the capacity offered: %v", err) + } + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("the allocator offered a server with a duplicate: %v", err) + } +} + +// TestARegressionWithdrawsTheNextOffer commissions a server, stops the +// projector from writing status, and then regresses its commissioning: a +// new run that fails, or a plan that replaces the one it passed under. The +// written status still says Available, but the next Offer reads live +// evidence, so it is withdrawn and the allocator refuses the server, with +// no projector pass in between. +func TestARegressionWithdrawsTheNextOffer(t *testing.T) { + for name, regress := range map[string]func(e *env, device *inventory.Device){ + "a new failed run": func(e *env, device *inventory.Device) { + target := e.enrollment[namespace+"/"+device.Name] + changed := *target.Hardware + changed.CPU.Cores = 4 + target.Hardware = &changed + e.enrollment[namespace+"/"+device.Name] = target + operation, err := custody.NewCommissioning(device, e.plan, ops.Creator{Username: "operator@example.com", UID: uid(805)}, "recommission") + if err != nil { + t.Fatal(err) + } + e.create(operation) + e.until("the new run ends with a Failed verdict", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + }, + "a replaced plan": func(e *env, _ *inventory.Device) { + plan := &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan-v2", Namespace: namespace}, Spec: e.plan.Spec} + plan.Spec.Supersedes = []string{e.plan.Name} + e.create(plan) + approval, err := custody.NewApproval(plan, ops.Creator{Username: "plan-approver@example.com", UID: uid(804)}) + if err != nil { + t.Fatal(err) + } + e.create(approval) + }, + } { + t.Run(name, func(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + e.until("the projector writes Available", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable) + return available != nil && available.Status == metav1.ConditionTrue + }) + e.loop.Capacity = nil + regress(e, device) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + if available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable); available == nil || available.Status != metav1.ConditionTrue { + t.Fatalf("status changed without a projector pass: %+v", capacity.Status.Conditions) + } + if offered, _, err := e.projector.Offer(e.ctx, capacity); err != nil || offered { + t.Fatalf("the next Offer after %s: %v %v", name, offered, err) + } + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("the allocator offered the server after %s: %v", name, err) + } + }) + } +} diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go index bd2815ec..f50804d9 100644 --- a/internal/allocation/flow_test.go +++ b/internal/allocation/flow_test.go @@ -161,7 +161,7 @@ func TestAnAllocationThatLostItsDeviceIsReplaced(t *testing.T) { } // A crash left the second Machine's allocation naming the taken Device, // before it claimed custody. - stale, err := e.allocator.newAllocation(e.request(2), e.capacity(taken.Name), taken, "") + stale, err := e.allocator.newAllocation(e.request(2), e.capacity(taken.Name), taken, fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 0079bf7e..7d662aea 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "go.datum.net/fleet/internal/capacity" + "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -55,6 +57,8 @@ type env struct { enrollment fixture.Enrollment class *fleetv1.MachineClass profile *fleetv1.MachineProfile + projector *capacity.Projector + plan *ops.DeviceCommissioningPlan } func scheme(t *testing.T) *runtime.Scheme { @@ -102,7 +106,7 @@ func startEnv(t *testing.T) *env { t.Fatal(err) } 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{}}, Poll: 20 * time.Millisecond} + 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, e.store, runner.Results, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) @@ -118,15 +122,35 @@ func startEnv(t *testing.T) *env { 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}}, }}} - e.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: namespace, + e.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: namespace, Cleaning: capacity.Fixed(map[string]string{"example-cleaning": policyDigest})} + e.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: namespace, Capacity: e.projector, Courier: &delivery.Courier{Client: admin, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}} e.allocator = &Allocator{ Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, Custody: coordinator, Namespace: namespace, Cleaning: func(string) (string, error) { return policyDigest, nil }, + Capacity: e.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } + // One qualified plan covers every fixture server: one person writes it + // and another approves it. + e.plan = &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan", Namespace: namespace}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: ops.Creator{Username: "plan-author@example.com", UID: uid(803)}, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/hardware-model": "example"}}, + Content: ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "2Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: policyDigest}, Duration: metav1.Duration{Duration: time.Minute}}, + }, + EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, + }} + e.create(e.plan) + approval, err := custody.NewApproval(e.plan, ops.Creator{Username: "plan-approver@example.com", UID: uid(804)}) + if err != nil { + t.Fatal(err) + } + e.create(approval) e.class = &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class-example"}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: "profile-example"}}}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: namespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} e.create(e.class) e.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} @@ -147,7 +171,7 @@ func (e *env) server(n int) *inventory.Device { e.t.Helper() name := fmt.Sprintf("server-example-%03d", n) mac := fmt.Sprintf("02:00:00:00:00:%02x", n) - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: inventory.DeviceSpec{ + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, Labels: map[string]string{"fleet.datumapis.com/hardware-model": "example"}}, Spec: inventory.DeviceSpec{ ClaimRef: inventory.LocalReference{Name: "claim-" + name}, Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-" + name, SystemUUID: uid(100 + n)}, BMC: &inventory.BMC{Endpoint: fmt.Sprintf("https://[2001:db8::%x]", n)}, @@ -155,18 +179,12 @@ func (e *env) server(n int) *inventory.Device { }} e.create(device) key := fmt.Sprintf("%064x", n) - e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}} + e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}, + Hardware: &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: mac}}}} e.loop.Courier.Sites.Devices[name] = []string{siteName} capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} e.create(capacity) - capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}} - for _, kind := range []string{"Prepared", "Healthy", "Available"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: "Fixture", ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now()}) - } - if err := e.admin.Status().Update(e.ctx, capacity); err != nil { - e.t.Fatal(err) - } if err := fixture.Discover(e.ctx, e.admin, fixture.Enrollment{namespace + "/" + name: e.enrollment[namespace+"/"+name]}, time.Now()); err != nil { e.t.Fatal(err) } @@ -174,9 +192,28 @@ func (e *env) server(n int) *inventory.Device { state := e.custody(name) return state != nil && state.Spec.State == ops.CustodyVerified }) + e.commission(device, capacity) return device } +// commission commissions the server under the fixture plan and waits until +// the projector offers its capacity. +func (e *env) commission(device *inventory.Device, capacity *fleetv1.MachineCapacity) { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + e.t.Fatal(err) + } + operation, err := custody.NewCommissioning(device, e.plan, ops.Creator{Username: "operator@example.com", UID: uid(805)}, "fixture intake") + if err != nil { + e.t.Fatal(err) + } + e.create(operation) + e.until("the capacity is offered", func() bool { + offered, _, err := e.projector.Offer(e.ctx, capacity) + return err == nil && offered + }) +} + // until runs coordinator passes until done holds. func (e *env) until(what string, done func() bool) { e.t.Helper() diff --git a/internal/allocation/release_test.go b/internal/allocation/release_test.go index 018fee80..b08bd082 100644 --- a/internal/allocation/release_test.go +++ b/internal/allocation/release_test.go @@ -72,7 +72,7 @@ func TestAnAllocationThatNeverHeldItsDeviceIsReleased(t *testing.T) { if _, err := q.Acquire(e.ctx, machine(1)); err != nil { t.Fatal(err) } - orphan, err := e.allocator.newAllocation(e.request(1), e.capacity(device.Name), device, "fleet-machine-601") + orphan, err := e.allocator.newAllocation(e.request(1), e.capacity(device.Name), device, fleetv1.Hardware{}, "fleet-machine-601") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/unidentified_test.go b/internal/allocation/unidentified_test.go new file mode 100644 index 00000000..eaef066b --- /dev/null +++ b/internal/allocation/unidentified_test.go @@ -0,0 +1,63 @@ +package allocation + +import ( + "context" + "errors" + "testing" + + 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" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +// offersAll offers every capacity with the profile's hardware, so only the +// allocator's own checks can refuse one. +type offersAll struct{} + +func (offersAll) Offer(context.Context, *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) { + return true, fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}}, nil +} + +// TestTheAllocatorNeverSelectsAServerWithoutAHardwareID gives the allocator +// an evaluation that offers everything and free custody, and checks that it +// still never selects capacity backed by a Device without a hardware ID +// (#131). The identified control case shows the setup is otherwise eligible. +func TestTheAllocatorNeverSelectsAServerWithoutAHardwareID(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{inventory.AddToScheme, ops.AddToScheme, fleetv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class-example"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{ + MachineCapacities: fleetv1.MachineSelector{Namespace: namespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} + profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} + for name, test := range map[string]struct { + identity inventory.DeviceIdentity + eligible bool + }{ + "recorded without a hardware ID": {inventory.DeviceIdentity{Model: "patch-panel", Unidentified: true, UnidentifiedReason: "the equipment has no serial"}, false}, + "with no serial or system UUID": {inventory.DeviceIdentity{Model: "patch-panel"}, false}, + "identified": {inventory.DeviceIdentity{Model: "example", Serial: "serial-example-001", SystemUUID: uid(101)}, true}, + } { + t.Run(name, func(t *testing.T) { + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001", Namespace: namespace, UID: types.UID(uid(1))}, Spec: inventory.DeviceSpec{Identity: test.identity}} + state := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: uid(1)}}, + Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name}, State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}}} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + device.Name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, + Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: device.Name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} + allocator := &Allocator{Provider: fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, state, capacity).Build(), Namespace: namespace, Capacity: offersAll{}} + selected, _, _, err := allocator.candidate(context.Background(), Request{Class: class, Profile: profile}, map[string]bool{}) + switch { + case test.eligible && (err != nil || selected == nil || selected.Name != capacity.Name): + t.Fatalf("the identified server was not selected: %v", err) + case !test.eligible && !errors.Is(err, ErrInsufficientCapacity): + t.Fatalf("a server without a hardware ID was selected: %v %v", selected, err) + } + }) + } +} diff --git a/internal/api/inventory/v1alpha1/aliases.go b/internal/api/inventory/v1alpha1/aliases.go new file mode 100644 index 00000000..608af685 --- /dev/null +++ b/internal/api/inventory/v1alpha1/aliases.go @@ -0,0 +1,27 @@ +package v1alpha1 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "strings" +) + +// Aliases returns the normalized hardware identifiers of a Device: serial, +// system UUID and, when present, the provider host reference. Two Devices +// sharing any alias may be the same machine. +func Aliases(device *Device) []string { + var result []string + pairs := [][2]string{{"serial", strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial))}, {"uuid", strings.ToLower(strings.TrimSpace(device.Spec.Identity.SystemUUID))}} + if reference := device.Spec.ProviderHostRef; reference != nil { + encoded, _ := json.Marshal([]string{strings.ToLower(strings.TrimSpace(reference.System)), strings.ToLower(strings.TrimSpace(reference.Type)), strings.ToLower(strings.TrimSpace(reference.ID))}) + pairs = append(pairs, [2]string{"provider", string(encoded)}) + } + for _, pair := range pairs { + if pair[1] != "" { + digest := sha256.Sum256([]byte(pair[0] + ":" + pair[1])) + result = append(result, pair[0]+":"+hex.EncodeToString(digest[:])) + } + } + return result +} diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index b989f9df..5d33b255 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -205,8 +205,11 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { "fleet.datumapis.com-device-commissioning-plan-author": p(group+"devicecommissioningplans", "create", "delete"), "fleet.datumapis.com-device-commissioning-plan-approver": p(group+"devicecommissioningplanapprovals", "create", "delete"), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), - "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), - "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), + p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), + "fleet.datumapis.com-capacity-projector": slices.Concat(p("metal.datumapis.com/machinecapacities", "get", "list", "watch", "updateStatus"), p(group+"devices", read...), p(group+"devicecustodies", read...), + p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), + "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries", "devicecommissionings"} { @@ -239,7 +242,11 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { for _, permission := range actual { parts := strings.SplitN(strings.TrimPrefix(permission, group), ".", 2) resource, verb := parts[0], parts[1] - // Only the coordinator writes custody or operation status. + // Only the coordinator writes custody or operation status; the + // projector writes only capacity status. + if name == "fleet.datumapis.com-capacity-projector" && strings.HasPrefix(permission, "metal.datumapis.com/machinecapacities.") { + continue + } if name != "fleet.datumapis.com-device-coordinator" && (strings.Contains(permission, "/status.") || strings.HasSuffix(permission, ".updateStatus") || (resource == "devicecustodies" && !slices.Contains(read, verb))) { t.Fatalf("%s writes custody or status: %s", name, permission) } diff --git a/internal/capacity/grants_test.go b/internal/capacity/grants_test.go new file mode 100644 index 00000000..d4e63567 --- /dev/null +++ b/internal/capacity/grants_test.go @@ -0,0 +1,102 @@ +package capacity + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/util/yaml" + sigsyaml "sigs.k8s.io/yaml" +) + +// TestEveryEvaluatorListsDevicesProjectWide fails when an identity that +// evaluates capacity cannot list Devices in every namespace of the provider +// project. Duplicate lists them all, so a namespaced grant would fail every +// evaluation, and with it every allocation, in that mode. +func TestEveryEvaluatorListsDevicesProjectWide(t *testing.T) { + root := filepath.Join("..", "..") + // Milo binds roles on the project, so a role's permission is project-wide. + for _, name := range []string{"installation-requester", "capacity-projector"} { + data, err := os.ReadFile(filepath.Join(root, "config", "components", "device-operations", "roles", name+".yaml")) + if err != nil { + t.Fatal(err) + } + var role struct { + Spec struct { + IncludedPermissions []string `json:"includedPermissions"` + } `json:"spec"` + } + if err := sigsyaml.Unmarshal(data, &role); err != nil { + t.Fatal(err) + } + if !slices.Contains(role.Spec.IncludedPermissions, "fleet.datumapis.com/devices.list") { + t.Errorf("the %s role cannot list Devices", name) + } + } + + // Standalone: each evaluating ServiceAccount is bound cluster-wide to a + // ClusterRole that lists Devices. + data, err := os.ReadFile(filepath.Join(root, "config", "standalone", "rbac.yaml")) + if err != nil { + t.Fatal(err) + } + listers := map[string]bool{} + var bindings []rbacv1.ClusterRoleBinding + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var object struct { + rbacv1.ClusterRole `json:",inline"` + RoleRef rbacv1.RoleRef `json:"roleRef"` + Subjects []rbacv1.Subject `json:"subjects"` + } + if err := decoder.Decode(&object); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + switch object.Kind { + case "ClusterRole": + for _, rule := range object.Rules { + if slices.Contains(rule.Resources, "devices") && slices.Contains(rule.Verbs, "list") && len(rule.ResourceNames) == 0 { + listers[object.Name] = true + } + } + case "ClusterRoleBinding": + bindings = append(bindings, rbacv1.ClusterRoleBinding{RoleRef: object.RoleRef, Subjects: object.Subjects}) + } + } + for _, account := range []string{"fleet-standalone-smoke", "fleet-capacity-projector"} { + bound := false + for _, binding := range bindings { + for _, subject := range binding.Subjects { + if subject.Kind == "ServiceAccount" && subject.Name == account && binding.RoleRef.Kind == "ClusterRole" && listers[binding.RoleRef.Name] { + bound = true + } + } + } + if !bound { + t.Errorf("the standalone %s ServiceAccount cannot list Devices in every namespace", account) + } + } + + // Multi-plane: the Metal provider and the projector hold ClusterRoles in + // the provider project that list Devices. + milo, err := os.ReadFile(filepath.Join(root, "hack", "multiplane", "milo.py")) + if err != nil { + t.Fatal(err) + } + source := string(milo) + provider := source[strings.Index(source, "if role=='provider':"):strings.Index(source, "components={")] + projector := source[strings.Index(source, "'projector':["):] + projector = projector[:strings.Index(projector, "]}]")] + for name, rules := range map[string]string{"Metal provider": provider, "projector": projector} { + if !strings.Contains(rules, "'devices'") || !strings.Contains(rules, "'list'") { + t.Errorf("the multi-plane %s cannot list Devices", name) + } + } +} diff --git a/internal/capacity/projector.go b/internal/capacity/projector.go new file mode 100644 index 00000000..c4aa62ba --- /dev/null +++ b/internal/capacity/projector.go @@ -0,0 +1,320 @@ +// Package capacity derives MachineCapacity status from evidence: the +// Device's latest commissioning and current plan, discovery, custody, the +// cleaning policy, and duplicate identities. The Projector is the only +// writer of a capacity's Prepared, Healthy and Available conditions and its +// hardware. The allocator calls Evaluate on live inputs and never reads the +// conditions, so editing status cannot make a server allocatable. +package capacity + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "slices" + "sync" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + apiequality "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// RegisteredDeviceUID is the annotation in which registration records the +// Device incarnation a registered capacity was created for. Registration +// admission keeps it unchanged. +const RegisteredDeviceUID = "fleet.datumapis.com/registration-device-uid" + +// ErrUnresolved is what a CleaningResolver returns for a name that does not +// resolve. Any other error means the owner could not be reached. +var ErrUnresolved = errors.New("the cleaning policy does not resolve") + +// CleaningResolver maps a cleaning policy name in the provider project to its +// current digest. The cleaning policy owner provides it. +type CleaningResolver func(ctx context.Context, name string) (string, error) + +// Unresolved is the resolver to use until the cleaning policy owner provides +// one: no name resolves, so no capacity is Available. +func Unresolved(context.Context, string) (string, error) { return "", ErrUnresolved } + +// Fixed resolves exactly the given names to their digests. Test modes use it. +func Fixed(digests map[string]string) CleaningResolver { + return func(_ context.Context, name string) (string, error) { + if digest, ok := digests[name]; ok && name != "" { + return digest, nil + } + return "", ErrUnresolved + } +} + +// Projector derives and writes capacity status. +type Projector struct { + // Reader reads the provider project. It must read the stored state. + Reader client.Reader + // Writer writes capacity status with the projector's identity. Evaluate + // does not need it. + Writer client.Client + Namespace string + Cleaning CleaningResolver + // DiscoveryMaxAge bounds how old discovery may be. It defaults to the + // coordinator's default. + DiscoveryMaxAge time.Duration + Now func() time.Time +} + +func (p *Projector) now() time.Time { + if p.Now != nil { + return p.Now() + } + return time.Now() +} + +// Evaluate derives the capacity's projection from live inputs. +func (p *Projector) Evaluate(ctx context.Context, capacity *metal.MachineCapacity) (custody.CapacityProjection, error) { + in, err := p.inputs(ctx, capacity) + if err != nil { + return custody.CapacityProjection{}, err + } + return custody.ProjectCapacity(in), nil +} + +func (p *Projector) inputs(ctx context.Context, capacity *metal.MachineCapacity) (custody.CapacityInputs, error) { + now := p.now() + in := custody.CapacityInputs{Generation: capacity.Generation, Now: now, AllocationPolicyEnabled: capacity.Spec.AllocationPolicy == "Enabled" && capacity.DeletionTimestamp.IsZero()} + resolve := p.Cleaning + if resolve == nil { + resolve = Unresolved + } + if _, err := resolve(ctx, capacity.Spec.CleaningPolicyRef.Name); err == nil { + in.Cleaning = custody.CleaningResolved + } else if errors.Is(err, ErrUnresolved) { + in.Cleaning = custody.CleaningUnresolved + } else { + in.Cleaning = custody.CleaningUnknown + } + device := &inventory.Device{} + if err := p.Reader.Get(ctx, client.ObjectKey{Namespace: capacity.Namespace, Name: capacity.Spec.DeviceRef.Name}, device); apierrors.IsNotFound(err) { + return in, nil + } else if err != nil { + return in, err + } + if registered, ok := capacity.Annotations[RegisteredDeviceUID]; ok && registered != string(device.UID) { + // A Device recreated under the name inherits nothing from capacity + // registered for the old incarnation. + in.DeviceReplaced = true + return in, nil + } + if inventory.CapacityBackingError(device) != nil { + // A server without a hardware ID never backs capacity (#131), so + // nothing else about it is read. + in.DeviceUnidentified = true + return in, nil + } + in.DeviceUID = string(device.UID) + in.DeviceSerial, in.DeviceSystemUUID = device.Spec.Identity.Serial, device.Spec.Identity.SystemUUID + in.DeviceActive = inventory.LifecycleOf(device) == inventory.DeviceActive && device.DeletionTimestamp.IsZero() + maxAge := p.DiscoveryMaxAge + if maxAge <= 0 { + maxAge = custody.DefaultDiscoveryMaxAge + } + in.Discovery.Current = custody.DiscoveryCurrent(device, now, maxAge) + if discovery := device.Status.Discovery; discovery != nil && discovery.TLS != nil { + in.Discovery.KeyDigest = discovery.TLS.PublicKeySHA256 + } + state := &ops.DeviceCustody{} + if err := p.Reader.Get(ctx, client.ObjectKeyFromObject(device), state); err == nil { + if state.Labels[ops.LabelDeviceUID] == string(device.UID) && state.DeletionTimestamp.IsZero() { + in.Custody = &state.Spec + } + } else if !apierrors.IsNotFound(err) { + return in, err + } + plan, reason, err := custody.CurrentPlan(ctx, p.Reader, device) + if plan == nil && reason == "" && err != nil { + return in, err + } + in.CurrentPlan = custody.CurrentPlanInput{Plan: plan, Reason: reason} + if plan != nil { + reference, err := custody.PlanReferenceOf(plan) + if err != nil { + return in, err + } + in.CurrentPlan.Reference = ops.ApprovedPlanReference{PlanReference: reference, Approval: custody.ApprovalName(plan)} + } + if in.Commissioning, err = latestCommissioning(ctx, p.Reader, device); err != nil { + return in, err + } + if in.Duplicate, err = Duplicate(ctx, p.Reader, device); err != nil { + return in, err + } + return in, nil +} + +// latestCommissioning returns the Device's latest succeeded commissioning +// with its evidence. +func latestCommissioning(ctx context.Context, reader client.Reader, device *inventory.Device) (*custody.LatestCommissioning, error) { + var list ops.DeviceCommissioningList + if err := reader.List(ctx, &list, client.InNamespace(device.Namespace)); err != nil { + return nil, err + } + var operations []ops.Operation + for index := range list.Items { + if list.Items[index].Spec.DeviceRef.Name == device.Name && list.Items[index].Labels[ops.LabelDeviceUID] == string(device.UID) { + operations = append(operations, &list.Items[index]) + } + } + latest, ok := custody.LatestSucceeded(operations)[custody.DeviceIncarnation{Name: device.Name, UID: string(device.UID)}] + if !ok { + return nil, nil + } + status := latest.OperationStatus() + if status.Evidence == nil { + return nil, nil + } + var evidence ops.CommissioningEvidence + if err := json.Unmarshal(status.Evidence.Raw, &evidence); err != nil { + return nil, nil + } + return &custody.LatestCommissioning{DeviceUID: latest.GetLabels()[ops.LabelDeviceUID], FinishedAt: status.FinishedAt.Time, Evidence: evidence}, nil +} + +// Duplicate reports whether another Device in the provider project, in any +// namespace, shares one of the Device's identity aliases. Retired Devices +// count until they are deleted. Registration admission checks the other +// provider projects when capacity is registered and enabled. +func Duplicate(ctx context.Context, reader client.Reader, device *inventory.Device) (bool, error) { + var devices inventory.DeviceList + if err := reader.List(ctx, &devices); err != nil { + return false, err + } + aliases := inventory.Aliases(device) + for index := range devices.Items { + other := &devices.Items[index] + if other.UID == device.UID { + continue + } + for _, alias := range inventory.Aliases(other) { + if slices.Contains(aliases, alias) { + return true, nil + } + } + } + return false, nil +} + +// Project writes the capacity's projected status if it changed. Only the +// projector's identity may write the status of registered capacity. +func (p *Projector) Project(ctx context.Context, capacity *metal.MachineCapacity) (bool, error) { + projection, err := p.Evaluate(ctx, capacity) + if err != nil { + return false, err + } + next := capacity.DeepCopyObject().(*metal.MachineCapacity) + for _, condition := range projection.Conditions { + apiMeta.SetStatusCondition(&next.Status.Conditions, condition) + } + next.Status.Hardware = hardware(projection.Hardware) + if apiequality.Semantic.DeepEqual(next.Status, capacity.Status) { + return false, nil + } + if err := p.Writer.Status().Update(ctx, next); err != nil { + return false, err + } + return true, nil +} + +// ProjectAll projects every capacity in the namespace, reading each list +// the evaluation needs once for the whole pass. +func (p *Projector) ProjectAll(ctx context.Context) error { + var capacities metal.MachineCapacityList + if err := p.Reader.List(ctx, &capacities, client.InNamespace(p.Namespace)); err != nil { + return err + } + pass := p.Snapshot() + var failed error + for index := range capacities.Items { + if _, err := pass.Project(ctx, &capacities.Items[index]); err != nil && !apierrors.IsConflict(err) { + failed = errors.Join(failed, fmt.Errorf("%s: %w", capacities.Items[index].Name, err)) + } + } + return failed +} + +// hardware converts inspected hardware to the MachineCapacity shape. +func hardware(in *ops.InspectedHardware) metal.Hardware { + if in == nil { + return metal.Hardware{} + } + out := metal.Hardware{CPU: metal.HardwareCPU{Architecture: in.CPU.Architecture, Model: in.CPU.Model, Sockets: in.CPU.Sockets, Cores: in.CPU.Cores}, Memory: metal.HardwareMemory{Capacity: in.Memory}} + for _, disk := range in.Disks { + out.Disks = append(out.Disks, metal.HardwareDisk{Name: disk.Name, Capacity: disk.Capacity}) + } + for _, nic := range in.Interfaces { + out.Interfaces = append(out.Interfaces, metal.HardwareInterface{Name: nic.Name, Speed: nic.Speed}) + } + return out +} + +// Hardware is the capacity hardware a projection carries. +func Hardware(projection custody.CapacityProjection) metal.Hardware { + return hardware(projection.Hardware) +} + +// Offer reports whether the capacity may be offered now, from live inputs, +// and the hardware its latest passed commissioning inspected. It never reads +// the capacity's conditions. +func (p *Projector) Offer(ctx context.Context, capacity *metal.MachineCapacity) (bool, metal.Hardware, error) { + projection, err := p.Evaluate(ctx, capacity) + if err != nil { + return false, metal.Hardware{}, err + } + return projection.Available(), hardware(projection.Hardware), nil +} + +// Pass returns an Offer for one allocation pass over many capacities. It +// reads each list the evaluation needs once and reuses it for every +// capacity of the pass. +func (p *Projector) Pass() func(context.Context, *metal.MachineCapacity) (bool, metal.Hardware, error) { + return p.Snapshot().Offer +} + +// Snapshot returns a projector for one pass over many capacities. It reads +// each list, the provider project's Devices, plans, approvals and +// commissionings, once and reuses it for the rest of the pass, so a pass +// costs a few lists rather than a few per capacity. Gets still read through. +// Use it for one pass only: it never sees a change made after its first +// read of a list. +func (p *Projector) Snapshot() *Projector { + q := *p + q.Reader = &snapshot{Reader: p.Reader, lists: map[string]client.ObjectList{}} + return &q +} + +// snapshot is a reader that lists each kind, namespace and selector once. +type snapshot struct { + client.Reader + mu sync.Mutex + lists map[string]client.ObjectList +} + +func (s *snapshot) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + options := (&client.ListOptions{}).ApplyOptions(opts) + key := fmt.Sprintf("%T|%s|%v|%v|%d|%s", list, options.Namespace, options.LabelSelector, options.FieldSelector, options.Limit, options.Continue) + s.mu.Lock() + defer s.mu.Unlock() + if cached, ok := s.lists[key]; ok { + reflect.ValueOf(list).Elem().Set(reflect.ValueOf(cached.DeepCopyObject()).Elem()) + return nil + } + if err := s.Reader.List(ctx, list, opts...); err != nil { + return err + } + s.lists[key] = list.DeepCopyObject().(client.ObjectList) + return nil +} diff --git a/internal/capacity/projector_test.go b/internal/capacity/projector_test.go new file mode 100644 index 00000000..c79c938f --- /dev/null +++ b/internal/capacity/projector_test.go @@ -0,0 +1,124 @@ +package capacity + +import ( + "context" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +// TestADuplicateInAnotherNamespaceCounts records the same serial number in +// two namespaces of one provider project. +func TestADuplicateInAnotherNamespaceCounts(t *testing.T) { + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "default", UID: "one"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-1", SystemUUID: "00000000-0000-4000-8000-000000000001"}}} + other := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "elsewhere", UID: "two"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: " serial-1", SystemUUID: "00000000-0000-4000-8000-000000000002"}}} + alone := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device).Build() + if duplicate, err := Duplicate(context.Background(), alone, device); err != nil || duplicate { + t.Fatalf("a lone Device has a duplicate: %v", err) + } + both := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, other).Build() + if duplicate, err := Duplicate(context.Background(), both, device); err != nil || !duplicate { + t.Fatalf("a duplicate in another namespace was missed: %v", err) + } +} + +// TestARecreatedDeviceInheritsNoRegisteredCapacity recreates the Device behind +// capacity registered and enabled for its old incarnation. +func TestARecreatedDeviceInheritsNoRegisteredCapacity(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + capacity := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "device-old", Namespace: "default", Generation: 2, + Annotations: map[string]string{RegisteredDeviceUID: "old"}}, + Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "server"}, AllocationPolicy: "Enabled", CleaningPolicyRef: metal.LocalReference{Name: "tenant-reuse"}}} + for name, test := range map[string]struct { + uid string + replaced bool + }{"the registered incarnation": {"old", false}, "a recreated Device": {"new", true}} { + t.Run(name, func(t *testing.T) { + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "default", UID: types.UID(test.uid)}, + Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Model: "example", Serial: "SERIAL-1", SystemUUID: "00000000-0000-4000-8000-000000000001"}}} + projector := &Projector{Reader: fake.NewClientBuilder().WithScheme(scheme).WithObjects(device).Build(), Namespace: "default", + Cleaning: Fixed(map[string]string{"tenant-reuse": "sha256:policy"})} + in, err := projector.inputs(context.Background(), capacity) + if err != nil { + t.Fatal(err) + } + if in.DeviceReplaced != test.replaced || (in.DeviceUID != "") == test.replaced { + t.Fatalf("inputs for %s: replaced %v, Device UID %q", name, in.DeviceReplaced, in.DeviceUID) + } + if !test.replaced { + return + } + projection, err := projector.Evaluate(context.Background(), capacity) + if err != nil { + t.Fatal(err) + } + if prepared := apiMeta.FindStatusCondition(projection.Conditions, "Prepared"); projection.Available() || prepared.Reason != "DeviceReplaced" { + t.Fatalf("a recreated Device inherited the capacity: %+v", projection.Conditions) + } + if offered, _, err := projector.Offer(context.Background(), capacity); err != nil || offered { + t.Fatalf("the allocator was offered capacity of a recreated Device: %v %v", offered, err) + } + }) + } +} + +// TestAServerWithoutAHardwareIDIsNeverOffered points enabled capacity at a +// Device recorded without a hardware ID, and at one whose identity is +// missing altogether, and checks that neither is ever offered (#131). +func TestAServerWithoutAHardwareIDIsNeverOffered(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + capacity := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-panel", Namespace: "default", Generation: 1}, + Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "panel"}, AllocationPolicy: "Enabled", CleaningPolicyRef: metal.LocalReference{Name: "tenant-reuse"}}} + for name, identity := range map[string]inventory.DeviceIdentity{ + "recorded without a hardware ID": {Model: "patch-panel", Unidentified: true, UnidentifiedReason: "the equipment has no serial"}, + "with no serial or system UUID": {Model: "patch-panel"}, + } { + t.Run(name, func(t *testing.T) { + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "panel", Namespace: "default", UID: "panel-uid"}, Spec: inventory.DeviceSpec{Identity: identity}} + // Free custody for the same incarnation, so only the identity + // check can withhold the offer. + state := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: "panel", Namespace: "default", Labels: map[string]string{ops.LabelDeviceUID: "panel-uid"}}, + Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: "panel"}, State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}}} + projector := &Projector{Reader: fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, state).Build(), Namespace: "default", + Cleaning: Fixed(map[string]string{"tenant-reuse": "sha256:policy"})} + in, err := projector.inputs(context.Background(), capacity) + if err != nil { + t.Fatal(err) + } + if !in.DeviceUnidentified || in.DeviceUID != "" || in.Custody != nil { + t.Fatalf("inputs read a Device without a hardware ID: %+v", in) + } + projection, err := projector.Evaluate(context.Background(), capacity) + if err != nil { + t.Fatal(err) + } + if prepared := apiMeta.FindStatusCondition(projection.Conditions, "Prepared"); projection.Available() || prepared.Reason != "DeviceUnidentified" { + t.Fatalf("a Device without a hardware ID was projected: %+v", projection.Conditions) + } + if offered, _, err := projector.Offer(context.Background(), capacity); err != nil || offered { + t.Fatalf("the allocator was offered a Device without a hardware ID: %v %v", offered, err) + } + }) + } +} diff --git a/internal/capacity/snapshot_test.go b/internal/capacity/snapshot_test.go new file mode 100644 index 00000000..91d075cf --- /dev/null +++ b/internal/capacity/snapshot_test.go @@ -0,0 +1,66 @@ +package capacity + +import ( + "context" + "fmt" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// TestAPassListsEachKindOnce evaluates many capacities in one pass and +// checks that the pass lists each kind once, rather than once per +// capacity, and that every capacity still sees its own Device's inputs. +func TestAPassListsEachKindOnce(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + var objects []client.Object + var capacities []*metal.MachineCapacity + for index := range 5 { + name := fmt.Sprintf("server-%d", index) + objects = append(objects, &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID(name)}, + Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Model: "example", Serial: "SERIAL-" + name, SystemUUID: fmt.Sprintf("00000000-0000-4000-8000-%012d", index)}}}) + capacities = append(capacities, &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: name}, AllocationPolicy: "Enabled"}}) + } + // Two Devices share a serial; only they are duplicates. + objects = append(objects, &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "copy", Namespace: "elsewhere", UID: "copy"}, + Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Model: "example", Serial: "SERIAL-server-0", SystemUUID: "00000000-0000-4000-8000-999999999999"}}}) + lists := map[string]int{} + reader := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithInterceptorFuncs(interceptor.Funcs{ + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lists[fmt.Sprintf("%T", list)]++ + return c.List(ctx, list, opts...) + }, + }).Build() + pass := (&Projector{Reader: reader, Namespace: "default"}).Snapshot() + for index, capacity := range capacities { + in, err := pass.inputs(context.Background(), capacity) + if err != nil { + t.Fatal(err) + } + if in.DeviceUID != capacity.Spec.DeviceRef.Name || in.Duplicate != (index == 0) { + t.Fatalf("%s: inputs for Device %q, duplicate %v", capacity.Name, in.DeviceUID, in.Duplicate) + } + } + for kind, count := range lists { + if count != 1 { + t.Fatalf("the pass listed %s %d times; want once: %v", kind, count, lists) + } + } + if len(lists) < 4 { + t.Fatalf("the pass listed %v; want Devices, plans, approvals and commissionings", lists) + } +} diff --git a/internal/custody/capacity.go b/internal/custody/capacity.go index bb842326..222a02a3 100644 --- a/internal/custody/capacity.go +++ b/internal/custody/capacity.go @@ -1,88 +1,186 @@ package custody import ( + "strings" + "time" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// MachineCapacity conditions the capacity projector derives. The projector -// is their only writer once it is wired; in Increment A it is a pure function -// and nothing calls it outside tests. +// MachineCapacity conditions the capacity projector derives. It is their only +// writer, and the allocator evaluates the same projection from live inputs +// instead of reading them. const ( ConditionPrepared = "Prepared" ConditionHealthy = "Healthy" ConditionAvailable = "Available" ) -// CommissioningEvidence is the latest succeeded commissioning of a Device. -type CommissioningEvidence struct { - // PlanDigest is the commissioning plan the run used. - PlanDigest string - // HealthCurrent says the run's health evidence is still current. - HealthCurrent bool +// CleaningState is what the cleaning policy owner said about a capacity's +// cleaning policy reference. +type CleaningState string + +const ( + CleaningResolved CleaningState = "Resolved" + CleaningUnresolved CleaningState = "Unresolved" + // CleaningUnknown means the owner could not be reached. Available is + // then Unknown, not False. + CleaningUnknown CleaningState = "Unknown" +) + +// LatestCommissioning is a Device's latest succeeded commissioning. +type LatestCommissioning struct { + DeviceUID string + FinishedAt time.Time + Evidence ops.CommissioningEvidence +} + +// CurrentPlanInput is the Device's current plan, or why it has none. +type CurrentPlanInput struct { + // Plan is nil when the Device has no current plan. + Plan *ops.DeviceCommissioningPlan + // Reference pins the plan incarnation and its content: its name, + // generation, digest and approval name. + Reference ops.ApprovedPlanReference + // Reason is NoCurrentPlan or PlanAmbiguous when Plan is nil. + Reason string +} + +// DiscoveryInput is what BMC discovery last proved about the Device. +type DiscoveryInput struct { + // Current is true when discovery matched the Device's identity for its + // current generation, read its inventory within twice the interval, and + // recorded the BMC key at its current endpoint. + Current bool + // KeyDigest is the BMC key digest discovery recorded. + KeyDigest string } -// CapacityInputs is everything the projector reads. +// CapacityInputs is everything the projector reads, all read before any +// write. type CapacityInputs struct { Generation int64 + Now time.Time + // DeviceUID is the UID of the capacity's Device; empty when it is + // missing. + DeviceUID string + // DeviceSerial and DeviceSystemUUID are the Device's recorded identity. + DeviceSerial, DeviceSystemUUID string + DeviceActive bool + // DeviceUnidentified is true when the capacity's Device has no hardware + // ID (inventory.CapacityBackingError). Such a Device never backs + // capacity. + DeviceUnidentified bool + // DeviceReplaced is true when the Device under the capacity's name is + // another incarnation than the one the capacity was registered for. + DeviceReplaced bool // Commissioning is nil when no commissioning has succeeded. - Commissioning *CommissioningEvidence - // CurrentPlanDigest is the plan the Device must be commissioned under. - CurrentPlanDigest string - // DiscoveryCurrent says BMC discovery evidence is current. - DiscoveryCurrent bool + Commissioning *LatestCommissioning + CurrentPlan CurrentPlanInput + Discovery DiscoveryInput // Custody is nil when the Device has no custody. Custody *ops.DeviceCustodySpec AllocationPolicyEnabled bool + Cleaning CleaningState + // Duplicate is true when another Device in the provider scope shares + // one of the Device's identity aliases. + Duplicate bool } -// ProjectCapacity derives Prepared, Healthy and Available. Available is -// advisory: the allocator decides with a conditional custody update. -func ProjectCapacity(in CapacityInputs) []metav1.Condition { - condition := func(kind string, ok bool, reason, message string) metav1.Condition { - status := metav1.ConditionFalse - if ok { - status = metav1.ConditionTrue +// CapacityProjection is the derived status: the three conditions and the +// inspected hardware, which is nil unless the latest commissioning passed. +type CapacityProjection struct { + Conditions []metav1.Condition + Hardware *ops.InspectedHardware +} + +// Available reports whether the projection offers the capacity. +func (p CapacityProjection) Available() bool { + for _, condition := range p.Conditions { + if condition.Type == ConditionAvailable { + return condition.Status == metav1.ConditionTrue } + } + return false +} + +// ProjectCapacity derives Prepared, Healthy and Available. Each false +// condition names the first check that failed. Available is advisory: the +// allocator decides with a conditional custody update. +func ProjectCapacity(in CapacityInputs) CapacityProjection { + condition := func(kind string, status metav1.ConditionStatus, reason, message string) metav1.Condition { return metav1.Condition{Type: kind, Status: status, Reason: reason, Message: message, ObservedGeneration: in.Generation} } + no := func(kind, reason, message string) metav1.Condition { + return condition(kind, metav1.ConditionFalse, reason, message) + } + var out CapacityProjection + latest := in.Commissioning + if latest != nil && (in.DeviceUID == "" || latest.DeviceUID != in.DeviceUID) { + // Evidence for another incarnation of the Device proves nothing. + latest = nil + } var prepared metav1.Condition + plan := in.CurrentPlan switch { - case in.Commissioning == nil: - prepared = condition(ConditionPrepared, false, "NotCommissioned", "no commissioning has succeeded") - case in.CurrentPlanDigest == "" || in.Commissioning.PlanDigest != in.CurrentPlanDigest: - prepared = condition(ConditionPrepared, false, "PlanChanged", "the last commissioning used a different plan") + case in.DeviceUnidentified: + prepared = no(ConditionPrepared, "DeviceUnidentified", "the Device has no hardware ID, so it cannot back capacity") + case in.DeviceReplaced: + prepared = no(ConditionPrepared, "DeviceReplaced", "the capacity was registered for another incarnation of its Device") + case latest == nil: + prepared = no(ConditionPrepared, "NotCommissioned", "no commissioning has succeeded") + case latest.Evidence.Result != ops.CommissioningPassed: + prepared = no(ConditionPrepared, "CommissioningFailed", "the latest commissioning failed in its "+string(latest.Evidence.FailedPhase)+" phase") + case plan.Plan == nil && plan.Reason == ReasonPlanAmbiguous: + prepared = no(ConditionPrepared, ReasonPlanAmbiguous, "more than one plan applies to the Device") + case plan.Plan == nil: + prepared = no(ConditionPrepared, ReasonNoCurrentPlan, "no qualified plan applies to the Device") + case latest.Evidence.Plan != plan.Reference: + prepared = no(ConditionPrepared, "PlanChanged", "the latest commissioning used another plan than the current one") default: - prepared = condition(ConditionPrepared, true, "Commissioned", "commissioning succeeded under the current plan") + prepared = condition(ConditionPrepared, metav1.ConditionTrue, "Commissioned", "the server passed commissioning under the current plan") + out.Hardware = latest.Evidence.Hardware } var healthy metav1.Condition switch { - case in.Commissioning == nil || !in.Commissioning.HealthCurrent: - healthy = condition(ConditionHealthy, false, "CommissioningEvidenceNotCurrent", "commissioning health evidence is missing or old") - case !in.DiscoveryCurrent: - healthy = condition(ConditionHealthy, false, "DiscoveryNotCurrent", "discovery evidence is missing or old") + case prepared.Status != metav1.ConditionTrue: + healthy = no(ConditionHealthy, "NotPrepared", "the server is not prepared") + case in.Now.After(latest.FinishedAt.Add(plan.Plan.Spec.EvidenceLifetime.Duration)): + healthy = no(ConditionHealthy, "EvidenceExpired", "the commissioning is older than the plan's evidence lifetime") + case !in.Discovery.Current: + healthy = no(ConditionHealthy, "DiscoveryNotCurrent", "discovery evidence is missing or old") + case !strings.EqualFold(strings.TrimSpace(in.DeviceSerial), strings.TrimSpace(latest.Evidence.SerialNumber)) || !strings.EqualFold(in.DeviceSystemUUID, latest.Evidence.SystemUUID) || in.Discovery.KeyDigest != latest.Evidence.BMCPublicKeySHA256: + healthy = no(ConditionHealthy, "IdentityChanged", "the Device's identity or BMC key differs from what commissioning recorded") default: - healthy = condition(ConditionHealthy, true, "EvidenceCurrent", "commissioning and discovery evidence are current") + healthy = condition(ConditionHealthy, metav1.ConditionTrue, "EvidenceCurrent", "commissioning and discovery evidence are current") } var available metav1.Condition custody := in.Custody switch { - case prepared.Status != metav1.ConditionTrue: - available = condition(ConditionAvailable, false, "NotPrepared", "the Device is not prepared") case healthy.Status != metav1.ConditionTrue: - available = condition(ConditionAvailable, false, "NotHealthy", "the Device is not healthy") + available = no(ConditionAvailable, "NotHealthy", "the server is not healthy") case custody == nil: - available = condition(ConditionAvailable, false, "CustodyMissing", "the Device has no custody") + available = no(ConditionAvailable, "CustodyMissing", "the Device has no custody") case custody.State != ops.CustodyVerified: - available = condition(ConditionAvailable, false, "CustodyUnverified", "custody is Unverified") + available = no(ConditionAvailable, "CustodyUnverified", "custody is Unverified") case custody.RecoveryHold != nil: - available = condition(ConditionAvailable, false, "RecoveryHold", "an operation outcome is unknown") + available = no(ConditionAvailable, "RecoveryHold", "an operation outcome is unknown") case custody.Holder.Type != ops.HolderNone || custody.ActiveOperation != nil: - available = condition(ConditionAvailable, false, "Held", "the holder is "+string(custody.Holder.Type)) + available = no(ConditionAvailable, "Held", "the holder is "+string(custody.Holder.Type)) case !in.AllocationPolicyEnabled: - available = condition(ConditionAvailable, false, "AllocationDisabled", "the allocation policy is not enabled") + available = no(ConditionAvailable, "AllocationDisabled", "the allocation policy is not enabled") + case !in.DeviceActive: + available = no(ConditionAvailable, "DeviceNotActive", "the Device is not Active") + case in.Duplicate: + available = no(ConditionAvailable, "IdentityConflict", "another Device shares an identity alias") + case in.Cleaning == CleaningUnknown: + available = condition(ConditionAvailable, metav1.ConditionUnknown, "CleaningPolicyUnknown", "the cleaning policy owner could not be reached") + case in.Cleaning != CleaningResolved: + available = no(ConditionAvailable, "CleaningPolicyUnresolved", "the cleaning policy reference does not resolve") default: - available = condition(ConditionAvailable, true, "Available", "the Device can be allocated") + available = condition(ConditionAvailable, metav1.ConditionTrue, "Available", "the server can be allocated") } - return []metav1.Condition{prepared, healthy, available} + out.Conditions = []metav1.Condition{prepared, healthy, available} + return out } diff --git a/internal/custody/commissioning_requests.go b/internal/custody/commissioning_requests.go new file mode 100644 index 00000000..da065e4e --- /dev/null +++ b/internal/custody/commissioning_requests.go @@ -0,0 +1,40 @@ +package custody + +import ( + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// NewApproval returns the approval that qualifies the plan as read, for the +// approver to create. +func NewApproval(plan *ops.DeviceCommissioningPlan, approver ops.Creator) (*ops.DeviceCommissioningPlanApproval, error) { + reference, err := PlanReferenceOf(plan) + if err != nil { + return nil, err + } + return &ops.DeviceCommissioningPlanApproval{ + ObjectMeta: metav1.ObjectMeta{Name: ApprovalName(plan), Namespace: plan.Namespace}, + Spec: ops.DeviceCommissioningPlanApprovalSpec{Creator: approver, PlanRef: reference}, + }, nil +} + +// NewCommissioning returns a commissioning of the Device under the plan as +// read, with an exact copy of its content, for the operator to create. +func NewCommissioning(device *inventory.Device, plan *ops.DeviceCommissioningPlan, operator ops.Creator, reason string) (*ops.DeviceCommissioning, error) { + reference, err := PlanReferenceOf(plan) + if err != nil { + return nil, err + } + return &ops.DeviceCommissioning{ + // The label records the Device incarnation, which admission compares + // with the Device. + ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-commission-", Namespace: device.Namespace, + Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, + Spec: ops.DeviceCommissioningSpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: operator, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: reason}}}, + Plan: ops.CommissioningPlanInput{ApprovedPlanReference: ops.ApprovedPlanReference{PlanReference: reference, Approval: ApprovalName(plan)}, Content: plan.Spec.Content}, + }, + }, nil +} diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 5196014b..125e94a4 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -878,6 +878,16 @@ func isRetry(kind *Kind, hold *ops.RecoveryHold, operation ops.Operation) bool { // generation, completed an inventory read within DiscoveryMaxAge, and // recorded the BMC key at the current endpoint. func (c *Coordinator) identityCurrent(device *inventory.Device, now time.Time) *Refusal { + return identityRefusal(device, now, c.config().DiscoveryMaxAge) +} + +// DiscoveryCurrent reports whether discovery evidence for the Device is +// current, by the same rule admission uses. +func DiscoveryCurrent(device *inventory.Device, now time.Time, maxAge time.Duration) bool { + return identityRefusal(device, now, maxAge) == nil +} + +func identityRefusal(device *inventory.Device, now time.Time, maxAge time.Duration) *Refusal { if device.Spec.BMC == nil || device.Spec.Identity.SystemUUID == "" { return refuse(ReasonDeviceIdentityMismatch, "the Device records no BMC endpoint or system UUID") } @@ -886,8 +896,8 @@ func (c *Coordinator) identityCurrent(device *inventory.Device, now time.Time) * return refuse(ReasonDeviceIdentityMismatch, "discovery has not matched the Device identity at its current generation") } discovery := device.Status.Discovery - if discovery == nil || discovery.Inventory == nil || now.Sub(discovery.Inventory.ObservedAt.Time) > c.config().DiscoveryMaxAge { - return refuse(ReasonDeviceIdentityMismatch, "discovery is older than %s", c.config().DiscoveryMaxAge) + if discovery == nil || discovery.Inventory == nil || now.Sub(discovery.Inventory.ObservedAt.Time) > maxAge { + return refuse(ReasonDeviceIdentityMismatch, "discovery is older than %s", maxAge) } if discovery.TLS == nil || discovery.TLS.PublicKeySHA256 == "" || discovery.TLS.Endpoint != device.Spec.BMC.Endpoint { return refuse(ReasonDeviceIdentityMismatch, "discovery has not recorded the BMC key at the current endpoint") diff --git a/internal/custody/lifecycle_test.go b/internal/custody/lifecycle_test.go index 2146fc63..ca03cad0 100644 --- a/internal/custody/lifecycle_test.go +++ b/internal/custody/lifecycle_test.go @@ -10,7 +10,6 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -28,8 +27,8 @@ func TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing(t *testing.T) { if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-example"); !errors.Is(err, ErrUnavailable) { t.Fatalf("Unverified custody was claimed: %v", err) } - conditions := ProjectCapacity(CapacityInputs{Custody: &custody.Spec, AllocationPolicyEnabled: true, DiscoveryCurrent: true}) - if conditions[2].Status != metav1.ConditionFalse { + projection := ProjectCapacity(CapacityInputs{Custody: &custody.Spec, AllocationPolicyEnabled: true, Discovery: DiscoveryInput{Current: true}, DeviceActive: true, Cleaning: CleaningResolved}) + if projection.Available() { t.Fatal("imported Device became Available") } // No configured site: nothing can fence the Device yet. diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index c637f8f7..252c9207 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -170,52 +170,88 @@ func TestEvidenceIsTypedAndBounded(t *testing.T) { } func TestCapacityProjection(t *testing.T) { - plan := "sha256:plan" - commissionings := map[string]*CommissioningEvidence{"none": nil, "old plan": {PlanDigest: "sha256:old", HealthCurrent: true}, "unhealthy": {PlanDigest: plan}, "current": {PlanDigest: plan, HealthCurrent: true}} - hold := &ops.RecoveryHold{Reason: "x"} - custodies := map[string]*ops.DeviceCustodySpec{ - "missing": nil, - "unverified": {State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}}, - "held": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}, RecoveryHold: hold}, - "allocated": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderAllocation}}, - "releasing": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderRelease}}, - "service": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderService}}, - "retired": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderRetired}}, - "free": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}}, + now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + plan := &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "plan", UID: "plan-uid", Generation: 1}, Spec: ops.DeviceCommissioningPlanSpec{EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}}} + pinned := ops.ApprovedPlanReference{PlanReference: ops.PlanReference{Name: "plan", Generation: 1, Digest: "sha256:plan"}, Approval: ApprovalName(plan)} + passed := func(mutate func(*LatestCommissioning)) *LatestCommissioning { + latest := &LatestCommissioning{DeviceUID: "device-uid", FinishedAt: now.Add(-time.Hour), Evidence: ops.CommissioningEvidence{ + Plan: pinned, Result: ops.CommissioningPassed, + SerialNumber: "SERIAL-1", SystemUUID: "uuid-1", BMCPublicKeySHA256: "key", Hardware: &ops.InspectedHardware{Memory: "2Gi"}}} + if mutate != nil { + mutate(latest) + } + return latest } - available := 0 - for commissioningName, commissioning := range commissionings { - for custodyName, custody := range custodies { - for _, discovery := range []bool{false, true} { - for _, enabled := range []bool{false, true} { - conditions := ProjectCapacity(CapacityInputs{Generation: 3, Commissioning: commissioning, CurrentPlanDigest: plan, DiscoveryCurrent: discovery, Custody: custody, AllocationPolicyEnabled: enabled}) - prepared := conditions[0].Status == metav1.ConditionTrue - healthy := conditions[1].Status == metav1.ConditionTrue - free := conditions[2].Status == metav1.ConditionTrue - if prepared != (commissioningName == "current" || commissioningName == "unhealthy") { - t.Fatalf("%s: Prepared = %v", commissioningName, prepared) - } - if healthy != (commissioningName != "none" && commissioning.HealthCurrent && discovery) { - t.Fatalf("%s discovery %v: Healthy = %v", commissioningName, discovery, healthy) - } - want := prepared && healthy && custodyName == "free" && enabled - if free != want { - t.Fatalf("%s %s discovery %v enabled %v: Available = %v (%s)", commissioningName, custodyName, discovery, enabled, free, conditions[2].Reason) - } - if free { - available++ - } - for _, condition := range conditions { - if condition.ObservedGeneration != 3 || condition.Reason == "" { - t.Fatalf("condition = %+v", condition) - } - } - } + free := &ops.DeviceCustodySpec{State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}} + base := func() CapacityInputs { + return CapacityInputs{Generation: 3, Now: now, DeviceUID: "device-uid", DeviceSerial: "serial-1", DeviceSystemUUID: "UUID-1", DeviceActive: true, + Commissioning: passed(nil), CurrentPlan: CurrentPlanInput{Plan: plan, Reference: pinned}, Discovery: DiscoveryInput{Current: true, KeyDigest: "key"}, + Custody: free, AllocationPolicyEnabled: true, Cleaning: CleaningResolved} + } + if projection := ProjectCapacity(base()); !projection.Available() || projection.Hardware == nil { + t.Fatalf("the base inputs are not Available: %+v", projection.Conditions) + } + for name, test := range map[string]struct { + mutate func(*CapacityInputs) + index int + reason string + status metav1.ConditionStatus + }{ + "never commissioned": {func(in *CapacityInputs) { in.Commissioning = nil }, 0, "NotCommissioned", metav1.ConditionFalse}, + "another incarnation": {func(in *CapacityInputs) { in.DeviceUID = "other" }, 0, "NotCommissioned", metav1.ConditionFalse}, + "device replaced": {func(in *CapacityInputs) { in.DeviceReplaced = true }, 0, "DeviceReplaced", metav1.ConditionFalse}, + "no hardware ID": {func(in *CapacityInputs) { in.DeviceUnidentified = true }, 0, "DeviceUnidentified", metav1.ConditionFalse}, + "failed": {func(in *CapacityInputs) { in.Commissioning.Evidence.Result = ops.CommissioningFailed }, 0, "CommissioningFailed", metav1.ConditionFalse}, + "no plan": {func(in *CapacityInputs) { in.CurrentPlan = CurrentPlanInput{Reason: ReasonNoCurrentPlan} }, 0, ReasonNoCurrentPlan, metav1.ConditionFalse}, + "ambiguous": {func(in *CapacityInputs) { in.CurrentPlan = CurrentPlanInput{Reason: ReasonPlanAmbiguous} }, 0, ReasonPlanAmbiguous, metav1.ConditionFalse}, + "plan changed": {func(in *CapacityInputs) { in.CurrentPlan.Reference.Digest = "sha256:new" }, 0, "PlanChanged", metav1.ConditionFalse}, + "plan regenerated": {func(in *CapacityInputs) { in.CurrentPlan.Reference.Generation = 2 }, 0, "PlanChanged", metav1.ConditionFalse}, + "plan recreated": {func(in *CapacityInputs) { + again := *plan + again.UID = "plan-uid-2" + in.CurrentPlan = CurrentPlanInput{Plan: &again, Reference: ops.ApprovedPlanReference{PlanReference: pinned.PlanReference, Approval: ApprovalName(&again)}} + }, 0, "PlanChanged", metav1.ConditionFalse}, + "expired": {func(in *CapacityInputs) { in.Now = now.Add(48 * time.Hour) }, 1, "EvidenceExpired", metav1.ConditionFalse}, + "discovery old": {func(in *CapacityInputs) { in.Discovery.Current = false }, 1, "DiscoveryNotCurrent", metav1.ConditionFalse}, + "key changed": {func(in *CapacityInputs) { in.Discovery.KeyDigest = "other" }, 1, "IdentityChanged", metav1.ConditionFalse}, + "serial changed": {func(in *CapacityInputs) { in.DeviceSerial = "other" }, 1, "IdentityChanged", metav1.ConditionFalse}, + "custody missing": {func(in *CapacityInputs) { in.Custody = nil }, 2, "CustodyMissing", metav1.ConditionFalse}, + "unverified": {func(in *CapacityInputs) { + in.Custody = &ops.DeviceCustodySpec{State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}} + }, 2, "CustodyUnverified", metav1.ConditionFalse}, + "hold": {func(in *CapacityInputs) { c := *free; c.RecoveryHold = &ops.RecoveryHold{}; in.Custody = &c }, 2, "RecoveryHold", metav1.ConditionFalse}, + "allocated": {func(in *CapacityInputs) { c := *free; c.Holder.Type = ops.HolderAllocation; in.Custody = &c }, 2, "Held", metav1.ConditionFalse}, + "disabled": {func(in *CapacityInputs) { in.AllocationPolicyEnabled = false }, 2, "AllocationDisabled", metav1.ConditionFalse}, + "not active": {func(in *CapacityInputs) { in.DeviceActive = false }, 2, "DeviceNotActive", metav1.ConditionFalse}, + "duplicate": {func(in *CapacityInputs) { in.Duplicate = true }, 2, "IdentityConflict", metav1.ConditionFalse}, + "cleaning unresolved": {func(in *CapacityInputs) { in.Cleaning = CleaningUnresolved }, 2, "CleaningPolicyUnresolved", metav1.ConditionFalse}, + "cleaning owner unknown": {func(in *CapacityInputs) { in.Cleaning = CleaningUnknown }, 2, "CleaningPolicyUnknown", metav1.ConditionUnknown}, + "cleaning state is empty": {func(in *CapacityInputs) { in.Cleaning = "" }, 2, "CleaningPolicyUnresolved", metav1.ConditionFalse}, + } { + in := base() + in.Commissioning = passed(nil) + test.mutate(&in) + projection := ProjectCapacity(in) + condition := projection.Conditions[test.index] + if condition.Status != test.status || condition.Reason != test.reason || projection.Available() { + t.Fatalf("%s: %+v", name, projection.Conditions) + } + if test.index == 0 && projection.Hardware != nil { + t.Fatalf("%s: unprepared capacity keeps hardware", name) + } + for _, condition := range projection.Conditions { + if condition.ObservedGeneration != 3 || condition.Reason == "" { + t.Fatalf("%s: condition = %+v", name, condition) } } } - if available != 1 { - t.Fatalf("%d combinations are Available, want exactly one", available) + // Serials compare without surrounding space on either side. + padded := base() + padded.Commissioning = passed(nil) + padded.DeviceSerial = " SERIAL-1" + padded.Commissioning.Evidence.SerialNumber = "serial-1 " + if projection := ProjectCapacity(padded); !projection.Available() { + t.Fatalf("a padded serial changed the identity: %+v", projection.Conditions) } } diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index 7b72dfa8..a6573ff9 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -184,7 +184,8 @@ func (c *Courier) Collect(ctx context.Context) error { } // Loop is the coordinator process: it reconciles every Device's custody, -// delivers active operations, collects results and sweeps retention. +// delivers active operations, collects results, projects capacity status and +// sweeps retention. type Loop struct { Client client.Reader Coordinator *custody.Coordinator @@ -194,6 +195,11 @@ type Loop struct { Interval time.Duration // OnError reports a pass's errors. The loop keeps running. OnError func(error) + // Capacity, when set, projects every MachineCapacity's status after the + // Devices settle, with the capacity projector's own identity. + Capacity interface { + ProjectAll(ctx context.Context) error + } // lastSweep is when retention last ran. lastSweep time.Time } @@ -236,6 +242,11 @@ func (l *Loop) Pass(ctx context.Context) error { if err := l.Courier.Collect(ctx); err != nil { failed = errors.Join(failed, err) } + if l.Capacity != nil { + if err := l.Capacity.ProjectAll(ctx); err != nil { + failed = errors.Join(failed, fmt.Errorf("capacity: %w", err)) + } + } if time.Since(l.lastSweep) > time.Hour { if _, err := l.Coordinator.SweepRetention(ctx); err != nil { failed = errors.Join(failed, err) diff --git a/internal/multiplane/commission.go b/internal/multiplane/commission.go new file mode 100644 index 00000000..ff9c64f7 --- /dev/null +++ b/internal/multiplane/commission.go @@ -0,0 +1,174 @@ +package multiplane + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// HardwareModelLabel is the label the local plan selects Devices by. +const HardwareModelLabel = "fleet.datumapis.com/hardware-model" + +// LocalPlanName is the local commissioning plan. +const LocalPlanName = "local-plan-v1" + +// LabFirmware is the firmware inventory the Redfish lab adapter serves +// (hack/redfish-lab/firmware.json). The Redfish run's plan requires it, so the +// worker's firmware check runs against the emulator. +var LabFirmware = []ops.FirmwareBaseline{{Component: "BMC", Version: "1.2.2-fleet-lab.1"}, {Component: "BIOS", Version: "lab-bios-1.0.0"}} + +// LocalPlan is the local commissioning plan: the hardware of the local guest +// and of lab target A, which the fixture profile requests, the given firmware +// baseline, and a one-minute burn-in of the site image. The local VM reports +// no firmware, so its plan has no baseline; the Redfish run's plan requires +// LabFirmware. +func LocalPlan(author ops.Creator, burnIn ops.ImageInput, firmware []ops.FirmwareBaseline) *ops.DeviceCommissioningPlan { + return &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: LocalPlanName, Namespace: DeviceNamespace}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: author, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{HardwareModelLabel: "synthetic"}}, + Content: ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "1Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + Firmware: firmware, + BurnIn: ops.CommissioningBurnIn{Image: burnIn, Duration: metav1.Duration{Duration: time.Minute}}, + }, + EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, + }} +} + +// Commission commissions the Device as three people: the plan author writes +// the local plan, another person approves its exact content, and an operator +// commissions the Device under it. It then waits until the capacity +// projector offers the capacity. It repeats safely: the plan and approval +// are found again by name, and the Device's commissioning by its Device. +func (r *Runner) Commission(ctx context.Context) error { + if err := r.verified(ctx); err != nil { + return err + } + staff := map[string]client.Client{} + creators := map[string]ops.Creator{} + for _, who := range []string{"plan-author", "plan-approver", "operator"} { + path := filepath.Join(r.Config.State, "provider", who+"-project.json") + api, err := API(path) + if err != nil { + return err + } + if creators[who], err = identity(ctx, path); err != nil { + return err + } + staff[who] = api + } + image, err := allocation.ParseImage(r.Config.Image) + if err != nil { + return fmt.Errorf("%w: the site image: %v", errTerminal, err) + } + plan := LocalPlan(creators["plan-author"], image, r.PlanFirmware) + if err := staff["plan-author"].Create(ctx, plan); apierrors.IsAlreadyExists(err) { + if err := staff["plan-author"].Get(ctx, client.ObjectKeyFromObject(plan), plan); err != nil { + return err + } + } else if err != nil { + return fmt.Errorf("write the plan: %w", err) + } + approval, err := custody.NewApproval(plan, creators["plan-approver"]) + if err != nil { + return err + } + if err := staff["plan-approver"].Create(ctx, approval); err != nil && !apierrors.IsAlreadyExists(err) { + return fmt.Errorf("approve the plan: %w", err) + } + operator := staff["operator"] + device := &inventory.Device{} + if err := operator.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { + return err + } + operation, err := r.commissioning(ctx, operator, device) + if err != nil { + return err + } + if operation == nil { + if operation, err = custody.NewCommissioning(device, plan, creators["operator"], "local intake"); err != nil { + return err + } + if err := operator.Create(ctx, operation); err != nil { + return fmt.Errorf("commission the Device: %w", err) + } + } + switch phase := operation.Status.Phase; { + case phase == ops.PhaseSucceeded: + case phase.Ended(): + return fmt.Errorf("%w: the commissioning ended %s: %s %s", errTerminal, phase, operation.Status.Reason, operation.Status.Message) + default: + return fmt.Errorf("%w: the commissioning is %s", errPending, phase) + } + var evidence ops.CommissioningEvidence + if operation.Status.Evidence == nil || json.Unmarshal(operation.Status.Evidence.Raw, &evidence) != nil { + return fmt.Errorf("%w: the commissioning succeeded without evidence", errTerminal) + } + if evidence.Result != ops.CommissioningPassed { + return fmt.Errorf("%w: the commissioning proved %s in %s: %v", errTerminal, evidence.Result, evidence.FailedPhase, evidence.Mismatches) + } + capacity := &fleet.MachineCapacity{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: "local-capacity"}, capacity); err != nil { + return err + } + available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable) + if available == nil || available.Status != metav1.ConditionTrue || available.ObservedGeneration != capacity.Generation { + reason := "no Available condition" + if available != nil { + reason = available.Reason + } + return fmt.Errorf("%w: the projector does not offer the capacity yet (%s)", errPending, reason) + } + record := map[string]any{"plan": plan.Name, "approval": approval.Name, "firmwareBaseline": plan.Spec.Content.Firmware, "firmware": evidence.Firmware, "author": creators["plan-author"].Username, "approver": creators["plan-approver"].Username, + "operator": creators["operator"].Username, "operation": operation.Name, "fence": operation.Status.Fence, "result": evidence.Result, + "burnIn": evidence.BurnIn, "steps": evidence.Steps, "hardware": capacity.Status.Hardware, "capacityAvailable": available.Reason} + data, err := json.MarshalIndent(record, "", " ") + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(r.Config.State, "commissioning.json"), data, 0o600); err != nil { + return err + } + fmt.Printf("commission: verified: %s wrote the plan, %s approved it, %s commissioned the Device; burn-in %s at fence %d; the projector offers the capacity\n", + creators["plan-author"].Username, creators["plan-approver"].Username, creators["operator"].Username, evidence.BurnIn.Result, operation.Status.Fence) + return nil +} + +// commissioning returns the Device's one commissioning, or nil before the +// first. More than one means a repeat created a second, which proves nothing. +func (r *Runner) commissioning(ctx context.Context, api client.Client, device *inventory.Device) (*ops.DeviceCommissioning, error) { + var list ops.DeviceCommissioningList + if err := api.List(ctx, &list, client.InNamespace(DeviceNamespace)); err != nil { + return nil, err + } + var mine []ops.DeviceCommissioning + for _, item := range list.Items { + if item.Spec.DeviceRef.Name == device.Name && item.Labels[ops.LabelDeviceUID] == string(device.UID) { + mine = append(mine, item) + } + } + sort.Slice(mine, func(i, j int) bool { return mine[i].Name < mine[j].Name }) + switch len(mine) { + case 0: + return nil, nil + case 1: + return &mine[0], nil + } + return nil, fmt.Errorf("%w: the Device has %d commissionings", errTerminal, len(mine)) +} diff --git a/internal/multiplane/commission_test.go b/internal/multiplane/commission_test.go new file mode 100644 index 00000000..72b1ceee --- /dev/null +++ b/internal/multiplane/commission_test.go @@ -0,0 +1,34 @@ +package multiplane + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +// TestLabFirmwareIsWhatTheLabServes keeps the Redfish run's plan baseline +// equal to the firmware inventory the lab adapter serves, so the +// commissioning's firmware check passes against the emulator. +func TestLabFirmwareIsWhatTheLabServes(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "hack", "redfish-lab", "firmware.json")) + if err != nil { + t.Fatal(err) + } + var served []struct{ Id, Version string } + if err := json.Unmarshal(data, &served); err != nil { + t.Fatal(err) + } + versions := map[string]string{} + for _, item := range served { + versions[item.Id] = item.Version + } + if len(LabFirmware) == 0 { + t.Fatal("the Redfish run's plan has no firmware baseline") + } + for _, baseline := range LabFirmware { + if versions[baseline.Component] != baseline.Version { + t.Errorf("the plan requires %s %s, the lab serves %q", baseline.Component, baseline.Version, versions[baseline.Component]) + } + } +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 62be3abd..15db2958 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -29,6 +29,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/coordination" "go.datum.net/fleet/internal/custody" @@ -71,11 +72,13 @@ type Project struct { } type Runner struct { - Config Config - Provider Project - Consumers [2]Project - Allocator *allocation.Allocator - Hub *coordination.Hub + Config Config + // PlanFirmware is the firmware baseline of the run's commissioning plan. + PlanFirmware []ops.FirmwareBaseline + Provider Project + Consumers [2]Project + Allocator *allocation.Allocator + Hub *coordination.Hub } func Scheme() *runtime.Scheme { @@ -192,7 +195,12 @@ func Coordinate(ctx context.Context, c Config, o CoordinatorOptions, onError fun if err != nil { return err } - loop := &delivery.Loop{Client: api, Coordinator: coord, Namespace: DeviceNamespace, OnError: onError, + projectorAPI, err := API(filepath.Join(c.State, "provider", "projector-project.json")) + if err != nil { + return err + } + projector := &capacity.Projector{Reader: projectorAPI, Writer: projectorAPI, Namespace: DeviceNamespace, Cleaning: cleaningResolver} + loop := &delivery.Loop{Client: api, Coordinator: coord, Namespace: DeviceNamespace, OnError: onError, Capacity: projector, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coord, Sites: sites, Namespace: DeviceNamespace}} go fixture.Run(ctx, discovery, c.Enrollment, 30*time.Second, func(err error) { onError(fmt.Errorf("fixture discovery: %w", err)) }) return loop.Run(ctx) @@ -245,13 +253,26 @@ func New(ctx context.Context, c Config) (*Runner, error) { if name != "local-cleaning" { return "", fmt.Errorf("no fixture cleaning policy %q", name) } - return custody.SpecDigest(`{"method":"overwrite","disks":"all"}`) + return custody.SpecDigest(localCleaningPolicy) }, + Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: cleaningResolver}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } return r, nil } +// localCleaningPolicy is the fixture cleaning policy record. The cleaning +// policy owner's resolution contract does not exist yet, so the run resolves +// this one name itself. +const localCleaningPolicy = `{"method":"overwrite","disks":"all"}` + +func cleaningResolver(_ context.Context, name string) (string, error) { + if name != "local-cleaning" { + return "", capacity.ErrUnresolved + } + return custody.SpecDigest(localCleaningPolicy) +} + func condition(kind string, status metav1.ConditionStatus, generation int64, reason string) metav1.Condition { return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, Reason: reason, Message: "Local multi-plane acceptance; synthetic IAM, quota, catalog and networkless fixtures", LastTransitionTime: metav1.Now()} } diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 216a8284..b2bfafed 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -56,15 +56,6 @@ func Seed(ctx context.Context, c Config) error { if err := provider.Status().Update(ctx, &class); err != nil { return err } - // The capacity projector is not wired, so the fixture writes Prepared, - // Healthy and Available. Custody decides which Machine gets the Device. - capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} - for _, kind := range []string{"Available", "Prepared", "Healthy"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, capacity.Generation, "SyntheticHardwareObservation")) - } - if err := provider.Status().Update(ctx, &capacity); err != nil { - return err - } var routing []map[string]string for _, name := range []string{"consumer-a", "consumer-b"} { api, err := API(filepath.Join(c.State, name, "bootstrap-project.json")) @@ -156,7 +147,8 @@ func enrolledDevices(c Config) ([]client.Object, error) { return nil, errors.New("an enrolled Device is outside the provider's Device namespace") } target := c.Enrollment[key] - out = append(out, &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: inventory.DeviceSpec{ + // The label is what the local commissioning plan selects. + out = append(out, &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, Labels: map[string]string{HardwareModelLabel: "synthetic"}}, Spec: inventory.DeviceSpec{ ClaimRef: inventory.LocalReference{Name: "claim-" + name}, Identity: inventory.DeviceIdentity{Model: "synthetic", Serial: "serial-" + name, SystemUUID: target.SystemUUID}, BMC: &inventory.BMC{Endpoint: target.BMCEndpoint}, diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 32637d58..973a04bc 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -14,8 +14,6 @@ package registration import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -75,25 +73,6 @@ type Handler struct { Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error } -// Aliases returns the normalized hardware identifiers of a Device: serial, -// system UUID and, when present, the provider host reference. Two Devices -// sharing any alias may be the same machine. -func Aliases(device *inventory.Device) []string { - var result []string - pairs := [][2]string{{"serial", strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial))}, {"uuid", strings.ToLower(strings.TrimSpace(device.Spec.Identity.SystemUUID))}} - if reference := device.Spec.ProviderHostRef; reference != nil { - encoded, _ := json.Marshal([]string{strings.ToLower(strings.TrimSpace(reference.System)), strings.ToLower(strings.TrimSpace(reference.Type)), strings.ToLower(strings.TrimSpace(reference.ID))}) - pairs = append(pairs, [2]string{"provider", string(encoded)}) - } - for _, pair := range pairs { - if pair[1] != "" { - digest := sha256.Sum256([]byte(pair[0] + ":" + pair[1])) - result = append(result, pair[0]+":"+hex.EncodeToString(digest[:])) - } - } - return result -} - var systemUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) func eligible(device *inventory.Device) bool { @@ -291,7 +270,7 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis // provider scope. It is a point-in-time read: see the stage-1 contract for the // race with a concurrently created duplicate Device. func (handler *Handler) scan(ctx context.Context, selectedProject string, selected *inventory.Device) error { - selectedAliases := Aliases(selected) + selectedAliases := inventory.Aliases(selected) for _, name := range handler.Projects { project, err := handler.Resolve(ctx, name) if err != nil { @@ -310,7 +289,7 @@ func (handler *Handler) scan(ctx context.Context, selectedProject string, select if name == selectedProject && device.UID == selected.UID { continue } - if overlaps(Aliases(device), selectedAliases) { + if overlaps(inventory.Aliases(device), selectedAliases) { return fmt.Errorf("another Device (%s) shares recorded hardware identity; resolve the duplicate before registration", describe(name, selectedProject, device.Namespace, device.Name)) } } @@ -329,7 +308,7 @@ func (handler *Handler) scan(ctx context.Context, selectedProject string, select if matched == nil || inventory.CapacityBackingError(matched) != nil { return fmt.Errorf("capacity %s has unresolved physical identity; registration cannot establish non-conflict", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } - if overlaps(Aliases(matched), selectedAliases) { + if overlaps(inventory.Aliases(matched), selectedAliases) { return fmt.Errorf("capacity %s is backed by a Device sharing recorded hardware identity", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } } diff --git a/internal/site/fixture/access.go b/internal/site/fixture/access.go index 7638fad7..0be44dab 100644 --- a/internal/site/fixture/access.go +++ b/internal/site/fixture/access.go @@ -8,6 +8,7 @@ import ( "context" "strings" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" ) @@ -20,6 +21,11 @@ type Target struct { BootMACAddress string `json:"bootMACAddress"` BMCPublicKeySHA256 string `json:"bmcPublicKeySHA256"` Disks []string `json:"disks"` + // Hardware is what a simulated commissioning inspects. A target without + // it cannot be commissioned. + Hardware *ops.InspectedHardware `json:"hardware,omitempty"` + // Firmware is the firmware a simulated commissioning reads. + Firmware []ops.FirmwareBaseline `json:"firmware,omitempty"` } // Enrollment maps "/" to each Device the site serves. diff --git a/internal/site/fixture/inspect.go b/internal/site/fixture/inspect.go new file mode 100644 index 00000000..8b076d68 --- /dev/null +++ b/internal/site/fixture/inspect.go @@ -0,0 +1,54 @@ +package fixture + +import ( + "fmt" + "slices" + + "k8s.io/apimachinery/pkg/api/resource" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// Inspect compares a target's enrolled hardware and firmware with the plan, +// as the Redfish worker compares what the BMC reports. It returns the phase +// that failed and what failed, or no phase when the target meets the plan. +// A synthetic Device has no BMC, so its enrollment is what a commissioning +// inspects. +func Inspect(plan ops.CommissioningPlanContent, hw *ops.InspectedHardware, firmware []ops.FirmwareBaseline) (ops.CommissioningPhase, []string) { + if hw == nil { + return ops.PhaseInspect, []string{"the site enrolls no hardware for the Device"} + } + var out []string + want := plan.Inspection + if hw.CPU.Architecture != want.CPU.Architecture || hw.CPU.Cores != want.CPU.Cores { + out = append(out, fmt.Sprintf("%s with %d cores, want %s with %d", hw.CPU.Architecture, hw.CPU.Cores, want.CPU.Architecture, want.CPU.Cores)) + } + if have, err := resource.ParseQuantity(hw.Memory); err != nil || have.Cmp(resource.MustParse(want.Memory.Capacity)) != 0 { + out = append(out, fmt.Sprintf("%s of memory, want %s", hw.Memory, want.Memory.Capacity)) + } + minimum := resource.MustParse(want.Disks.MinCapacity) + var disks int64 + for _, disk := range hw.Disks { + if have, err := resource.ParseQuantity(disk.Capacity); err == nil && have.Cmp(minimum) >= 0 { + disks++ + } + } + if disks < want.Disks.Count { + out = append(out, fmt.Sprintf("%d disks of at least %s, want %d", disks, want.Disks.MinCapacity, want.Disks.Count)) + } + if int64(len(hw.Interfaces)) < want.Interfaces.Count { + out = append(out, fmt.Sprintf("%d network interfaces, want %d", len(hw.Interfaces), want.Interfaces.Count)) + } + if len(out) > 0 { + return ops.PhaseInspect, out + } + for _, baseline := range plan.Firmware { + if !slices.Contains(firmware, baseline) { + out = append(out, baseline.Component+" does not report version "+baseline.Version) + } + } + if len(out) > 0 { + return ops.PhaseFirmware, out + } + return "", nil +} diff --git a/internal/site/simwork/commissioning.go b/internal/site/simwork/commissioning.go new file mode 100644 index 00000000..8469d776 --- /dev/null +++ b/internal/site/simwork/commissioning.go @@ -0,0 +1,68 @@ +package simwork + +import ( + "context" + "encoding/json" + "slices" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" +) + +// Commissioning is the simulator's DeviceCommissioning worker. It inspects +// the hardware and firmware the site enrolls for the Device, then records +// one burn-in step in the fenced journal. The simulated burn-in always +// passes. It is never a production executor. +type Commissioning struct{} + +var _ site.Kind = Commissioning{} + +func commissioningSpec(work *site.Work) (ops.DeviceCommissioningSpec, *custody.Refusal) { + var spec ops.DeviceCommissioningSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.Plan.Digest == "" { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceCommissioning spec"} + } + return spec, nil +} + +func (Commissioning) Check(_ context.Context, work *site.Work) *custody.Refusal { + if _, refusal := commissioningSpec(work); refusal != nil { + return refusal + } + if connection(work) == nil || connection(work).Target.Hardware == nil { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site enrolls no hardware for the Device"} + } + return nil +} + +func (Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := commissioningSpec(work) + if refusal != nil { + return nil, refusal + } + target := connection(work).Target + inspected := *target.Hardware + evidence := ops.CommissioningEvidence{Plan: spec.Plan.ApprovedPlanReference, SerialNumber: work.Snapshot.Extra[custody.SnapshotSerialNumber], SystemUUID: target.SystemUUID, + BMCPublicKeySHA256: target.BMCPublicKeySHA256, Hardware: &inspected, Firmware: slices.Clone(target.Firmware)} + if phase, mismatches := fixture.Inspect(spec.Plan.Content, target.Hardware, target.Firmware); len(mismatches) > 0 { + evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, phase, mismatches + return evidence, nil + } + // The step name marks the evidence as simulated, so a simulated pass is + // never read as a real burn-in. + step := site.Step{Name: "simulated-burnin", Send: func(context.Context) error { return nil }, Idempotent: true} + if err := work.Step(ctx, step); err != nil { + return nil, err + } + at, _ := work.JournaledAt(step.Name) + evidence.Steps = []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}} + // The simulated burn-in takes no time; its evidence records the plan's + // duration, as a real image would report after running it. + evidence.BurnIn = &ops.BurnInEvidence{Result: ops.BurnInPassed, StartedAt: metav1.NewTime(at.UTC()), CompletedAt: metav1.NewTime(at.UTC().Add(spec.Plan.Content.BurnIn.Duration.Duration))} + evidence.Result = ops.CommissioningPassed + return evidence, nil +} diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go index 824d41e4..d07c77e5 100644 --- a/internal/site/vmwork/boot.go +++ b/internal/site/vmwork/boot.go @@ -139,7 +139,7 @@ func (c Config) BootHandler(store *site.Store) http.Handler { switch name { case "boot.ipxe": base := c.origin() + "/" + parts[1] + "/" + boot.Token - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, base)) + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, modeArgs(boot), base)) size = int64(len(data)) case "kernel", "installer.gz": // Hash the pinned artifact, then serve the same open file. diff --git a/internal/site/vmwork/commissioning.go b/internal/site/vmwork/commissioning.go new file mode 100644 index 00000000..aa8c7459 --- /dev/null +++ b/internal/site/vmwork/commissioning.go @@ -0,0 +1,275 @@ +package vmwork + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" +) + +// burnInStage is the commissioning's one boot: the site image in burn-in +// mode, booted from the network like the installer. +const burnInStage = "burnin" + +// burnInMarker prefixes the burn-in image's one result line. +const burnInMarker = "FLEET-BURNIN:" + +// Commissioning is the local VM's DeviceCommissioning worker. The local VM +// has no BMC, so inspection compares the hardware and firmware the site +// enrolls for the Device, which describe the guest the site defines, with the +// plan. Burn-in is real: one network boot of the site image in burn-in mode +// on a scratch disk, proven by its console receipt. The scratch disk is +// removed afterwards, so a commissioning leaves no disk behind. +type Commissioning struct{ Config } + +var _ site.Kind = Commissioning{} + +func (k Commissioning) spec(work *site.Work) (ops.DeviceCommissioningSpec, *custody.Refusal) { + var spec ops.DeviceCommissioningSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.Plan.Digest == "" { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceCommissioning spec"} + } + return spec, nil +} + +func (k Commissioning) Check(_ context.Context, work *site.Work) *custody.Refusal { + spec, refusal := k.spec(work) + if refusal != nil { + return refusal + } + connection, _ := work.Connection.(*fixture.Connection) + if connection == nil { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site does not run local VMs"} + } + if connection.Target.Hardware == nil || len(connection.Target.Disks) != 1 { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site enrolls no hardware, or not exactly one disk, for the Device"} + } + burnIn := spec.Plan.Content.BurnIn + if burnIn.Image.Name+"@"+burnIn.Image.Digest != k.Image { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site does not serve the plan's burn-in image"} + } + if d := burnIn.Duration.Duration; d < time.Minute || d > 24*time.Hour { + return &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the burn-in duration is outside 1 minute to 24 hours"} + } + return nil +} + +func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := k.spec(work) + if refusal != nil { + return nil, refusal + } + target := work.Connection.(*fixture.Connection).Target + plan := spec.Plan.Content + inspected := *target.Hardware + evidence := ops.CommissioningEvidence{Plan: spec.Plan.ApprovedPlanReference, SerialNumber: work.Snapshot.Extra[custody.SnapshotSerialNumber], SystemUUID: target.SystemUUID, + BMCPublicKeySHA256: target.BMCPublicKeySHA256, Hardware: &inspected, Firmware: slices.Clone(target.Firmware)} + if phase, mismatches := fixture.Inspect(plan, target.Hardware, target.Firmware); len(mismatches) > 0 { + evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, phase, mismatches + return evidence, nil + } + result, err := k.burnIn(ctx, work, plan.BurnIn.Duration.Duration) + if err != nil { + return nil, err + } + for _, step := range []string{burnInStage + "-start", burnInStage + "-verified", burnInStage + "-disk-removed"} { + at, _ := work.JournaledAt(step) + evidence.Steps = append(evidence.Steps, ops.StepEvidence{Name: step, CompletedAt: metav1.NewTime(at.UTC())}) + } + started, _ := work.JournaledAt(burnInStage + "-start") + completed, _ := work.JournaledAt(burnInStage + "-verified") + evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metav1.NewTime(started.UTC()), CompletedAt: metav1.NewTime(completed.UTC())} + switch { + case result != ops.BurnInPassed: + evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, ops.PhaseBurnIn, []string{"the burn-in image reported a failure"} + case completed.Sub(started) < plan.BurnIn.Duration.Duration: + evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, ops.PhaseBurnIn, []string{"the burn-in reported before the plan's duration"} + default: + evidence.Result = ops.CommissioningPassed + } + return evidence, nil +} + +// bootRecord reads the commissioning's boot admission, creating it once in +// burn-in mode. The receipt is fixed before any boot, so a replay waits for +// the same receipt. +func (k Commissioning) bootRecord(work *site.Work, duration time.Duration) (Boot, error) { + var boot Boot + found, err := work.Store().GetRecord(work.Device, bootRecords, Key(work.Key()), &boot) + if err != nil || found { + return boot, err + } + receipt, token := make([]byte, 32), make([]byte, 32) + if _, err := rand.Read(receipt); err != nil { + return boot, err + } + if _, err := rand.Read(token); err != nil { + return boot, err + } + boot = Boot{Operation: work.Key(), Fence: work.Fence, Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: k.now().Add(k.window()), + Mode: burnInStage, DurationSeconds: int64(duration / time.Second)} + return boot, Installation(k).save(work, boot) +} + +// burnIn boots the site image in burn-in mode once on a scratch disk and +// reads its one result. Each effect is a journaled step, so a resumed worker +// continues instead of booting again. +func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration time.Duration) (ops.BurnInResult, error) { + install := Installation(k) + boot, err := k.bootRecord(work, duration) + if err != nil { + return "", err + } + dir := install.directory(work.Device, work.Key()) + disk := filepath.Join(dir, "disk.raw") + if !work.Journaled(burnInStage + "-verified") { + if err := work.Step(ctx, site.Step{ + Name: burnInStage + "-disk", + Send: func(context.Context) error { return createDisk(dir, disk) }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + _, err := os.Stat(disk) + return err == nil, nil + }, + }); err != nil { + return "", err + } + if k.PXE && !work.Journaled(burnInStage+"-start") { + if boot.Closed || !k.now().Before(boot.Expires) { + return "", errors.New("the boot admission expired or closed before the network boot") + } + if err := work.Step(ctx, site.Step{Name: burnInStage + "-network", Send: func(ctx context.Context) error { return install.prepareNetwork(ctx, work, boot) }, Idempotent: true}); err != nil { + return "", err + } + boot.Open = true + if err := install.save(work, boot); err != nil { + return "", err + } + } + xml := install.domainXML(work, boot, burnInStage) + if err := os.WriteFile(filepath.Join(dir, burnInStage+".xml"), []byte(xml), 0o600); err != nil { + return "", err + } + // A failed network boot closes its admission at once, as an + // installer's does. + fail := func(err error) error { + if k.PXE && boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { + boot.Open, boot.Closed = false, true + _ = install.save(work, boot) + } + return err + } + if err := work.Step(ctx, site.Step{ + Name: burnInStage + "-start", + Send: func(ctx context.Context) error { + _, err := k.virsh(ctx, "create", filepath.Join(dir, burnInStage+".xml")) + return err + }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { + running, err := install.running(ctx, work.Key()) + if err != nil || running { + return running, err + } + _, err = os.Stat(filepath.Join(dir, burnInStage+".log")) + return err == nil, nil + }, + }); err != nil { + return "", fail(err) + } + if _, err := k.waitBurnIn(ctx, work, boot); err != nil { + return "", fail(err) + } + if k.PXE { + if err := install.verifyNetworkBoot(ctx, work); err != nil { + return "", fail(err) + } + boot.Open, boot.Closed = false, true + if err := install.save(work, boot); err != nil { + return "", err + } + } + if err := work.Step(ctx, site.Step{Name: burnInStage + "-verified", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { + return "", err + } + } + result, err := k.burnInResult(work, boot) + if err != nil { + return "", err + } + if k.PXE { + if err := work.Step(ctx, site.Step{Name: burnInStage + "-network-off", Send: k.stopNetwork, Idempotent: true}); err != nil { + return "", err + } + } + // The burn-in only reads its scratch disk; removing it leaves the Device + // with no disk the commissioning made. + if err := work.Step(ctx, site.Step{ + Name: burnInStage + "-disk-removed", + Send: func(context.Context) error { + if err := os.Remove(disk); err != nil && !os.IsNotExist(err) { + return err + } + return syncDir(dir) + }, + Idempotent: true, + }); err != nil { + return "", err + } + return result, nil +} + +// waitBurnIn waits for the guest to stop, then reads its result. +func (k Commissioning) waitBurnIn(ctx context.Context, work *site.Work, boot Boot) (ops.BurnInResult, error) { + for { + running, err := Installation(k).running(ctx, work.Key()) + if err != nil { + return "", err + } + if !running { + return k.burnInResult(work, boot) + } + select { + case <-ctx.Done(): + return "", context.Cause(ctx) + case <-time.After(time.Second): + } + } +} + +// burnInResult reads the one result line with this boot's receipt. Any other +// count proves nothing. +func (k Commissioning) burnInResult(work *site.Work, boot Boot) (ops.BurnInResult, error) { + data, err := os.ReadFile(filepath.Join(Installation(k).directory(work.Device, work.Key()), burnInStage+".log")) + if err != nil { + return "", err + } + prefix := burnInMarker + boot.Receipt + ":" + var results []string + for _, line := range strings.Split(string(data), "\n") { + if line = strings.TrimSpace(line); strings.HasPrefix(line, prefix) { + results = append(results, strings.TrimPrefix(line, prefix)) + } + } + if len(results) != 1 { + return "", errors.New("the guest stopped without exactly one burn-in result") + } + switch results[0] { + case "passed": + return ops.BurnInPassed, nil + case "failed": + return ops.BurnInFailed, nil + } + return "", errors.New("the burn-in result is neither passed nor failed") +} diff --git a/internal/site/vmwork/commissioning_test.go b/internal/site/vmwork/commissioning_test.go new file mode 100644 index 00000000..c3198914 --- /dev/null +++ b/internal/site/vmwork/commissioning_test.go @@ -0,0 +1,143 @@ +package vmwork + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" +) + +// localHardware is what the site enrolls for the local guest. +var localHardware = &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", + Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: "02:00:00:00:00:01"}}} + +// commissioningRig is a rig whose site store clock advances a minute on each +// read, so a burn-in the fake guest finishes at once spans the plan's +// duration in the journal. tick false keeps the real clock. +func commissioningRig(t *testing.T, tick bool) *rig { + r := newRig(t) + if tick { + var mu sync.Mutex + now := time.Now().UTC() + store, err := site.OpenStore(filepath.Join(filepath.Dir(r.config.Disks), "store"), func() time.Time { + mu.Lock() + defer mu.Unlock() + now = now.Add(time.Minute) + return now + }) + if err != nil { + t.Fatal(err) + } + r.store, r.runner.Store, r.runner.Results = store, store, site.NewResults(store) + } + access := r.runner.Access.(fixture.Access) + target := access.Enrollment[device] + target.Hardware = localHardware + access.Enrollment[device] = target + r.runner.Kinds["DeviceCommissioning"] = Commissioning{r.config} + return r +} + +func commissioningSpec(mutate func(*ops.CommissioningPlanContent)) ops.DeviceCommissioningSpec { + name, digest, _ := strings.Cut(image, "@") + content := ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "1Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: name, Digest: digest}, Duration: metav1.Duration{Duration: time.Minute}}, + } + if mutate != nil { + mutate(&content) + } + envelope := envelope() + envelope.Authority = ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "intake"}} + return ops.DeviceCommissioningSpec{OperationEnvelope: envelope, Plan: ops.CommissioningPlanInput{ + ApprovedPlanReference: ops.ApprovedPlanReference{PlanReference: ops.PlanReference{Name: "local-plan", Generation: 1, Digest: "sha256:" + key}, Approval: "local-plan-approval"}, + Content: content}} +} + +func (r *rig) commission(uid string, spec ops.DeviceCommissioningSpec) (custody.SiteResult, ops.CommissioningEvidence) { + r.t.Helper() + work := r.assignment("DeviceCommissioning", uid, 2, spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + result, err := r.runner.Run(context.Background(), work) + if err != nil { + r.t.Fatal(err) + } + var evidence ops.CommissioningEvidence + if result.Phase == ops.PhaseSucceeded { + if err := json.Unmarshal(result.Evidence, &evidence); err != nil { + r.t.Fatal(err) + } + // The evidence passes the kind's own validation. + operation := &ops.DeviceCommissioning{Spec: spec, Status: ops.OperationStatus{Snapshot: &work.Snapshot}} + if _, err := custody.DeviceCommissioningKind().Evidence(operation, result.Evidence); err != nil { + r.t.Fatalf("the kind rejects the worker's evidence: %v", err) + } + } + return result, evidence +} + +// TestCommissioningBurnsInOnceAndLeavesNoDisk inspects the enrolled guest, +// boots the site image once in burn-in mode, and passes on its receipt. +func TestCommissioningBurnsInOnceAndLeavesNoDisk(t *testing.T) { + r := commissioningRig(t, true) + result, evidence := r.commission("00000000-0000-4000-8000-000000000301", commissioningSpec(nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningPassed || evidence.BurnIn == nil || evidence.BurnIn.Result != ops.BurnInPassed { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + if r.vm.creates != 1 { + t.Fatalf("boots = %d, want one burn-in boot", r.vm.creates) + } + xml, err := os.ReadFile(filepath.Join(r.config.directory(device, r.assignment("DeviceCommissioning", "00000000-0000-4000-8000-000000000301", 2, nil).Key()), burnInStage+".xml")) + if err != nil || !strings.Contains(string(xml), "fleet.mode=burnin fleet.duration=60") { + t.Fatalf("the burn-in boot does not pass the mode and duration: %v", err) + } + if disks, _ := filepath.Glob(filepath.Join(r.config.Disks, "*", "*", "disk.raw")); len(disks) != 0 { + t.Fatalf("the commissioning left disks %v", disks) + } +} + +// TestABurnInFailureOrAShortBurnInFails records a failed burn-in, and one +// that reported before the plan's duration, as proven failures. +func TestABurnInFailureOrAShortBurnInFails(t *testing.T) { + failing := commissioningRig(t, true) + failing.vm.burnInFails = true + if result, evidence := failing.commission("00000000-0000-4000-8000-000000000302", commissioningSpec(nil)); result.Phase != ops.PhaseSucceeded || + evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || evidence.BurnIn.Result != ops.BurnInFailed { + t.Fatalf("a failed burn-in = %+v, %+v", result, evidence) + } + // With the real clock the fake guest reports at once, well short of the + // plan's minute. + short := commissioningRig(t, false) + if result, evidence := short.commission("00000000-0000-4000-8000-000000000303", commissioningSpec(nil)); result.Phase != ops.PhaseSucceeded || + evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { + t.Fatalf("a short burn-in = %+v, %+v", result, evidence) + } +} + +// TestCommissioningChecksBeforeAnyBoot fails a guest that does not meet the +// plan, and refuses a burn-in image the site does not serve, without booting. +func TestCommissioningChecksBeforeAnyBoot(t *testing.T) { + r := commissioningRig(t, true) + result, evidence := r.commission("00000000-0000-4000-8000-000000000304", commissioningSpec(func(c *ops.CommissioningPlanContent) { c.Inspection.CPU.Cores = 4 })) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseInspect || r.vm.creates != 0 { + t.Fatalf("a mismatched guest = %+v, %+v, boots %d", result, evidence, r.vm.creates) + } + refused, _ := r.commission("00000000-0000-4000-8000-000000000305", commissioningSpec(func(c *ops.CommissioningPlanContent) { + c.BurnIn.Image.Digest = "sha256:" + strings.Repeat("c", 64) + })) + if refused.Phase != ops.PhaseFailed || refused.Reason != custody.ReasonTargetUnsupported || r.vm.creates != 0 { + t.Fatalf("another burn-in image = %+v, boots %d", refused, r.vm.creates) + } +} diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 559e09c1..938a0b49 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -169,6 +169,10 @@ type Boot struct { // Accelerator is the one the installation runs under, fixed before any // boot, so a replacement worker never resumes it under another. Accelerator string `json:"accelerator"` + // Mode is the boot image's mode: empty to install, burnin for a + // commissioning's burn-in. DurationSeconds is how long a burn-in runs. + Mode string `json:"mode,omitempty"` + DurationSeconds int64 `json:"durationSeconds,omitempty"` } const bootRecords = "vmboot" @@ -352,8 +356,8 @@ func (k Installation) domainXML(work *site.Work, boot Boot, stage string) string dir := k.directory(work.Device, work.Key()) bootXML := "" nic := "" - if stage == "installer" { - bootXML = fmt.Sprintf("%s/kernel%s/installer.gzconsole=ttyS0 rdinit=/init fleet.receipt=%s", k.Artifacts, k.Artifacts, boot.Receipt) + if stage == "installer" || stage == burnInStage { + bootXML = fmt.Sprintf("%s/kernel%s/installer.gzconsole=ttyS0 rdinit=/init fleet.receipt=%s%s", k.Artifacts, k.Artifacts, boot.Receipt, modeArgs(boot)) if k.PXE { bootXML = "" nic = "" @@ -366,6 +370,14 @@ func (k Installation) domainXML(work *site.Work, boot Boot, stage string) string return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(work.Key()), bootXML, nic, dir, dir, stage) } +// modeArgs is the kernel arguments that select the boot image's mode. +func modeArgs(boot Boot) string { + if boot.Mode == "" { + return "" + } + return fmt.Sprintf(" fleet.mode=%s fleet.duration=%d", boot.Mode, boot.DurationSeconds) +} + // waitReceipt waits for the guest to stop with exactly this phase's receipt. func (k Installation) waitReceipt(ctx context.Context, work *site.Work, boot Boot, stage string) error { marker := "FLEET-INSTALLED:" diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index a32d25dc..17ebd0f1 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -40,6 +40,8 @@ type hypervisor struct { stuck bool // exited makes destroy fail because the guest exited first. exited bool + // burnInFails makes a burn-in guest report a failure. + burnInFails bool } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -59,7 +61,13 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e log := regexp.MustCompile(``).FindStringSubmatch(xml)[1] marker := "FLEET-DISK-BOOT:" receipt := "" - if match := receiptArg.FindStringSubmatch(xml); match != nil { + if match := receiptArg.FindStringSubmatch(xml); match != nil && strings.Contains(xml, "fleet.mode=burnin") { + result := "passed" + if h.burnInFails { + result = "failed" + } + marker, receipt = "FLEET-BURNIN:", match[1]+":"+result + } else if match != nil { marker, receipt = "FLEET-INSTALLED:", match[1] } else { // The disk boot prints the receipt the installer wrote. diff --git a/internal/staging/handler.go b/internal/staging/handler.go index 82685548..83cdfe36 100644 --- a/internal/staging/handler.go +++ b/internal/staging/handler.go @@ -131,13 +131,6 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ now := h.Now().UTC() for i := range list.Items { machine := &list.Items[i] - available := true - if current := apiMeta.FindStatusCondition(machine.Status.Conditions, "Available"); current != nil && current.Status == metav1.ConditionFalse { - available = false - } - if err := h.ensureObservation(ctx, machineClient, machine, available); err != nil { - return manager.Outcome{RetryError: err} - } machines = append(machines, *machine) evidence[machine.UID] = now } @@ -162,13 +155,6 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ if err != nil { return manager.Outcome{RetryError: err} } - for i := range list.Items { - if list.Items[i].Name == record.Spec.MachineCapacityRef.Name { - if err := h.ensureObservation(ctx, machineClient, &list.Items[i], false); err != nil { - return manager.Outcome{RetryError: err} - } - } - } observed := metav1.NewTime(now) if claim.Status.AllocatedHardware != nil && claim.Status.AllocatedHardware.ObservedAt != nil { observed = *claim.Status.AllocatedHardware.ObservedAt @@ -268,41 +254,11 @@ func (h Handler) release(ctx context.Context, namespace string, uid types.UID, c if current == nil { return manager.Outcome{} } - // The released capacity is offered again. Custody stays the authority. - capacity := &fleetv1.MachineCapacity{} - reference := current.Spec.MachineCapacityRef - if err := h.Allocator.Provider.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, capacity); apierrors.IsNotFound(err) { - return manager.Outcome{} - } else if err != nil { - return manager.Outcome{RetryError: err} - } - if err := h.ensureObservation(ctx, h.Allocator.Provider, capacity, true); err != nil { - return manager.Outcome{RetryError: err} - } + // The capacity projector offers the released capacity again from + // evidence; custody stays the authority. return manager.Outcome{} } -func (h Handler) ensureObservation(ctx context.Context, target client.Client, machine *fleetv1.MachineCapacity, available bool) error { - want := fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} - conditions := []metav1.Condition{ - condition("Prepared", metav1.ConditionTrue, machine.Generation, "SyntheticProvider", "Synthetic staging provider reports the machine prepared."), - condition("Healthy", metav1.ConditionTrue, machine.Generation, "SyntheticProvider", "Synthetic staging provider reports the machine healthy."), - } - if available { - conditions = append(conditions, condition("Available", metav1.ConditionTrue, machine.Generation, "SyntheticProvider", "Synthetic staging provider reports the machine available; private custody enforces exclusivity.")) - } else { - conditions = append(conditions, condition("Available", metav1.ConditionFalse, machine.Generation, "Allocated", "Private custody records an active allocation.")) - } - if machine.Status.Hardware.CPU.Cores == want.CPU.Cores && machine.Status.Hardware.Memory.Capacity == want.Memory.Capacity { - current := apiMeta.FindStatusCondition(machine.Status.Conditions, "Available") - if current != nil && current.Status == conditions[2].Status && current.ObservedGeneration == machine.Generation { - return nil - } - } - machine.Status = fleetv1.MachineCapacityStatus{Hardware: want, Conditions: conditions} - return target.Status().Update(ctx, machine) -} - func publishedFor(object client.Object, provider controller.ProjectIdentity) bool { annotations := object.GetAnnotations() return annotations[publicationManagedByAnnotation] == publicationManager && annotations[publicationProviderUIDAnnotation] == string(provider.UID) && annotations[publicationSourceUIDAnnotation] != "" && annotations[publicationSourceNameAnnotation] != "" diff --git a/internal/staging/handler_test.go b/internal/staging/handler_test.go index aa4420ff..1635fcda 100644 --- a/internal/staging/handler_test.go +++ b/internal/staging/handler_test.go @@ -225,10 +225,11 @@ func TestPublishedConsumerClaimAllocatesProviderMachine(t *testing.T) { if holder := s.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != allocated.Name { t.Fatalf("holder = %+v", holder) } - capacity := s.capacity(device.Name) - if c := apiMeta.FindStatusCondition(capacity.Status.Conditions, "Available"); c == nil || c.Status != metav1.ConditionFalse { - t.Fatalf("provider capacity not marked allocated: %#v", capacity.Status.Conditions) - } + // The capacity projector, not the handler, withdraws the offer. + s.until("the projector withdraws the allocated capacity", func() bool { + c := apiMeta.FindStatusCondition(s.capacity(device.Name).Status.Conditions, "Available") + return c != nil && c.Status == metav1.ConditionFalse && c.Reason == "Held" + }) if err := consumerKube.Delete(s.ctx, &got); err != nil { t.Fatal(err) @@ -242,10 +243,10 @@ func TestPublishedConsumerClaimAllocatesProviderMachine(t *testing.T) { if holder := s.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { t.Fatalf("holder after release = %+v", holder) } - capacity = s.capacity(device.Name) - if c := apiMeta.FindStatusCondition(capacity.Status.Conditions, "Available"); c == nil || c.Status != metav1.ConditionTrue { - t.Fatalf("provider capacity did not become reusable: %#v", capacity.Status.Conditions) - } + s.until("the projector offers the released capacity again", func() bool { + c := apiMeta.FindStatusCondition(s.capacity(device.Name).Status.Conditions, "Available") + return c != nil && c.Status == metav1.ConditionTrue + }) } func (s *stack) capacity(device string) *fleetv1.MachineCapacity { diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index 63816c5b..106be793 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "go.datum.net/fleet/internal/capacity" + "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -60,6 +62,8 @@ type stack struct { sites *delivery.Sites class *fleetv1.MachineClass profile *fleetv1.MachineProfile + projector *capacity.Projector + plan *ops.DeviceCommissioningPlan } func stackScheme(t *testing.T) *runtime.Scheme { @@ -109,7 +113,7 @@ func startStack(t *testing.T) *stack { } enrollment := fixture.Enrollment{} 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{}}, Poll: 20 * time.Millisecond} + 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 })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) @@ -125,15 +129,34 @@ func startStack(t *testing.T) *stack { 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}}, }}} - s.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: providerNamespace, + s.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: providerNamespace, Cleaning: capacity.Fixed(map[string]string{"example-cleaning": policyDigest})} + s.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: providerNamespace, Capacity: s.projector, Courier: &delivery.Courier{Client: admin, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: providerNamespace}} s.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, Namespace: providerNamespace, Cleaning: func(string) (string, error) { return policyDigest, nil }, + Capacity: s.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } + // One qualified plan covers every fixture server. + s.plan = &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan", Namespace: providerNamespace}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: ops.Creator{Username: "plan-author@example.com", UID: uid(803)}, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/hardware-model": "example"}}, + Content: ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 24}, Memory: ops.InspectionValue{Capacity: "128Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "100Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: policyDigest}, Duration: metav1.Duration{Duration: time.Minute}}, + }, + EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, + }} + s.create(s.plan) + approval, err := custody.NewApproval(s.plan, ops.Creator{Username: "plan-approver@example.com", UID: uid(804)}) + if err != nil { + t.Fatal(err) + } + s.create(approval) s.servers = enrollment s.sites = sites s.class = &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: className}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: profileName}}}, Access: &fleetv1.AccessPolicy{}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: providerNamespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} @@ -157,26 +180,20 @@ func (s *stack) server(n int) *inventory.Device { s.t.Helper() name := fmt.Sprintf("server-example-%03d", n) mac := fmt.Sprintf("02:00:00:00:00:%02x", n) - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: providerNamespace}, Spec: inventory.DeviceSpec{ + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: providerNamespace, Labels: map[string]string{"fleet.datumapis.com/hardware-model": "example"}}, Spec: inventory.DeviceSpec{ ClaimRef: inventory.LocalReference{Name: "claim-" + name}, Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-" + name, SystemUUID: uid(100 + n)}, BMC: &inventory.BMC{Endpoint: fmt.Sprintf("https://[2001:db8::%x]", n)}, Interfaces: []inventory.Interface{{Name: "primary", MACAddress: mac}}, }} s.create(device) - target := fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), Disks: []string{"disk-0"}} + target := fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), Disks: []string{"disk-0"}, + Hardware: &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Sockets: 2, Cores: 24}, Memory: "128Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "960Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: mac}}}} s.servers[providerNamespace+"/"+name] = target s.sites.Devices[name] = []string{siteName} capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: providerNamespace, Labels: map[string]string{"pool": "example"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} s.create(capacity) - capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} - for _, kind := range []string{"Prepared", "Healthy", "Available"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: "Fixture", ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now()}) - } - if err := s.admin.Status().Update(s.ctx, capacity); err != nil { - s.t.Fatal(err) - } if err := fixture.Discover(s.ctx, s.admin, fixture.Enrollment{providerNamespace + "/" + name: target}, time.Now()); err != nil { s.t.Fatal(err) } @@ -184,6 +201,19 @@ func (s *stack) server(n int) *inventory.Device { state := s.custody(name) return state != nil && state.Spec.State == ops.CustodyVerified }) + // Commission the server, so the projector offers it. + if err := s.admin.Get(s.ctx, client.ObjectKeyFromObject(device), device); err != nil { + s.t.Fatal(err) + } + operation, err := custody.NewCommissioning(device, s.plan, ops.Creator{Username: "operator@example.com", UID: uid(805)}, "fixture intake") + if err != nil { + s.t.Fatal(err) + } + s.create(operation) + s.until("the capacity is offered", func() bool { + offered, _, err := s.projector.Offer(s.ctx, capacity) + return err == nil && offered + }) return device } diff --git a/internal/staging/multicluster_test.go b/internal/staging/multicluster_test.go index 22963c51..2251c667 100644 --- a/internal/staging/multicluster_test.go +++ b/internal/staging/multicluster_test.go @@ -7,7 +7,6 @@ import ( "time" corev1 "k8s.io/api/core/v1" - apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -22,6 +21,7 @@ import ( metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/manager" @@ -183,12 +183,9 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { if hw := get(consumer).Status.RequestedHardware; hw == nil || hw.CPU.Cores != 24 { t.Fatalf("consumer requested hardware = %#v", hw) } - var allocated fleetv1.MachineCapacity - if err := provider.Client.Get(ctx, client.ObjectKeyFromObject(capacity), &allocated); err != nil { - t.Fatal(err) - } - if c := apiMeta.FindStatusCondition(allocated.Status.Conditions, "Available"); c == nil || c.Status != metav1.ConditionFalse { - t.Fatalf("provider capacity not allocated: %#v", allocated.Status.Conditions) + // Custody, not a status condition, records that the server is taken. + if state := s.custody(capacity.Spec.DeviceRef.Name); state == nil || state.Spec.Holder.Type != ops.HolderAllocation { + t.Fatalf("provider capacity not allocated: custody %+v", state) } multiclustertest.Eventually(t, "the other project resolves requested hardware", func() bool { hw := get(other).Status.RequestedHardware @@ -206,16 +203,12 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { hw := get(provider).Status.RequestedHardware return hw != nil && hw.CPU.Cores == 24 }) - writes := capacityStatusWrites.Load() - multiclustertest.Consistently(t, "the provider project gets nothing but requested hardware and its capacity stays allocated once", func() bool { + // Only the capacity projector writes capacity status; the handler never + // does. + multiclustertest.Consistently(t, "the provider project gets nothing but requested hardware and the handler writes no capacity status", func() bool { m := get(provider) - var current fleetv1.MachineCapacity - if err := provider.Client.Get(ctx, client.ObjectKeyFromObject(capacity), ¤t); err != nil { - return false - } - c := apiMeta.FindStatusCondition(current.Status.Conditions, "Available") return m.Status.Phase == "" && len(m.Finalizers) == 0 && len(m.Status.Conditions) == 1 && - c != nil && c.Status == metav1.ConditionFalse && capacityStatusWrites.Load() == writes && get(consumer).Status.Phase == "Ready" + capacityStatusWrites.Load() == 0 && get(consumer).Status.Phase == "Ready" }) // Only the consumer's Machine holds provider capacity, on custody, and // the power projector reports for it alone. diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 20dbb4fa..3ec3d0ad 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "strings" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -18,6 +19,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" @@ -27,10 +29,11 @@ import ( ) const ( - PhaseAllocate = "allocate" - PhaseInstall = "install" - PhaseReinstall = "reinstall" - PhaseRelease = "release" + PhaseCommission = "commission" + PhaseAllocate = "allocate" + PhaseInstall = "install" + PhaseReinstall = "reinstall" + PhaseRelease = "release" ) type Options struct { @@ -64,8 +67,19 @@ func DefaultOptions() Options { type Runner struct { Client client.Client Allocator *allocation.Allocator - Options Options - Now func() time.Time + // Staff are the commissioning phase's three people. + Staff *Staff + Options Options + Now func() time.Time +} + +// Staff are the plan author, the approver and the commissioning operator, +// each with their own identity, so the two-person rule holds. +type Staff struct { + Author, Approver, Operator client.Client + // AuthorCreator, ApproverCreator and OperatorCreator are each client's + // authenticated identity. + AuthorCreator, ApproverCreator, OperatorCreator ops.Creator } func (r Runner) Run(ctx context.Context, phase string) error { @@ -76,6 +90,8 @@ func (r Runner) Run(ctx context.Context, phase string) error { r.Now = time.Now } switch phase { + case PhaseCommission: + return r.commission(ctx) case PhaseAllocate: return r.allocate(ctx) case PhaseInstall: @@ -131,9 +147,6 @@ func (r Runner) allocate(ctx context.Context) error { if lost, err := r.Allocator.Get(ctx, second.machine); err != nil || lost != nil { return fmt.Errorf("the losing consumer kept an allocation: %v", err) } - if err := r.projectOccupied(ctx, capacity); err != nil { - return err - } return r.projectPending(ctx, second, profile, "InsufficientCapacity", "The only synthetic machine is allocated to another consumer.") } @@ -255,10 +268,7 @@ func (r Runner) release(ctx context.Context) error { if reused.Spec.DeviceRef.Name != capacity.Spec.DeviceRef.Name { return errors.New("the waiting consumer did not reuse the released Device") } - if err := r.projectBound(ctx, second, profile, reused); err != nil { - return err - } - return r.projectOccupied(ctx, capacity) + return r.projectBound(ctx, second, profile, reused) } // await polls until done, a failure, or the phase's wait bound. @@ -280,9 +290,8 @@ func (r Runner) await(ctx context.Context, what string, done func() (bool, error } } -// inputs reads the fixtures and writes the synthetic capacity evidence. The -// capacity projector is not wired, so the fixture writes Prepared, Healthy -// and Available itself. Custody stays authoritative for exclusivity. +// inputs reads the fixtures. The capacity projector, not the phase, writes +// the capacity's status from commissioning evidence. func (r Runner) inputs(ctx context.Context) (*fleetv1.MachineClass, *fleetv1.MachineProfile, *fleetv1.MachineCapacity, error) { var class fleetv1.MachineClass var profile fleetv1.MachineProfile @@ -299,15 +308,6 @@ func (r Runner) inputs(ctx context.Context) (*fleetv1.MachineClass, *fleetv1.Mac if class.Spec.Capacity == nil || class.Spec.Capacity.MachineCapacities.Namespace != r.Options.ProviderNamespace { return nil, nil, nil, errors.New("synthetic provider scope does not match configuration") } - capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} - capacity.Status.Conditions = []metav1.Condition{ - condition("Prepared", metav1.ConditionTrue, capacity.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), - condition("Healthy", metav1.ConditionTrue, capacity.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), - condition("Available", metav1.ConditionTrue, capacity.Generation, "SyntheticEvidence", "Device custody remains authoritative for exclusivity."), - } - if err := r.Client.Status().Update(ctx, &capacity); err != nil { - return nil, nil, nil, err - } return &class, &profile, &capacity, nil } @@ -406,11 +406,6 @@ func (r Runner) projectPower(ctx context.Context, machine allocation.Machine) er return manager.ProjectPower(ctx, r.Client, r.Client, r.Options.ProviderNamespace, machine) } -func (r Runner) projectOccupied(ctx context.Context, capacity *fleetv1.MachineCapacity) error { - apiMeta.SetStatusCondition(&capacity.Status.Conditions, condition("Available", metav1.ConditionFalse, capacity.Generation, "Allocated", "Device custody names an active allocation.")) - return r.Client.Status().Update(ctx, capacity) -} - func (r Runner) removeFinalizer(ctx context.Context, key client.ObjectKey, uid types.UID) error { return retry.RetryOnConflict(retry.DefaultRetry, func() error { var current fleetv1.Machine @@ -452,3 +447,90 @@ func remove(v []string, w string) []string { } return out } + +// Plan is the synthetic commissioning plan: the fixture profile's hardware, +// the simulator's firmware, and a one-minute burn-in. +func (o Options) Plan(author ops.Creator) *ops.DeviceCommissioningPlan { + return &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-plan-v1", Namespace: o.ProviderNamespace}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: author, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/hardware-model": "synthetic"}}, + Content: ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 24}, Memory: ops.InspectionValue{Capacity: "128Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "100Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + Firmware: []ops.FirmwareBaseline{{Component: "BMC", Version: "synthetic-1.0"}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "synthetic-burn-in", Digest: "sha256:" + strings.Repeat("5", 64)}, Duration: metav1.Duration{Duration: time.Minute}}, + }, + EvidenceLifetime: metav1.Duration{Duration: 30 * 24 * time.Hour}, + }} +} + +// commission qualifies the synthetic plan with two people, commissions the +// fixture Device under it, and waits until the projector offers the +// capacity. It repeats safely. +func (r Runner) commission(ctx context.Context) error { + if r.Staff == nil { + return errors.New("commission needs the plan author, approver and operator") + } + _, _, capacity, err := r.inputs(ctx) + if err != nil { + return err + } + plan := r.Options.Plan(r.Staff.AuthorCreator) + if err := r.Staff.Author.Create(ctx, plan); apierrors.IsAlreadyExists(err) { + if err := r.Staff.Author.Get(ctx, client.ObjectKeyFromObject(plan), plan); err != nil { + return err + } + } else if err != nil { + return fmt.Errorf("write the plan: %w", err) + } + approval, err := custody.NewApproval(plan, r.Staff.ApproverCreator) + if err != nil { + return err + } + if err := r.Staff.Approver.Create(ctx, approval); err != nil && !apierrors.IsAlreadyExists(err) { + return fmt.Errorf("approve the plan: %w", err) + } + device := &inventory.Device{} + if err := r.Staff.Operator.Get(ctx, client.ObjectKey{Namespace: r.Options.ProviderNamespace, Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + return err + } + if err := r.await(ctx, "custody of the fixture Device is Verified", func() (bool, error) { + state := &ops.DeviceCustody{} + if err := r.Client.Get(ctx, client.ObjectKeyFromObject(device), state); apierrors.IsNotFound(err) { + return false, nil + } else if err != nil { + return false, err + } + return state.Spec.State == ops.CustodyVerified, nil + }); err != nil { + return err + } + operation, err := custody.NewCommissioning(device, plan, r.Staff.OperatorCreator, "synthetic intake") + if err != nil { + return err + } + if err := r.Staff.Operator.Create(ctx, operation); err != nil { + return fmt.Errorf("commission the Device: %w", err) + } + if err := r.await(ctx, "the commissioning succeeds", func() (bool, error) { + if err := r.Staff.Operator.Get(ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + return false, err + } + switch phase := operation.Status.Phase; { + case phase == ops.PhaseSucceeded: + return true, nil + case phase.Ended(): + return false, fmt.Errorf("the commissioning ended %s: %s", phase, operation.Status.Reason) + } + return false, nil + }); err != nil { + return err + } + return r.await(ctx, "the projector offers the capacity", func() (bool, error) { + if err := r.Client.Get(ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + return false, err + } + available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable) + return available != nil && available.Status == metav1.ConditionTrue && available.ObservedGeneration == capacity.Generation, nil + }) +}