diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d537961b..779f4dfa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh - run: ./hack/multiplane/test-harness.sh - - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime + - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime standalone-smoke: runs-on: ubuntu-latest timeout-minutes: 35 diff --git a/.gitignore b/.gitignore index f0b5f928..217d5f65 100644 --- a/.gitignore +++ b/.gitignore @@ -36,4 +36,7 @@ config/multiplane/flux/gotk-components.yaml # Locally built binaries /fleet-multiplane -/fleet-local-vm +/fleet-manager +/fleet-registration +/fleet-simulator +/fleet-standalone-smoke diff --git a/Taskfile.yaml b/Taskfile.yaml index 6b55c0d2..5210d72d 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -40,14 +40,6 @@ tasks: cmds: - ./hack/multiplane/test-harness.sh - local-vm:acceptance: - desc: Single-plane local VM PXE acceptance with explicit TCG in the task-owned Colima profile. - env: - DOCKER_CONTEXT: colima-fleet-acceptance-tcg - FLEET_LOCAL_VM_ACCEL: tcg - cmds: - - bash hack/local-vm/run.sh - manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/fleet-local-vm/main.go b/cmd/fleet-local-vm/main.go deleted file mode 100644 index 71ea5570..00000000 --- a/cmd/fleet-local-vm/main.go +++ /dev/null @@ -1,230 +0,0 @@ -// fleet-local-vm is an explicit local acceptance harness, not a deployed controller. -package main - -import ( - "context" - "encoding/json" - "errors" - "fmt" - api "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/localvm" - "go.datum.net/fleet/internal/simulator" - core "k8s.io/api/core/v1" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/tools/clientcmd" - "os" - "sigs.k8s.io/controller-runtime/pkg/client" - "strings" - "time" -) - -type crashAfterEffect struct{ *localvm.Provider } - -func (p crashAfterEffect) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { - r, e := p.Provider.Execute(ctx, q) - if e == nil && q.Kind == "install" { - os.Exit(75) - } - return r, e -} - -func main() { - if e := work(); e != nil { - fmt.Fprintln(os.Stderr, e) - os.Exit(1) - } -} -func work() error { - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) - defer cancel() - p, e := localvm.Open() - if e != nil { - return e - } - if len(os.Args) == 2 && os.Args[1] == "boot-denials" { - summary, err := p.CheckClosedBoot("") - if err != nil { - return err - } - return os.WriteFile(localvm.Root+"/boot-denials.txt", []byte(summary+"\n"), 0600) - } - if len(os.Args) == 2 && os.Args[1] == "boot-service" { - return p.ServeBoot() - } - if len(os.Args) == 2 && os.Args[1] == "image" { - fmt.Println(p.ImageReference()) - return nil - } - if len(os.Args) != 2 { - return errors.New("phase required") - } - config, e := clientcmd.BuildConfigFromFlags("", "/run/fleet/kubeconfig") - if e != nil { - return e - } - scheme := runtime.NewScheme() - core.AddToScheme(scheme) - api.AddToScheme(scheme) - k, e := client.New(config, client.Options{Scheme: scheme}) - if e != nil { - return e - } - var backend executor.Client = p - if os.Args[1] == "install-crash" { - backend = crashAfterEffect{p} - } - c, e := controller.NewCoordinator(k, "fleet-system-private", backend, controller.LocalDigestImageResolver{}, nil, time.Hour) - if e != nil { - return e - } - var capacity api.MachineCapacity - var class api.MachineClass - var profile api.MachineProfile - for _, item := range []struct { - key client.ObjectKey - obj client.Object - }{{client.ObjectKey{Namespace: "fleet-provider", Name: "central1-baremetal-01"}, &capacity}, {client.ObjectKey{Name: "standard-metal"}, &class}, {client.ObjectKey{Name: "general-purpose-24c-128g"}, &profile}} { - if e = k.Get(ctx, item.key, item.obj); e != nil { - return e - } - } - // Explicit operator-owned local inventory; no imported device is adopted. - capacity.Status.Hardware = api.Hardware{CPU: api.HardwareCPU{Architecture: "amd64", Cores: 2, Threads: 2, Sockets: 1}, Memory: api.HardwareMemory{Capacity: "2Gi"}} - now := time.Now().UTC() - for _, name := range []string{"Prepared", "Healthy", "Available"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, meta.Condition{Type: name, Status: meta.ConditionTrue, ObservedGeneration: capacity.Generation, LastTransitionTime: meta.NewTime(now), Reason: "LocalDisposableDevice", Message: "Operator-created local VM slot; private custody is authoritative."}) - } - if e = k.Status().Update(ctx, &capacity); e != nil { - return e - } - getClaim := func(ns string) (*api.Machine, *core.Namespace, error) { - m := &api.Machine{} - n := &core.Namespace{} - if e := k.Get(ctx, client.ObjectKey{Namespace: ns, Name: "allocation"}, m); e != nil { - return nil, nil, e - } - if e := k.Get(ctx, client.ObjectKey{Name: ns}, n); e != nil { - return nil, nil, e - } - return m, n, nil - } - allocate := func(ns string) (*controller.AssetRecord, error) { - m, n, e := getClaim(ns) - if e != nil { - return nil, e - } - auth := controller.AdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(m.UID)} - if e = c.EnsureClaimCustody(ctx, m, n.UID, auth); e != nil { - return nil, e - } - if len(m.Finalizers) == 0 { - m.Finalizers = []string{controller.MachineFinalizer} - if e = k.Update(ctx, m); e != nil { - return nil, e - } - } - return c.Allocate(ctx, controller.AllocationRequest{Claim: m, Class: &class, Profile: &profile, MachineCapacities: []api.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: now}, NamespaceUID: n.UID, Admission: auth, LocalClassName: class.Name, LocalClassUID: class.UID, LocalProfileName: profile.Name, LocalProfileUID: profile.UID}) - } - phase := os.Args[1] - switch phase { - case "allocate": - r, e := allocate("fleet-project-a") - if e != nil { - return e - } - if _, e = allocate("fleet-project-b"); !errors.Is(e, controller.ErrInsufficientCapacity) { - return fmt.Errorf("contention failed: %v", e) - } - fmt.Printf("exclusive allocation %s asset %s\n", r.BindingID, r.AssetID) - case "install", "install-crash", "reinstall": - m, n, e := getClaim("fleet-project-a") - if e != nil { - return e - } - name := "debian-12" - if phase == "reinstall" { - name += "-reinstall" - } - var in api.Installation - if e = k.Get(ctx, client.ObjectKey{Namespace: m.Namespace, Name: name}, &in); e != nil { - return e - } - m.Status.Phase = "Pending" - m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionUnknown, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalInstallationUnverified", Message: "Installation outcome has not been verified."}} - if e = k.Status().Update(ctx, m); e != nil { - return e - } - result, e := c.Install(ctx, controller.InstallationRequest{Claim: m, Installation: &in, NamespaceUID: n.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(in.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + strings.Split(p.ImageReference(), "@")[1]}}) - if e != nil { - return e - } - receipt, found, e := p.Lookup(ctx, result.Record.OperationID) - if e != nil || !found || receipt.InputDigest != result.RequestDigest { - return errors.New("exact provider receipt missing") - } - in.Status = api.InstallationStatus{Phase: "Ready", CompletedAt: &meta.Time{Time: *receipt.CompletedAt}, Conditions: []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: in.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Pinned Linux installer and disk boot verified through local libvirt."}}} - if e = k.Status().Update(ctx, &in); e != nil { - return e - } - m.Status.CurrentInstallationRef = &api.LocalReference{Name: name} - m.Status.Phase = "Ready" - m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Exact installation-bound disk boot and powered-off handoff verified."}} - if e = k.Status().Update(ctx, m); e != nil { - return e - } - fmt.Printf("verified installation %s operation %s\n", in.UID, receipt.ID) - case "release": - m, _, e := getClaim("fleet-project-a") - if e != nil { - return e - } - if m.DeletionTimestamp == nil { - if e = k.Delete(ctx, m, client.Preconditions{UID: &m.UID, ResourceVersion: &m.ResourceVersion}); e != nil { - return e - } - } - r, e := c.Release(ctx, m.UID) - if e != nil { - return e - } - if !r.SafeToRemoveFinalizer { - return errors.New("cleanup not verified") - } - current := &api.Machine{} - if e = k.Get(ctx, client.ObjectKeyFromObject(m), current); e != nil { - return e - } - if current.UID != m.UID { - return errors.New("consumer machine identity changed during release") - } - kept := current.Finalizers[:0] - for _, f := range current.Finalizers { - if f != controller.MachineFinalizer { - kept = append(kept, f) - } - } - current.Finalizers = kept - if e = k.Update(ctx, current); e != nil { - return e - } - - if _, e = allocate("fleet-project-b"); e != nil { - return e - } - fmt.Println("cleanup verified; capacity exclusively reused by second consumer") - case "evidence": - var installs api.InstallationList - if e = k.List(ctx, &installs); e != nil { - return e - } - b, _ := json.MarshalIndent(installs, "", " ") - return os.WriteFile(localvm.Root+"/installations.json", b, 0600) - default: - return errors.New("unsupported phase") - } - return nil -} diff --git a/cmd/fleet-manager/clientcert_test.go b/cmd/fleet-manager/clientcert_test.go new file mode 100644 index 00000000..375bdfdc --- /dev/null +++ b/cmd/fleet-manager/clientcert_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "k8s.io/client-go/rest" +) + +// clientCertDir writes a cert-manager style Secret directory, tls.crt and +// tls.key, holding a client certificate for commonName signed by ca. +func clientCertDir(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, commonName string) string { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: commonName}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}} + der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for name, block := range map[string]*pem.Block{"tls.crt": {Type: "CERTIFICATE", Bytes: der}, "tls.key": {Type: "EC PRIVATE KEY", Bytes: keyDER}} { + if err := os.WriteFile(filepath.Join(dir, name), pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + } + return dir +} + +// TestEachComponentAuthenticatesToMiloWithItsOwnClientCertificate builds +// the coordinator's connection from the manager's: the same endpoint and +// server CA, but only the coordinator's client certificate, and none of the +// manager's credentials. +func TestEachComponentAuthenticatesToMiloWithItsOwnClientCertificate(t *testing.T) { + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + caTemplate := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "synthetic-client-ca"}, IsCA: true, BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour)} + caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + ca, err := x509.ParseCertificate(caDER) + if err != nil { + t.Fatal(err) + } + pool := x509.NewCertPool() + pool.AddCert(ca) + type seen struct { + commonName string + authorization string + } + requests := make(chan seen, 1) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got := seen{authorization: r.Header.Get("Authorization")} + if len(r.TLS.PeerCertificates) == 1 { + got.commonName = r.TLS.PeerCertificates[0].Subject.CommonName + } + requests <- got + })) + server.TLS = &tls.Config{ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool} + server.StartTLS() + defer server.Close() + serverCA := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}) + + manager := clientCertDir(t, ca, caKey, "fleet-manager") + provider := &rest.Config{Host: server.URL, BearerToken: "manager-token", TLSClientConfig: rest.TLSClientConfig{ + CAData: serverCA, CertFile: filepath.Join(manager, "tls.crt"), KeyFile: filepath.Join(manager, "tls.key")}} + config, err := withClientCert(provider, clientCertDir(t, ca, caKey, "custody-coordinator")) + if err != nil { + t.Fatal(err) + } + client, err := rest.HTTPClientFor(config) + if err != nil { + t.Fatal(err) + } + response, err := client.Get(config.Host + "/readyz") + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if got := <-requests; got.commonName != "custody-coordinator" || got.authorization != "" { + t.Fatalf("Milo saw client certificate %q and authorization %q, want only the coordinator's certificate", got.commonName, got.authorization) + } + if _, err := withClientCert(provider, t.TempDir()); err == nil { + t.Fatal("a directory without a client certificate was accepted") + } +} diff --git a/cmd/fleet-manager/main.go b/cmd/fleet-manager/main.go index 73d378c4..9108516e 100644 --- a/cmd/fleet-manager/main.go +++ b/cmd/fleet-manager/main.go @@ -4,9 +4,7 @@ import ( "context" "errors" "flag" - "net/http" "os" - "time" "golang.org/x/sync/errgroup" "k8s.io/apimachinery/pkg/runtime" @@ -16,11 +14,13 @@ import ( ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" ctrlcluster "sigs.k8s.io/controller-runtime/pkg/cluster" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" eventmanager "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/projectdiscovery" "go.datum.net/fleet/internal/staging" @@ -35,23 +35,28 @@ import ( const leaseName = "fleet-manager.fleet.datumapis.com" type managerFlags struct { - configPath, privateNamespace, leaderElectionNamespace string + configPath, leaderElectionNamespace string syntheticStaging bool syntheticProviderURL, syntheticTokenFile, syntheticLocation string syntheticConsumerProjectName string syntheticProviderProjectName, syntheticPublishedClassName string syntheticPublishedProfileName string + syntheticCoordinatorCertDir, syntheticReleaseCertDir string + syntheticEnrollmentFile, syntheticDeviceNamespace string } func bindFlags(flags *flag.FlagSet) *managerFlags { f := &managerFlags{} flags.StringVar(&f.configPath, "config", "", "path to the FleetManager configuration file (authority and project discovery)") - flags.StringVar(&f.privateNamespace, "private-namespace", "", "service-controlled private record namespace") flags.StringVar(&f.leaderElectionNamespace, "leader-election-namespace", "", "management-cluster namespace for the leader lease") flags.BoolVar(&f.syntheticStaging, "synthetic-staging", false, "enable the explicit non-production synthetic allocation integration for one consumer project") flags.StringVar(&f.syntheticProviderURL, "synthetic-provider-url", "http://127.0.0.1:8080", "synthetic provider runtime URL") - flags.StringVar(&f.syntheticTokenFile, "synthetic-provider-token-file", "", "file containing the synthetic provider bearer token") + flags.StringVar(&f.syntheticTokenFile, "synthetic-provider-token-file", "", "file containing the synthetic provider site's bearer token") + flags.StringVar(&f.syntheticCoordinatorCertDir, "synthetic-coordinator-client-cert-dir", "", "directory holding the custody coordinator's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticReleaseCertDir, "synthetic-release-client-cert-dir", "", "directory holding the release controller's Milo client certificate as tls.crt and tls.key") + flags.StringVar(&f.syntheticEnrollmentFile, "synthetic-site-enrollment-file", "", "JSON enrollment of the Devices the synthetic provider site serves") + flags.StringVar(&f.syntheticDeviceNamespace, "synthetic-device-namespace", "default", "namespace of the Devices, capacities and allocations in the provider project") flags.StringVar(&f.syntheticLocation, "synthetic-location", "us-central-1", "only location accepted by synthetic staging") flags.StringVar(&f.syntheticConsumerProjectName, "synthetic-consumer-project-name", "", "the one engaged consumer project synthetic staging allocates for and publishes into") flags.StringVar(&f.syntheticProviderProjectName, "synthetic-provider-project-name", "", "provider project used by synthetic cross-project staging") @@ -64,17 +69,17 @@ var errFlags = errors.New("invalid fleet-manager flags") // validate checks flag combinations before any cluster is contacted. func (f *managerFlags) validate() error { - if f.configPath == "" || f.privateNamespace == "" || f.leaderElectionNamespace == "" { - return errors.Join(errFlags, errors.New("--config, --private-namespace, and --leader-election-namespace are required")) + if f.configPath == "" || f.leaderElectionNamespace == "" { + return errors.Join(errFlags, errors.New("--config and --leader-election-namespace are required")) } if !f.syntheticStaging { - if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" { + if f.syntheticConsumerProjectName != "" || f.syntheticProviderProjectName != "" || f.syntheticPublishedClassName != "" || f.syntheticPublishedProfileName != "" || f.syntheticTokenFile != "" || f.syntheticCoordinatorCertDir != "" || f.syntheticReleaseCertDir != "" || f.syntheticEnrollmentFile != "" { return errors.Join(errFlags, errors.New("synthetic flags require --synthetic-staging")) } return nil } - if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" { - return errors.Join(errFlags, errors.New("--synthetic-staging requires --synthetic-provider-token-file and --synthetic-consumer-project-name")) + if f.syntheticTokenFile == "" || f.syntheticConsumerProjectName == "" || f.syntheticCoordinatorCertDir == "" || f.syntheticReleaseCertDir == "" || f.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.syntheticProviderProjectName != "" && (f.syntheticPublishedClassName == "" || f.syntheticPublishedProfileName == "") { return errors.Join(errFlags, errors.New("--synthetic-provider-project-name requires the published class and profile names")) @@ -98,6 +103,8 @@ func main() { scheme := runtime.NewScheme() must(clientgoscheme.AddToScheme(scheme)) must(fleetv1.AddToScheme(scheme)) + must(inventory.AddToScheme(scheme)) + must(ops.AddToScheme(scheme)) must(networkingv1.AddToScheme(scheme)) must(locationsv1alpha1.AddToScheme(scheme)) must(quotav1alpha1.AddToScheme(scheme)) @@ -131,37 +138,33 @@ func main() { for _, runnable := range selection.LocalRunnables { must(mgr.GetLocalManager().Add(runnable)) } - privateCluster, err := ctrlcluster.New(hostConfig, func(options *ctrlcluster.Options) { - options.Scheme = scheme - options.Cache = eventmanager.PrivateCacheOptions(flags.privateNamespace) - }) - must(err) - setupOptions := eventmanager.SetupOptions{PrivateNamespace: flags.privateNamespace, PrivateCluster: privateCluster, HandlersFor: eventmanager.DefaultHandlers} + setupOptions := eventmanager.SetupOptions{HandlersFor: eventmanager.DefaultHandlers} // Without --synthetic-staging every project gets blocked lifecycle // handlers: no allocation, installation, provider call, or custody write. // Only the requested-hardware projector writes. if flags.syntheticStaging { - // Private lifecycle records are retained authority, not eventually - // consistent projections. Coordinator reads observe API-server state - // directly; the private cluster cache only delivers events. - privateRecordClient, err := ctrlclient.New(hostConfig, ctrlclient.Options{Scheme: scheme}) - must(err) - provider, err := executor.NewHTTPClientFromTokenFile(flags.syntheticProviderURL, flags.syntheticTokenFile, &http.Client{Timeout: 30 * time.Second}) - must(err) - coordinator, err := controller.NewCoordinator(privateRecordClient, flags.privateNamespace, provider, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - must(err) consumerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticConsumerProjectName) must(err) - template := staging.Handler{Coordinator: coordinator, Location: flags.syntheticLocation} + // Devices, capacities, allocations and custody live in the provider + // project, which is the consumer project when nothing is published. + providerProject := consumerProject if flags.syntheticProviderProjectName != "" { - providerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticProviderProjectName) + providerProject, err = eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticProviderProjectName) must(err) if providerProject.SameLifetime(consumerProject) { must(eventmanager.ErrEventWiringUnavailable) } - providerConfig, err := projectdiscovery.ProjectRESTConfig(selection.ProjectConfig, providerProject.RouteName) - must(err) + } + providerConfig, err := projectdiscovery.ProjectRESTConfig(selection.ProjectConfig, providerProject.RouteName) + must(err) + allocator, loop, discover, err := syntheticCustody(ctx, scheme, providerConfig, flags) + must(err) + // Both need the leader lease: one coordinator writes custody. + must(mgr.GetLocalManager().Add(manager.RunnableFunc(loop.Run))) + must(mgr.GetLocalManager().Add(manager.RunnableFunc(discover))) + template := staging.Handler{Allocator: allocator, Location: flags.syntheticLocation} + if flags.syntheticProviderProjectName != "" { providerCluster, err := ctrlcluster.New(providerConfig, func(options *ctrlcluster.Options) { options.Scheme = scheme options.Cache = eventmanager.ProjectCacheOptions() @@ -177,7 +180,7 @@ func main() { must(eventmanager.Setup(ctx, mgr, projects, setupOptions)) // Readiness reflects discovery and cache health only. It never depends on // a provider integration, and passing it enables no lifecycle effect. - must(projectdiscovery.AddHealthChecks(mgr, selection.Discovery, tracker, projectdiscovery.NamedCache{Name: "private-records", Cache: privateCluster.GetCache()})) + must(projectdiscovery.AddHealthChecks(mgr, selection.Discovery, tracker)) group, ctx := errgroup.WithContext(ctx) for _, runnable := range selection.SideRunnables { diff --git a/cmd/fleet-manager/main_test.go b/cmd/fleet-manager/main_test.go index 5341a6cf..a4b3e6d3 100644 --- a/cmd/fleet-manager/main_test.go +++ b/cmd/fleet-manager/main_test.go @@ -18,7 +18,7 @@ func parse(t *testing.T, args ...string) error { return f.validate() } -var required = []string{"--config=/etc/fleet/manager/config.yaml", "--private-namespace=fleet-system-private", "--leader-election-namespace=fleet-system"} +var required = []string{"--config=/etc/fleet/manager/config.yaml", "--leader-election-namespace=fleet-system"} func TestDefaultConfigurationHasNoSyntheticIntegration(t *testing.T) { if err := parse(t, required...); err != nil { @@ -38,7 +38,7 @@ func TestDefaultConfigurationHasNoSyntheticIntegration(t *testing.T) { } func TestRemovedSingleProjectFlagsAreRejected(t *testing.T) { - for _, removed := range []string{"--project-name=consumer", "--authority-id=milo", "--project-kubeconfig=/k", "--enable-requested-hardware-projector=false"} { + for _, removed := range []string{"--project-name=consumer", "--authority-id=milo", "--project-kubeconfig=/k", "--enable-requested-hardware-projector=false", "--private-namespace=fleet-system-private"} { if err := parse(t, append(required, removed)...); err == nil { t.Fatalf("%s was accepted", removed) } @@ -52,10 +52,27 @@ func TestSyntheticFlagsRequireAndScopeStaging(t *testing.T) { if err := parse(t, append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t")...); !errors.Is(err, errFlags) { t.Fatalf("staging without a consumer project: %v", err) } - staging := append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t", "--synthetic-consumer-project-name=consumer") + components := []string{"--synthetic-coordinator-client-cert-dir=/c", "--synthetic-release-client-cert-dir=/r", "--synthetic-site-enrollment-file=/e"} + staging := append(append(required, "--synthetic-staging", "--synthetic-provider-token-file=/t", "--synthetic-consumer-project-name=consumer"), components...) if err := parse(t, staging...); err != nil { t.Fatal(err) } + // Each component authenticates as itself, and the site's Devices are + // configuration: staging refuses to start without any of them. + for _, missing := range components { + var args []string + for _, arg := range staging { + if arg != missing { + args = append(args, arg) + } + } + if err := parse(t, args...); !errors.Is(err, errFlags) { + t.Fatalf("staging without %s: %v", missing, err) + } + if err := parse(t, append(required, missing)...); !errors.Is(err, errFlags) { + t.Fatalf("%s without --synthetic-staging: %v", missing, err) + } + } if err := parse(t, append(staging, "--synthetic-provider-project-name=provider-project")...); !errors.Is(err, errFlags) { t.Fatalf("provider project without publication names: %v", err) } diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go new file mode 100644 index 00000000..66d33ec8 --- /dev/null +++ b/cmd/fleet-manager/synthetic.go @@ -0,0 +1,156 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/allocation" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/siteapi" +) + +// syntheticSite is the synthetic provider: the simulator site. +const syntheticSite = "synthetic-provider" + +// syntheticCleaningPolicy is the fixture cleaning policy record every +// synthetic capacity names. Its digest is what each allocation pins. +const syntheticCleaningPolicy = `{"method":"overwrite","disks":"all"}` + +// syntheticCustody builds the allocator, the custody coordinator loop and +// fixture discovery for synthetic staging. The manager's own identity is the +// Metal provider; the coordinator and the release controller authenticate +// to Milo with their own client certificates, so each component's writes +// carry its identity. +func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfig *rest.Config, flags *managerFlags) (*allocation.Allocator, *delivery.Loop, func(context.Context) error, error) { + enrollment, err := readEnrollment(flags.syntheticEnrollmentFile) + if err != nil { + return nil, nil, nil, err + } + coordinatorConfig, err := withClientCert(providerConfig, flags.syntheticCoordinatorCertDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("custody coordinator credential: %w", err) + } + releaseConfig, err := withClientCert(providerConfig, flags.syntheticReleaseCertDir) + 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} { + // 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] + providerCreator, err := allocation.Creator(ctx, providerConfig) + if err != nil { + return nil, nil, nil, fmt.Errorf("identify the Metal provider: %w", err) + } + releaseCreator, err := allocation.Creator(ctx, releaseConfig) + if err != nil { + return nil, nil, nil, fmt.Errorf("identify the release controller: %w", err) + } + registry, err := custody.DefaultRegistry() + if err != nil { + return nil, nil, nil, err + } + remote, err := siteapi.NewClient(flags.syntheticProviderURL, func() (string, error) { return readToken(flags.syntheticTokenFile) }, &http.Client{Timeout: 30 * time.Second}) + if err != nil { + return nil, nil, nil, err + } + namespace := flags.syntheticDeviceNamespace + sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}} + for device := range enrollment { + deviceNamespace, name, _ := strings.Cut(device, "/") + if deviceNamespace != namespace { + return nil, nil, nil, fmt.Errorf("enrolled Device %s is outside %s", device, namespace) + } + sites.Devices[name] = []string{syntheticSite} + } + principals := custody.Principals{ + custody.CreatorMetalProvider: {{Username: providerCreator.Username, UID: providerCreator.UID}}, + custody.CreatorReleaseController: {{Username: releaseCreator.Username, UID: releaseCreator.UID}}, + } + if err := principals.Validate(); err != nil { + return nil, nil, nil, err + } + coordinator := &custody.Coordinator{Client: coordinatorClient, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals}} + log := ctrl.Log.WithName("custody") + loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, + 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{ + Provider: provider, ProviderCreator: providerCreator, + Releaser: releaseClient, ReleaseCreator: releaseCreator, + Custody: coordinator, Namespace: namespace, + Cleaning: func(string) (string, error) { return custody.SpecDigest(syntheticCleaningPolicy) }, + // The synthetic site enrolls one boot NIC and one disk per Device. + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + } + // Synthetic staging has no BMC discovery. The manager writes fixture + // discovery for the synthetic site's Devices instead. + discover := func(ctx context.Context) error { + fixture.Run(ctx, provider, enrollment, time.Minute, func(err error) { log.Info("fixture discovery incomplete", "error", err.Error()) }) + return nil + } + return allocator, loop, discover, nil +} + +// withClientCert is the Milo connection of config, the same endpoint and +// server CA, authenticated only by the client certificate in dir. The +// directory holds a cert-manager certificate Secret's tls.crt and tls.key. +// client-go rereads both files, so a renewed certificate is used without a +// restart; mount the whole Secret, never a subPath. +func withClientCert(config *rest.Config, dir string) (*rest.Config, error) { + certFile, keyFile := filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key") + if _, err := tls.LoadX509KeyPair(certFile, keyFile); err != nil { + return nil, fmt.Errorf("load the client certificate in %s: %w", dir, err) + } + copied := rest.AnonymousClientConfig(config) + copied.CertFile, copied.KeyFile = certFile, keyFile + return copied, nil +} + +func readToken(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(data)) + if token == "" || strings.ContainsAny(token, "\r\n") { + return "", errors.New("the token must be one nonempty line") + } + return token, nil +} + +func readEnrollment(path string) (fixture.Enrollment, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var enrollment fixture.Enrollment + decoder := json.NewDecoder(strings.NewReader(string(data))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&enrollment); err != nil { + return nil, err + } + if len(enrollment) == 0 { + return nil, errors.New("the synthetic site enrolls no Device") + } + return enrollment, nil +} diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 0a547a1b..ad806389 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -1,5 +1,5 @@ // fleet-multiplane is an opt-in local acceptance binary. Production managers do -// not import its synthetic admission, quota or hardware enrollment fixtures. +// not import its synthetic admission, quota or discovery fixtures. package main import ( @@ -13,14 +13,14 @@ import ( "syscall" "time" - "go.datum.net/fleet/internal/coordination" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/localvm" - "go.datum.net/fleet/internal/multiplane" - "go.datum.net/fleet/internal/redfish" "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/multiplane" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" ) func main() { @@ -29,145 +29,60 @@ func main() { os.Exit(1) } } + func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|dhcp-feed|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) - once := fs.Bool("once", false, "one reconcile attempt for fault injection") + once := fs.Bool("once", false, "one attempt, for fault injection") handoff := fs.String("handoff", "", "exact delivered handoff name (site-worker)") - origin := fs.String("origin", "", "boot listener origin to probe (boot-denials); default the configured origin") + origin := fs.String("origin", "", "boot listener origin to probe, http://IPv4:port (boot-denials; required)") interval := fs.Duration("interval", 10*time.Second, "observation refresh interval (site-observer)") configPath := fs.String("config", "", "private acceptance config JSON") kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") cell := fs.String("cell", "", "exact Karmada member name") - scoped := fs.String("scoped-asset", "", "exact retained provider-scoped Device ID") extraMAC := fs.String("extra-mac", "", "another enrolled NIC whose boot script must be denied (boot-denials, Redfish mode)") endpoint := fs.String("endpoint", "", "Redfish endpoint (redfish-probe)") credentials := fs.String("credentials", "", "directory holding username and password files (redfish-probe)") system := fs.String("system", "", "enrolled Redfish System Id (redfish-probe)") uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") + pin := fs.String("pin", "", "the BMC's approved key digest; the probe connects only to that key (redfish-probe)") syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") if err := fs.Parse(os.Args[2:]); err != nil { return err } switch os.Args[1] { - case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse", "asset": + case "coordinator": config, err := multiplane.ReadConfig(*configPath) if err != nil { return err } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() - if os.Args[1] == "seed" { - return multiplane.Seed(ctx, config) - } - r, err := multiplane.New(ctx, config) - if err != nil { - return err - } - if os.Args[1] == "asset" { - fmt.Println(r.ScopedAsset()) - return nil - } - var action func(context.Context) error - switch os.Args[1] { - case "allocate": - action = r.Allocate - case "install", "admit-install": - action = r.Install - case "install-b": - action = r.InstallSecond - case "release": - action = r.Release - case "release-b": - action = r.ReleaseSecond - case "reuse": - action = r.Reuse - } - for { - err = action(ctx) - if os.Args[1] == "admit-install" { - if errors.Is(err, executor.ErrOutcomeUnknown) { - fmt.Println("Installation intent retained; execution result remains Unknown") - return nil - } - if err == nil { - return fmt.Errorf("admission probe unexpectedly completed; run before starting cell") - } - return err - } - if (*once || terminal(err)) && err != nil { - return err - } - if err == nil { - fmt.Println(os.Args[1] + ": verified local acceptance phase (synthetic authority)") - return nil - } - if ctx.Err() != nil { - return fmt.Errorf("%s did not converge; authority retained; last error: %w", os.Args[1], err) - } - time.Sleep(3 * time.Second) - } - } - if os.Args[1] == "redfish-probe" { - return probe(*endpoint, *credentials, *system, *uuid) - } - if redfishMode() { - switch os.Args[1] { - case "boot-service", "boot-denials", "dhcp-feed": - p, err := redfish.OpenReadOnly() - if err != nil { - return err - } - if os.Args[1] == "boot-service" { - return p.ServeBoot() - } - if os.Args[1] == "dhcp-feed" { - token, err := os.ReadFile(*syncToken) - if err != nil { - return fmt.Errorf("DHCP synchronizer token: %w", err) - } - return p.ServeDHCP(strings.TrimSpace(string(token))) - } - var extra []string - if *extraMAC != "" { - extra = append(extra, *extraMAC) - } - summary, err := p.CheckClosedBoot(*origin, extra) - if err != nil { - return err - } - fmt.Println(summary) - return nil - } - } - switch os.Args[1] { - case "image", "boot-service", "boot-denials": - // Read-only: the boot service mounts the journal read-only. - p, err := localvm.OpenReadOnly() - if err != nil { - return err - } - switch os.Args[1] { - case "image": - fmt.Println(p.ImageReference()) - return nil - case "boot-service": - return p.ServeBoot() - } - summary, err := p.CheckClosedBoot(*origin) + fmt.Println("coordinator: custody coordinator running") + return multiplane.Coordinate(ctx, config, func(err error) { + fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) + }) + case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse": + return phase(os.Args[1], *configPath, *once) + case "redfish-probe": + return probe(*endpoint, *credentials, *system, *uuid, *pin) + case "image": + image, err := siteImage() if err != nil { return err } - fmt.Println(summary) + fmt.Println(image) return nil + case "boot-service", "boot-denials", "dhcp-feed": + return boot(os.Args[1], *origin, *extraMAC, *syncToken) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") } - if *cell == "" || *scoped == "" || (os.Args[1] == "site-worker" && *handoff == "") { - return fmt.Errorf("cell, scoped-asset and (for site-worker) handoff required") + if *cell == "" || (os.Args[1] == "site-worker" && *handoff == "") { + return fmt.Errorf("cell and (for site-worker) handoff required") } cfg, err := rest.InClusterConfig() if *kubeconfig != "" { @@ -183,65 +98,96 @@ func run() error { } ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() + store, err := openStore() + if err != nil { + return err + } + cellView := &coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell} if os.Args[1] == "site-observer" { - // The observer never executes: its provider is read-only. - var p executor.Client - var err error - if redfishMode() { - p, err = redfish.OpenReadOnly() - } else { - p, err = localvm.OpenReadOnly() - } - if err != nil { - return err - } - mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} - observer := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} - return observer.Observe(ctx, *interval, func(name string, err error) { + // The observer never runs work: it reports what the store holds. + return cellView.Observe(ctx, *interval, store, site.NewResults(store), func(name string, err error) { fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) }) } - // A Redfish worker has no libvirt fallback: redfish.Open refuses any - // hypervisor configuration, and the worker reaches the target only - // through its enrolled BMC. - var p executor.Client - if redfishMode() { - p, err = redfish.Open() - } else { - p, err = localvm.Open() - } + runner, err := siteRunner(ctx, cfg, *cell, store) if err != nil { return err } - mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} - worker := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} - err = worker.Execute(ctx, *handoff) + err = cellView.Work(ctx, *handoff, runner) fmt.Fprintf(os.Stderr, "site-worker: handoff %s: %s\n", *handoff, classify(err)) + switch { + case err == nil, errors.Is(err, site.ErrAlreadyRunning): + return nil + case errors.Is(err, site.ErrStaleFence), errors.Is(err, coordination.ErrNotDelivered): + os.Exit(exitRejected) + } + os.Exit(exitRetry) + return nil +} + +// phase runs one management phase until it converges, retrying pending +// effects. +func phase(name, configPath string, once bool) error { + config, err := multiplane.ReadConfig(configPath) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + if name == "seed" { + return multiplane.Seed(ctx, config) + } + r, err := multiplane.New(ctx, config) if err != nil { - if terminal(err) { - os.Exit(exitRejected) + return err + } + action := map[string]func(context.Context) error{ + "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "install-b": r.InstallSecond, + "release": r.Release, "release-b": r.ReleaseSecond, "reuse": r.Reuse, + }[name] + last := "" + for { + err = action(ctx) + // Report each new reason a phase is waiting, so a phase that times + // out shows what it waited for. + if err != nil && err.Error() != last { + last = err.Error() + fmt.Printf("%s: waiting: %v\n", name, err) + } + if name == "admit-install" && errors.Is(err, multiplane.ErrAdmittedUnknown) { + fmt.Println("Installation admitted and delivered; its result remains Unknown") + return nil + } + if err == nil { + fmt.Println(name + ": verified local acceptance phase (synthetic authority)") + return nil } - os.Exit(exitRetry) + if once || multiplane.Terminal(err) || errors.Is(err, multiplane.ErrLocationNotServed) { + return err + } + if ctx.Err() != nil { + return fmt.Errorf("%s did not converge; last error: %w", name, err) + } + time.Sleep(3 * time.Second) } - return nil } const coordinationNamespace = "fleet-coordination" -// redfishMode selects the Redfish executor for site roles. The site's Flux -// layers set it; there is no automatic choice between providers. +// redfishMode selects the Redfish workers for site roles. The site's Flux +// layers set it; there is no automatic choice between them. func redfishMode() bool { return os.Getenv("FLEET_SITE_PROVIDER") == "redfish" } // probe performs read-only Redfish discovery of one enrolled System and // prints only an outcome class. Exit codes: 0 discovered, 10 credential // rejected, 11 capability unsupported, 12 identity mismatch. -func probe(endpoint, credentials, system, uuid string) error { +func probe(endpoint, credentials, system, uuid, pin string) error { user, err1 := os.ReadFile(credentials + "/username") password, err2 := os.ReadFile(credentials + "/password") if credentials == "" || err1 != nil || err2 != nil { return fmt.Errorf("redfish-probe: credentials unavailable") } - c, err := redfish.NewClient(endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) + c, err := redfish.NewPinnedClient(endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), pin, 20*time.Second) if err != nil { return err } @@ -265,10 +211,11 @@ func probe(endpoint, credentials, system, uuid string) error { return err } -// Worker exit codes are the Job podFailurePolicy contract: rejected authority -// fails the Job without retry; anything else is retried by the Job controller -// against the same retained operation. Exit 0 only follows a validated -// terminal journal result, and still does not publish or authorize readiness. +// Worker exit codes are the Job podFailurePolicy contract: a handoff that is +// not this cell's, or an assignment below the Device's stored fence, fails +// the Job without retry; anything else is retried by the Job controller +// against the same assignment. Exit 0 follows a stored result, which only +// the coordinator turns into custody. const ( exitRejected = 65 exitRetry = 75 @@ -278,27 +225,14 @@ const ( func classify(err error) string { switch { case err == nil: - return "terminal result verified in provider journal" - case errors.Is(err, executor.ErrFenced): - return "fenced: " + err.Error() - case errors.Is(err, executor.ErrConflict): - return "conflict: " + err.Error() - case errors.Is(err, executor.ErrInvalid): - return "invalid: " + err.Error() - case errors.Is(err, executor.ErrOutcomeUnknown): - return "outcome unknown: " + err.Error() + return "result stored in the site store" + case errors.Is(err, site.ErrAlreadyRunning): + return "another worker runs this assignment" + case errors.Is(err, site.ErrStaleFence): + return "fenced: a newer operation was admitted for the Device" + case errors.Is(err, coordination.ErrNotDelivered): + return "invalid: not an assignment for this cell" default: return "pending: " + err.Error() } } - -// terminal errors are authority rejections; retrying cannot change them and -// Unknown (the only retained-uncertainty result) stays retryable. -func terminal(err error) bool { - for _, target := range []error{executor.ErrConflict, executor.ErrFenced, executor.ErrInvalid, multiplane.ErrLocationNotServed} { - if errors.Is(err, target) { - return true - } - } - return false -} diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go new file mode 100644 index 00000000..459f59c8 --- /dev/null +++ b/cmd/fleet-multiplane/site.go @@ -0,0 +1,258 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/redfishwork" + "go.datum.net/fleet/internal/site/vmwork" +) + +// The site's retained volume: the site store, the local VM disks, and the +// installer artifacts baked into the site image. +const ( + defaultStore = "/var/lib/fleet-local/site" + vmDisks = "/var/lib/fleet-local/vm" + artifacts = "/opt/fleet-local/artifacts" + // libvirtSocketDir is where a local VM site mounts the hypervisor. A + // Redfish site must not have it. + libvirtSocketDir = "/run/fleet-libvirt" +) + +// openStore opens the site store, creating its owner-only root once. A +// read-only role, such as the boot server, finds it existing. +func openStore() (*site.Store, error) { + root := os.Getenv("FLEET_SITE_STATE") + if root == "" { + root = defaultStore + } + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return nil, errors.New("FLEET_SITE_STATE must be a clean absolute path") + } + if _, err := os.Stat(root); os.IsNotExist(err) { + if err := os.MkdirAll(root, 0o700); err != nil { + return nil, err + } + } + return site.OpenStore(root, nil) +} + +func siteImage() (string, error) { return redfish.VerifyArtifacts(artifacts) } + +func bootRoot() (string, error) { + root := os.Getenv("FLEET_BOOT_EVIDENCE") + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return "", errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + return root, nil +} + +// vmBootConfig is what the local VM boot server needs: the artifacts it +// serves, the image they are, and where it records deliveries. +func vmBootConfig() (vmwork.Config, error) { + if os.Getenv("FLEET_LOCAL_VM") != "disposable-container" { + return vmwork.Config{}, errors.New("the local VM site requires its disposable container") + } + image, err := siteImage() + if err != nil { + return vmwork.Config{}, err + } + origin, err := redfish.ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return vmwork.Config{}, err + } + boot, err := bootRoot() + if err != nil { + return vmwork.Config{}, err + } + return vmwork.Config{Artifacts: artifacts, Image: image, Disks: vmDisks, BootRoot: boot, BootOrigin: origin, PXE: true}, nil +} + +// vmConfig is the local VM worker's configuration from its environment: +// the boot configuration, the hypervisor, and the site's enrollment. +func vmConfig() (vmwork.Config, fixture.Enrollment, error) { + config, err := vmBootConfig() + if err != nil { + return vmwork.Config{}, nil, err + } + accelerator := os.Getenv("FLEET_LOCAL_VM_ACCEL") + switch accelerator { + case "": + accelerator = "kvm" + case "kvm", "tcg": + default: + return vmwork.Config{}, nil, errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") + } + if accelerator == "kvm" { + if _, err := os.Stat("/dev/kvm"); err != nil { + return vmwork.Config{}, nil, err + } + } + uri := os.Getenv("FLEET_LIBVIRT_URI") + if !strings.HasPrefix(uri, "qemu:///system?socket="+libvirtSocketDir+"/") { + return vmwork.Config{}, nil, errors.New("FLEET_LIBVIRT_URI must name the site's libvirt socket") + } + var enrollment fixture.Enrollment + decoder := json.NewDecoder(strings.NewReader(os.Getenv("FLEET_SITE_ENROLLMENT"))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&enrollment); err != nil || len(enrollment) == 0 { + return vmwork.Config{}, nil, errors.New("FLEET_SITE_ENROLLMENT must enroll the site's Devices") + } + config.Accelerator, config.URI = accelerator, uri + return config, enrollment, nil +} + +// redfishBootServer is what the Redfish boot server needs: the artifacts it +// serves, the image they are, the listener firmware reaches, and where it +// records deliveries. It reads no enrollment or credential. +func redfishBootServer(store *site.Store) (redfishwork.BootServer, error) { + boot, err := bootRoot() + if err != nil { + return redfishwork.BootServer{}, err + } + origin, err := redfish.ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return redfishwork.BootServer{}, err + } + image, err := siteImage() + if err != nil { + return redfishwork.BootServer{}, err + } + return redfishwork.BootServer{Store: store, Origin: origin, Artifacts: artifacts, Image: image, BootRoot: boot}, nil +} + +// redfishConfig is the Redfish worker's configuration from its environment. +// A Redfish site has no hypervisor fallback. +func redfishConfig() (redfishwork.Config, redfish.Enrollment, error) { + if os.Getenv("FLEET_LIBVIRT_URI") != "" { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("a Redfish site refuses a libvirt URI") + } + if _, err := os.Stat(libvirtSocketDir); err == nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("a Redfish site refuses a mounted libvirt socket") + } + enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, err + } + console := os.Getenv("FLEET_REDFISH_CONSOLE") + if !filepath.IsAbs(console) { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") + } + boot, err := bootRoot() + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, err + } + return redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced}, enrollment, nil +} + +// siteRunner is the site runner for this cell's mode. A Redfish worker reads +// each Device's own BMC credential Secret, never a shared credential. +func siteRunner(_ context.Context, config *rest.Config, cell string, store *site.Store) (*site.Runner, error) { + runner := &site.Runner{Site: cell, Store: store, Results: site.NewResults(store)} + if !redfishMode() { + vm, enrollment, err := vmConfig() + if err != nil { + return nil, err + } + runner.Access = fixture.Access{Enrollment: enrollment} + runner.Kinds = map[string]site.Kind{"DeviceInstallation": vmwork.Installation{Config: vm}, "DeviceWipe": vmwork.Wipe{Config: vm}} + return runner, nil + } + work, enrollment, err := redfishConfig() + if err != nil { + return nil, err + } + namespace, project := os.Getenv("FLEET_SITE_CREDENTIALS_NAMESPACE"), os.Getenv("FLEET_SITE_PROJECT") + if namespace == "" || project == "" { + return nil, errors.New("FLEET_SITE_CREDENTIALS_NAMESPACE and FLEET_SITE_PROJECT name the per-Device credential Secrets") + } + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + return nil, err + } + reader, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return nil, err + } + targets := site.StaticTargets{} + for _, target := range enrollment.Targets { + targets[target.Device] = target + } + 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}} + return runner, nil +} + +// boot serves network boots, the DHCP reservation feed, or probes that +// every closed admission is denied. +func boot(command, origin, extraMAC, syncToken string) error { + store, err := openStore() + if err != nil { + return err + } + if command == "boot-denials" { + // The probe needs only the store's admissions and the listener it + // probes, given explicitly; it reads no boot server configuration. + origin, err := redfish.ParseBootOrigin(origin) + if err != nil { + return err + } + var summary string + if redfishMode() { + var extra []string + if extraMAC != "" { + extra = append(extra, extraMAC) + } + summary, err = redfishwork.BootServer{Store: store}.CheckClosedBoot(origin, extra) + } else { + summary, err = vmwork.Config{}.CheckClosedBoot(store, origin) + } + if err != nil { + return err + } + fmt.Println(summary) + return nil + } + if redfishMode() { + server, err := redfishBootServer(store) + if err != nil { + return err + } + if command == "dhcp-feed" { + // Reservations name each Device's provisioning attachment, which + // only the enrollment records. + enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return err + } + server.Enrollment = enrollment + token, err := os.ReadFile(syncToken) + if err != nil { + return fmt.Errorf("DHCP synchronizer token: %w", err) + } + return server.ServeDHCP(strings.TrimSpace(string(token))) + } + return server.Serve(vmwork.DefaultBootWindow * 2) + } + if command == "dhcp-feed" { + return errors.New("the DHCP reservation feed serves only a Redfish site") + } + vm, err := vmBootConfig() + if err != nil { + return err + } + return vm.ServeBoot(store) +} diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index a6e33268..98c80483 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -23,6 +23,8 @@ import ( "k8s.io/client-go/tools/clientcmd" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/fleet/internal/custody/creatorwebhook" ) func main() { @@ -74,7 +76,7 @@ func run(ctx context.Context, configFile, providers, cert, key, clientCA string) if err != nil { return err } - server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} + server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(&creatorwebhook.Handler{Projects: projects, Resources: creatorwebhook.Resources}), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} go func() { <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index e4b38324..c9baa2d0 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -1,10 +1,12 @@ package main import ( + "bytes" "context" - "crypto/subtle" + "encoding/json" "errors" "flag" + "fmt" "io" "log/slog" "net/http" @@ -15,84 +17,146 @@ import ( "time" "unicode" - "go.datum.net/fleet/internal/simulator" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/simwork" + "go.datum.net/fleet/internal/site/siteapi" ) const shutdownTimeout = 10 * time.Second const maxTokenFileBytes = 4096 +// fleet-simulator is the simulator site: synthetic Devices with no BMC whose +// install and wipe effects go through the site framework's fenced journal. +// The coordinator reaches it over the site API. func main() { - var runtimeAddress, adminAddress, statePath, runtimeTokenPath, adminTokenPath string - flag.StringVar(&runtimeAddress, "listen-address", "127.0.0.1:8080", "runtime HTTP listen address") - flag.StringVar(&adminAddress, "admin-listen-address", "", "optional admin HTTP listen address; disabled by default") - flag.StringVar(&statePath, "state-file", "/var/lib/fleet-simulator/state.json", "durable state path") - flag.StringVar(&runtimeTokenPath, "runtime-token-file", "", "required file containing the runtime bearer token") - flag.StringVar(&adminTokenPath, "admin-token-file", "", "file containing the admin bearer token; required when the admin listener is enabled") + var address, stateDir, tokenPath, siteName, enrollmentPath string + var discover bool + var discoveryInterval time.Duration + flag.StringVar(&address, "listen-address", "127.0.0.1:8080", "site API listen address") + flag.StringVar(&stateDir, "state-dir", "/var/lib/fleet/site", "the site store's owner-only directory") + flag.StringVar(&tokenPath, "runtime-token-file", "", "required file containing the site API bearer token") + flag.StringVar(&siteName, "site", "simulator", "this site's name") + flag.StringVar(&enrollmentPath, "enrollment-file", "", "required JSON enrollment of the Devices this site serves") + flag.BoolVar(&discover, "discover", false, "write fixture discovery for the enrolled Devices, using the in-cluster credential") + flag.DurationVar(&discoveryInterval, "discovery-interval", time.Minute, "how often fixture discovery runs") flag.Parse() logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - runtimeToken, err := readToken(runtimeTokenPath) - if err != nil { - logger.Error("load runtime token", "error", err) + fail := func(what string, err error) { + logger.Error(what, "error", err) os.Exit(1) } - store, err := simulator.Open(statePath) + if _, err := readToken(tokenPath); err != nil { + fail("load site token", err) + } + enrollment, err := readEnrollment(enrollmentPath) if err != nil { - logger.Error("open simulator state", "error", err) - os.Exit(1) + fail("load enrollment", err) } - - runtimeTokenSource := func() (string, error) { return readToken(runtimeTokenPath) } - servers := []*http.Server{newServer(runtimeAddress, simulator.RuntimeHandlerWithTokenSource(store, runtimeTokenSource, logger), logger)} - if adminAddress != "" { - adminToken, err := readToken(adminTokenPath) + if err := os.MkdirAll(stateDir, 0o700); err != nil { + fail("create the site store", err) + } + if err := os.Chmod(stateDir, 0o700); err != nil { + fail("restrict the site store", err) + } + store, err := site.OpenStore(stateDir, nil) + if err != nil { + fail("open the site store", err) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + results := site.NewResults(store) + runner := &site.Runner{Site: siteName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}}} + 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 { + api, err := discoveryClient() if err != nil { - logger.Error("load admin token", "error", err) - os.Exit(1) + fail("build the discovery client", err) } - if err := validateDistinctTokens(runtimeToken, adminToken); err != nil { - logger.Error("validate simulator credentials", "error", err) - os.Exit(1) - } - adminTokenSource := func() (string, error) { return readToken(adminTokenPath) } - servers = append(servers, newServer(adminAddress, simulator.AdminHandlerWithTokenSource(store, adminTokenSource, logger), logger)) - } - - errCh := make(chan error, len(servers)) - for _, server := range servers { - server := server go func() { - logger.Info("fleet simulator listening", "address", server.Addr) - errCh <- server.ListenAndServe() + for { + if err := fixture.Discover(ctx, api, enrollment, time.Now()); err != nil && ctx.Err() == nil { + logger.Info("fixture discovery incomplete", "error", err.Error()) + } + select { + case <-ctx.Done(): + return + case <-time.After(discoveryInterval): + } + } }() } - - signals := make(chan os.Signal, 1) - signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) + errCh := make(chan error, 1) + go func() { + logger.Info("simulator site listening", "address", address, "site", siteName, "devices", len(enrollment)) + errCh <- server.ListenAndServe() + }() failed := false select { - case sig := <-signals: - logger.Info("shutting down fleet simulator", "signal", sig.String()) + case <-ctx.Done(): + logger.Info("shutting down the simulator site") case err := <-errCh: if !errors.Is(err, http.ErrServerClosed) { - logger.Error("fleet simulator server failed", "error", err) + logger.Error("simulator site server failed", "error", err) failed = true } } - - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + shutdown, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() - for _, server := range servers { - if err := server.Shutdown(ctx); err != nil { - logger.Error("shut down fleet simulator server", "address", server.Addr, "error", err) - failed = true - } + if err := server.Shutdown(shutdown); err != nil { + logger.Error("shut down the simulator site", "error", err) + failed = true } + // Workers stopped by shutdown store no result; the next process + // resumes them from the journal. + dispatcher.Wait() if failed { os.Exit(1) } } +func readEnrollment(path string) (fixture.Enrollment, error) { + if path == "" { + return nil, errors.New("an enrollment file is required") + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + var enrollment fixture.Enrollment + if err := decoder.Decode(&enrollment); err != nil { + return nil, err + } + for device, target := range enrollment { + if !strings.Contains(device, "/") || target.SystemUUID == "" || target.BMCEndpoint == "" || target.BMCPublicKeySHA256 == "" || len(target.Disks) == 0 { + return nil, fmt.Errorf("enrollment of %s is incomplete", device) + } + } + return enrollment, nil +} + +func discoveryClient() (client.Client, error) { + config, err := rest.InClusterConfig() + if err != nil { + return nil, err + } + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + return nil, err + } + return client.New(config, client.Options{Scheme: scheme}) +} + func readToken(path string) (string, error) { if path == "" { return "", errors.New("token file is required") @@ -126,13 +190,6 @@ func readToken(path string) (string, error) { return token, nil } -func validateDistinctTokens(runtimeToken, adminToken string) error { - if len(runtimeToken) == len(adminToken) && subtle.ConstantTimeCompare([]byte(runtimeToken), []byte(adminToken)) == 1 { - return errors.New("runtime and admin tokens must be distinct") - } - return nil -} - func newServer(address string, handler http.Handler, logger *slog.Logger) *http.Server { return &http.Server{ Addr: address, diff --git a/cmd/fleet-simulator/main_test.go b/cmd/fleet-simulator/main_test.go index 12260921..017240cf 100644 --- a/cmd/fleet-simulator/main_test.go +++ b/cmd/fleet-simulator/main_test.go @@ -41,12 +41,28 @@ func TestReadToken(t *testing.T) { } } -func TestRuntimeAndAdminTokensMustDiffer(t *testing.T) { - if err := validateDistinctTokens("runtime", "admin"); err != nil { - t.Fatalf("distinct tokens rejected: %v", err) +func TestReadEnrollmentRequiresCompleteTargets(t *testing.T) { + dir := t.TempDir() + complete := filepath.Join(dir, "complete.json") + if err := os.WriteFile(complete, []byte(`{"fleet-provider/server-example-001":{"bmcEndpoint":"https://[2001:db8::1]","systemUUID":"00000000-0000-4000-8000-000000000001","bootMACAddress":"02:00:00:00:00:01","bmcPublicKeySHA256":"`+strings.Repeat("a", 64)+`","disks":["disk-0"]}}`), 0o600); err != nil { + t.Fatal(err) + } + if enrollment, err := readEnrollment(complete); err != nil || len(enrollment) != 1 { + t.Fatalf("complete enrollment = %v, %v", enrollment, err) } - if err := validateDistinctTokens("same", "same"); err == nil { - t.Fatal("equal runtime and admin tokens were accepted") + for name, body := range map[string]string{ + "no-namespace": `{"server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k","disks":["disk-0"]}}`, + "no-key": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","disks":["disk-0"]}}`, + "no-disks": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k"}}`, + "unknown": `{"fleet-provider/server-example-001":{"bmcEndpoint":"e","systemUUID":"u","bmcPublicKeySHA256":"k","disks":["disk-0"],"extra":true}}`, + } { + path := filepath.Join(dir, name+".json") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if _, err := readEnrollment(path); err == nil { + t.Errorf("%s: enrollment accepted", name) + } } } diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index e8b4c484..b4546881 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -1,91 +1,166 @@ +// fleet-standalone-smoke runs the standalone smoke test's phases, and the +// coordinator process the phases rely on, in one kind cluster. package main import ( "context" + "errors" "flag" "fmt" + "log/slog" "net/http" "os" + "os/signal" "strings" + "syscall" "time" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site/siteapi" "go.datum.net/fleet/internal/standalone" ) +const ( + providerPrincipal = "system:serviceaccount:fleet-system:fleet-standalone-smoke" + releasePrincipal = "system:serviceaccount:fleet-system:fleet-release-controller" + // cleaningPolicy is the fixture's cleaning policy record. Its digest is + // what each allocation pins. + cleaningPolicy = `{"name":"synthetic-tenant-reuse-v1","method":"overwrite","disks":"all"}` +) + func main() { options := standalone.DefaultOptions() - var phase, simulatorURL, tokenFile string - flag.StringVar(&phase, "phase", "", "required synthetic smoke phase: allocate, install, reinstall, or release") - flag.StringVar(&simulatorURL, "simulator-url", "http://fleet-simulator:8080", "synthetic simulator runtime URL") - flag.StringVar(&tokenFile, "runtime-token-file", "", "file containing the synthetic simulator runtime token") - flag.StringVar(&options.PrivateNamespace, "private-namespace", options.PrivateNamespace, "private record namespace") + var phase, coordinatorToken, releaseToken, siteURL, siteToken, siteName, devices string + flag.StringVar(&phase, "phase", "", "required: allocate, install, reinstall, release, or coordinate") + flag.StringVar(&coordinatorToken, "coordinator-token-file", "", "the custody coordinator's ServiceAccount token (phases)") + flag.StringVar(&releaseToken, "release-token-file", "", "the release controller's ServiceAccount token (phases)") + flag.StringVar(&siteURL, "site-url", "http://fleet-simulator:8080", "the simulator site's API (coordinate)") + flag.StringVar(&siteToken, "site-token-file", "", "the simulator site's bearer token (coordinate)") + flag.StringVar(&siteName, "site", "simulator", "the simulator site's name (coordinate)") + flag.StringVar(&devices, "devices", "synthetic-device-central-01", "comma-separated Devices the site serves (coordinate)") flag.StringVar(&options.ProviderNamespace, "provider-namespace", options.ProviderNamespace, "synthetic provider namespace") flag.StringVar(&options.FirstNamespace, "first-namespace", options.FirstNamespace, "first consumer namespace stand-in") flag.StringVar(&options.SecondNamespace, "second-namespace", options.SecondNamespace, "second consumer namespace stand-in") - flag.StringVar(&options.ImageName, "image", options.ImageName, "digest-pinned synthetic image name") flag.Parse() - if phase == "" || tokenFile == "" { - fail(fmt.Errorf("phase and runtime-token-file are required")) - } - tokenBytes, err := os.ReadFile(tokenFile) - if err != nil { - fail(err) + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + config := ctrl.GetConfigOrDie() + registry, err := custody.DefaultRegistry() + must(err) + if phase == "coordinate" { + must(coordinate(ctx, config, registry, options.ProviderNamespace, siteName, siteURL, siteToken, strings.Split(devices, ","))) + return } - token := strings.TrimSpace(string(tokenBytes)) - if token == "" || strings.ContainsAny(token, "\r\n") { - fail(fmt.Errorf("runtime token must be one nonempty line")) + if coordinatorToken == "" || releaseToken == "" { + must(errors.New("phases need the coordinator and release controller token files")) } - scheme := runtime.NewScheme() - if err := clientgoscheme.AddToScheme(scheme); err != nil { - fail(err) + provider, err := newClient(config) + must(err) + coordinatorConfig, releaseConfig := withToken(config, coordinatorToken), withToken(config, releaseToken) + coordinatorClient, err := newClient(coordinatorConfig) + must(err) + releaseClient, err := newClient(releaseConfig) + must(err) + providerCreator, err := allocation.Creator(ctx, config) + must(err) + releaseCreator, err := allocation.Creator(ctx, releaseConfig) + must(err) + 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, + // The fixture Device's boot NIC and the simulator's one enrolled disk. + BootInterface: "primary", TargetDisks: []string{"disk-0"}, } - if err := fleetv1.AddToScheme(scheme); err != nil { - fail(err) + must(standalone.Runner{Client: provider, Allocator: allocator, Options: options}.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") } - kube, err := client.New(ctrl.GetConfigOrDie(), client.Options{Scheme: scheme}) + api, err := newClient(config) if err != nil { - fail(err) + return err } - provider, err := executor.NewHTTPClient(simulatorURL, token, &http.Client{Timeout: 30 * time.Second}) + remote, err := siteapi.NewClient(siteURL, func() (string, error) { return readToken(tokenFile) }, &http.Client{Timeout: 30 * time.Second}) if err != nil { - fail(err) - } - if err := awaitSimulator(simulatorURL, 2*time.Minute); err != nil { - fail(err) + return err } - if err := (standalone.Runner{Client: kube, Executor: provider, Options: options}).Run(context.Background(), phase); err != nil { - fail(err) + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + for _, device := range devices { + if device = strings.TrimSpace(device); device != "" { + sites.Devices[device] = []string{siteName} + } } - fmt.Printf("standalone synthetic smoke phase %s completed\n", phase) + 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}, + 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) } -func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) } +func principals() custody.Principals { + return custody.Principals{custody.CreatorMetalProvider: {{Username: providerPrincipal}}, custody.CreatorReleaseController: {{Username: releasePrincipal}}} +} -// awaitSimulator waits until the simulator's Service answers readiness. A -// phase started just after a simulator restart can otherwise reach no pod, -// and the lifecycle correctly reports that transport failure as an unknown -// outcome. Readiness has no effect and is never operation evidence. -func awaitSimulator(base string, limit time.Duration) error { - c := &http.Client{Timeout: 5 * time.Second} - deadline := time.Now().Add(limit) - for { - resp, err := c.Get(strings.TrimRight(base, "/") + "/readyz") - if err == nil { - resp.Body.Close() - if resp.StatusCode == http.StatusOK { - return nil - } - } - if time.Now().After(deadline) { - return fmt.Errorf("simulator did not become reachable and ready within %s", limit) +func fixtureCleaning(name string) (string, error) { + if name != "synthetic-tenant-reuse-v1" { + return "", fmt.Errorf("no fixture cleaning policy %q", name) + } + return custody.SpecDigest(cleaningPolicy) +} + +func newClient(config *rest.Config) (client.Client, error) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, fleetv1.AddToScheme, inventory.AddToScheme, ops.AddToScheme} { + if err := add(scheme); err != nil { + return nil, err } - time.Sleep(time.Second) + } + return client.New(config, client.Options{Scheme: scheme}) +} + +// withToken is the in-cluster config authenticated as another +// ServiceAccount. +func withToken(config *rest.Config, tokenFile string) *rest.Config { + copied := rest.AnonymousClientConfig(config) + copied.BearerTokenFile = tokenFile + return copied +} + +func readToken(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(data)) + if token == "" || strings.ContainsAny(token, "\r\n") { + return "", errors.New("the token must be one nonempty line") + } + return token, nil +} + +func must(err error) { + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } } diff --git a/config/README.md b/config/README.md index 77bd2da6..7647a777 100644 --- a/config/README.md +++ b/config/README.md @@ -14,8 +14,9 @@ target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook. Devices can be deleted. | -| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, the Device custody and operation kinds with their roles and creator webhook, and the mandatory capacity-registration webhook. Devices can be deleted. | +| `config/milo-synthetic` | A separate non-production Milo control plane | The same kinds, ProtectedResources and roles, with the Device custody kinds but without the creator webhook and the capacity-registration webhook | +| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, and admission fences. It holds no private records: the Secret-backed records and their namespace are removed. | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | `config/components/device-deletion-protection` is a reusable component: a @@ -63,8 +64,14 @@ legacy management-cluster install and will be removed. See `config/components/device-operations` registers `DeviceCustody`, the Device operation kinds, their ProtectedResources, the coordinator, requester, viewer -and recovery operator roles, and the creator webhook. It is implemented and -inert: no root includes it yet. See [device custody](../docs/development/device-custody.md). +and recovery operator roles, and the creator webhook. `config/milo` includes all +of it, and the `fleet-registration` server serves the webhook at +`/validate-operation-creator`. `config/milo-synthetic` includes the kinds, +ProtectedResources and roles without the webhook, because it installs no +registration webhook. `config/standalone` includes only the CRDs and enforces the +creator rule with a ValidatingAdmissionPolicy. Including the kinds installs no +coordinator: the production manager has no provider, so nothing creates +custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). `config/base/bmc-discovery` runs read-only BMC discovery for one Milo project in a cluster that can reach the BMC network: one replica, no leader election, @@ -84,7 +91,7 @@ graph. The harness stages them into an OCI artifact; see production roots, and neither production root may reference them. `config/overlays/synthetic-staging` is the temporary Milo-routed acceptance -environment. It uses the real private custody, exclusivity, cleanup, and reuse +environment. It uses the real Device custody, exclusivity, release, and reuse implementation, but substitutes synthetic admission and provider evidence. It accepts only powered-off, networkless claims in `us-central-1`; its status conditions identify that boundary. The manager still engages every consuming @@ -93,42 +100,67 @@ configured consumer project (`consumerProjectName`); every other engaged project gets blocked lifecycle handlers and requested-hardware resolution. With the publication keys documented below it uses one distinct provider project, publishes a locked class reference and exact profile copy into the consumer, -and retains both project lifetimes in allocation custody. Provider Machine events wake +and records both project lifetimes on each allocation. Provider Machine events wake consumer claims directly; no polling resync is enabled. -The simulator runs in a separate `fleet-synthetic-provider` Deployment behind a -ClusterIP Service. The manager uses Service DNS and mounts the same dedicated -runtime credential as the provider. The environment must supply the -`fleet-system/fleet-synthetic-provider-auth` Secret with a `token` key; the -staging infra overlay generates it through External Secrets with `CreatedOnce`. -Neither process uses a Kubernetes API token to authenticate provider requests. -The provider has its own service account with token automount disabled and no -RBAC grants. Its NetworkPolicy permits runtime ingress only from manager pods -in the same namespace and denies egress. The runtime uses cluster-local HTTP; -this is a synthetic staging boundary, not a production transport-security design. -The admin listener is disabled. - -The provider keeps its operation log on a retained 1 Gi ReadWriteOnce PVC using -the cluster's default StorageClass. It runs one replica with a `Recreate` strategy: -its file store is not safe for multiple writers. Do not scale it above one or -force-delete a running provider pod. Manager rollouts do not restart the provider -or discard its state. Provider rollouts briefly interrupt runtime calls; private -Fleet authority and the persisted simulator log retain exact inputs and outcomes. -Both mounts read the credential from the projected Secret directory, allowing -rotation without a restart; projection skew may temporarily reject requests. -This overlay must never be promoted to production. - -### Moving from the colocated simulator - -Deploy the environment's generated credential before publishing this overlay. -Stop the old manager and verify all synthetic allocations and private custody -have completed release before replacing the sidecar. Do not treat missing public -Machines as proof of cleanup. The new PVC starts empty: this change does not copy -the sidecar's ephemeral state and must not be used to abandon active operations. -After rollout, verify both Deployments, Service routing, PVC binding, and a fresh -allocation and verified release. Check provider restart recovery with an active -synthetic claim before treating persistent-state recovery as verified in staging. -Do not delete the PVC as a recovery shortcut. +The simulator is a site. It runs in a separate `fleet-synthetic-provider` +Deployment behind a ClusterIP Service. The manager runs the custody coordinator +loop, and reaches the site through Service DNS with the site API bearer token. +The environment must supply the `fleet-system/fleet-synthetic-provider-auth` +Secret with a `token` key; the environment generates it, for example through +External Secrets with `CreatedOnce`. The provider has its own service account with token +automount disabled and no RBAC grants. Its NetworkPolicy permits runtime ingress +only from manager pods in the same namespace and denies egress. The runtime uses +cluster-local HTTP; this is a synthetic staging boundary, not a production +transport-security design. The admin listener is disabled. + +The site keeps its store on a retained 1 Gi ReadWriteOnce PVC using the cluster's +default StorageClass. The store holds each Device's fence and its simulated +server. It runs one replica with a `Recreate` strategy: the store is not safe for +multiple writers. Do not scale it above one or force-delete a running provider +pod. Manager rollouts do not restart the provider or discard its state. Provider +rollouts briefly interrupt site calls; custody and the site store retain exact +inputs and outcomes. The site reads its token from the projected Secret +directory, allowing rotation without a restart; projection skew may temporarily +reject requests. This overlay must never be promoted to production. + +### Moving from the Secret-backed staging + +The cutover to Device custody deletes the private records, their namespace and +RBAC, and the manager's `--private-namespace` flag. It adds no migration and +reads no old record. An environment that ran the old overlay must do the +following before the new manager runs: + +1. Release every old synthetic allocation, or discard the synthetic state. Do not + treat missing public Machines as proof of cleanup. +2. Make sure the provider project has its records: Devices with their BMC + endpoints and identities, and the capacities, as in [Planning and + registering physical devices](../docs/operations/physical-inventory.md). + Records GitOps already manages stay with it; import by hand only the ones it + does not. +3. Create 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 + issue each a client certificate with a cert-manager Certificate whose + Secret is the one below. +4. Give the manager's own identity, the Metal provider, these roles in the + provider project: `metal.datumapis.com-controller`, which now deletes an + allocation that lost its Device before it held it; + `fleet.datumapis.com-device-installation-requester`; and + `fleet.datumapis.com-inventory-discoverer`, because in synthetic staging the manager writes the + fixture discovery of the site's Devices. One manager process holds all + three component credentials. Each write carries its own component's + identity, but the process can act as any of them: this is the synthetic + seam, not production separation. +5. Replace the site enrollment placeholder with the Devices the site serves. +6. Delete the old `fleet-system-private` namespace and its Secrets by hand. + Its manifest was never pruned, so Flux leaves it in place. +7. Delete the publisher's copy of the MachineClass in the consumer project. Its + source names the old `project` field and is immutable, so the publisher + recreates it with `publisherRef`. +8. After rollout, verify both Deployments, Service routing, PVC binding, and a + fresh allocation and verified release. Do not delete the PVC as a recovery + shortcut. Render the Milo and management-cluster roots before publishing the Kustomize bundle: @@ -215,6 +247,21 @@ data: publishedProfileName: ``` +The overlay also takes these inputs for the custody coordinator, which the +manager runs under its leader lease together with fixture discovery: + +| Input | Flag | Content | +| --- | --- | --- | +| Secret `fleet-system/fleet-custody-coordinator-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-coordinator-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-coordinator` role in the provider project, as a cert-manager Certificate writes it. Supplied by the environment. | +| Secret `fleet-system/fleet-release-controller-client-cert`, keys `tls.crt` and `tls.key` | `--synthetic-release-client-cert-dir` | The Milo client certificate of an identity with the `fleet.datumapis.com-device-wipe-requester` role in the provider project. Supplied by the environment. | +| ConfigMap `fleet-system/fleet-synthetic-site-enrollment`, key `enrollment.json` | `--synthetic-site-enrollment-file` | The Devices the synthetic site serves, keyed `/`, each with its BMC endpoint, system UUID, boot MAC address, key digest and disks. The overlay ships a synthetic placeholder for `server-example-001`, and an environment replaces it with the Devices it imports. | +| `--synthetic-device-namespace` | Default `default` | The namespace of the Devices, capacities and allocations in the provider project. Every enrolled Device must be in it. | + +The manager's own identity is the Metal provider. Fixture discovery is written by +the manager because the synthetic site has no API credential. The cutover +requires a person to re-import the records and create the two credentials; see +[Moving from the Secret-backed staging](#moving-from-the-secret-backed-staging). + The publisher refuses name collisions, reference chains, mutable profile-copy drift, a profile not allowed by the source class, or replacement source/project lifetimes. It writes only into the engaged consumer project, and only a @@ -266,11 +313,10 @@ the discovery role and the project identity needs the controller role plus Fleet, NSO, quota, entitlement, Namespace, and Event access goes through the routed Milo project credential. The management-cluster service account has no -cluster-wide role. It receives only leader-election access in `fleet-system` -and Secret access in `fleet-system-private`; the separate host cache is confined -to that private namespace. Cache scoping is not an authorization boundary. The -private namespace and `fleet-system` have Flux pruning disabled so uninstalling -one release cannot implicitly delete retained lifecycle authority. +cluster-wide role. It receives only leader-election access in `fleet-system`. +It holds no Secret access: allocations, custody and operations live in the +provider project, not in the management cluster. `fleet-system` has Flux pruning +disabled. ## Project discovery @@ -281,10 +327,9 @@ gets its own runtime: the identity read from Milo, a client and cache bound to that project's control plane, a verifier run before every reconcile, its own mappers, and its own lifecycle owners. Every request carries its project's cluster name and is reconciled only through that runtime, and only when the -runtime's identity matches the request. Private records stay in the one host -namespace `fleet-system-private`; their names and indexes already key on the -consumer project's authority and UID, and a private-record event reaches only -the runtime engaged for exactly that project lifetime. +runtime's identity matches the request. A MachineAllocation lives in the +provider project and is named from the consumer project's UID and the Machine +UID, so equal Machine UIDs in two projects never share one. The synthetic provider project may itself be an Active `metal` consumer. It then engages like any other consumer, with blocked lifecycle handlers and the @@ -306,9 +351,9 @@ standby is warm. When a project leaves the consumer set (its ServiceConsumer is Denied or deleted), the manager only stops reconciling it. It does not release custody, call a provider, delete Fleet records, or rewrite Machine status, including -for a project with active custody. Private records for the departed project -stay in place, and its queued events and deadlines are dropped. If the project -is engaged again, reconciliation resumes from the retained records. Discovery +for a project with active custody. Its allocations stay in place, and its queued +events and deadlines are dropped. If the project is engaged again, +reconciliation resumes from the retained allocations. Discovery is observational: the manager adds no ServiceConsumer finalizer, so it never gates a project's deletion, and it does not confirm platform suspension (it drops the consumer library's `Paused` status patch, because Fleet implements no @@ -319,8 +364,8 @@ suspension). `/readyz` on port `health` (8081) reports discovery and cache health, not provider readiness. It passes when the provider project's ServiceConsumer cache has synced, every project with an Active `metal` ServiceConsumer is engaged on -that replica, every engaged project cache has synced, and the private-record -cache has synced. It never depends on a provider integration. It also keeps +that replica, and every engaged project cache has synced. It never depends on a +provider integration. It also keeps failing, with an explicit `project discovery is misconfigured` error, while no Service is registered for `metal.datumapis.com`, or while `consumerScopedProjection.providerProject` differs from that Service's @@ -363,7 +408,7 @@ removing the manifest does not authorize deletion or settle old obligations. Before explicitly deleting an existing legacy registration, verify there are no legacy grants, claims, allowance buckets, or creation policies, and all legacy allocations have verified release. Never retarget its immutable `spec.resourceType` -or delete retained private allocation records. Environments that have not completed +or delete a retained MachineAllocation. Environments that have not completed this audit must retain their existing registration. Coordinate environment changes before publishing the corrected bundle: publication @@ -372,55 +417,4 @@ must use `metal.datumapis.com/v1alpha1`, location availability must reference `metal`, and staff bindings must reference the Metal IAM roles. Gate the manager on inventory and service availability as well as the Milo configuration. Confirm old allocations are released immediately before rollout; absence of public -Machines alone does not prove private cleanup is complete. - -### Hand off bootstrap field ownership before removing the sidecar - -A staging Deployment initially applied by `fleet-staging-bootstrap` may retain -that server-side apply owner's fields alongside `kustomize-controller`. Removing -the sidecar from the Flux manifest can then fail with -`spec.template.spec.containers[1].image: Required value`: Flux removes the image -it owns, while bootstrap ownership retains the rest of the obsolete container. -The new provider Deployment does not cause this validation error. - -After stopping the manager, waiting for its Pods to terminate, and verifying -all private custody/asset records are Released, inspect the Deployment with -`kubectl get deployment fleet-manager -n fleet-system --show-managed-fields -o json`. -Use the explicit staging context for every command. Confirm that the obsolete -sidecar is co-owned by `fleet-staging-bootstrap` and `kustomize-controller`. -Do not remove managedFields directly or delete/recreate the Deployment. - -The old bootstrap apply owner can relinquish its fields by applying only the -Deployment's identity under its original field-manager name: - -```sh -kubectl --context "$staging_context" -n fleet-system apply \ - --server-side --field-manager=fleet-staging-bootstrap \ - --dry-run=server --show-managed-fields -o json -f - <<'YAML' -apiVersion: apps/v1 -kind: Deployment -metadata: - name: fleet-manager - namespace: fleet-system -YAML -``` - -Compare the returned `spec` with a fresh live read. They must be identical, -including `replicas: 0`, and the sidecar's remaining apply owner must be -`kustomize-controller`. If these checks fail, stop and investigate exclusive -bootstrap-owned fields rather than forcing the change. This relinquishes the -bootstrap **Apply** ownership; any historical **Update** entries are distinct -and must not be erased indiscriminately. - -Once reviewed, repeat the same command without `--dry-run=server`. Re-read the -Deployment to confirm the same invariants, then request reconciliation of -`fleet-system/fleet-host`. Flux can now remove the entire obsolete container and -install the separate provider. This handoff changes ownership only; it must not -restart the old manager, modify private records, rotate credentials, or remove -provider state. Continue with the allocation, restart recovery, and release -checks described above. - -On November 12, 2026, the staging server accepted this ownership-only dry run: -the complete Deployment spec remained identical at zero replicas, and only -`kustomize-controller` retained sidecar ownership. Execution and successful -post-handoff reconciliation must be verified separately. +Machines alone does not prove cleanup is complete. diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 16a1fde1..481cb14b 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -34,9 +34,18 @@ spec: properties: source: type: object - required: [project, name] + required: [publisherRef, name] properties: - project: {type: string, minLength: 1} + publisherRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a publisher is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} name: {type: string, minLength: 1} profilePolicy: {type: object, x-kubernetes-preserve-unknown-fields: true} access: {type: object, x-kubernetes-preserve-unknown-fields: true} @@ -355,15 +364,26 @@ spec: metadata: {type: object} spec: type: object - required: [machineRef, machineCapacityRef] + required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicyDigest, bootInterface, targetDisks] x-kubernetes-validations: - {rule: 'self == oldSelf', message: MachineAllocation identity and endpoints are immutable} properties: + # No spec holds an object UID. The allocation's name hashes the + # consumer and Machine UIDs, and its labels record them. + consumerRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a consumer is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} machineRef: type: object - required: [project, namespace, name] + required: [namespace, name] properties: - project: {type: string, minLength: 1} namespace: {type: string, minLength: 1} name: {type: string, minLength: 1} machineCapacityRef: @@ -372,6 +392,59 @@ spec: properties: namespace: {type: string, minLength: 1} name: {type: string, minLength: 1} + deviceRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + accepted: + type: object + required: [machineClassRef, machineProfileRef, cpu, memory] + properties: + machineClassRef: + type: object + required: [name, generation, digest] + properties: + name: {type: string, minLength: 1} + generation: {type: integer, format: int64, minimum: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + machineProfileRef: + type: object + required: [name, generation, digest] + properties: + name: {type: string, minLength: 1} + generation: {type: integer, format: int64, minimum: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + cpu: + type: object + required: [architecture, cores] + properties: + architecture: {type: string, minLength: 1, maxLength: 63} + cores: {type: integer, format: int64, minimum: 1} + memory: + type: object + required: [capacity] + properties: + capacity: {type: string, minLength: 1} + hardware: {type: object, x-kubernetes-preserve-unknown-fields: true} + authority: + type: object + required: [principal, decision] + properties: + principal: {type: string, minLength: 1, maxLength: 253} + decision: {type: string, minLength: 1, maxLength: 253} + quotaClaimRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + cleaningPolicyDigest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + bootInterface: {type: string, minLength: 1, maxLength: 63} + targetDisks: + type: array + minItems: 1 + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} status: type: object x-kubernetes-validations: @@ -379,6 +452,12 @@ spec: message: a released MachineAllocation is terminal properties: phase: {type: string, enum: [Pending, Active, Releasing, Released, Unknown]} + wipe: + type: object + required: [name, step] + properties: + name: {type: string, minLength: 1} + step: {type: integer, format: int32, minimum: 1} conditions: type: array items: {type: object, x-kubernetes-preserve-unknown-fields: true} diff --git a/config/base/manager/deployment.yaml b/config/base/manager/deployment.yaml index e0546962..8697749e 100644 --- a/config/base/manager/deployment.yaml +++ b/config/base/manager/deployment.yaml @@ -37,7 +37,6 @@ spec: # blocked and only requested hardware is resolved. args: - --config=/etc/fleet/manager/config.yaml - - --private-namespace=fleet-system-private - --leader-election-namespace=fleet-system ports: - name: health diff --git a/config/base/manager/kustomization.yaml b/config/base/manager/kustomization.yaml index b61f6474..8820a53a 100644 --- a/config/base/manager/kustomization.yaml +++ b/config/base/manager/kustomization.yaml @@ -5,6 +5,4 @@ resources: - service-account.yaml - leader-election-role.yaml - leader-election-role-binding.yaml - - private-record-role.yaml - - private-record-role-binding.yaml - deployment.yaml diff --git a/config/base/manager/namespace.yaml b/config/base/manager/namespace.yaml index 8b8553ab..cf4711d0 100644 --- a/config/base/manager/namespace.yaml +++ b/config/base/manager/namespace.yaml @@ -5,11 +5,3 @@ metadata: annotations: kustomize.toolkit.fluxcd.io/prune: disabled fleet.datumapis.com/shared-with-standalone: "true" ---- -apiVersion: v1 -kind: Namespace -metadata: - name: fleet-system-private - annotations: - kustomize.toolkit.fluxcd.io/prune: disabled - fleet.datumapis.com/shared-with-standalone: "true" diff --git a/config/base/manager/private-record-role-binding.yaml b/config/base/manager/private-record-role-binding.yaml deleted file mode 100644 index 679abd8b..00000000 --- a/config/base/manager/private-record-role-binding.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-manager-private-records - namespace: fleet-system-private -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: fleet-manager-private-records -subjects: - - kind: ServiceAccount - name: fleet-manager - namespace: fleet-system diff --git a/config/base/manager/private-record-role.yaml b/config/base/manager/private-record-role.yaml deleted file mode 100644 index 4c9159fc..00000000 --- a/config/base/manager/private-record-role.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-manager-private-records - namespace: fleet-system-private -rules: - - apiGroups: [''] - resources: [secrets] - verbs: [get, list, watch, create, update, patch, delete] diff --git a/config/base/simulator/statefulset.yaml b/config/base/simulator/statefulset.yaml index 9fe530fc..6f968d59 100644 --- a/config/base/simulator/statefulset.yaml +++ b/config/base/simulator/statefulset.yaml @@ -13,6 +13,8 @@ spec: labels: {app.kubernetes.io/name: fleet-simulator} spec: serviceAccountName: fleet-simulator + # Fixture discovery writes the status of the Devices this site serves. + automountServiceAccountToken: true securityContext: runAsNonRoot: true runAsUser: 65532 @@ -27,10 +29,12 @@ spec: args: - --listen-address=0.0.0.0:8080 - --runtime-token-file=/var/run/fleet/token - - --state-file=/var/lib/fleet/state.json + - --state-dir=/var/lib/fleet/site + - --enrollment-file=/etc/fleet/enrollment/enrollment.json + - --discover ports: [{name: runtime, containerPort: 8080}] readinessProbe: {httpGet: {path: /readyz, port: runtime}, periodSeconds: 2} - livenessProbe: {httpGet: {path: /healthz, port: runtime}, periodSeconds: 10} + livenessProbe: {httpGet: {path: /readyz, port: runtime}, periodSeconds: 10} securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} resources: requests: {cpu: 20m, memory: 32Mi} @@ -38,9 +42,12 @@ spec: volumeMounts: - {name: state, mountPath: /var/lib/fleet} - {name: runtime-token, mountPath: /var/run/fleet, readOnly: true} + - {name: enrollment, mountPath: /etc/fleet/enrollment, readOnly: true} volumes: - name: runtime-token secret: {secretName: fleet-simulator-runtime, defaultMode: 0440} + - name: enrollment + configMap: {name: fleet-simulator-enrollment, defaultMode: 0440} volumeClaimTemplates: - metadata: {name: state} spec: diff --git a/config/components/admission/policies.yaml b/config/components/admission/policies.yaml index 234d30cc..fef959f6 100644 --- a/config/components/admission/policies.yaml +++ b/config/components/admission/policies.yaml @@ -26,35 +26,3 @@ metadata: spec: policyName: fleet-machine-finalizer-protection validationActions: [Deny] ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-private-record-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [CREATE, UPDATE, DELETE] - resources: [secrets] - matchConditions: - - name: private-record - expression: >- - (request.operation != 'DELETE' && has(object.metadata.labels) && - 'fleet.datumapis.com/private-record' in object.metadata.labels) || - (request.operation != 'CREATE' && has(oldObject.metadata.labels) && - 'fleet.datumapis.com/private-record' in oldObject.metadata.labels) - validations: - - expression: >- - request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-manager' - message: Fleet private coordination records are service-controlled. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-private-record-protection -spec: - policyName: fleet-private-record-protection - validationActions: [Deny] diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 6b60afe9..e3f20eb3 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -54,13 +54,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid state: type: string enum: @@ -116,10 +111,6 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 fence: type: integer format: int64 @@ -180,7 +171,6 @@ spec: maxLength: 512 required: - username - - uid settles: type: object properties: @@ -192,18 +182,17 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 + fence: + type: integer + format: int64 + minimum: 0 required: - kind - name - - uid + - fence required: - kind - name - - uid - fence - phase - admittedAt @@ -222,10 +211,6 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 fence: type: integer format: int64 @@ -256,7 +241,6 @@ spec: required: - kind - name - - uid - fence - phase - finishedAt @@ -271,10 +255,6 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 fence: type: integer format: int64 @@ -327,14 +307,14 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 + fence: + type: integer + format: int64 + minimum: 0 required: - kind - name - - uid + - fence retries: type: integer format: int32 @@ -345,7 +325,6 @@ spec: required: - kind - name - - uid - fence - since - reason @@ -464,7 +443,6 @@ spec: maxLength: 512 required: - username - - uid deviceRef: type: object properties: @@ -472,13 +450,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid authority: type: object properties: @@ -503,10 +476,6 @@ spec: x-kubernetes-validations: - rule: has(self.allocationRef) != has(self.serviceRequest) message: set exactly one of allocationRef and serviceRequest - requestUID: - type: string - minLength: 1 - maxLength: 64 image: type: object properties: @@ -550,7 +519,6 @@ spec: - creator - deviceRef - authority - - requestUID - image - bootInterface - targetDisks @@ -560,6 +528,15 @@ spec: status: type: object properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence phase: type: string enum: @@ -688,7 +665,6 @@ spec: maxLength: 512 required: - username - - uid deviceRef: type: object properties: @@ -696,13 +672,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid authority: type: object properties: @@ -756,6 +727,15 @@ spec: status: type: object properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence phase: type: string enum: @@ -884,7 +864,6 @@ spec: maxLength: 512 required: - username - - uid deviceRef: type: object properties: @@ -892,13 +871,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid authority: type: object properties: @@ -1022,6 +996,15 @@ spec: status: type: object properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence phase: type: string enum: diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml index 093f38a4..0b86e400 100644 --- a/config/components/device-operations/kustomization.yaml +++ b/config/components/device-operations/kustomization.yaml @@ -1,6 +1,7 @@ -# Device custody and operations (#174 at d4d17f9). Implemented and inert: no -# deployment root includes this component yet, so nothing serves these kinds -# or calls the webhook. +# Device custody and operations (#174 at d4d17f9): the kinds, their +# ProtectedResources and roles, and the creator webhook, which the +# fleet-registration server serves. config/milo includes all of it; +# config/milo-synthetic includes everything but the webhook. apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: diff --git a/config/components/iam/roles/controller.yaml b/config/components/iam/roles/controller.yaml index 1ba48bd0..5739cf1b 100644 --- a/config/components/iam/roles/controller.yaml +++ b/config/components/iam/roles/controller.yaml @@ -19,6 +19,9 @@ spec: - metal.datumapis.com/machineallocations.get - metal.datumapis.com/machineallocations.watch - metal.datumapis.com/machineallocations.create + # An allocation that lost its Device before it ever held it is deleted, + # and the allocator selects again. + - metal.datumapis.com/machineallocations.delete - metal.datumapis.com/machineallocations.update - metal.datumapis.com/machineallocations.patch - metal.datumapis.com/machineallocations.updateStatus diff --git a/config/milo-synthetic/kustomization.yaml b/config/milo-synthetic/kustomization.yaml index 0f5a7f84..17a59dbd 100644 --- a/config/milo-synthetic/kustomization.yaml +++ b/config/milo-synthetic/kustomization.yaml @@ -5,3 +5,8 @@ resources: - ../components/iam - ../components/service-catalog - ../components/inventory + # Device custody and operations without the creator webhook: this root + # installs no webhook, as it installs no registration webhook. + - ../components/device-operations/crds + - ../components/device-operations/protected-resources + - ../components/device-operations/roles diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index c6a9b5d5..698ac665 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -6,3 +6,4 @@ resources: - ../components/service-catalog - ../components/inventory - ../components/registration-admission + - ../components/device-operations diff --git a/config/multiplane/clusters/hub/hub.yaml b/config/multiplane/clusters/hub/hub.yaml index a31b21ce..67b9f73f 100644 --- a/config/multiplane/clusters/hub/hub.yaml +++ b/config/multiplane/clusters/hub/hub.yaml @@ -20,19 +20,6 @@ spec: sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} path: ./config/multiplane/karmada --- -# Private custody namespace and the custodian identity on the host API. -apiVersion: kustomize.toolkit.fluxcd.io/v1 -kind: Kustomization -metadata: {name: fleet-host, namespace: flux-system} -spec: - interval: 10m - retryInterval: 30s - timeout: 5m - prune: true - wait: true - sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} - path: ./config/multiplane/host ---- # Handoff CRD and namespace on the Karmada API. prune false: never # garbage-collect a CRD with retained intent (as datum-cloud/infra karmada-crds). apiVersion: kustomize.toolkit.fluxcd.io/v1 diff --git a/config/multiplane/coordination/crd.yaml b/config/multiplane/coordination/crd.yaml index bb4d4591..bd0e3234 100644 --- a/config/multiplane/coordination/crd.yaml +++ b/config/multiplane/coordination/crd.yaml @@ -1,5 +1,6 @@ -# Experimental handoff API: install on the Karmada API and participating cells. -# Never install in consumer project APIs. Payloads contain private authority. +# Federation handoff API: install on the Karmada API and participating cells. +# Never install in consumer project APIs. A handoff carries one admitted +# operation's site assignment, or asks for a Device's fence report. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: @@ -27,16 +28,19 @@ spec: properties: spec: type: object - required: [cell, requestJSON] + required: [cell, device] x-kubernetes-validations: - rule: self == oldSelf - message: Retained handoff intent is immutable + message: A handoff is immutable properties: cell: {type: string, minLength: 1, maxLength: 63} - requestJSON: + # The Device as namespace/name in the provider project. + device: {type: string, minLength: 3, maxLength: 317} + # The exact assignment JSON; absent on a fence report request. + assignmentJSON: type: string minLength: 1 - maxLength: 1048576 + maxLength: 65536 status: type: object x-kubernetes-preserve-unknown-fields: true diff --git a/config/multiplane/host/custody.yaml b/config/multiplane/host/custody.yaml deleted file mode 100644 index 327eff17..00000000 --- a/config/multiplane/host/custody.yaml +++ /dev/null @@ -1,32 +0,0 @@ -# Private allocation custody on the management host API. Only the shared -# lifecycle coordinator's custodian identity may read or write these Secrets; -# its token is minted by bootstrap and never stored in the source. -apiVersion: v1 -kind: Namespace -metadata: - name: fleet-system-private - annotations: - # Holds retained allocation custody. Never garbage-collect it. Same name - # and policy as the production manager's private namespace. - kustomize.toolkit.fluxcd.io/prune: disabled - fleet.datumapis.com/shared-with-standalone: "true" ---- -apiVersion: v1 -kind: ServiceAccount -metadata: {name: fleet-custodian, namespace: fleet-system-private} -automountServiceAccountToken: false ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: {name: fleet-custodian, namespace: fleet-system-private} -rules: - - apiGroups: [""] - resources: [secrets] - verbs: [get, list, watch, create, update, patch] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: {name: fleet-custodian, namespace: fleet-system-private} -subjects: - - {kind: ServiceAccount, name: fleet-custodian, namespace: fleet-system-private} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-custodian} diff --git a/config/multiplane/host/kustomization.yaml b/config/multiplane/host/kustomization.yaml deleted file mode 100644 index b838ac56..00000000 --- a/config/multiplane/host/kustomization.yaml +++ /dev/null @@ -1,4 +0,0 @@ -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization -resources: - - custody.yaml diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml index 858908e6..17fb5d66 100644 --- a/config/multiplane/karmada-api/hub-rbac.yaml +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -9,7 +9,8 @@ metadata: {name: fleet-management, namespace: fleet-coordination} rules: - apiGroups: [coordination.fleet.datumapis.com] resources: [machineallocationhandoffs] - verbs: [get, list, watch, create] + # patch marks a handoff's result answered; the spec stays immutable. + verbs: [get, list, watch, create, patch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/config/overlays/synthetic-staging/kustomization.yaml b/config/overlays/synthetic-staging/kustomization.yaml index f8b3b726..48b464ea 100644 --- a/config/overlays/synthetic-staging/kustomization.yaml +++ b/config/overlays/synthetic-staging/kustomization.yaml @@ -33,6 +33,15 @@ patches: - op: add path: /spec/template/spec/containers/0/args/- value: --synthetic-published-profile-name=$(FLEET_PUBLISHED_PROFILE_NAME) + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-coordinator-client-cert-dir=/var/run/fleet/coordinator + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-release-client-cert-dir=/var/run/fleet/release + - op: add + path: /spec/template/spec/containers/0/args/- + value: --synthetic-site-enrollment-file=/etc/fleet/enrollment/enrollment.json - op: add path: /spec/template/spec/containers/0/env value: @@ -71,6 +80,59 @@ patches: name: synthetic-provider-token mountPath: /var/run/fleet/provider readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: custody-coordinator-client-cert + mountPath: /var/run/fleet/coordinator + readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: release-controller-client-cert + mountPath: /var/run/fleet/release + readOnly: true + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: synthetic-site-enrollment + mountPath: /etc/fleet/enrollment + readOnly: true + - op: add + path: /spec/template/spec/volumes/- + value: + name: custody-coordinator-client-cert + # A cert-manager Certificate's Secret for the coordinator's Milo + # identity. The whole Secret is mounted so a renewal is picked up. + secret: + secretName: fleet-custody-coordinator-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: release-controller-client-cert + # A cert-manager Certificate's Secret for the release controller's + # Milo identity. + secret: + secretName: fleet-release-controller-client-cert + defaultMode: 0440 + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - op: add + path: /spec/template/spec/volumes/- + value: + name: synthetic-site-enrollment + configMap: + name: fleet-synthetic-site-enrollment + defaultMode: 0440 - op: add path: /spec/template/spec/volumes/- value: diff --git a/config/overlays/synthetic-staging/provider.yaml b/config/overlays/synthetic-staging/provider.yaml index 37ecbe78..30497a71 100644 --- a/config/overlays/synthetic-staging/provider.yaml +++ b/config/overlays/synthetic-staging/provider.yaml @@ -1,3 +1,16 @@ +# The synthetic provider site's enrollment: the Devices it serves, with the +# identity their Device records carry and the key digest fixture discovery +# reports. This placeholder is synthetic; an environment replaces it with the +# Devices it imports. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-synthetic-site-enrollment + namespace: fleet-system +data: + enrollment.json: | + {"default/server-example-001": {"bmcEndpoint": "https://[2001:db8::31]", "systemUUID": "00000000-0000-4000-8000-000000000031", "bootMACAddress": "02:00:00:00:00:31", "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", "disks": ["disk-0"]}} +--- apiVersion: v1 kind: ServiceAccount metadata: @@ -25,7 +38,7 @@ metadata: namespace: fleet-system spec: replicas: 1 - # The simulator state file has one writer; never overlap provider pods. + # The site store has one writer; never overlap provider pods. strategy: type: Recreate selector: @@ -56,7 +69,8 @@ spec: args: - --listen-address=0.0.0.0:8090 - --runtime-token-file=/var/run/fleet/provider/token - - --state-file=/var/lib/fleet/state.json + - --state-dir=/var/lib/fleet/site + - --enrollment-file=/etc/fleet/enrollment/enrollment.json ports: - name: runtime containerPort: 8090 @@ -64,7 +78,7 @@ spec: httpGet: {path: /readyz, port: runtime} periodSeconds: 2 livenessProbe: - httpGet: {path: /healthz, port: runtime} + httpGet: {path: /readyz, port: runtime} periodSeconds: 10 resources: requests: {cpu: 10m, memory: 24Mi} @@ -79,7 +93,14 @@ spec: - name: runtime-token mountPath: /var/run/fleet/provider readOnly: true + - name: enrollment + mountPath: /etc/fleet/enrollment + readOnly: true volumes: + - name: enrollment + configMap: + name: fleet-synthetic-site-enrollment + defaultMode: 0440 - name: state persistentVolumeClaim: claimName: fleet-synthetic-provider-state diff --git a/config/site/base/enrollment.json b/config/site/base/enrollment.json new file mode 100644 index 00000000..d02d4f85 --- /dev/null +++ b/config/site/base/enrollment.json @@ -0,0 +1 @@ +{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"]}} diff --git a/config/site/base/kustomization.yaml b/config/site/base/kustomization.yaml index 064bf927..9ad8af9f 100644 --- a/config/site/base/kustomization.yaml +++ b/config/site/base/kustomization.yaml @@ -4,3 +4,12 @@ resources: - site.yaml - kro.yaml - reconcilers.yaml +# The local VM site's enrollment of the one synthetic Device it serves: the +# identity its fixture Device records and the key digest fixture discovery +# reports. Synthetic data only. The Redfish site enrolls its targets in its +# graph instead. +configMapGenerator: + - name: fleet-site-enrollment + namespace: fleet-site + files: [enrollment.json] + options: {disableNameSuffixHash: true} diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml index d7f6e080..fd996eab 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -1,13 +1,13 @@ # kro ResourceGraphDefinition for one selected local cell. For each delivered -# MachineAllocationHandoff it creates one bounded worker Job with its own +# assignment handoff it creates one bounded worker Job with its own # ServiceAccount, Role and RoleBinding, and nothing else. The shared site # services, their boot Service and the journal volume are owned by the cell's # Flux (config/site/services, config/site/base); this graph only references # them, so deleting the instance or the graph cannot delete them. # # Every resource here is derived execution state: none of it allocates, admits, -# completes or releases anything. Management trusts only Karmada-reflected, -# journal-derived handoff status. +# completes or releases anything. The coordinator trusts only the +# Karmada-reflected status the observer derives from the site store. apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: @@ -22,7 +22,6 @@ spec: group: site.fleet.datumapis.com spec: cell: string | required=true - scopedAsset: string | required=true # Workers are created only after dispatch is enabled. The acceptance uses # this to prove delivery and retention before any effect can start. dispatch: boolean | default=false @@ -75,8 +74,9 @@ spec: kind: Deployment metadata: name: fleet-site-observer - # Delivered intent for this cell, watched by kro. The workers re-validate - # the cell, name and exact request; selection here is not authority. + # Delivered assignments for this cell, watched by kro. Fence report + # handoffs start no worker. The workers re-validate the cell, name and + # exact assignment; selection here is not authority. - id: handoffs externalRef: apiVersion: coordination.fleet.datumapis.com/v1alpha1 @@ -88,6 +88,9 @@ spec: - key: coordination.fleet.datumapis.com/cell operator: In values: ["${schema.spec.cell}"] + - key: coordination.fleet.datumapis.com/role + operator: In + values: [assignment] # Per-operation identity and policy: each worker may read exactly its own # handoff and nothing else. It has no status, list or Secret permission. # The fleet-site-kro-worker-identity admission policy enforces this shape. @@ -142,10 +145,10 @@ spec: apiGroup: rbac.authorization.k8s.io kind: Role name: ${"w-" + handoff.metadata.name} - # One bounded Job per delivered operation. The Job controller retries and - # replaces Pods; every Pod replays the same retained operation from the - # journal. Job completion is not readiness: only the observer publishes, - # and only management validates the reflected result. The Job runs the + # One bounded Job per delivered assignment. The Job controller retries + # and replaces Pods; every Pod resumes the same assignment from the site + # store's journal. Job completion is not readiness: only the observer + # publishes, and only the coordinator accepts the reflected result. The Job runs the # runtime's image (the fleet-site-kro-worker-jobs admission policy also # requires it) and reaches the runtime only through its libvirt socket. - id: workers @@ -172,13 +175,13 @@ spec: backoffLimit: 6 activeDeadlineSeconds: 3600 # A replacement Pod starts only after the previous Pod is terminal, - # so two workers for one operation never overlap; the journal lock - # is the second guard. + # so two workers for one operation never overlap; the Device's run + # lock is the second guard. podReplacementPolicy: Failed podFailurePolicy: rules: - # Exit 65: fenced, conflicting or invalid authority. Retrying - # cannot change it; fail without another attempt. + # Exit 65: a handoff not for this cell, or an assignment below + # the Device's stored fence. Retrying cannot change it. - action: FailJob onExitCodes: {containerName: worker, operator: In, values: [65]} - action: Ignore @@ -196,9 +199,13 @@ spec: - name: worker image: ${hypervisor.spec.template.spec.containers[0].image} imagePullPolicy: IfNotPresent - command: [fleet-multiplane, site-worker, --handoff, "${handoff.metadata.name}", --cell, "${schema.spec.cell}", --scoped-asset, "${schema.spec.scopedAsset}"] + command: [fleet-multiplane, site-worker, --handoff, "${handoff.metadata.name}", --cell, "${schema.spec.cell}"] env: - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + # The site's enrollment of the Devices it serves. + - name: FLEET_SITE_ENROLLMENT + valueFrom: + configMapKeyRef: {name: fleet-site-enrollment, key: enrollment.json} - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} diff --git a/config/site/instance/dispatcher.yaml b/config/site/instance/dispatcher.yaml index ae051632..5bb6bdf5 100644 --- a/config/site/instance/dispatcher.yaml +++ b/config/site/instance/dispatcher.yaml @@ -15,5 +15,4 @@ metadata: fleet.datumapis.com/source-marker: "${FLEET_SOURCE_MARKER}" spec: cell: "${FLEET_CELL}" - scopedAsset: "${FLEET_SCOPED_ASSET}" dispatch: ${FLEET_SITE_DISPATCH} diff --git a/config/site/redfish/base/credentials.yaml b/config/site/redfish/base/credentials.yaml new file mode 100644 index 00000000..e8b69bd8 --- /dev/null +++ b/config/site/redfish/base/credentials.yaml @@ -0,0 +1,32 @@ +# The site's per-Device BMC credential Secrets, by the BMC discovery contract. +# The harness enrolls them; they are never part of a source revision. Each +# Secret is named from its Device (bmc- and 20 hex digits of the Device's +# SHA-256), and each worker may get only its own Device's, then requires the +# contract's annotations and its approved pin. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site-credentials + annotations: + # Deleting the namespace deletes the enrolled credentials. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# To create a per-operation Role that gets a credential Secret here, kro +# itself must hold get on it. kro cannot list or watch them. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-credentials, namespace: fleet-site-credentials} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [secrets] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-credentials, namespace: fleet-site-credentials} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-credentials} diff --git a/config/site/redfish/base/kustomization.yaml b/config/site/redfish/base/kustomization.yaml index f9bf8fbd..e1697134 100644 --- a/config/site/redfish/base/kustomization.yaml +++ b/config/site/redfish/base/kustomization.yaml @@ -6,21 +6,10 @@ kind: Kustomization resources: - ../../base - bmc.yaml + - credentials.yaml patches: - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-jobs} patch: |- - # Guard: fail the build if the shared policy's volume rule moved. - - op: test - path: /spec/validations/5/message - value: a worker Job may mount only the site journal claim and emptyDir - - op: replace - path: /spec/validations/5 - value: - expression: >- - !has(variables.pod.volumes) || variables.pod.volumes.all(v, - (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir) || - (has(v.secret) && v.secret.secretName == 'fleet-site-bmc-credentials')) - message: a Redfish worker Job may mount only the site journal claim, emptyDir and the BMC credential # Redfish workers reach the lab hardware only through Redfish: no # libvirt socket mount and no libvirt URI, and the Redfish provider. - op: add @@ -38,3 +27,26 @@ patches: c.env.exists(e, e.name == 'FLEET_SITE_PROVIDER' && has(e.value) && e.value == 'redfish') && !c.env.exists(e, e.name == 'FLEET_LIBVIRT_URI')) message: a Redfish worker Job must select the Redfish provider and carry no libvirt URI + # kro may create, in fleet-site-credentials, only a per-operation Role + # that gets one named credential Secret, bound to that operation's own + # ServiceAccount. + - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-identity} + patch: |- + - op: test + path: /spec/validations/2/message + value: a worker Role may grant only get on its own handoff + - op: replace + path: /spec/matchConstraints/namespaceSelector/matchExpressions/0/values + value: [fleet-site, fleet-coordination, fleet-site-credentials] + - op: replace + path: /spec/validations/2 + value: + expression: >- + variables.kind != 'roles' || (request.namespace == 'fleet-site-credentials' ? + (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && + r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && size(r.resourceNames) == 1 && + r.resourceNames.all(n, n.matches('^bmc-[a-f0-9]{20}$')))) : + (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && + r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && + has(r.resourceNames) && r.resourceNames == [variables.handoff]))) + message: a worker Role may grant only get on its own handoff, or get on one named BMC credential diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index d171e202..b6d20b16 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -1,8 +1,10 @@ # Redfish-mode dispatcher graph: the shared graph with the worker template -# switched to the Redfish provider. Workers mount the journal, the boot -# evidence and the lab console capture (all read-only except the journal) and -# the synthetic BMC credential; they have no libvirt socket. The worker also -# waits for the Flux-owned lab BMC through an externalRef. +# switched to the Redfish workers. Workers mount the site store, the boot +# evidence and the lab console capture (all read-only except the store); they +# have no libvirt socket. Each worker may get exactly its Device's BMC +# credential Secret in fleet-site-credentials, and list or watch none; there +# is no shared credential. The worker also waits for the Flux-owned lab BMC +# through an externalRef. apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: @@ -19,15 +21,16 @@ patches: - {name: FLEET_SITE_PROVIDER, value: redfish} - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} - - {name: FLEET_REDFISH_CREDENTIALS, value: /etc/fleet-redfish} - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} - # Explicit site enrollment: each physical asset ID maps to exactly one - # BMC endpoint, Redfish System (Id and UUID), NIC and console capture. + - {name: FLEET_SITE_CREDENTIALS_NAMESPACE, value: fleet-site-credentials} + - {name: FLEET_SITE_PROJECT, value: provider} + # Explicit site enrollment: each Device maps to exactly one BMC + # endpoint, Redfish System (Id and UUID), NIC and console capture. # The lab's dnsmasq hands out static leases, so DHCP is "static" and # targets carry no provisioning attachment. Only target A is # published as capacity; target B is enrolled to prove isolation. - name: FLEET_REDFISH_ENROLLMENT - value: '{"dhcp":"static","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","endpoint":"http://10.96.0.81:8000","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","endpoint":"http://10.96.0.81:8000","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + value: '{"dhcp":"static","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' - {name: HOME, value: /tmp} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts @@ -35,16 +38,64 @@ patches: - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console, readOnly: true} - - {name: credentials, mountPath: /etc/fleet-redfish, readOnly: true} - {name: tmp, mountPath: /tmp} - - op: add - path: /spec/resources/9/template/spec/template/spec/volumes/- - value: - name: credentials - secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} - op: add path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1bmc value: ${bmc.metadata.name} + # Each worker may get exactly its Device's credential Secret. The graph + # derives the Secret's name from the Device the assignment itself names, + # as site.CredentialSecretName does, so no handoff field can name + # another Device's Secret. Only a handoff whose Device is its + # assignment's gets a Role; any other is refused by its worker with no + # grant at all. It may not list or watch Secrets. + - op: add + path: /spec/resources/- + value: + id: workerCredentialRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs.filter(h, h.spec.device == json.unmarshal(h.spec.assignmentJSON).device)} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-credentials + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: ["${'bmc-' + '%x'.format([hash.sha256(json.unmarshal(handoff.spec.assignmentJSON).device)]).substring(0, 20)}"] + verbs: [get] + - op: add + path: /spec/resources/- + value: + id: workerCredentialBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs.filter(h, h.spec.device == json.unmarshal(h.spec.assignmentJSON).device)} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-credentials + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/roles: ${string(size(workerCredentialRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1credentials + value: ${string(size(workerCredentialBindings))} - op: add path: /spec/resources/- value: diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml index 39407870..258caa56 100644 --- a/config/site/redfish/services/bmc.yaml +++ b/config/site/redfish/services/bmc.yaml @@ -2,8 +2,9 @@ # lab-only adapter (hack/redfish-lab), from a digest-pinned image. It is the # only Redfish endpoint and, besides the runtime, the only holder of the # libvirt socket. It owns the lab targets' definitions and provisioning -# network; Fleet workers reach it only over HTTP with the synthetic -# credential. Plain HTTP on the cluster network is a documented lab seam. +# network. It serves Redfish over TLS with a key the harness generates per +# run; Fleet workers reach it only over a connection pinned to that key, with +# each Device's own synthetic credential. apiVersion: v1 kind: Service metadata: @@ -14,7 +15,7 @@ spec: clusterIP: "${FLEET_BMC_SERVICE_IP}" selector: {app.kubernetes.io/name: fleet-site-bmc} ports: - - {name: redfish, port: 8000, targetPort: 8000, protocol: TCP} + - {name: redfish, port: 8443, targetPort: 8443, protocol: TCP} --- apiVersion: apps/v1 kind: Deployment @@ -42,9 +43,9 @@ spec: - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} - {name: HOME, value: /tmp} ports: - - {name: redfish, containerPort: 8000} + - {name: redfish, containerPort: 8443} readinessProbe: - httpGet: {path: /redfish/v1/, port: 8000} + httpGet: {path: /redfish/v1/, port: 8443, scheme: HTTPS} periodSeconds: 5 securityContext: runAsUser: 0 @@ -58,11 +59,14 @@ spec: - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} - {name: state, mountPath: /var/lib/fleet-bmc, subPath: bmc-state} - {name: credentials, mountPath: /etc/fleet-bmc-credentials, readOnly: true} + - {name: tls, mountPath: /etc/fleet-bmc-tls, readOnly: true} - {name: tmp, mountPath: /tmp} volumes: - name: state persistentVolumeClaim: {claimName: fleet-site-state} - name: credentials secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} + - name: tls + secret: {secretName: fleet-site-bmc-tls, defaultMode: 0400} - name: tmp emptyDir: {} diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml index 2ec7f2cf..d1290c1a 100644 --- a/config/site/services/services.yaml +++ b/config/site/services/services.yaml @@ -78,7 +78,7 @@ spec: - name: state persistentVolumeClaim: {claimName: fleet-site-state} --- -# Boot service: journal read-only; writes only its own delivery evidence. +# Boot service: site store read-only; writes only its own delivery evidence. apiVersion: apps/v1 kind: Deployment metadata: @@ -123,7 +123,8 @@ spec: - name: state persistentVolumeClaim: {claimName: fleet-site-state} --- -# Observer: the only handoff status writer, from the journal only. +# Observer: the only handoff status writer. It reports the site store's fences +# and results, and deletes a result once the coordinator answered it. apiVersion: apps/v1 kind: Deployment metadata: @@ -143,7 +144,7 @@ spec: - name: observer image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --scoped-asset, "${FLEET_SCOPED_ASSET}", --interval, 10s] + command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --interval, 10s] env: - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} securityContext: @@ -155,7 +156,7 @@ spec: requests: {cpu: 20m, memory: 32Mi} limits: {memory: 128Mi} volumeMounts: - - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} volumes: - name: state persistentVolumeClaim: {claimName: fleet-site-state} diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 269582b1..d4f0d938 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -18,6 +18,17 @@ spec: cpu: {architecture: amd64, cores: 24} memory: {capacity: 128Gi} --- +# The synthetic Device behind the capacity. The simulator site serves it, and +# its fixture discovery writes the Device's status. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: {name: synthetic-device-central-01, namespace: fleet-provider} +spec: + claimRef: {name: synthetic-claim-central-01} + identity: {model: synthetic, serial: synthetic-serial-central-01, systemUUID: 00000000-0000-4000-8000-000000000021} + bmc: {endpoint: "https://[2001:db8::21]"} + interfaces: [{name: primary, macAddress: "02:00:00:00:00:21"}] +--- apiVersion: metal.datumapis.com/v1alpha1 kind: MachineCapacity metadata: diff --git a/config/standalone/kustomization.yaml b/config/standalone/kustomization.yaml index c6fdb9c6..267e7b74 100644 --- a/config/standalone/kustomization.yaml +++ b/config/standalone/kustomization.yaml @@ -4,11 +4,14 @@ commonAnnotations: fleet.datumapis.com/standalone-only: "true" resources: - ../base/crd + - ../components/inventory/crds + - ../components/device-operations/crds - ../base/simulator - namespaces.yaml - runtime-secret.yaml - rbac.yaml - fixtures.yaml + - site.yaml - smoke-cronjobs.yaml images: - name: ghcr.io/datum-cloud/fleet-simulator diff --git a/config/standalone/namespaces.yaml b/config/standalone/namespaces.yaml index f185e578..310c0240 100644 --- a/config/standalone/namespaces.yaml +++ b/config/standalone/namespaces.yaml @@ -7,13 +7,6 @@ metadata: --- apiVersion: v1 kind: Namespace -metadata: - name: fleet-system-private - annotations: - fleet.datumapis.com/shared-with-standalone: "true" ---- -apiVersion: v1 -kind: Namespace metadata: name: fleet-provider --- diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index 7ad110cf..3c5e477b 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -30,14 +30,28 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-synthetic-provider-writer, namespace: fleet-provider} rules: + # The Metal provider selects capacity, records allocations and creates + # installations. It reads custody and Devices only to skip taken capacity; + # custody decides. - apiGroups: [metal.datumapis.com] resources: [machinecapacities] - resourceNames: [central1-baremetal-01] - verbs: [get] + verbs: [get, list] - apiGroups: [metal.datumapis.com] resources: [machinecapacities/status] resourceNames: [central1-baremetal-01] verbs: [get, update] + - apiGroups: [metal.datumapis.com] + resources: [machineallocations] + verbs: [get, list, create, delete] + - apiGroups: [metal.datumapis.com] + resources: [machineallocations/status] + verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations] + verbs: [get, list, create] + - apiGroups: [fleet.datumapis.com] + resources: [devices, devicecustodies] + verbs: [get] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -94,17 +108,110 @@ roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-synthetic subjects: - {kind: ServiceAccount, name: fleet-standalone-smoke, namespace: fleet-system} --- +# The custody coordinator writes custody and operation status, and reads the +# Devices, allocations and operations custody depends on. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-custody-coordinator, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-custody-coordinator-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-custody-coordinator} +type: kubernetes.io/service-account-token +--- apiVersion: rbac.authorization.k8s.io/v1 kind: Role -metadata: {name: fleet-private-record-writer, namespace: fleet-system-private} +metadata: {name: fleet-custody-coordinator, namespace: fleet-provider} rules: - - apiGroups: [""] - resources: [secrets] - verbs: [get, list, watch, create, update] + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get, list, watch] + - apiGroups: [fleet.datumapis.com] + resources: [devicecustodies] + verbs: [get, list, watch, create, update, delete] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations, devicewipes, devicerecoveries] + verbs: [get, list, watch, delete] + - apiGroups: [fleet.datumapis.com] + resources: [deviceinstallations/status, devicewipes/status, devicerecoveries/status] + verbs: [get, update] + - apiGroups: [metal.datumapis.com] + resources: [machineallocations] + verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding -metadata: {name: fleet-private-record-writer, namespace: fleet-system-private} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-private-record-writer} +metadata: {name: fleet-custody-coordinator, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-custody-coordinator} subjects: - - {kind: ServiceAccount, name: fleet-standalone-smoke, namespace: fleet-system} + - {kind: ServiceAccount, name: fleet-custody-coordinator, namespace: fleet-system} +--- +# A BMC key must be unique among every Device that is not retired, so the +# coordinator reads Devices in every namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-custody-coordinator-devices} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-custody-coordinator-devices} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-custody-coordinator-devices} +subjects: + - {kind: ServiceAccount, name: fleet-custody-coordinator, namespace: fleet-system} +--- +# The release controller creates the wipes of a release. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-release-controller, namespace: fleet-system} +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-release-controller-token + namespace: fleet-system + annotations: {kubernetes.io/service-account.name: fleet-release-controller} +type: kubernetes.io/service-account-token +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-release-controller, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devicewipes] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-release-controller, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-release-controller} +subjects: + - {kind: ServiceAccount, name: fleet-release-controller, namespace: fleet-system} +--- +# The simulator site's fixture discovery writes only the status of the +# Device it serves. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-simulator-discovery, namespace: fleet-provider} +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + resourceNames: [synthetic-device-central-01] + verbs: [get] + - apiGroups: [fleet.datumapis.com] + resources: [devices/status] + resourceNames: [synthetic-device-central-01] + verbs: [get, update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-simulator-discovery, namespace: fleet-provider} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-simulator-discovery} +subjects: + - {kind: ServiceAccount, name: fleet-simulator, namespace: fleet-system} diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml new file mode 100644 index 00000000..06b90e09 --- /dev/null +++ b/config/standalone/site.yaml @@ -0,0 +1,66 @@ +# The simulator site's enrollment: the one synthetic Device it serves, with +# the identity its fixture Device records and the key digest its fixture +# discovery reports. Synthetic data only. +apiVersion: v1 +kind: ConfigMap +metadata: {name: fleet-simulator-enrollment, namespace: fleet-system} +data: + enrollment.json: | + {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"]}} +--- +# The custody coordinator: the only writer of custody and of operation +# status. It delivers admitted operations to the simulator site and reports +# their results. +apiVersion: apps/v1 +kind: Deployment +metadata: {name: fleet-custody-coordinator, namespace: fleet-system} +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-custody-coordinator} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-custody-coordinator} + spec: + serviceAccountName: fleet-custody-coordinator + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: coordinator + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=coordinate, --site-token-file=/var/run/fleet/token] + 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}}] +--- +# The creator rule. Milo projects ignore admission policies, so Milo uses the +# creator webhook; a plain cluster enforces the same rule with this policy: +# an operation's creator is the caller who created it and never changes. A +# caller is its username, plus its UID when its credential carries one. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-operation-creator} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ["*"] + operations: [CREATE, UPDATE] + resources: [deviceinstallations, devicewipes, devicerecoveries] + validations: + - expression: "request.operation != 'CREATE' || (object.spec.creator.username == request.userInfo.username && (has(object.spec.creator.uid) ? object.spec.creator.uid : '') == (has(request.userInfo.uid) ? request.userInfo.uid : ''))" + message: spec.creator must be the authenticated caller's username, and UID when it has one + - expression: "request.operation != 'UPDATE' || object.spec.creator == oldObject.spec.creator" + message: spec.creator cannot change +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-operation-creator} +spec: + policyName: fleet-operation-creator + validationActions: [Deny] diff --git a/config/standalone/smoke-cronjobs.yaml b/config/standalone/smoke-cronjobs.yaml index fd7e8749..529d5ab2 100644 --- a/config/standalone/smoke-cronjobs.yaml +++ b/config/standalone/smoke-cronjobs.yaml @@ -16,10 +16,14 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=allocate, --runtime-token-file=/var/run/fleet/token] + args: [--phase=allocate, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- apiVersion: batch/v1 kind: CronJob @@ -39,10 +43,14 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=install, --runtime-token-file=/var/run/fleet/token] + args: [--phase=install, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- apiVersion: batch/v1 kind: CronJob @@ -62,10 +70,14 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=reinstall, --runtime-token-file=/var/run/fleet/token] + args: [--phase=reinstall, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} --- apiVersion: batch/v1 kind: CronJob @@ -85,7 +97,11 @@ spec: - name: smoke image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev imagePullPolicy: Never - args: [--phase=release, --runtime-token-file=/var/run/fleet/token] + args: [--phase=release, --coordinator-token-file=/var/run/fleet/coordinator/token, --release-token-file=/var/run/fleet/release/token] securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} - volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] - volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] + volumeMounts: + - {name: coordinator-token, mountPath: /var/run/fleet/coordinator, readOnly: true} + - {name: release-token, mountPath: /var/run/fleet/release, readOnly: true} + volumes: + - {name: coordinator-token, secret: {secretName: fleet-custody-coordinator-token, defaultMode: 0440, items: [{key: token, path: token}]}} + - {name: release-token, secret: {secretName: fleet-release-controller-token, defaultMode: 0440, items: [{key: token, path: token}]}} diff --git a/docs/architecture/README.md b/docs/architecture/README.md index ab88c8b8..6a0a339f 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -152,8 +152,7 @@ under new identities or delete old authority records to bypass cleanup. Environment-owned overlays must update service references and publication rules before enabling the renamed service. No live environment is changed by this PR. -Repository, Go module, binaries, private record labels and Secret types, and -release finalizers retain Fleet names. They are implementation identities. +Repository, Go module, binaries, and release finalizers retain Fleet names. They are implementation identities. The [design context](design.md) and [source proposals](../proposals/fleet-management/README.md) provide the lifecycle rationale; this document supersedes their provisional API naming where broader resource placement remains unresolved. diff --git a/docs/development/README.md b/docs/development/README.md index f459ea45..faf64def 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -6,19 +6,21 @@ This development guide records the implemented subset and its limitations. See [build, test, and run](#build-test-and-run) for local commands and the [implementation roadmap](roadmap.md) for proposed milestones and required evidence. -Status: public API foundation, standalone synthetic provider simulator, -same-cluster allocation/installation lifecycle library, unwired NSO network -lifecycle adapter, unwired Milo tenancy/quota authority contracts, and an -event-only manager wiring scaffold with an injected Machine lifecycle -handler implemented. The public allocation API now uses customer `Machine`, -provider `MachineCapacity`, protected immutable `MachineAllocation`, and -`Installation.machineRef`; authored references contain names while exact -incarnation evidence remains private. A packaged standalone synthetic smoke -scenario exercises local-scope contention, install recovery, cleanup, and -capacity reuse. An explicit Milo-routed synthetic staging overlay exercises -event-driven Machine allocation, contention, cleanup, and reuse through the -public project API. Production caller-preserving allocation -admission, replayable Milo event adapters, and production provider integration are not implemented. +Status: public API foundation, the persistent simulator site, an +allocation and release library on Device custody, an unwired NSO network +lifecycle adapter, a Milo quota claim, and an event-only manager wiring scaffold +with an injected Machine lifecycle handler. The public allocation API uses +customer `Machine`, provider `MachineCapacity`, protected immutable +`MachineAllocation`, and `Installation.machineRef`. Authored references contain +names. A MachineAllocation names its consumer, a Milo Project or a standalone +Namespace, with a typed `consumerRef`, and its name and labels record the exact +incarnations. A packaged +standalone synthetic smoke scenario exercises local-scope contention, install +recovery, release with a wipe, and capacity reuse on Device custody. An explicit +Milo-routed synthetic staging overlay exercises event-driven Machine allocation, +contention, release, and reuse through the public project API. Production +caller-preserving allocation admission, replayable Milo event adapters, and +production provider integration are not implemented. Inert [inventory-backed capacity registration](inventory-capacity-registration.md) now has a stateless caller-preserving admission service that checks live Devices, one capacity per Device through a Device-derived name, a Device @@ -28,38 +30,34 @@ a deleting namespace, and a session-fenced default-namespace Device picker. It a unconfigured, and governs only capacity that carries the registration marker; synthetic, hand-made and legacy capacity and all capacity status writes are not routed to it. Deployment trust inputs and live Milo acceptance remain required. -An opt-in [local KVM installation harness](../operations/local-vm.md) implements -a bounded libvirt executor and guest installer using the same lifecycle library. -It uses a disposable Kubernetes API and explicit local authority fixtures; it is -not wired into the production manager. + +[Device custody and operations](device-custody.md) is **implemented** through +Increment C, the cutover. Every mode allocates, installs and releases on +`DeviceCustody`, with the custody coordinator as its only writer. The +Secret-backed coordinator, its private records and the old executors are deleted, +and an allocation's private facts live on its MachineAllocation. The standalone +smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. + The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes -that executor with native Milo project APIs and actual Karmada delivery. On the -selected cell it runs as [Flux-owned site Deployments and kro-created per-operation worker Jobs](../operations/site-execution.md). +the [local VM site](../operations/local-vm.md) with native Milo project APIs, the +custody coordinator, and actual Karmada delivery. On the selected cell the site +runs as [Flux-owned Deployments and kro-created per-assignment worker Jobs](../operations/site-execution.md). Each local cluster's [Flux](../operations/gitops.md) installs Milo, Karmada, kro and the shared site services from an OCI artifact staged from the checkout. Run it with `task multiplane:acceptance`. Its exit codes, bounded phases and sanitized `evidence/` directory are documented there; `task multiplane:test-harness` runs its -offline tests, which CI also runs. -`internal/redfish` implements a Redfish executor behind the same contracts: discovery, -one-time boot overrides, power, observation-based recovery and a booted wipe -cleanup. [Redfish-mode acceptance](../operations/redfish-lab.md) -(`task multiplane:redfish-acceptance`) exercises it against the unmodified DMTF Redfish -Interface Emulator and a lab-only libvirt adapter. It is not qualified against a -physical BMC or server, and the production manager does not use it. +offline tests, which CI also runs. Verification of that run on custody is +pending. The Redfish site workers (`internal/site/redfishwork`) read each +Device's own credential and connect only to its approved TLS key. +[Redfish-mode acceptance](../operations/redfish-lab.md) +(`task multiplane:redfish-acceptance`) exercises them against the unmodified DMTF +Redfish Interface Emulator and a lab-only libvirt adapter, and its verification is +pending too. They are not qualified against a physical BMC or server, and the +production manager does not use them. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. -[Device custody and operations](device-custody.md) Increment A is implemented -and inert: the `DeviceCustody` and Device operation kinds, the creator webhook, -the kind registry and admission rule table, and the coordinator that admits, -fences, holds, recovers and rebuilds custody. Tests against a real API server -verify it. No deployment root, manager or staging overlay includes it, and the -Secret-backed lifecycle is unchanged. Increment B, the site framework with -per-Device fencing, journal, credentials and pinned TLS and the Redfish -install and wipe workers, is implemented and inert until the cutover. The -cutover and the end-to-end failure scenarios are proposed. - ## API group naming The additive [shared hardware catalog](hardware-catalog.md) implements @@ -84,22 +82,18 @@ The implemented alpha surface follows the current machine-allocation proposal: `machineClassRef`, `machineProfileRef`, and `locationRef` names; - provider projects publish `MachineCapacity` objects whose immutable `deviceRef` names the separately owned physical inventory record; -- Fleet owns `MachineAllocation` records in the provider project. Their generated - names are allocation identities, their specs are immutable, and `Released` is - terminal; and +- Fleet owns `MachineAllocation` records in the provider project. Each is named + `alloc-` and 16 hex characters of the SHA-256 of the consumer UID and + the Machine UID, its spec is immutable, and `Released` is terminal; and - `Installation` names its Machine and, for reinstalls, the preceding - Installation. Fleet retains exact local object incarnations privately instead - of exposing Kubernetes UIDs in authored specs or status. + Installation. A MachineAllocation records the exact Machine, project and Device + incarnations, so authored specs and status expose no Kubernetes UIDs. CRDs, Go types, scheme registration, IAM ProtectedResources and roles, manager watches and routes, quota labels, standalone fixtures, and smoke assertions use -those names. The lifecycle library's existing service-owned Secret is still the -implemented storage encoding for the protected allocation record; introducing -the `MachineAllocation` kind does not make that record customer-writable. The -simulator continues to carry a private binding token and monotonic executor epoch -to fence its legacy single-file backend. Those values are absent from the public -and proposed resource contracts and must be replaced by immutable allocation -name plus executor fencing token before a production backend is connected. +those names. The MachineAllocation is the stored record, and no customer role can +write it. Fences are Device custody's, not an epoch or token in a record; see +[Device custody](device-custody.md#cutover-increment-c). ## Requested hardware @@ -109,14 +103,10 @@ removed as a breaking `v1alpha1` change with no conversion or migration. Stored profiles with the old shape must be recreated before upgrading. The allocator matches capacity only when the observed cores and memory equal the request. -Private asset records, custody proposals, and Milo authority records retain -`acceptedRequirements` as the exact `MachineProfileSpec`. A private record whose -requirements use any other shape fails to decode, like a version 1 -installation record or any other malformed record. Fleet keeps no decoder or -release path for older record shapes. How the coordinator contains such a -record, and how an operator removes it, is described in -[Undecodable private records](#undecodable-private-records). See the -[MachineProfile notes](../enhancements/machine-lifecycle/README.md#machineprofile). +A MachineAllocation records the accepted class and profile references, with the +exact CPU and memory it allocated against. Fleet keeps no decoder or release +path for older record shapes, because the Secret-backed records are deleted. See +the [MachineProfile notes](../enhancements/machine-lifecycle/README.md#machineprofile). `requestedhardware.Project` is the one projection that writes `status.requestedHardware` and `RequestResolved`, and @@ -142,86 +132,6 @@ provenance, missing and invalid profiles, post-acceptance profile changes, inert-mode wiring, and staging and standalone carry-forward. See [requested hardware](../enhancements/machine-lifecycle/README.md#requested-hardware). -## Undecodable private records - -A private lifecycle record that does not decode into the current shape returns -`controller.ErrRecordUnreadable`, which wraps `ErrRecordInvalid`. This covers -asset, claim custody, installation, and Milo authority records. The record -blocks only the claim it belongs to (implemented): - -- **Attribution.** The coordinator does not trust the body of a record it cannot - decode. It attributes the record by the `fleet.datumapis.com/claim-uid` - label, which `encodeRecord` and the Milo record store write on every record. -- **Scans across claims.** The asset scan behind allocation, installation, - network refresh, and release, and the installation scan by binding, skip a - record labeled for another claim. A record labeled for the scanning claim - fails that claim closed. A record with no claim label might belong to any - claim, so it fails every claim-scoped scan closed. Fleet never writes an - unlabeled record, so this case means the Secret was edited by hand. One such - Secret halts allocation, installation, and release for every claim on the - coordinator until an operator removes it. -- **Release from a selection.** A claim released while its custody only - proposes an asset reads that asset's record by name. If the record is - labeled for another claim, that claim holds the asset and the releasing - claim never did, so its custody is released without touching the record. - The record keeps fencing the asset's epoch. A record labeled for the - releasing claim, or with no label, fails release closed. -- **Capacity and epoch fencing.** Allocation reads each candidate asset's - record by name. If that record, or the custody record of the claim that last - held the asset, cannot be decoded, the asset is never proposed and allocation - tries the next candidate. Nothing proves that asset was released or what - epoch it reached, so treating it as free could double-bind it or restart its - epoch below a stale operation. A retained `Released` record that cannot be - decoded therefore keeps its asset out of allocation. It does not admit any - operation for its former claim either, because that claim's own scans fail - closed on it. -- **The claim's own work.** Allocation, installation, and release for the - attributed claim return `ErrRecordUnreadable`. They do not treat the claim as - having no record, and they never rewrite the record. Synthetic staging - reports the Machine as `Phase=Pending` with `Bound=False` and `Ready=False`, - reason `UnreadablePrivateRecord`, and does not requeue it. The managed - Machine handler also stops requeueing, and sets no condition: it writes no - Machine status at all, so synthetic staging is the only writer of Machine - lifecycle conditions. Release never removes the finalizer through such a - record. -- **Signals.** Every lifecycle decode goes through one reporting decoder, so - each record is logged once per lifecycle call at error level, whichever read - found it. - The log names the Secret and the attributed claim UID, never record - contents. The counter `fleet_private_lifecycle_record_undecodable_total` - counts the same events, labeled only by `record_type` (`asset`, `custody`, - `installation`, or `milo-authority`). - -Fleet has no automated release for an undecodable record. To clear an affected -Machine, an operator does the following: - -1. Find the Machine's UID. List the Secrets in `fleet-system-private` that - carry `fleet.datumapis.com/claim-uid=`. The error log names the - undecodable one. -2. If the Machine held an asset, set that MachineCapacity's - `allocationPolicy` to `Disabled`. Removing the records discards the binding, - its epoch, and any pending cleanup, so the physical machine's state is - unknown. Re-enable allocation only after the machine has been verified clean. - The next binding starts again at epoch 1, and an executor that retained a - higher epoch refuses it until its own fence is reset. -3. Delete the Machine. Release stops at the undecodable record and leaves the - finalizer in place. -4. Remove the `fleet.datumapis.com/machine-protection` finalizer from the - Machine by hand. Fleet cannot release through the record, so it never - removes the finalizer itself. -5. Delete every listed private record Secret for that claim UID, not only the - undecodable one. The claim no longer exists, and a record left behind keeps - describing authority that nothing will ever release. - -A retained `Released` asset record whose Machine is already gone affects only -that asset. Delete that Secret after step 2 to return the asset to allocation. - -Event routing reads only records that decode, so editing or deleting an -undecodable Secret wakes no claim. This is why the procedure deletes the -Machine and removes its finalizer before deleting the records. A claim blocked -by an unlabeled record is reconciled again on its next own event, or when the -manager restarts. - ## Multi-project discovery `cmd/fleet-manager` runs one set of controllers over every project that @@ -248,14 +158,10 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no `SameProject` against its identity, run its verifier, and delegate to the existing `ProjectReconciler` and `RouteReconciler`. A request for a project that is not engaged is dropped with no effect. -- **Private records.** All projects share the host namespace - `fleet-system-private`. Custody, operation, and authority record names hash - `(authorityID, projectUID, claimUID)`; asset records are keyed by provider - asset and are deliberately global, which is what makes allocation exclusive - across consumers. The private-record watch routes a record by its recorded - consumer project to the runtime engaged for exactly that lifetime. The - unscoped `Coordinator.Release(claimUID)` requires exactly one match, so equal - claim UIDs in two projects fail closed instead of colliding. +- **Allocations.** A MachineAllocation lives in the provider project and is named + from the consumer project UID and the Machine UID, so equal Machine UIDs in two + consumer projects never share one. Exclusivity belongs to Device custody, which + is global to the Device and so spans consumers. - **Handlers.** `manager.DefaultHandlers` gives each project blocked lifecycle handlers and the requested-hardware projector. `--synthetic-staging` uses `staging.ConsumerHandlers`, which installs the staging handler only for @@ -264,7 +170,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no into that project. Provider MachineCapacity events wake only that project. - **Provider as consumer.** The synthetic provider project may also be an Active metal consumer. It engages with `DefaultHandlers`; its runtime maps - only its own Machines and private records whose consumer is that project, so + only its own Machines, so provider MachineCapacity events cannot reach the synthetic consumer's claims through it, and its blocked handlers never write MachineCapacity status. The synthetic consumer itself must still differ from the provider. @@ -281,7 +187,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no consumer set. It does not release custody, call a provider, delete records, or rewrite status, including for a project with active custody. Its deadlines and queued events are dropped, and re-engagement resumes from the - retained private records. Unbinding drains direct and dependency-route + retained allocations. Unbinding drains direct and dependency-route reconciliations that already acquired the runtime before removing it from the registry; a retained runtime pointer cannot start work after that barrier. A blocked in-flight handler therefore delays completed departure rather than @@ -302,7 +208,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no A handler that never returns still prevents safe replacement; cancellation is not evidence that its effects have stopped. Deterministic direct/routed replacement, cancellation, stale-pointer, registry-revalidation and concurrent engagement - tests cover these process-local barriers, not distributed executor fencing. + tests cover these process-local barriers, not distributed site fencing. A per-cluster-route engagement gate also serializes publication through the entire downstream controller setup call and failure cleanup. Draining alone was insufficient: a paused predecessor's setup could otherwise resume after @@ -345,8 +251,7 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no always-running group. Unlike Compute, this is done for every `ProviderRunnable`, so the consumer provider is not started twice. - **Readiness.** `/readyz` requires discovery to have synced, every consuming - project to be engaged, every engaged project cache to have synced, and the - private-record cache to have synced. It fails with `ErrDiscoveryMisconfigured` + project to be engaged, and every engaged project cache to have synced. It fails with `ErrDiscoveryMisconfigured` while the metal Service is missing or its producer project differs from `consumerScopedProjection.providerProject`. The former integration gate, which failed unless synthetic staging was on, is removed. Removing it enables no @@ -365,21 +270,21 @@ API servers (`internal/multiclustertest`) whose writes produce watch events. They cover: - no provider: two projects with identical Machine names and UIDs each pin from - their own profile, with no private record, finalizer, lifecycle condition, + their own profile, with no allocation, finalizer, lifecycle condition, or Installation change; -- custody isolation: a custody record wakes only its own project, and scoped - reads and an unscoped release cannot cross projects; +- project isolation: an event wakes only its own project, and scoped reads cannot + cross projects; - departure with active custody, re-engagement, restart with a replaced profile, and identity failures (unknown project, two clusters for one lifetime, project recreated while engaged); - synthetic staging end to end: allocation only in the publication consumer, with another engaged project untouched. -Coordinator tests already cover custody, allocation, and installation scoping -across project APIs with equal claim UIDs. An envtest test runs the real -consumer provider against separate API servers that serve every watched kind, -behind a Milo-shaped project router, with a real host lease and private cache. -It needs envtest binaries and is skipped without them. +Allocation tests cover custody and installation scoping with equal Machine UIDs +in separate project lifetimes. An envtest test runs the real consumer provider +against separate API servers that serve every watched kind, behind a Milo-shaped +project router, with a real host lease. It needs envtest binaries and is skipped +without them. ## Location authority @@ -414,33 +319,31 @@ ServiceAvailability can project a Location into entitled projects. ## Standalone synthetic smoke environment `cmd/fleet-standalone-smoke` is a test-only, phase-oriented harness around the -implemented lifecycle coordinator. The packaged fixture uses two Kubernetes +allocation library on Device custody. The packaged fixture uses two Kubernetes namespaces as project stand-ins and one synthetic `us-central-1` machine with 24 -cores and 128Gi of memory. The allocate phase retains custody before adding the -Fleet finalizer, binds one claim, and leaves the competing claim pending. The -install phase admits one exact digest-pinned operation through the persistent +cores and 128Gi of memory. A coordinator Deployment runs the custody loop, and +the simulator is the only site. The allocate phase waits for the Device's custody +to be `Verified`, allocates for one claim, and leaves the competing claim pending. +The install phase admits one exact digest-pinned `DeviceInstallation` through the simulator and is idempotent across worker and simulator restart. A bounded reinstall phase uses a distinct Installation naming the initial Installation as its predecessor, retains the same allocation, and recovers the same successor -operation across retries and restart. Unknown completion closes readiness and -keeps the capacity occupied. The release -phase verifies cleanup before finalizer removal and advances the retained asset -epoch before the waiting claim binds. - -The harness is the designated writer for one retained synthetic Machine evidence -record and public fixture status. The evidence pins the Machine UID, configured -location, hardware, and observation time; it is not refreshed across phases. -Both contenders pass capacity preflight against the same retained -`Available=True` evidence before private custody selects the sole winner. The -lifecycle coordinator remains the writer of custody, asset, -and operation records. It does not patch status from shell, delete private -records, strip finalizers, or use public status as authority. The simulator runs -under an explicit non-root UID/GID with a writable `fsGroup` PVC and group-readable -runtime-only bearer Secret; its admin listener is off. Docker bases are digest -pinned, and the smoke script derives a source-specific local image tag and -verifies the running workloads use it with pulls disabled. That identity commits -to HEAD, its tree, the tracked diff, and untracked file contents; a CI regression -test proves distinct clean commits produce distinct IDs. +operation across retries and restart. An unknown result keeps readiness unknown +and the Device held. The release phase wipes the Device with a `DeviceWipe`, under +a fence above both installations, before the waiting claim is allocated. + +The phases run as the Metal provider, with the custody coordinator's and the +release controller's tokens in their own clients, so each write carries its +component's identity. The harness is the designated writer for the synthetic +capacity conditions and the public fixture status, because the capacity projector +is not wired. It does not patch custody or operation status, strip finalizers, or +use public status as authority. The simulator runs under an explicit non-root +UID/GID with a writable `fsGroup` PVC and group-readable runtime-only bearer +Secret; its admin listener is off. Docker bases are digest pinned, and the smoke +script derives a source-specific local image tag and verifies the running +workloads use it with pulls disabled. That identity commits to HEAD, its tree, +the tracked diff, and untracked file contents; a CI regression test proves +distinct clean commits produce distinct IDs. This is not the proposal acceptance environment. Namespace stand-ins do not model Milo project APIs, caller identity, IAM, entitlement, quota, purge, or @@ -476,23 +379,12 @@ freshness deadline scheduler. Queue keys include the Milo authority ID, root Project UID, namespace, name, and object UID. Equal names or UIDs in separate project lifetimes cannot share work. -The manager uses two controller-runtime caches with explicitly non-nil zero -`SyncPeriod` values. Its primary cache is scoped by Milo's project control-plane -URL and contains public Fleet, NSO, quota, entitlement, and Namespace resources. -A separate management-cluster cache is confined to `fleet-system-private` and -contains service-owned Secrets. Public and private reverse indexes are -registered on their owning caches, and Secret event sources explicitly use the -host cache. Leader election also uses the management-cluster configuration. -Dependency mappers use exact field indexes; private indexes consume only typed metadata exposed after the lifecycle -or Milo record owner validates the complete record and deterministic Secret -identity. Unknown or nested JSON lookalike fields have no routing meaning. The -manager's private-record predicate treats the Secret type and complete label set -as part of that trusted envelope, so a valid record that is relabelled or has -its type substituted is immediately reconciled into quarantine rather than -being hidden as a data-no-op update. The -mappers do not perform unqualified application Lists. Informer initial Add -events route retained private records after restart, including when the consumer -object is gone. Public status-only updates, including status written by an +The manager uses a controller-runtime cache with an explicitly non-nil zero +`SyncPeriod`. It is scoped by Milo's project control-plane URL and contains +public Fleet, NSO, quota, entitlement, and Namespace resources. Reverse indexes +are registered on that cache. Leader election uses the management-cluster +configuration. Dependency mappers use exact field indexes and do not perform +unqualified application Lists. Public status-only updates, including status written by an external actor, do not feed the lifecycle coordinator; external facts that must drive lifecycle work require an owned dependency resource and route. Claim and Installation spec generations, labels, annotations, finalizers, and @@ -505,30 +397,17 @@ a cache read or List failure is retried as the same source event instead of bein mistaken for an empty target set. Every direct and routed handler also verifies the configured Project lifetime through an injected trusted verifier. -`MachineHandler` implements the lifecycle ordering at the manager boundary. It -exact-reads the queued Machine and namespace lifetimes, resolves only injected -authoritative inputs, retains authority and custody before adding Fleet's -finalizer, waits for the finalizer update event before allocation, and removes -the finalizer only after verified cleanup and external settlement. Dependency -waits return without a timed requeue. Trusted evidence expiry can request one -exact coordinator-owned deadline; it is not a polling interval. Deletion and -same-name recreation use exact Machine incarnation evidence retained privately. - -`MiloMachineLifecycle` is the concrete bridge to the existing Milo adapter and -allocator. `PrepareOrRecoverClaim` validates current resolved inputs against the -immutable private authority record, so the finalizer event and manager restart -reuse the retained caller receipt rather than reauthorizing a different caller. -Release recovers from the exact consumer Project and Machine lifetimes and does -not require the public Machine, class, or profile to remain present. - -This handler is an orchestration seam, not a live integration. Watched objects -do not contain the create-time caller identity, protected publication -provenance, or trusted Machine observation time and location required by the -lifecycle contract. The manager binary therefore does not instantiate the -handler; lifecycle handlers stay blocked. An environment must provide those -inputs plus the Milo admission fence and quota custodian before enabling effects; -controller credentials, annotations, public status, and synthetic timestamps -are not accepted substitutes. +The manager has no production lifecycle handler. Allocation, installation and +release are the `internal/allocation` library on Device custody, which the +synthetic staging handler, the standalone smoke and the multi-plane runner call. +The Machine handler and Milo lifecycle bridge of the Secret-backed design are +deleted. A production handler needs the inputs the manager cannot get from +watched objects: the create-time caller identity, protected publication +provenance, and a trusted Machine observation time and location. The manager +binary therefore instantiates no handler, and lifecycle handlers stay blocked. An +environment must provide those inputs plus the Milo admission fence and quota +custodian before enabling effects; controller credentials, annotations, public +status, and synthetic timestamps are not accepted substitutes. Every dependency route now retains the source object's UID and exact routing snapshot. Non-delete work checks that UID against the current named object; if a @@ -553,10 +432,10 @@ drains timers, waits for any in-flight emission, and prevents post-stop work. Informer initial Add processing reconstructs still-relevant deadlines after a fresh process starts. -The setup watches the implemented Fleet resources, private records, NSO Network, +The setup watches the implemented Fleet resources, NSO Network, NetworkInterfaceClaim and NetworkInterface resources, Milo quota claims, and the reviewed ServiceEntitlement shape. External IAM, project-lifecycle, catalog, and -executor sources must provide durable cursor/replay or materialize watched state; +site sources must provide durable cursor/replay or materialize watched state; a lossy channel is not sufficient. Business pending states wait for their next dependency event and do not return a timed requeue. @@ -572,8 +451,8 @@ remain integration-owner responsibilities. `cmd/fleet-manager` discovers every consuming project, resolves each project's exact lifetime from Milo, derives each routed Milo REST host from an -environment-owned project kubeconfig template, keeps host-private records and -leader election on the management cluster, and starts the event graph. Its +environment-owned project kubeconfig template, keeps leader election on the +management cluster, and starts the event graph. Its readiness reports discovery and cache health only. Its production handlers deliberately perform no lifecycle or provider effects until trusted create-time caller/finalizer admission and live, replayable Milo adapters are supplied. A @@ -583,36 +462,35 @@ with annotations or controller credentials. The opt-in `--synthetic-staging` mode is a temporary acceptance boundary. It accepts only powered-off, networkless claims in `us-central-1`, synthesizes -clearly labelled admission and provider evidence, and invokes the same durable -coordinator used by the standalone and future production adapters. It is -event-driven: claim, class, profile, Machine, namespace, private-record, and -deletion events route exact work; it adds no periodic re-sync. One synthetic -Machine is exclusively bound, competing claims remain pending, cleanup must -complete before finalizer removal, and release wakes waiting claims for reuse. +clearly labelled admission and provider evidence, and uses the same allocation +library on Device custody as the standalone smoke. The manager also runs the +custody coordinator loop and fixture discovery under its leader lease. It is +event-driven: claim, class, profile, Machine, namespace, and deletion events +route exact work; it adds no periodic re-sync. One synthetic Machine is +exclusively bound, competing claims remain pending, release must complete before +finalizer removal, and release wakes waiting claims for reuse. Public conditions say `SyntheticStagingAdmission`, so this result cannot be mistaken for Milo caller-preserving authorization. `config/overlays/synthetic-staging` is the only packaged activation path. It -packages the simulator as a separate single-replica Deployment and ClusterIP -Service using the same immutable Fleet release image. The manager reaches it -through Service DNS with an environment-owned shared runtime Secret; the provider +packages the simulator site as a separate single-replica Deployment and +ClusterIP Service using the same immutable Fleet release image. The manager +reaches it through Service DNS with an environment-owned site token; the provider has no Kubernetes API credential or RBAC grants. A NetworkPolicy restricts access to same-namespace manager pods, and the admin listener stays disabled. -The simulator's operation state resides on a retained PVC and survives manager -and provider pod replacement. A `Recreate` rollout avoids overlapping file-store -writers. The durable private coordinator continues to retain exact operation -inputs and recover idempotently. Store persistence and credential reload are -covered by local tests; independent Deployment restart recovery still requires -live staging verification after rollout. This remains synthetic API validation, -not production provider qualification. See the -[deployment and migration contract](../../config/README.md#moving-from-the-colocated-simulator). +The site store resides on a retained PVC and survives manager and provider pod +replacement. A `Recreate` rollout avoids overlapping store writers. Custody and +the site store retain exact operation inputs, and recovery is idempotent. Site +store persistence is covered by local tests. This remains synthetic API +validation, not production provider qualification. The overlay needs imported +records and two new credentials; see the [deployment and migration +contract](../../config/README.md#moving-from-the-secret-backed-staging). `config/overlays/management-plane` now packages the manager Deployment so its identity, RBAC, admission, image, and readiness boundary can be reviewed and -rolled out fail-closed. Its service account receives Secret permissions only -through a namespaced Role for `fleet-system-private`; cache scoping is not an -authorization boundary, and it has no host ClusterRole. The environment must +rolled out fail-closed. Its service account receives only leader-election access +in `fleet-system` and has no host ClusterRole. The environment must provide the authority ID and Project name in `fleet-manager-config`, mount the generated `milo-configuration-kubeconfig` Secret, and pin the image. The manager resolves the immutable Project UID from Milo at startup and fails @@ -632,67 +510,47 @@ source-specific publication example. Those remain environment/provider state. The two production roots target different API servers and must not be combined into one Flux reconciliation. -## Standalone lifecycle library - -`internal/controller` implements the recovery-critical core without installing a -manager or watches. Callers first create retained claim custody before adding a -claim finalizer, retaining the namespace lifetime plus a trusted caller-supplied -principal UID and admission decision ID; the library never manufactures an -authorization result. Allocation requires that exact finalizer and authority and -rejects deleting claims. -Allocation then selects only current, healthy, available machines -with fresh externally supplied evidence. It atomically reserves each physical -asset through deterministic private Secrets and retains `Preparing`, `Committed`, -`Releasing`, and `Released` authority. Released records are not deleted; a later -binding advances the provider epoch and receives new binding and fence tokens. -The claim-level `Selecting` record retains the complete proposed asset authority -before creation, allowing deletion to materialize and tombstone the proposal so -a delayed allocator cannot resurrect it. - -An independent custody record distinguishes a claim proven never bound from a -claim whose sole asset authority is unexpectedly missing. Release removes a -finalizer only after an unbound proof or retained cleanup completion. Corrupt, -duplicate, or cross-lifetime deterministic records fail closed. - -Installation admission retains exact inputs and a private predecessor before the -provider effect, including the initiating principal and installation decision plus -the image catalog authority, revision, and image decision. The operation also -retains the installation and claim namespace, name, and UID, so an informer -initial Add can route unfinished work after restart even when the public -Installation has been deleted. This is installation-record schema v2. A record -in any other schema version is invalid: it is quarantined from event routing -and effects and is never rewritten, guessed, or treated as ready. Image -references must -resolve to canonical lowercase SHA-256 digests. Stable operation and result -identities include the authority/project claim scope, so equal claim UIDs from -independent project APIs cannot share an operation record. Installation custody -and asset lookup use that same scope; standalone requests derive an explicit -local scope from the Namespace UID. Response-loss recovery is therefore an exact -operation lookup rather than a second effect. Public claim status is not used as -predecessor authority. Before image resolution, operation creation, or a provider -effect, installation also requires Bound custody whose asset, claim identity, -scope, consumer/provider Projects, authority record, and external hold exactly -match the selected retained asset. - -`internal/executor` is the typed bearer-authenticated client for the simulator's -runtime surface. Transport failures, unavailable responses, malformed terminal -results, and lost responses are classified as unknown outcomes for lookup-based -recovery. Bearer HTTP remains a test-only transport, not a production identity -contract. - -The private namespace is a security boundary: the Fleet service account must be -its exclusive writer, and the `fleet-claim-`, `fleet-asset-`, and -`fleet-install-` name prefixes are reserved. Provider health, availability, and -observation timestamps supplied to the library must come from a trusted, -authenticated provider-status path; this increment does not establish that path. +## Allocation on Device custody + +`internal/allocation` is the recovery-critical core. It allocates, installs and +releases through Device custody and creates no Secret record. The allocator takes +an admitted request: the Machine's exact project and Machine incarnation, the +class and profile, and the admission decision. It writes in a fixed order: the +quota claim, then the MachineAllocation (create only), then the custody claim (a +conditional update). A retry finds the same allocation by its name. An allocation +whose Device another holder took, and which never held it, is deleted, and the +allocator selects again. An `Active` allocation that lost custody is not repaired +(`ErrCustodyLost`). + +Installation admission creates a `DeviceInstallation` named from the allocation +and the Installation UID. The Installation's predecessor must be the Machine's +current installation, and a bootstrap reference is refused. Response-loss +recovery is an exact lookup by name, not a second effect. Release moves the +holder to `Release`, closes the gates, wipes the Device, deletes the quota claim, +and only then returns the Device to `None`. The allocation, installations and +wipes remain as the fence history. See [Cutover](device-custody.md#cutover-increment-c) +for the gates, wipe steps and recovery. + +The component identities are separate: the Metal provider creates allocations +and installations, the release controller creates wipes, and the custody +coordinator is the only writer of custody and operation status. Provider health, +availability and observation timestamps supplied to the library must come from a +trusted, authenticated provider-status path; this increment does not establish +that path. ## Network lifecycle adapter +Status: **implemented and inert**. The allocation library on Device custody does +not call this adapter, because no mode provisions Network or Address. Those +release gates close at once. The private asset and operation records this section +names were deleted in the cutover. The retention they describe is the contract a +future wiring must keep. Where it keeps it is **proposed**. + `internal/network` defines an NSO-independent lifecycle contract. Allocation preflights every requested interface before hardware selection, requiring exact namespace and location lifetime authority plus a caller-preserving network-use decision. The accepted Network UIDs, normalized request, decisions, and request -digest are retained in the private asset record before any NSO effect. +digest must be retained by the caller before any NSO effect. Fleet validates NSO's attachment shape before preflight and physical selection: families are unique `IPv4`/`IPv6` values with at most two entries, and address classes are unique with at most four entries. The Fleet CRD carries the same @@ -713,10 +571,10 @@ against guard closure; a separate pre-create check is insufficient. Immediately retained Network UID and generation are currently Ready and every retained address-class name still has the exact authorized lifetime UID. -The coordinator retains exact claim and interface UIDs plus current-generation -`Allocated`, `Prepared`, and `Programmed` observations. Installation admission -requires fresh `Allocated` and `Prepared` evidence and copies the exact network -revision and inputs into the private operation record. Public projection is a +The contract has the caller retain exact claim and interface UIDs plus +current-generation `Allocated`, `Prepared`, and `Programmed` observations. +Installation admission requires fresh `Allocated` and `Prepared` evidence and +copies the exact network revision and inputs into the operation's inputs. Public projection is a pure helper that publishes only Network names, MTU, addresses, and normalized conditions only while the observation is within the configured evidence age; stale evidence projects `NetworkReady=Unknown`. Internal UIDs, NSO claim names, @@ -726,8 +584,8 @@ Create intent for every interface is durably returned before any NSO create. Release first durably admits an exact per-interface delete vector without effects, then retries execute and verify individual deletes. Provider cleanup and finalizer release remain blocked while network deletion, retained-interface detachment, or outcome evidence is pending -or unknown. Object absence counts only after the private record proves deletion -was admitted for the exact retained UID. `Retain` additionally requires the +or unknown. Object absence counts only after the caller's retained record proves +deletion was admitted for the exact retained UID. `Retain` additionally requires the same retained interface UID to report `Available` with no claim reference. For `Retain`, an absent claim completes only when the closed guard proves the claim was never created, or when an exact interface name and UID retained before @@ -740,114 +598,54 @@ Production wiring must supply a location-scoped client, caller-preserving authorizer, and durable object guard; otherwise networked allocations fail closed before selection. -## Milo authority contracts - -`internal/milo` composes the lifecycle library with internal Milo project, -source-use, entitlement, quota, admission-fence, and release-custody contracts. -It is a library and test-fake integration only; it does not register a manager, -watches, webhooks, deployment, or acceptance environment. - -Project identity retains the configured Milo authority ID, route name, and root -Project UID. The authority ID and root UID identify the lifetime; the route name -only selects a control plane. Preparation verifies both consumer and provider -lifetimes, then retains consumer Namespace UID, claim UID, local and canonical -class/profile UIDs, canonical class revision and content digest, immutable -profile requirements, publisher revision, initiating principal UID, and the -caller-preserving source decision in a private service-controlled Secret. The -lifecycle custody record links that protected authority record before later -work. Custody names and claim lookups include the authority ID, consumer Project -UID, and claim UID; standalone use has an explicit local scope keyed by the -Namespace UID. Equal claim UIDs from independent project API servers therefore -cannot occupy the same private record. Provider asset identity includes the Milo -authority and provider Project UID, preventing reuse across project lifetimes. - -The adapter checks the exact retained claim, class, profile, location authority -(name, UID, and revision), revision, and content before capacity, quota, -fencing, or provider work. The source-use decision and admission commit bind -that complete class/profile/location combination. Current Machine inventory -does not carry separately authoritative placement evidence, so proving that a -selected Machine is physically in the retained location remains an upstream API -and provider-authority gap. The adapter accepts the -reviewed Milo v0.32.5 ServiceEntitlement evidence shape: Active phase plus a -current Ready condition on the exact entitlement UID. That API does not publish -the proposal's separate suspension evidence; ordering suspension against binding -remains an upstream admission-fence requirement rather than an invented local -condition. - -Deleting claims and claims missing Fleet's protection finalizer are rejected -before quota acquire, admission fencing, or any provider effect. - -Quota preparation durably records a deterministic intent before creating or -recovering one exact Milo ResourceClaim for -`metal.datumapis.com/machines`. Grant evidence requires the exact object UID, -request, consumer and resource references, and current status -`observedGeneration`. ResourceClaim deletion or `NotFound` is never -quota-settlement proof. Allocation requires an injected protected custodian -before requesting quota. Acquire, intent recovery/no-hold closure, and settlement -all pass through that custodian under the exact Project, authority record, and -intent lifetime. A no-hold receipt closes that intent against a later acquire; -the adapter never calls the ResourceClaim manager directly. A full -admission-commit digest binds the retained -source decision, exact entitlement lifetime, and exact quota hold UID, -generation, and evidence to the fence receipt. Sequential checks are not -presented as ordering concurrent invalidation against binding. - -Cleanup advances assets only to `CleanupVerified` while an external hold exists. -Fleet persists an exact custodian settlement receipt before releasing lifecycle -custody, and only then advances the asset to `Released` and permits finalizer -removal. Any retained hold is first installed into core custody even when a -crash occurred before that write. Quota recovery and settlement use the exact -retained consumer Project lifetime through the service-owned custodian rather -than resolving a possibly deleted or route-name-reused consumer API endpoint. -Retried allocation and release resume persisted fence, binding, intent, and -settlement states before considering new work. Persisted fence receipts are -revalidated against the complete retained commit on every decode. Unknown -create, release, or project outcomes retain custody and remain unknown. - -The tests verify source and lifetime substitution rejection before effects, -concurrent authority-record creation, both admission-fence orderings, stale or -corrupt persisted fence receipt rejection, lost quota-create recovery, a paused -acquire racing no-hold closure, hold-write crash recovery, pending-hold deletion, -binding recovery after a lost response, retry after a crash between core hold -clear and authority reset, cross-project claim-UID collisions, -cleanup-before-quota ordering, settlement-receipt replay, deleted or -route-name-reused consumer-project cleanup, malformed authority state rejection, -and delayed allocation or settlement racing completed release. These are -contract tests with fakes, not evidence of -a working Milo production integration. - -## Persistent provider simulator - -`cmd/fleet-simulator` is a test-only process for exercising provider-operation -recovery before a real hardware adapter exists. It supports synchronous -`install`, `power`, and `cleanup` operations plus operation lookup. It never -contacts, enrolls, or authorizes real hardware. - -The simulator writes one versioned JSON state file. Each mutation writes and -syncs a temporary file, atomically renames it over the retained state, and syncs -the parent directory. Operation IDs are idempotency keys: replaying the exact -request returns its retained result, while different retained input conflicts. -Every effect carries an asset ID, binding ID, monotonically increasing epoch, -and fencing token. Cleanup closes that epoch so delayed work from the released -binding cannot reactivate the asset; a later binding must advance the epoch. - -The `lost-response` fault persists the completed effect and consumes the fault in -the same state write before returning an unavailable response. A caller recovers -the retained result by operation ID instead of submitting new authority. A -failure after the state-file rename remains queryable in memory and is reported -as an unknown response outcome rather than rolling the process back behind the -visible file. - -The runtime and fault-injection surfaces use separate bearer credentials. The -admin listener is disabled by default, and the runtime listener defaults to -loopback. Runtime responses omit binding IDs, fencing tokens, and exact inputs. -Request bodies, identifiers, headers, and server timeouts are bounded. These -controls limit the local test surface; bearer authentication over plain HTTP is -not a production executor identity protocol. - -The persisted schema and HTTP endpoints are internal alpha interfaces. No -compatibility promise exists yet. The process fails closed if retained state is -corrupt or uses an unsupported schema version. +## Milo quota claim + +`internal/milo` holds Fleet's Milo service identity (`metal.datumapis.com`) and one +quota claim. The authority contracts of the Secret-backed design, which retained +project, source-use, entitlement and admission-fence evidence in private records, +are deleted. Production source-use, entitlement and admission-fence integration +is not implemented. + +The quota claim is **implemented and verified** by unit tests, and **implemented +and inert** end to end: no mode in this repository has Milo quota. The allocator +creates a Milo `ResourceClaim` named `fleet-machine-` and 16 hex characters of the +SHA-256 of the consumer project UID and the Machine UID, in the Machine's +namespace, before it creates the MachineAllocation. A retried create finds the +claim by name. Only a granted claim reserves quota, so a pending claim returns +`ErrQuotaPending` and the allocator retries. A claim that is not the claim Fleet +would create for that Machine is `ErrQuotaInvalid`. Release deletes the claim and +reports it released only once it is gone (`TestReleaseIsObservedNotAssumed`). + +Milo v0.32.5 supplies ResourceClaim evidence but no service-owned quota custody +anchor or explicit release acknowledgment, so deletion is observed, not +acknowledged. + +## Simulator site + +`cmd/fleet-simulator` is a test-only site for exercising the custody delivery and +recovery paths before a real hardware adapter exists. It serves a site HTTP API +(`internal/site/siteapi`) with a bearer token: it takes an assignment +(`PUT /v1/assignments`), reports a Device's fences (`GET /v1/fences/{namespace}/{name}`), +lists the results it holds (`GET /v1/results`) and forgets a result the +coordinator answered (`DELETE /v1/results`). It never contacts, enrolls or +authorizes real hardware. + +Its workers (`internal/site/simwork`) run on the [site +framework](device-custody.md#site-execution-increment-b). They keep a simulated +server in fenced records of the site store, so an older fence is refused, a +newer assignment stops an older worker, and a result is fenced and typed like a +real site's. With `--discover`, the process also writes fixture discovery for its +enrolled Devices, as BMC discovery would. Fixture access checks the enrollment +against the snapshot, with no BMC. The site store is an owner-only directory, and +every write replaces a file atomically and syncs it, so the simulator refuses +older fences after a restart. + +The runtime listener defaults to loopback, and the admin listener of the earlier +simulator is gone. Request bodies, identifiers, headers, and server timeouts are +bounded. The simulator refuses to start without a token and an enrollment. +Bearer authentication over plain HTTP is not a production site identity protocol. +The persisted store and the HTTP endpoints are internal alpha interfaces with no +compatibility promise. ## Physical inventory subset @@ -896,28 +694,25 @@ go test -race ./... `task test:envtest` runs the same command. -For an isolated local run, create a synthetic credential file and keep the -default loopback listener: +For an isolated local simulator site, create a synthetic token file and a +synthetic enrollment, and keep the default loopback listener: ```sh +state_dir=$(mktemp -d) runtime_token_file=$(mktemp) chmod 600 "$runtime_token_file" openssl rand -hex 32 >"$runtime_token_file" +cat >"$state_dir/enrollment.json" <<'JSON' +{"default/server-example-001": {"bmcEndpoint": "https://[2001:db8::31]", "systemUUID": "00000000-0000-4000-8000-000000000031", "bootMACAddress": "02:00:00:00:00:31", "bmcPublicKeySHA256": "3131313131313131313131313131313131313131313131313131313131313131", "disks": ["disk-0"]}} +JSON go run ./cmd/fleet-simulator \ --runtime-token-file="$runtime_token_file" \ - --state-file=/tmp/fleet-simulator-state.json -``` - -Fault injection and full retained-state inspection are disabled by default. To -enable them locally, create a second credential with a different value and add: - -```text ---admin-listen-address=127.0.0.1:8081 ---admin-token-file=/path/to/distinct-admin-token + --enrollment-file="$state_dir/enrollment.json" \ + --state-dir="$state_dir/site" ``` -The process refuses to start if the runtime and admin credential values match. -Remove the synthetic token and state files when the local run is complete. +Add `--discover` to write fixture discovery with the in-cluster credential. Remove +the synthetic token and state files when the local run is complete. ## Explicit gaps @@ -967,7 +762,7 @@ acceptance inventory. surfaces, but production lifecycle handlers and public status writes remain unwired. Trusted create-time caller capture and protected finalizer admission cannot be reconstructed from informer events. -- Live Milo project/IAM/catalog/quota event adapters and asynchronous executor +- Live Milo project/IAM/catalog/quota event adapters and asynchronous site completion sources are not implemented. They must support durable replay; polling is intentionally not a fallback. - Cross-project class sources and bootstrap secret retention are rejected rather @@ -976,25 +771,21 @@ acceptance inventory. and profile across two exact Milo project lifetimes. It uses synthetic admission, quota-hold, and source-use evidence, labels that boundary in public status, refuses publication collisions or profile drift, and is not production - authorization. The Milo adapter can - resolve a canonical source only when injected with trusted source authority, - fence, and custody implementations. The network adapter remains deliberately - unwired until production location, authorization, and object-guard owners are - available. + authorization. The network adapter remains deliberately unwired until + production location, authorization, and object-guard owners are available. - Milo v0.32.5 supplies ResourceClaim evidence but no service-owned quota custody anchor or explicit release acknowledgment. It also does not supply Fleet's caller-preserving source/provenance receipt, atomic invalidation-versus-bind fence, consumer-project deletion recovery, or provider-project purge guard. - Production cross-project allocation therefore fails closed; only test fakes - implement these interfaces in this increment. + Production cross-project allocation therefore fails closed, and the quota claim + has no end-to-end run. - `LocalDigestImageResolver` is test-only. Production image authority, namespace authorization, catalog lifetime identity, and digest resolution are not implemented. - No container image or Kubernetes deployment is delivered in this increment. - There is no mTLS workload identity, target-level authorization, or production - provider credential protocol. -- Operations complete synchronously. Delayed completion, partial effects, - cancellation boundaries, synchronization barriers, and worker takeover remain - unimplemented. -- The state file is intended for a single simulator process. Replication, + site credential protocol. +- The capacity projector is unwired (O1) and bootstrap is refused (O10); see + [Device custody](device-custody.md#points-for-a-person). +- The site store is intended for a single site process per Device. Replication, migration, backup, and upgrade/downgrade compatibility are not implemented. diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index dff962f2..9a8f0d78 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -12,9 +12,9 @@ marked **implemented and verified**, **implemented and inert**, or | Increment | What it covers | Status | | --- | --- | --- | -| A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and inert.** Verified with unit tests and with tests against a real API server. No deployment root, manager, or staging overlay includes it. The existing Secret-backed lifecycle is unchanged. | -| B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and inert.** Unit tested, including against TLS BMC stubs. Nothing delivers to it until C; the old executors keep their own journals until C deletes them. | -| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, the site access layer for the local VM and simulator executors, removal of the private Secret records and the old executor journals | **Proposed.** Starts after B. | +| A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and verified**, except the capacity projector, which is **implemented and inert**. Verified with unit tests and with tests against a real API server. Increment C wires the rest into every mode. | +| B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | +| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | ## What Increment A adds @@ -22,14 +22,16 @@ marked **implemented and verified**, **implemented and inert**, or - **Kinds.** `DeviceCustody` and three operation kinds in `fleet.datumapis.com`, served only in provider project control planes. The component that registers them, with their ProtectedResources, roles and - webhook, is not included by any root. A test fails if one includes it. + webhook, is in the production Milo root. The synthetic Milo root has it + without the webhook, and the standalone cluster has only the CRDs. + `TestComponentRoots` pins this, and no root ships the test-only kinds. - **Custody.** One `DeviceCustody` per Device, with the same name. Its fields are in `spec`, like a Lease, and it has no status. The finalizer `fleet.datumapis.com/custody` stays until the holder is `Retired`. CEL keeps the fence from decreasing, keeps `Retired` terminal, and requires the active operation to carry the current fence. - **Operations.** Every kind starts with one envelope: `creator`, `deviceRef` - (name and UID) and `authority` (exactly one of `allocationRef` and + (the Device's name) and `authority` (exactly one of `allocationRef` and `serviceRequest`). The spec is immutable after create. Status phases move forward only, and an ended phase is final. `Pending` may end `OutcomeUnknown`, because rebuild holds an operation whose status still @@ -38,10 +40,11 @@ marked **implemented and verified**, **implemented and inert**, or operation status. Every custody change is one update that carries the resourceVersion just read. On a conflict it reads again and decides again. - **The creator webhook** (`internal/custody/creatorwebhook`) admits a create - only when `spec.creator` is the authenticated caller's username and UID, and - an update only when the creator is unchanged. + 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. + `Healthy` and `Available`. Nothing calls it outside tests (**implemented and + inert**; see [Capacity](#other-decisions)). Creating or importing a Device creates `Unverified` custody. That sends nothing to a BMC and makes no capacity `Available`. @@ -49,11 +52,10 @@ nothing to a BMC and makes no capacity `Available`. ## Site execution (Increment B) Increment B adds the site framework (`internal/site`) and the Redfish -install and wipe workers (`internal/site/redfishwork`). It is implemented and -inert. Until Increment C, the old coordinator still drives the old executors -with their own site-wide journals, and nothing delivers an assignment to the -new framework. There is no bridge between the two paths, and C deletes the old -one. +install and wipe workers (`internal/site/redfishwork`). It is **implemented and +verified**. Increment C delivers assignments to it and deletes the old +executors and their site-wide journals. Every site, simulator, local VM and +Redfish, now runs on it. ### Where a site stores fences and its journal @@ -114,7 +116,7 @@ so work on one Device never waits for another. - **Boot admissions.** A network boot is served only while the operation's admission is open, unexpired, and at the Device's stored fence, so a superseded operation can never boot the server. The boot server reads - admissions this way from Increment C. + admissions from the site store. ### The Redfish workers @@ -132,8 +134,9 @@ The port differs from the old executor in three ways: - After a crash or a lost response, a power-on is observed and never sent again. The old executor sent `On` again, up to a small budget, when the server was still off and armed after a settle window. -- Synchronized DHCP reservations are not yet supported by the new workers. - They arrive with the cutover. +- Synchronized DHCP reservations are supported from Increment C. The feed + reads the site store, and the worker waits for the DHCP owner's reports. See + [Boot network](../operations/boot-network.md). - Its timing values match the old executor's, including the five-minute power-off bound and the 30-second wait for a receipt after power-off, and each is configurable. @@ -141,9 +144,242 @@ The port differs from the old executor in three ways: ### Access to the server How the framework reaches a server is behind an `Access` interface. -`RedfishAccess` performs the credential, pin and identity checks above. In C, -the local VM and simulator executors get their own access types and workers. -That adds no change to the worker contract. +`RedfishAccess` performs the credential, pin and identity checks above. The +simulator and local VM sites use `fixture.Access`, which checks the site's +enrollment against the snapshot and has no BMC. Each has its own workers. That +added no change to the worker contract. + +## Cutover (Increment C) + +Increment C moves every mode onto custody and deletes the old path. All of it +is **implemented**. The standalone smoke (`task standalone:test`) and both +multi-plane runs, local VM and Redfish, verify it end to end. Increment C adds +no migration and no compatibility code. The Secret-backed coordinator and its +records are gone, and a person re-imports records where an environment needs +them. + +| Piece | Status | +| --- | --- | +| MachineAllocation, allocation, installation and release | **Implemented and verified** by tests against a real API server and the standalone smoke | +| Quota claim | **Implemented and verified** by unit tests. **Inert** end to end: no run exercises it | +| Delivery and the coordinator loop | **Implemented and verified** by the standalone smoke and both multi-plane runs | +| Federation handoffs | **Implemented and verified** by unit tests and both multi-plane runs | +| Creator webhook in the production Milo root | **Implemented and verified** by unit tests and a test against a real API server. The root registers it, and nothing runs the coordinator there | +| Simulator site | **Implemented and verified** by the standalone smoke | +| Local VM site | **Implemented and verified** by unit tests and the multi-plane local VM run | +| Redfish site workers | **Implemented and verified** by unit tests and the multi-plane Redfish run | +| Synthetic staging mode | **Implemented.** The manager's flag handling is unit tested, and no run exercises the mode | +| Power projector | **Implemented and verified** by the standalone smoke | +| Synchronized DHCP feed on the site store | **Implemented and verified** by a unit test. Not exercised at a site | + +### MachineAllocation + +A `MachineAllocation` holds the allocation's private facts (O8). It lives in the +provider project, and only the Metal provider writes it. + +- **Spec (immutable).** The consumer as a typed reference, the Machine by + namespace and name, the capacity, the Device by name, the accepted class and profile pinned by + generation and spec digest, the CPU and memory, the hardware snapshot, the + admission authority, an optional quota claim, the pinned cleaning policy + digest, the boot interface and the target disks. +- **Labels.** `fleet.datumapis.com/machine-uid`, + `fleet.datumapis.com/consumer-uid` and + `fleet.datumapis.com/device-uid` record the incarnations the allocation was + made for. See [No object UIDs in spec](#no-object-uids-in-spec). +- **Status.** A phase, `Active`, `Releasing` or `Released`, and the latest wipe. +- **Name.** `alloc-` and the first 16 hex characters of the SHA-256 of + `/`. See [the decision](#cutover-decisions). +- **Secrets.** None. Staff recovery operators may read it. + +### Consumers + +An allocation names its consumer with `consumerRef`, a typed reference of API +group, kind and name in the shape of Milo's quota consumer reference. The +consumer's UID is never in the spec; the allocation's name and +`consumer-uid` label carry it. + +| Consumer | `consumerRef` | Served by | +| --- | --- | --- | +| Milo project | `{apiGroup: resourcemanager.miloapis.com, kind: Project, name: consumer-a}` | The managed and multi-plane modes, through project discovery | +| Standalone namespace | `{apiGroup: "", kind: Namespace, name: fleet-project-a}` | The standalone mode, where each namespace stands in for a project | + +The allocator and the API both refuse any other kind. The allocator refuses +it before it reserves quota or looks for capacity. + +A published MachineClass names its source the same way: +`source: {publisherRef: {apiGroup, kind, name}, name}`, the provider that +publishes the class and the source class's name. The same kinds are allowed. +A claim allocates through a published class only when its `publisherRef` +resolves to the provider incarnation that published it. + +One tenancy interface resolves a reference to the consumer's current +incarnation, its UID, and the client of its API. The allocator, release, +quota claims, the Machine power projector, staging and the standalone and +multi-plane runners reach a consumer only through it. The managed mode +resolves a project through the engaged project runtimes, so a project that is +not engaged is unavailable, never assumed gone. Only a Milo project has +quota. A quota claim is never made in a project recreated under the same +name, and releasing the Machine's claim in a recreated project finds nothing, +because the claim went with the earlier project. + +### Allocation, installation and release + +`internal/allocation` writes in this order: the quota claim, then the +MachineAllocation (create only), then the custody claim (a conditional +update). A retry finds the same allocation by its name. + +- **A lost race.** An allocation whose Device another holder took, and which + never held it, is deleted, and the allocator selects again. +- **Lost custody.** An `Active` allocation that no longer holds its Device is + not repaired. The allocator returns `ErrCustodyLost`, the Machine reports + `Pending` with reason `CustodyLost`, and an operator resolves it. +- **Installation.** The `DeviceInstallation` is named from the allocation and the + Installation UID, which its `fleet.datumapis.com/installation-uid` label + records. Its predecessor must be the Machine's current installation. + A bootstrap reference is refused. +- **Release.** The allocation's holder moves to `Release` with all six gates + open. Then: + - Access, Network and Address close at once. + - Operations closes when no installation of the allocation is active or + unended. + - Cleaning creates a `DeviceWipe`, step 1. A wipe that ended `Failed` sent + nothing, so it gets a new step, up to step 3. Then the release stops with + `ErrWipeFailed`. A wipe that ended `OutcomeUnknown` gets a new wipe only + after a `DeviceRecovery` `Retry`, under the name custody gives it. + - Quota deletes the claim and observes it gone. +- **Done.** Custody returns the Device to `None` only when no gate, hold or + operation remains. Then the allocation becomes `Released`. + +### Quota claim + +`internal/milo` creates a Milo `ResourceClaim` named `fleet-machine-` and the same +16 hex characters, in the Machine's namespace. Release deletes it and waits until +it is gone. No mode in this repository has Milo quota. The claim is **implemented +and verified** by unit tests, but **implemented and inert** end to end: no run +exercises it. + +### Delivery and the coordinator loop + +`internal/delivery` builds each assignment from custody's active operation and +the operation spec exactly as admitted. It delivers the assignment to the sites +serving the Device once the admission is copied to operation status. It collects +results and accepts them by fence. The coordinator loop runs reconcile, deliver, +collect and the retention sweep. The coordinator configuration names the sites +that serve each Device. + +### Identities + +Every mode uses three identities, one per component: + +| Identity | Writes | +| --- | --- | +| The custody coordinator | Custody, operation status. It is the only custody writer. | +| The Metal provider | MachineAllocations and DeviceInstallations | +| The release controller | DeviceWipes | + +An operation's creator is the identity a `SelfSubjectReview` reports. + +- **Standalone** enforces the same creator rule as the webhook with a + ValidatingAdmissionPolicy (`config/standalone/site.yaml`). +- **The production Milo root** (`config/milo`) includes the device-operations + component, with the creator webhook served by `fleet-registration`. +- **The synthetic Milo root** (`config/milo-synthetic`) includes the kinds, + ProtectedResources and roles, but not the webhook, because it installs no + registration webhook. +- **The multi-plane local Milo** enforces the CRD rules but registers no creator + webhook. This is a gap. See [Points for a person](#points-for-a-person). + +### Sites + +- **The simulator is a site.** `cmd/fleet-simulator` serves a site HTTP API + (`internal/site/siteapi`). Its workers (`internal/site/simwork`) keep the + simulated server in fenced records in the site store. +- **The local VM site** (`internal/site/vmwork`) ports the old executor. It + gives each installation an exclusive disk. It proves the installer boot with one + console receipt, and in PXE mode also with boot deliveries and a DHCP lease. It + then does a disk boot. A boot is started once and is observed after a crash. + The boot server serves only an open admission at the Device's stored fence. A + wipe deletes every installation disk of the Device. +- **The Redfish workers** (`internal/site/redfishwork`) are live. Each reads the + Device's own credential Secret by the [BMC discovery](../operations/bmc-discovery.md) + contract. There is no shared credential. The boot server and the synchronized + DHCP feed read the site store. +- **Fixture access and discovery** (`internal/site/fixture`) serve synthetic + Devices that have no BMC. Access checks the enrollment against the snapshot. + Fixture discovery writes Device status the way BMC discovery would. Who writes + it depends on the mode; see [Modes](#modes). + +### Federation + +`internal/coordination` carries one site assignment per `MachineAllocationHandoff` +(`spec.device` and `assignmentJSON`), or a request for a Device's fence report. +The cell observer writes the fence report and the stored result to the handoff's +status. The coordinator accepts only this cell's observation of exactly the +assignment the handoff carries. It then labels the handoff answered, and the cell +deletes its copy of the result. + +Worker Jobs are created by kro as before. A worker exits 65 for a handoff that +is not for this cell, or for an assignment below the Device's stored fence. The +private custody namespace on the hub host is gone. + +### Modes + +| Mode | Where the coordinator runs | Site | Fixture discovery writer | Status | +| --- | --- | --- | --- | --- | +| Standalone smoke | A Deployment | The simulator | The simulator site | **Implemented and verified** by `task standalone:test`. The phases run as the Metal provider, with the coordinator's and release controller's tokens. | +| Synthetic staging | `fleet-manager`, under its leader lease | The simulator | The manager | **Implemented.** The manager's flag handling is unit tested. No run in this repository exercises it. | +| Multi-plane, local VM and Redfish | A workstation process for the run (`hack/multiplane/coordinator.sh`) | The cell, over Karmada | A separate discovery identity on the workstation | **Implemented and verified** by both runs. | + +- **Synthetic staging.** The manager runs the coordinator loop and fixture + discovery. Its flags are `--synthetic-coordinator-client-cert-dir`, + `--synthetic-release-client-cert-dir`, `--synthetic-site-enrollment-file` and + `--synthetic-device-namespace`. The coordinator and the release controller + each sign in to Milo with their own client certificate, on the manager's + endpoint and server CA and without its credentials. The overlay mounts two + environment-supplied cert-manager Secrets, + `fleet-custody-coordinator-client-cert` and + `fleet-release-controller-client-cert`, each with `tls.crt` and `tls.key`, + and a `fleet-synthetic-site-enrollment` ConfigMap. The ConfigMap in the overlay + holds a synthetic placeholder, and an environment replaces it. An environment + must also make sure its records exist and create the two client-certificate + identities; see [Points for a person](#points-for-a-person). +- **Multi-plane.** The provider project gets the inventory and custody CRDs and one + token per component. The lab BMC serves TLS with a key generated per run, and + each Device's credential carries that key's digest as its pin. Real BMC + discovery is not part of the run. This is a lab gap. One lab BMC serves both + targets with one key, and custody refuses a key that two active Devices + record, so only target A is a Device. Target B stays enrolled at the site, + with its own credential, to prove isolation. + +### Machine power + +The manager's `PowerProjector` is the only writer of `Machine.status.power`. It +reports `Unknown` while a recovery hold exists or custody is unverified, and +otherwise the power state discovery last observed. A Machine with no active +allocation has no power. The harness runners call the same projection. In the +manager, custody, allocation and Device events in the provider project wake +the consumer's Machines, so a new hold shows as `Unknown` without a Machine +event. + +### Deleted, with no compatibility + +- The Secret-backed coordinator and its records, the private-record RBAC, the + private namespace and its admission policy, and the manager's private-namespace + plumbing (`--private-namespace` is removed). +- The executor client, the simulator store, the local VM and Redfish executors and + their journals, and the shared Redfish credential. +- The old handoff `requestJSON` shape. +- The single-plane local VM harness (`hack/local-vm/run.sh`, + `task local-vm:acceptance`, `cmd/fleet-local-vm`). The multi-plane local VM + mode runs the same workers. This is a decision for a person; see [Points for a + person](#points-for-a-person). + +### Unchanged and still open + +- 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. ## Implementation decisions @@ -151,25 +387,29 @@ Each decision lists the open point from the implementation brief it settles. ### Who created an operation (O14) -- The client sets `spec.creator` to its own username and UID. The webhook - rejects any other value and any change. That is how #174 at `d4d17f9` reads, - so "clients cannot set the creator" becomes "clients can set only - themselves". CEL also makes the creator immutable, as part of the spec. +- The client sets `spec.creator` to its own username, and to its UID only when + its credential carries one. A caller is identified by username, as Kubernetes + RBAC identifies it, because some credentials, such as client certificates, + carry no UID. The webhook rejects any other value and any change. That is + how #174 at `d4d17f9` reads, so "clients cannot set the creator" becomes + "clients can set only themselves". CEL also makes the creator immutable, as + part of the spec. - Milo's root API server calls the webhook, because Milo v0.32.5 does not evaluate admission policies stored in a project. The webhook reads the original caller from the admission request, with the project in Milo's extras, and refuses a caller outside the configured provider projects. It reads nothing else and keeps no state. -- The webhook will be served by the existing `fleet-registration` server on - its own path, `/validate-operation-creator`, when Increment C wires it. That - server already has the API-server client CA and the Milo root route, and the - new handler needs no project reads. In Increment A the handler exists and is - tested, and the server does not serve it yet. +- The existing `fleet-registration` server serves the webhook on its own + path, `/validate-operation-creator`. It shares that server because the caller, + the transport and the provider-project scope are the same, and the handler + keeps no state. The production Milo root registers it (Increment C). - The coordinator classifies a creator by configuration. Each service class, such as the Fleet provider for Metal or the release controller, maps to - configured principals by username and, optionally, UID. Any other creator is - staff. IAM decides which staff may create which kind, and the API server has - already authorized the create. No identity is hard-coded. + configured principals by username. A principal configured with a UID + matches only a creator with that UID; one without a UID matches the username + alone. Any other creator is staff. IAM decides which staff may create which + kind, and the API server has already authorized the create. No identity is + hard-coded. ### Admission @@ -244,7 +484,8 @@ Each decision lists the open point from the implementation brief it settles. - **Only `Retire` and `Resolve` skip checks 5 and 6.** A `DeviceRecovery` with `Retire` or `Resolve` skips current discovery and the shared-key check, because it must work when a BMC is unreachable, for example to retire a dead - server. The Device UID is always checked. `Settle` still needs current + server. The operation's `device-uid` label is always checked against the + Device's UID. `Settle` still needs current discovery: settling a power hold needs fresh discovery evidence of the power state, as the #174 settlement table says. `Retry` needs no evidence of its own, and it still passes both checks. The settling operation it authorizes @@ -255,10 +496,10 @@ Each decision lists the open point from the implementation brief it settles. staff power and generation-based names for provider power; otherwise the kind's rule applies. An operation that does not follow its rule ends `Failed` with `NameMismatch`. A `DeviceInstallation` is named from its allocation and - a digest of the Installation UID. A `DeviceWipe` is named from its allocation + a digest of the Installation UID in its `installation-uid` label. A `DeviceWipe` is named from its allocation and step. Staff kinds must use a generated name. - **Order.** Pending operations are admitted oldest first. Ties break on kind, - then name, then UID, so every coordinator picks the same one. + then name, then the object UID, so every coordinator picks the same one. - **Refusals use current custody.** The coordinator reads custody, lists the operations, and reads custody again. It decides only if custody did not change in between. A claim followed by its installation's create is @@ -290,7 +531,7 @@ Each value is configurable. ### Unknown outcomes and recovery (O2, O3, O6, O7) - `OutcomeUnknown` moves the operation from `activeOperation` to - `recoveryHold` in the same update, keeping its kind, name, UID and fence. + `recoveryHold` in the same update, keeping its kind, name and fence. The holder stays. - A result whose evidence does not match the kind's schema proves nothing, and ends `OutcomeUnknown` with `InvalidEvidence`. @@ -317,7 +558,8 @@ Each value is configurable. `Release` requires a disk disposal record. - `Resolve` is the only operation `Unverified` custody admits. It records the holder (`None`, `Allocation`, `Release` or `Retired`), marks custody - `Verified`, and adopts the current Device UID. The holder must agree with + `Verified`, and adopts the current Device UID in custody's `device-uid` + label. The holder must agree with the Device's live MachineAllocations, both at admission and when it is applied: `None` or `Retired` when none names the Device, and `Allocation` or `Release` with the one that does. A rebuilt hold stays, to be settled @@ -330,9 +572,11 @@ Each value is configurable. succeeded `Retire` recoveries, its MachineAllocations that are not `Released`, and its operations. A releasing allocation rebuilds `Release` with every gate open. -- Every operation that has not ended is held, even if its status says - `Pending`, because custody is written before status. Its status is ended - `OutcomeUnknown` with reason `Rebuilt`, and it is never admitted again. +- Every admitted operation that has not ended is held, even if its status + says `Pending`, because custody is written before the rest of its status. + Its status is ended `OutcomeUnknown` with reason `Rebuilt`, and it is never + admitted again. An operation records its admission before custody names + it, so one without an admission record was never admitted and is not held. - An operation that ended `OutcomeUnknown` is held again unless something later settled it: a succeeded operation with a higher fence whose kind settles the held kind, or a succeeded recovery that cleared that exact @@ -341,7 +585,8 @@ Each value is configurable. held and custody stays `Unverified`, so a `Resolve` must decide and the hold is never dropped. - Two live allocations, holder sources that disagree, a Device UID that - differs from custody, or a missing Device also keep custody `Unverified` + differs from custody's `device-uid` label, or a missing Device also keep + custody `Unverified` until a `Resolve`. - Custody becomes `Verified` only after every site configured to serve the Device reports its stored fence. The new fence is above every fence those @@ -360,8 +605,9 @@ of the machine lifecycle: identity, the accepted contract, the hardware snapshot, authority and quota evidence, and lifecycle and release obligations. Immutable accepted inputs go in spec. Lifecycle goes in status. Each allocation is named from its Machine UID, per #174. Nothing secret goes on it, -and staff roles may read it. Increment C implements this. It replaces the -private `AssetRecord` and the other Secret records. +and staff roles may read it. Increment C implements this (**implemented**; see +[MachineAllocation](#machineallocation)). It replaces the private `AssetRecord` +and the other Secret records, which are deleted. ### Release gates (O17) @@ -402,8 +648,9 @@ remains. Device's interfaces, and the snapshot records its MAC. Target disks stay a site-local enrollment fact that the worker checks (Increment B). - **Cleaning policy (O11).** `DeviceWipe` requires the digest of the cleaning - policy record pinned at allocation. The private fixture resolver that pins it - arrives in Increment C. + 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` @@ -411,6 +658,106 @@ remains. as written would make every server unallocatable, because commissioning is not built. +### No object UIDs in spec + +No resource spec holds an object UID (#211). A deterministic name, a label or +status pins each incarnation. The one exception is an operation's +`creator.uid`, the authenticated caller's UID when its credential carries one, +as in a Kubernetes CertificateSigningRequest. Each same-name recreation is +guarded, and a test fails if its guard is removed: + +| Recreated | Guard | Test | +| --- | --- | --- | +| Machine or consumer | The allocation's name hashes both UIDs, and its `machine-uid` and `consumer-uid` labels must match | `TestAnAllocationForAnotherMachineIncarnationIsAConflict` | +| Machine or consumer, against the authority | The allocator refuses an admission authority that records the Machine or consumer UID, so the decision is named by name | `TestTheAllocationAuthorityNamesNoIncarnation` | +| Consumer, under another kind or name | The allocation's `consumerRef` must name the Machine's consumer | `TestAnAllocationForAnotherConsumerIsAConflict` | +| Publisher, against a published class | A published class's `publisherRef` must resolve to the provider incarnation that published it | `TestAClassFromAnotherPublisherIsRejected` | +| Consumer project, against quota | Quota resolves the project and requires the incarnation the Machine was admitted in | `TestQuotaServesOnlyTheMachinesProjectIncarnation` | +| Device | Custody's `device-uid` label must match the Device, or custody stays `Unverified` until a `Resolve` | `TestARecreatedDeviceLeavesCustodyUnverified` | +| Device, against free capacity | Custody for another Device incarnation is never free | `TestCustodyForAnotherDeviceIncarnationIsNotFree` | +| Device, against a claim | `Claim` takes the Device incarnation the allocation names, and refuses unless both the live Device and custody's label match it | `TestCustodyForAnotherDeviceIncarnationIsNeverClaimed`, `TestARecreatedDeviceIsNeverClaimedUnderItsStaleLabel`, `TestARecreatedDeviceIsNeverClaimedForTheEarlierIncarnation` | +| Device, against an operation | An operation's `device-uid` label must match the Device at admission | `TestAdmissionPreconditions` | +| Device, against an existing operation | The Metal provider and release controller require an existing same-name operation to carry the same labels | `TestAnOperationForAnotherDeviceIncarnationIsAConflict` | +| Installation | The `DeviceInstallation` name hashes the Installation UID, so a same-name Installation gets a new operation | `TestAllocateInstallReleaseReuse` | +| Operation, as the active operation | Custody names an operation by kind and name with the fence it admitted it at, and an operation matches only if its `status.admission.fence` carries that fence | `TestARecreatedActiveOperationNeverGetsItsResult` | +| Operation, as the last result | The same match: the result is never copied to a same-name operation created later | `TestARecreatedOperationNeverInheritsItsLastResult` | +| Operation, as the recovery hold | The same match: a same-name operation is neither held nor excluded as the held one | `TestARecreatedHeldOperationNeverTakesTheHold` | +| Operation, as a Retry's settling operation | The same match: a same-name operation is never admitted or settled as the Retry's | `TestARecreatedRetryIsNeverCountedAsTheRetry` | +| Operation, as a later retry at rebuild | A later retry supersedes a held operation only if it carries an admission record | `TestARecreatedRetryNeverSupersedesARebuiltHold` | + +The coordinator writes `status.admission.fence` to the operation before it +writes custody, so custody never names an operation that cannot prove it is +the one admitted. A same-name object created later has no admission record, +so it never matches custody's active operation, last result, hold or Retry +lineage. An operation without an admission record was never admitted, so +rebuild holds only operations that carry one. + +The site keys its journal, results and boot records by the admission, not by +an object UID: `..`, with the name replaced by +its digest if the key would exceed the site store's 128-character limit. A +same-name operation admitted later has a higher fence and so another key. + +### Cutover decisions + +Each decision was made while building Increment C. Each is open for review by a +person. + +- **Allocation names.** An allocation is named from the Machine UID within its + consumer project, and its labels record both UIDs. A retried create then + collides with the first, and equal Machine UIDs in two consumer projects + never share an allocation. +- **Lost custody is not repaired.** An allocation that never held its Device is + deleted and the allocator selects again, because it exposed nothing. An `Active` + allocation that lost custody means the records disagree about who holds a + server a customer may be using. Fleet leaves it to an operator. +- **Release gates.** Access, Network and Address close at once, because no mode + provisions them. There is nothing to wait for. +- **Wipe retries.** A wipe that ended `Failed` sent nothing, so a new step is safe. + A wipe that ended `OutcomeUnknown` may have written to disks, so only a + `DeviceRecovery` `Retry` allows another. +- **Sites are configuration.** The sites that serve a Device are explicit + coordinator configuration, because inventory has no sites field yet. They are + never inferred from placement. +- **Three identities in every mode.** The coordinator is the only custody writer. + The provider and the release controller each create only their own operation + kinds. One identity per component keeps one writer per surface and lets the + creator rule tell the callers apart. +- **The creator webhook shares `fleet-registration`.** The caller, transport and + provider scope are the same, and the handler keeps no state. +- **Fixture discovery writer by mode.** In standalone the simulator site writes it. + In synthetic staging the manager writes it, because the staging site has no API + credential. In multi-plane a separate discovery identity on the workstation + writes it, in both modes. +- **No migration.** The old records are deleted and nothing reads them. Fleet + keeps no legacy compatibility, and re-importing records is acceptable. +- **Quota follows the Machine.** The quota claim is named from the Machine, as + its allocation is. A Machine deleted before its allocation existed, such as + one still waiting for capacity, releases its claim by that name. +- **Each worker reads only its Device's credential.** Each Device has its own + BMC credential Secret, named from the Device (`bmc-` and 20 hex digits of + the Device's SHA-256), bound to it by the discovery contract and its + approved pin; there is no shared credential. No handoff field names a + Secret. kro derives the name from the Device the operation's own assignment + names, as the site does, and grants the operation's worker `get` on exactly + that Secret, with no list or watch. Only a handoff whose Device is its + assignment's gets that Role; any other gets no grant, and its worker + refuses it. The API refuses a handoff that names a credential, so no input + can get a worker another Device's Secret. The worker + refuses a handoff whose Device is not its assignment's, reads the Secret + with one get, and still requires the contract's annotations and pin. + Admission lets kro create a credential Role only of that shape. The + `delivery-faults` phase forges a handoff naming another Device's credential, + and one whose assignment names another Device, and checks that the first is + refused, the second gets no Role, and no Role grants that Secret. +- **The observer deletes answered results.** The site observer is the only + handoff status writer, and it deletes the site's copy of a result once the + coordinator answered it. Its mount of the site store is therefore writable. +- **One staging process, three identities.** Synthetic staging runs the + coordinator, the Metal provider and the release controller in the manager + process with three credentials. Each write carries its component's identity, + but one process can act as all three. This is the synthetic seam, not + production separation. + ### Extension points for power and commissioning The agent rebuilding `DevicePowerOperation` on this foundation asked for @@ -429,25 +776,66 @@ these seams. Each is decided here. | 9 | Delivery carries the admission time, and kinds declare a start-by window | A kind that implements `StartBy` refuses as `Stale` when its worker starts later than the window after admission, with nothing sent. A worker resuming steps an earlier worker sent is not stale. | Implemented and inert | | 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only, through the Redfish client's identity walk. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, and drives the System through a connection bound to it. | Implemented and inert | | 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. Whether anything was sent comes from the journal. | Implemented and inert | -| 12 | The single writer of `Machine.status.power` | The manager's Machine status projector stays the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists it reports power `Unknown`, and otherwise it reports the power state of the last succeeded power operation's evidence or of discovery, whichever is newer. | Proposed for C | +| 12 | The single writer of `Machine.status.power` | The manager's `PowerProjector` is the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists, or custody is unverified, it reports power `Unknown`. Otherwise it reports the power state discovery last observed. A Machine with no active allocation has no power. The harness runners call the same projection. A power operation's evidence becomes a second source when the power kind exists. | Implemented and verified by the standalone smoke, which reads the projected state | -None of these conflicts with #174. +Rows 1 to 11 keep the status recorded when Increment A added them. The +install and wipe kinds use some of them, such as step payloads and the refusal +rule. No power or commissioning kind exists yet, so no shipped kind uses the +settle hook or `Supersedes`. None of these conflicts with #174. ## Points for a person These need a decision before the increment that depends on them. -- **O1, before C: the interim source of `Prepared` and `Healthy`.** Until it - is decided, the projector stays unwired. +- **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. - **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in every increment until a store is chosen. - **A second person for `DeviceRecovery`.** Not required yet. A person accepted this for now, and it stays open for a later decision. +- **Synthetic staging needs its records imported again, new credentials and + roles, and its old namespace deleted.** The cutover deletes the old records + and reads none of them. Before the new manager runs in an environment, a + person must, in order: + 1. Release every old synthetic allocation, or discard the synthetic state. + 2. Make sure each Device, with its BMC endpoint and identity, and each + capacity exists in the provider project. Records GitOps already manages + stay with it; import by hand only the ones it does not. + 3. Create 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 + 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. + 5. Supply the site's enrollment. + 6. Delete the old `fleet-system-private` namespace and its Secrets. + 7. Delete the publisher's copy of the MachineClass in the consumer project. + Its source names the old `project` field and is immutable, so the + publisher recreates it with `publisherRef`. + 8. After rollout, verify a fresh allocation and a verified release. + + The commands are in [Moving from the Secret-backed + staging](../../config/README.md#moving-from-the-secret-backed-staging). No + run in this repository exercises synthetic staging, so a person runs these + steps in a staging environment before merge. +- **Retiring the single-plane local VM harness.** C removed + `hack/local-vm/run.sh`, `task local-vm:acceptance` and `cmd/fleet-local-vm`, + because the multi-plane local VM mode runs the same workers. A person should + confirm that the single-plane run is not needed. +- **The multi-plane creator webhook gap.** The local Milo in the multi-plane run + enforces the CRD rules but registers no creator webhook. A forged + `spec.creator` is therefore not refused in that run, and the run does not + prove the webhook. A person decides whether the run must install it. Already decided by a person: [where an allocation's private facts live](#where-an-allocations-private-facts-live-o8), that [only `Retire` and `Resolve` skip checks 5 and 6](#admission), and that a `DeviceRecovery` that -no site confirms ends `Failed`, not `OutcomeUnknown`. +no site confirms ends `Failed`, not `OutcomeUnknown`. The [cutover +decisions](#cutover-decisions) are recorded for review and are not yet +confirmed by a person. ## Adding an operation kind @@ -546,7 +934,7 @@ a real API server: | A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | | CEL rules | `TestCRDRules` | | Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | -| Creator recording and caller preservation | `TestHandler`, `TestCreatorAgainstAPIServer` | +| Creator recording and caller preservation, including callers whose credential carries no UID | `TestHandler`, `TestCreatorAgainstAPIServer`, `TestStandaloneCreatorPolicyAgainstAPIServer`, `TestCreatorIdentifiesTheCallerByUsername` | | CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | Increment A has no site, so "nothing was sent" means custody admitted nothing @@ -569,3 +957,25 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | | Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | + +Increment C's tests run with `task test:envtest`, and the smoke runs with +`task standalone:test`: + +| Area | Tests | +| --- | --- | +| Allocation, a losing contender, a retried allocation, installation, reinstallation, release with a wipe, and reuse under a higher fence, against a real API server and a simulator site | `TestAllocateInstallReleaseReuse` | +| Six allocators race for one Device; one allocation remains and custody names it | `TestConcurrentAllocatorsOneWinner` | +| An allocation that never held its Device is deleted and the allocator selects again | `TestAnAllocationThatLostItsDeviceIsReplaced` | +| The quota claim is named from the Machine and granted once; release is observed, not assumed | `TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce`, `TestReleaseIsObservedNotAssumed` | +| Federation: an assignment's round trip, only this cell's observation accepted, a stale fence report ignored, a cell runs only its own assignments | `TestAssignmentRoundTrip`, `TestReflectionIsRejectedUnlessItIsThisCellsObservation`, `TestAStaleFenceReportIsNoReport`, `TestTheCellRunsOnlyItsOwnAssignments` | +| The local VM site: install then wipe, a wipe with a running domain not proven, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipeWithARunningDomainIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | +| Synchronized DHCP follows the open admission; a worker waits for the reservation and for its withdrawal | `TestSyncedDHCPFollowsTheOpenAdmission` | +| The simulator site's token, enrollment and server bounds | `TestReadToken`, `TestReadEnrollmentRequiresCompleteTargets`, `TestNewServerHasFiniteResourceBounds` | +| The manager's synthetic flags, and the creator webhook's trusted caller | `TestSyntheticFlagsRequireAndScopeStaging`, `TestRemovedSingleProjectFlagsAreRejected`, `TestWebhookRequiresTrustedAPIServerClient` | +| Where the component ships | `TestComponentRoots` | +| The standalone smoke: contention, install, a simulator restart and recovery, reinstall, release with a wipe, reuse, and the role checks that keep one writer per kind | `task standalone:test` | + +The multi-plane local VM and Redfish runs (`task multiplane:acceptance` and +`task multiplane:redfish-acceptance`) run the same workers. Their verification +is pending. The acceptance state of each #174 test is in the [coverage +inventory](../../test/acceptance/coverage.md#device-custody-and-operations). diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 76853e3e..e9a51e9f 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -619,8 +619,9 @@ Remove the Secrets and the ConfigMap by hand. The current service never reads them, and they hold Device identity digests, project names and signed control requests that no longer protect anything. If you want a record of the identities the ledger retained, export the Secrets to private storage outside -Git first. Do not delete the `fleet-system-private` namespace: the manager -keeps its own private records there. +Git first. After the Device custody cutover nothing keeps records in the +`fleet-system-private` namespace, so delete it as the last step of [moving +from the Secret-backed staging](../../config/README.md#moving-from-the-secret-backed-staging). Delete in this order, on the host cluster, after the current registration release is running and no older registration pod remains: diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index 767f0644..c4bfd7b6 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -47,10 +47,12 @@ and incomplete cleaning cannot cause duplicate effects or premature reuse. The [device custody and operations work](device-custody.md) replaces per-allocation fencing with one custody record per Device, ahead of real -hardware qualification. Increment A, the inert control-plane foundation, is -implemented, and so is Increment B, the inert site execution framework. -Increments C (cutover) and D (end-to-end failure scenarios) are proposed. An allocation's private facts will live on -its MachineAllocation, which C implements after B. +hardware qualification. Increment A (the control-plane foundation), Increment B +(site execution) and Increment C (the cutover) are implemented. C moves every +mode onto custody and deletes the Secret-backed path. An allocation's private +facts live on its MachineAllocation. The standalone smoke verifies C. Verification +of the two multi-plane runs, local VM and Redfish, is pending. Increment D +(end-to-end failure scenarios) is proposed. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local end-to-end runs, with "nothing sent" proven by the lab BMC audit. diff --git a/docs/enhancements/machine-lifecycle/README.md b/docs/enhancements/machine-lifecycle/README.md index d6394fa6..b3d6dcf1 100644 --- a/docs/enhancements/machine-lifecycle/README.md +++ b/docs/enhancements/machine-lifecycle/README.md @@ -394,7 +394,7 @@ rewritten. It blocks only the claim it belongs to (implemented): Fleet has no automated recovery. An operator disables allocation on the affected capacity, deletes the Machine, removes its finalizer by hand, then deletes that claim's private record Secrets. The -[implementation status](../../development/README.md#undecodable-private-records) +[implementation status](../../development/device-custody.md) lists the steps. GPU, disk, and interface requirements keep numeric constraints with inclusive diff --git a/docs/operations/README.md b/docs/operations/README.md index 0a6f9ac6..915aab13 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -12,11 +12,11 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Task | Guide | What it establishes | | --- | --- | --- | | Build and test locally or run the simulator | [Implementation commands](../development/README.md#build-test-and-run) | Behavior of the implemented code and synthetic provider | -| Exercise allocation, install recovery, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | -| Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | -| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | -| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | -| Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | +| Exercise allocation, install recovery, release with a wipe, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle on Device custody, with a simulator site and namespaces as project stand-ins | +| Understand the local VM site that the multi-plane run drives | [Local VM site](local-vm.md) | The workers that install a real OS over firmware PXE into a disposable libvirt domain, boot it from disk, and wipe it; the single-plane harness is retired; not KVM or hardware qualification | +| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; verification of the run on the custody path is pending; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | +| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; verification of the run is pending; not physical BMC or hardware qualification | +| Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-Device BMC endpoints and provisioning attachments, a reservation feed read from the site store that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | @@ -45,7 +45,9 @@ a successful local smoke run as proof that the production service is ready. `fleet-manager` serves every project that consumes the `metal` service; see [project discovery](../../config/README.md#project-discovery). In production it has no provider and no synthetic integration, so its lifecycle handlers stay -blocked: no allocation, installation, provider call, or custody write. The only +blocked: no allocation, installation, provider call, or custody write. The +production Milo root registers the Device custody kinds and their roles, but +nothing runs the custody coordinator there. The only effect is pinning `status.requestedHardware` and `RequestResolved` on Machines. `/readyz` reports discovery and cache health, not provider readiness, and passing it enables nothing. Fleet ships the code, Milo roles, and manifests; diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 29f139e0..cb149386 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -196,8 +196,9 @@ Each attempt runs in this order: All requests go through the shared Redfish transport guard: the enrolled `https://IPv4:port` only, paths under `/redfish/v1`, no redirects, no environment proxy, and a 1 MiB bound on each response. -`redfish.NewPinnedClient` and `redfish.PinnedTLSConfig` are available to the -provisioning executor too; its behavior is unchanged. +The Redfish site workers use `redfish.NewPinnedClient` and +`redfish.PinnedTLSConfig` too, with the same per-Device credential Secret and +approved pin. A pin the workers cannot match sends nothing. ### Approving a pin diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index e5f7fd4b..5a12bc7a 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -3,7 +3,7 @@ A physical host has addresses that belong to the asset, separate from the addresses a consumer's Machine receives. Fleet records the physical ones in the site enrollment and, for network boot, publishes a DHCP reservation only while an -operation's boot is admitted. The network owner's DHCP applies it and reports +operation's boot is admitted at the Device's stored fence. The network owner's DHCP applies it and reports back; those reports are the evidence that the boot was reachable and that provisioning networking was later revoked. @@ -29,8 +29,8 @@ needs a dedicated provisioning network on the install NIC. ## Enrollment -The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit, retained -mapping of physical assets. It sets a site DHCP mode and, per target, the BMC +The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit mapping of the +Devices a Redfish site serves. It sets a site DHCP mode and, per target, the BMC endpoint, the Redfish System, the boot NIC and, in synchronized mode, the provisioning attachment: @@ -38,7 +38,7 @@ provisioning attachment: { "dhcp": "synced", "targets": [{ - "assetID": "fleet-provider/fleet.datumapis.com/Device/example-01", + "device": "default/server-example-001", "endpoint": "https://192.0.2.20:443", "systemID": "Self", "systemUUID": "00000000-0000-4000-8000-000000000001", @@ -50,6 +50,7 @@ provisioning attachment: } ``` +- **`device`** is the Device's `/` in the provider project. - **`endpoint`** is per target. Physical BMCs each expose one System, often with the same Id (`Self`), so a System is identified by its endpoint plus Id, and by its UUID. @@ -60,17 +61,19 @@ provisioning attachment: address in prefix form and a different host in the same prefix as gateway. Provisioning addresses are unique within the enrollment. -The executor retains the enrollment once and refuses a changed enrollment for -the retained journal. +Before it sends anything, the site worker checks the enrollment against the +operation's admitted snapshot: the BMC endpoint, the system UUID and the boot +MAC. A mismatch ends the operation without an effect. ## Reservation lifecycle In synchronized mode the site serves a reservation feed derived only from the -journal. A target's boot NIC holds its provisioning address while its operation: +site store. A target's boot NIC holds its provisioning address while its +operation's boot admission: -- is the journal's current epoch, binding and fence, and is not done; -- has a boot capability whose window has not expired; and -- has not closed boot admission. +- is at the Device's stored fence, so a superseded operation holds none; +- has a window that has not expired; and +- has not been closed. That window opens at admission, before power-on, so DHCP is ready when firmware asks. The boot handler's narrower rule still decides which scripts and artifacts @@ -80,13 +83,13 @@ The worker gates its effects on reports: 1. **Before arming a network boot** it waits, with no effect, until some DHCP instance reports a feed that serves the boot NIC at its exact provisioning - address, accepted after this operation was admitted. A report from an earlier - operation is not evidence. If the boot window expires first, the operation - stays Unknown and effect-free. + address, accepted after this operation's boot admission was created. A report + from an earlier operation is not evidence. If the boot window expires first, + the worker stops before it arms the boot, and nothing is sent. 2. **Before reporting success** it waits until every DHCP instance that served - the reservation during this operation reports a later feed without it. A - silent instance may still be serving, so the outcome stays Unknown and replay - waits again. Completion therefore includes verified withdrawal. + the reservation during this operation reports a later feed without it, for up to ten + minutes. A silent instance may still be serving, so the worker does not + report success. Completion therefore includes verified withdrawal. Report times are the boot service's clock and admission times the worker's, so both roles must run on synchronized clocks. @@ -98,7 +101,7 @@ what to boot; see the boot-program row below. The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file …`) listens on `:8081`, never on the firmware-facing boot listener. It reads the -journal read-only and writes only `dhcp-applied.log` in the boot-evidence +site store read-only and writes only `dhcp-applied.log` in the boot-evidence directory. Every request needs `Authorization: Bearer `; the token is at least 32 characters. @@ -143,6 +146,6 @@ instance being removed until it reports an empty feed. | Provisioning attachments allocated by Networking/IPAM instead of enrollment values | Proposed | | NIC MACs and BMC endpoints recorded as Fleet inventory observations | Proposed; the enrollment is the only record | | Deployment of `dhcp-feed` and the synchronizer, TLS to the feed, relay and provisioning VLAN at a site | Proposed; not exercised end to end | -| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the executor still arms `Pxe`, which relies on site DHCP for the boot file | +| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer rejects it | | Lab acceptance in synced mode | Not run; the lab uses static DHCP | diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md index d0c03849..7d32b86b 100644 --- a/docs/operations/gitops.md +++ b/docs/operations/gitops.md @@ -23,8 +23,8 @@ under [what is not production](#what-is-not-production). platform cluster hub cluster (host) cell cluster Flux v2.9.6 Flux v2.9.6 Flux v2.9.6 ├ milo-provider ├ karmada (HelmRelease) ├ fleet-coordination (CRD, ns) - ├ milo-consumer-a ├ fleet-host (custody RBAC) ├ fleet-federation (member identity) - └ milo-consumer-b └ karmada-system/… ├ kro (OCI chart HelmRelease) + ├ milo-consumer-a └ karmada-system/… ├ fleet-federation (member identity) + └ milo-consumer-b ├ kro (OCI chart HelmRelease) ├ fleet-karmada-coordination├ fleet-site-base (ns, Retain PVC, identities, ├ fleet-karmada-api │ RBAC, kro grants, admission) └ fleet-karmada-members ├ fleet-site-services (runtime, boot, observer, @@ -43,15 +43,14 @@ under [what is not production](#what-is-not-production). | Milo project API Deployments, etcd StatefulSets, PVCs, Services | Platform Flux (`milo-`) | Harness (it suspends the Kustomization before fault injection) | | Karmada chart | hub helm-controller (`HelmRelease karmada`) | Harness (suspended during reflection faults) | | Handoff CRD, management role, interpreter, member `Cluster`, `PropagationPolicy` on the Karmada API | hub kustomize-controller through the chart's `karmada-kubeconfig` | — | -| Private custody namespace and custodian identity (host) | hub Flux (`fleet-host`) | — | | kro controller | cell helm-controller (`HelmRelease kro`) | — | -| Site namespace, StorageClass, journal PVC, service identities, observer RBAC, kro grants and admission policies | cell Flux (`fleet-site-base`) | kro does not manage these; its delete grants still cover service identities and coordination RBAC (see trust model) | +| Site namespace, StorageClass, site store PVC, service identities, observer RBAC, kro grants and admission policies | cell Flux (`fleet-site-base`) | kro does not manage these; its delete grants still cover service identities and coordination RBAC (see trust model) | | Shared runtime, boot and observer Deployments, boot Service, worker-policy parameter | cell Flux as `fleet-site-services-reconciler` | kro (read only; verified by label, inventory and RBAC), harness (drift is injected, repair is Flux's) | | `ResourceGraphDefinition fleet-handoff-dispatcher` | cell Flux as `fleet-site-graph-reconciler` | — | | `HandoffDispatcher/dispatcher`, including `dispatch` | cell Flux as `fleet-site-dispatch-reconciler`, from a source revision | Harness (dispatch is a pushed revision; the graph-lifecycle fault suspends the layer first) | | Per-operation `w-` ServiceAccounts, Roles, RoleBindings and Jobs | kro only, admission-checked | Flux (verified absent from every inventory) | | `MachineAllocationHandoff` objects and their status | Management/Karmada (intent), site observer (status) | Flux, kro | -| Allocation custody Secrets | Shared lifecycle coordinator | Flux | +| Device custody, operation and allocation records in the provider project | The custody coordinator, the Metal provider and the release controller, each with its own token | Flux, and every source revision | | Credentials: Milo static tokens and serving keys, ServiceAccount tokens, Karmada member Secret | Bootstrap credential enrollment | Any source revision | Fleet and Karmada stay the operation authority and delivery path. Nothing per @@ -112,7 +111,7 @@ hash. | r3 | `dispatch: true`, pushed while the hub is paused; the cell's Flux applies it from the registry | | r4 | Fail-closed: kro chart pinned to a digest no registry serves | | r5 | Recovery: pinned kro chart restored | -| r6 | Retention: the journal PVC removed from the source | +| r6 | Retention: the site store PVC removed from the source | | r7 | Retention: the PVC restored to the source | ## Versions and pins @@ -183,9 +182,8 @@ source, or deleting their Kustomization, never deletes them: - the site and coordination namespaces; - the handoff CRD; -- `fleet-site-retain` and the journal PVC; +- `fleet-site-retain` and the site store PVC; - the RGD and the `HandoffDispatcher`; -- the private custody namespace; - the Karmada `HelmRelease` and member `Cluster`; - each Milo namespace. @@ -196,8 +194,8 @@ or instance lifecycle can delete them. The StorageClass and PVC are also `ssa: IfNotPresent`: Flux creates them once and never updates them. A reconcile, a controller restart or a source change -therefore cannot replace the journal volume. A fresh journal would let replayed -handoffs be admitted as new operations; see the +therefore cannot replace the site store volume. A fresh store would report a lower +fence than the one last admitted; see the [known limitations](multiplane.md#known-limitations-of-the-local-mvp). Retiring a site or unjoining a member is an ordered manual procedure, as in datum-cloud/infra's Karmada runbook. @@ -215,14 +213,14 @@ These phases run in addition to the existing scenarios; see | --- | --- | --- | | `flux-verify` | Each cluster's source is at the pushed digest. Every expected Kustomization and HelmRelease is Ready at the current generation and revision. The kro chart source is at the pinned digest, the Karmada chart artifact matches the pinned SHA-256, and controllers are digest-pinned. Ownership audit: the services, graph and dispatch inventories are exactly their objects. Each shared Deployment, Service, ConfigMap, ServiceAccount, Role, binding, policy and the PVC carries its one Flux layer label, is in that inventory, and has no kro label or owner reference. kro has written nothing before dispatch. No Job, Pod, handoff, Secret or `w-` object is in any Flux inventory. Shared layers do not depend on kro. Protected objects carry `prune: disabled`. | `flux-verify.json`, `flux-initial.json` | | `rbac` | The revoked observer RoleBinding is restored by kustomize-controller under a new UID, not by the harness. As kro's identity, 8 worker-scoped verbs are allowed and 15 others denied, including Deployment, Service, PVC and ConfigMap writes, Jobs outside `fleet-site`, Secrets and handoff status. Server-side dry runs admit worker-shaped objects. They deny, by policy, a Job running as the observer, a privileged Job, another image, a hostPath volume and the host network; a broader Role; a RoleBinding to another Role; and a ServiceAccount outside the worker set. | `flux-rbac-restore.json`, `kro-rbac.json` | -| `flux-graph-lifecycle` | With the install terminal and its workers present, the ownership audit passes. The dispatcher's layer is suspended and the instance deleted. kro removes exactly that handoff's Job, ServiceAccount, Role and RoleBinding. Every shared object, the RGD and the StorageClass keep their UIDs, and the PVC/PV, journal and custody are unchanged. Resuming lets Flux recreate the instance under a new UID, and the recreated Job replays a verified no-op (exit 0). Orphaned terminal Pods are listed. | `flux-graph-lifecycle.json` | +| `flux-graph-lifecycle` | With the install terminal and its workers present, the ownership audit passes. The dispatcher's layer is suspended and the instance deleted. kro removes exactly that handoff's Job, ServiceAccount, Role and RoleBinding. Every shared object, the RGD and the StorageClass keep their UIDs, and the PVC/PV, site store and custody are unchanged. Resuming lets Flux recreate the instance under a new UID, and the recreated Job replays a verified no-op (exit 0). Orphaned terminal Pods are listed. | `flux-graph-lifecycle.json` | | `partition`, `partition-readiness` | Consumer A is stopped by suspending its Kustomization and scaling it to zero. The suspension, UID, generation, zero replicas and no Pods survive the platform root reconciling r3. Resuming leaves Flux to restore it. | `flux-partition.json`, `flux-reconciles.json` | | `dispatch` | Dispatch arrives as r3 through the cell's Flux while the hub is paused | `flux-revisions.json` | | `heal` | Flux on every cluster acknowledges fresh requests and is Ready at the current revision after both node restarts | `flux-reconciles.json` | -| `flux-drift` | Five out-of-band changes are each corrected by Flux, with journal, Jobs, PVC/PV and custody unchanged. helm-controller restores the kro Deployment scaled to 0 (same UID). kustomize-controller recreates the Karmada interpreter deleted on the Karmada API, and reverts a widened `fleet-site-kro` grant. As `fleet-site-services-reconciler`, it recreates the deleted shared boot Service under a new UID with the same fixed ClusterIP, ports and selector, and no kro label. It also restores the shared observer Deployment scaled to 0 (same UID). The dispatcher returns to `ACTIVE` and the ownership audit passes. | `flux-drift.json` | -| `flux-restart` | Every Flux controller Pod on the three clusters is deleted. Each source, Kustomization and HelmRelease then acknowledges a request token issued after the restart. No Helm release revision, inventory, Job, journal or custody changes. | `flux-restart.json`, `flux-reconciles.json` | +| `flux-drift` | Five out-of-band changes are each corrected by Flux, with the site store, Jobs, PVC/PV and custody unchanged. helm-controller restores the kro Deployment scaled to 0 (same UID). kustomize-controller recreates the Karmada interpreter deleted on the Karmada API, and reverts a widened `fleet-site-kro` grant. As `fleet-site-services-reconciler`, it recreates the deleted shared boot Service under a new UID with the same fixed ClusterIP, ports and selector, and no kro label. It also restores the shared observer Deployment scaled to 0 (same UID). The dispatcher returns to `ACTIVE` and the ownership audit passes. | `flux-drift.json` | +| `flux-restart` | Every Flux controller Pod on the three clusters is deleted. Each source, Kustomization and HelmRelease then acknowledges a request token issued after the restart. No Helm release revision, inventory, Job, site store or custody changes. | `flux-restart.json`, `flux-reconciles.json` | | `flux-fail-closed` | r4 leaves the kro chart source and Kustomization not Ready. The graph and dispatcher report `DependencyNotReady` and their new revision is not applied (marker unchanged). The site base and shared services layers are Ready at r4, with every shared object UID and Deployment generation unchanged. The running kro Deployment and site are untouched. r5 converges. | `flux-fail-closed.json` | -| `flux-retention` | r6 drops the PVC from the inventory without deleting it (same PVC/PV UID, journal and custody). r7 re-adopts the same claim. | `flux-retention.json` | +| `flux-retention` | r6 drops the PVC from the inventory without deleting it (same PVC/PV UID, site store and custody). r7 re-adopts the same claim. | `flux-retention.json` | | `flux-final` | All three clusters are at the final revision with nothing suspended, and the ownership audit passes with the cleanup workers present | `flux-final.json`, `flux-ownership-final.json` | ## What is not production diff --git a/docs/operations/local-vm-adversarial-validation.md b/docs/operations/local-vm-adversarial-validation.md index 9dced04a..90a37716 100644 --- a/docs/operations/local-vm-adversarial-validation.md +++ b/docs/operations/local-vm-adversarial-validation.md @@ -1,119 +1,22 @@ -# Local VM prototype: independent validation +# Local VM site: proposed adversarial checks -Review date: 2026-11-14. This report covers a shared, uncommitted working tree. -Only the three new adversarial test files and this report belong to this review. -Implementation files, existing tests, and pre-existing dirty changes were not edited. +[Local VM site](local-vm.md) · [Operations guide](README.md) -## Observed results +Status: **proposed**. This page lists checks to apply to the [local VM +site](local-vm.md). None has been run as written. -Parent follow-up: both findings below are fixed in the shared working tree. -The coordinator now compares every terminal result's input digest with the exact -request, including cleanup and recovered results. Lookup rejects `.` and `..` -before transport. Synthetic executor fixtures now return genuine request digests. -`go test -race ./internal/controller ./internal/executor ./internal/simulator -./internal/milo ./internal/staging ./internal/standalone` passed, including both -new regression tests. This follow-up is not independent approval of the VM adapter. -The original review observations below describe the pre-fix implementation. +Earlier reviews examined the prototype that the cutover to Device custody +deleted: its Secret-backed coordinator, executor client, simulator store and +single-plane executor. Their findings were fixed in that code and are not +retained, because the code is gone. The site that replaced it keeps per-Device +fences, a journal, and results keyed by operation and fence, so several checks +below now map to the site framework's tests, such as +`TestStoreRefusesOlderFencesAndSurvivesARestart` and +`TestAResumedBootIsObservedNotRepeated`. They do not replace a live run. -Commands executed locally: +## Checks -```sh -go test ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone -go test -race ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone -git diff --check -``` - -Both Go commands failed on the two new regression tests described below. Simulator -and standalone packages passed; standalone results were cached. No race warning -was reported. Whitespace validation passed. No VM, Docker, kind, deployment, -external review, or hosted CI resources were started by this reviewer. - -### High: wrong-asset cleanup evidence releases custody - -At review time, `validateTerminalResult` in -[lifecycle.go](../../internal/controller/lifecycle.go) (line 1531) checks operation -ID, kind, phase, completion presence, and result text, but does not compare -`InputDigest` with the exact retained request. Both direct completion and lookup -recovery use this validator. - -[The regression test](../../internal/controller/evidence_adversarial_test.go) -returns a successful cleanup with the requested operation ID and a valid digest -computed for a different physical asset. Both direct and recovered responses -produce `State:Released`, `SafeToRemoveFinalizer:true`, and no error. The waiting -consumer then allocates the asset successfully. These are observed unit-test -results, not a hypothetical gap inferred only from code. - -Required fix: compare verified result evidence against the exact request before -any custody transition, including cleanup and recovery. Missing or mismatched -digests must remain unknown. Update synthetic executor fixtures to supply genuine -request digests rather than allowing absent evidence for compatibility. The -standalone runner's additional install-history digest check does not protect -the coordinator's cleanup path. - -### Medium: dot-segment lookup leaves the operation path - -[client.go](../../internal/executor/client.go) (lines 140–144) rejects slash-bearing -IDs but passes `.` and `..` through `path.Join`. The new -[lookup test](../../internal/executor/path_adversarial_test.go) observes requests -to `/v1/operations` and `/v1`, respectively. A 404 produces no error. This is an -HTTP path-confusion finding; it does not establish shell execution or filesystem -access. - -Required fix: reject dot segments before transport, or construct a URL whose -single opaque path segment cannot be normalized out of the operation endpoint. -Retain the negative tests for both values. - -### Passing adversarial coverage - -[The simulator test](../../internal/simulator/binding_adversarial_test.go) retains -an installation, reopens its store, and individually substitutes asset, binding, -epoch, fence, and image under the same operation ID. Every attempt returns -`ErrConflict` without changing the snapshot. This establishes simulator request -binding, not real executor fencing or artifact verification. - -## Existing coverage evaluated - -- [Lifecycle tests](../../internal/controller/lifecycle_test.go): exclusive - allocation, competing candidate selection, custody tombstones, release and - epoch reuse, missing authority, private predecessor checks, unknown-operation - recovery, malformed completion, retained routing identity, and network cleanup - ordering. Tests predominantly use an in-memory executor and fake Kubernetes - client; they do not demonstrate remote-worker fencing or API-server behavior. -- [Simulator tests](../../internal/simulator/store_test.go): serialized duplicate - submissions, request conflicts, fencing, cleanup retirement, lost responses, - persistence failure boundaries, corrupt-state rejection, and digest retention. - These test synthetic effects; no OS is installed. -- [Standalone reinstall tests](../../internal/standalone/reinstall_test.go): exact - operation recovery across simulator reopen, stale predecessors, concurrent - reinstall convergence, unknown result retaining custody, and rejection of - missing/substituted terminal history. These tests were already dirty/untracked - when this review began and were not authored or modified here. -- [Executor tests](../../internal/executor/client_test.go): authentication, token - rotation, lost-response lookup, malformed evidence, operation-specific result - text, and bounded HTTP timeout. They do not qualify libvirt commands or XML. - -## Real adapter inspection boundary - -During ordinary review, [the image build](../../hack/local-vm/Containerfile), -[installer](../../hack/local-vm/init), and [disk boot script](../../hack/local-vm/boot) -appeared. The installer partitions `/dev/vda`, writes a filesystem and receipt, -installs GRUB, and emits `FLEET-INSTALLED`. The boot script checks an ext4 root on -`/dev/vda1` and emits `FLEET-DISK-BOOT` with the receipt. This is source inspection -only. Separate markers are useful, but there is no observed VM execution here. - -The build generates SHA256SUMS, but its Debian base tag and apt package versions -are mutable. Generated checksums alone do not establish trusted artifact -provenance or prove that the executor enforces an admitted checksum. A reproducible -build and verification of the exact locally built bytes are distinct claims. - -No Go real-VM adapter was present in the inspected source inventory. Final adapter -validation remains pending. The parent should request a fresh review after the -adapter and its execution commands are available; this report is not approval of -implementation added after the inspection boundary. - -## Concrete acceptance assertions still required - -These are proposed checks, not successful results. Run destructive cases only +These are proposed checks, not results. Run destructive cases only against uniquely scoped disposable domains and disks with a decoy resource to detect unintended effects. @@ -137,8 +40,8 @@ detect unintended effects. output, or return a predecessor receipt; readiness must remain unverified. 4. **Restart/retry:** interrupt before command, after effect but before journal update, after completion but before response, and during evidence collection. - Reopen the executor and retry the same operation. Assert one domain/disk set, - stable IDs, no repeated format/install, and bounded recovery. Race two executor + Restart the worker and retry the same operation. Assert one domain/disk set, + stable IDs, no repeated format/install, and bounded recovery. Race two worker processes, not just goroutines. Ambiguous crash windows retain custody instead of blindly recreating or reinstalling resources. 5. **Reinstall predecessor:** require a new Installation naming the durable current @@ -173,39 +76,7 @@ Real hardware and firmware, production Milo/IAM/quota/network integration, and hosted CI qualification remain separate acceptance tracks. The synthetic [standalone smoke](standalone-smoke.md) cannot qualify OS installation. -## Follow-up: adapter durability and regression coverage - -A subsequent independent adapter review identified a missing directory sync -between disk creation and the `prepared` journal transition, plus insufficient -adapter-specific tests. The parent implementation now syncs the created disk and -its operation directory before advancing the journal. Verified serial evidence -files and their directory are also synced before recording the corresponding -verified stage. Journal writes retain their existing root-directory sync. - -Private provider fields allow tests to substitute a temporary state root, command -execution, and directory-sync failure without changing the production constructor -or exposing new configuration. The new -[adapter lifecycle tests](../../internal/localvm/lifecycle_test.go) exercise exact -request substitution, reopened journal replay without duplicate commands, -authority advancement only after cleanup, live-domain cleanup rejection, decoy -preservation, stale cleanup replay after reuse, directory-sync failure propagation, -exclusive disk creation after uncertain preparation, and absent/stale/wrong-stage -receipt recovery without repeating the installer. These are filesystem and fake -command tests, not completed guest installation evidence or power-loss tests. - -## PXE HTTP evidence correction - -Independent review of the PXE implementation corroborated firmware network boot, -DHCP, real installation, and disk-only boot in the saved acceptance run. It also -reproduced a logging defect: a zero-byte failed HTTP write still recorded the -intended response length as admitted delivery. The parent corrected this by -retaining `admitted` as an attempt and adding `write-complete` only when the -response writer reports the entire body written without error. Both adapter and -harness verification now require completed entries. Regression tests cover failed -writes, short writes without errors, and successful writes. - -A completed server write does not prove client receipt. The separate installer -and disk-boot receipts remain mandatory. The earlier saved PXE acceptance run -uses the old attempt-only logs; it is not evidence that this corrected logging -path has passed a fresh VM run. Subsequent end-to-end acceptance must capture the -new entries. Neither logging scheme alone proves successful OS provisioning. +Real hardware and firmware, production Milo, IAM, quota and network +integration, and hosted CI qualification remain separate acceptance tracks. The +synthetic [standalone smoke](standalone-smoke.md) cannot qualify OS +installation. diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index f7b107e2..64929739 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -1,315 +1,110 @@ -# Local Fleet PXE installation with KVM or explicit TCG +# Local VM site -This opt-in development harness uses the existing [lifecycle library](../development/README.md) -and a real disposable Kubernetes API. It does not deploy Fleet or contact a -production cluster. The production manager remains unwired to this provider. +[Operations guide](README.md) · [Multi-plane acceptance](multiplane.md) -Run `hack/local-vm/run.sh` from a workstation with Go, Docker, kind, kubectl and -Python 3. The default KVM mode requires Linux amd64 Docker and working `/dev/kvm`. First build the -`fleet-vm-local` runtime described in infra PR 9332; the runner image supplies -libvirt, QEMU and `fleet-start-libvirt`. The harness builds its own guest installer -and Go executable. It never invokes the infrastructure smoke script. +The local VM site installs a real operating system into a disposable libvirt +domain over firmware PXE. It is one of the sites that run +[Device custody](../development/device-custody.md#cutover-increment-c) work. It +is a disposable acceptance executor, not production hardware control, and it is +not KVM or hardware qualification. -For a local runtime without reliable x86 KVM, explicitly select software execution: +Status: **implemented**. The standalone smoke does not use it. The +[multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) runs it, +and verification of that run after the cutover is pending. -```sh -DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh -``` +## The single-plane harness is retired -`task local-vm:acceptance` runs the same TCG command. For the multi-plane composition -of this provider with Milo and Karmada, use the one-command -[multi-plane acceptance](multiplane.md) harness instead. +Before the cutover, `hack/local-vm/run.sh` (also `task local-vm:acceptance`) +ran the local VM executor against a disposable kind cluster on its own. The +cutover deleted that harness, its `cmd/fleet-local-vm` command, and the old +executor and its journal. The multi-plane local VM mode runs the same workers, +so no separate harness remains. -The named Docker context must already identify your dedicated disposable runtime. -TCG builds a native amd64 or arm64 Debian libvirt/QEMU runner and boots the same -amd64 installer and blank disk, with no simulator or preinstalled guest image. -The installer build requires amd64 container execution (for example Rosetta on -an arm64 Colima runtime). TCG acceptance qualifies the real installation/control-plane -path, **not KVM acceleration**. There is no automatic fallback: invalid modes fail, -the runner checks `/dev/kvm` in KVM mode, and the provider rejects changing the -accelerator for a retained journal. Legacy journals without a mode mean KVM. -Evidence records the explicit accelerator, runtime architecture, and transferred -executable checksum. The executable is checksum-verified before being renamed -into its runnable path, preventing a truncated transfer from being executed. +This is a decision for a person. If a single-plane run is still needed, it must +be rebuilt on the site framework. -The wrapper creates a fresh kind cluster and privileged libvirt container on the -disposable Docker kind network. It mounts no host directories or libvirt sockets. -Installer guests have one e1000 NIC on an isolated libvirt bridge inside the -container. Disk-verification guests have **no NIC**. Libvirt/dnsmasq is the sole -local DHCP/network authority; there is no forwarding, host LAN DHCP, external -bridge, or published HTTP port. NSO, Milo, IAM and quota boundaries remain synthetic. Privilege is restricted operationally to this disposable -Docker environment; this is not a sandbox for untrusted users or guest images. -Failures retain the named container, cluster, private kubeconfigs and executor -journal for recovery. Inspect the printed resource name before removing only -those resources with `docker rm -f NAME` and `kind delete cluster --name NAME`. -Do not share the raw failure directory: it contains local kubeconfig credentials -and private fencing tokens. Successful runs remove credentials and redact tokens. +The earlier execution records, which describe the retired executor, are not +kept. The guest installer and the site image build are still in `hack/local-vm`. -## Implemented contract +## What the site does -The operator-owned capacity fixture references a distinct Device slot; this is -local virtual inventory, not physical discovery or a new Device API implementation. -The harness sets its actual configured CPU/memory bounds and uses the existing -Coordinator to reserve the slot exclusively for a consumer Machine. A second -consumer must receive InsufficientCapacity. IAM, image admission and quota are -explicit local test authorities; NSO, Milo and production network policy are not -claimed. Importing a record does not invoke the adapter. +The workers are in `internal/site/vmwork`. They run on the +[site framework](../development/device-custody.md#site-execution-increment-b), +so each Device has its own fence and journal, and a newer fence stops an older +worker. The site reaches a Device through enrollment, with no BMC. The +enrollment is checked against the admission snapshot before anything is sent. -The adapter implements `executor.Client`. It accepts one fixed asset, one -artifact-manifest-derived image reference, install and cleanup operations. All -resource names derive from hashes of retained operation IDs. Callers cannot -supply XML, commands, paths, URLs, boot arguments, or cleanup targets. One flock -serializes processes. Every exact request, request digest, authority and random -boot receipt is fsynced before effects. The journal survives process restart. -Changed retries conflict; unfinished operations block later operations. Cleanup -closes the allocation epoch; stale authority cannot reopen it. +| Operation | What the worker does | +| --- | --- | +| `DeviceInstallation` | Creates an exclusive blank disk for the installation. Boots the installer once and waits for exactly one console receipt. In PXE mode it also requires completed boot deliveries and a DHCP lease. Then boots from the disk alone and waits for the disk-boot receipt. | +| `DeviceWipe` | Deletes every installation disk of the Device. It refuses while any local domain exists, because it could not prove the disks are unused. | -A pinned Debian base supplies a Linux kernel, BusyBox and GRUB. Package resolution -currently uses Debian repositories at image-build time, so rebuilding is **not -bit-reproducible**. The build emits SHA256SUMS; the executor verifies both artifacts -and derives the admitted image digest from that exact manifest. Changing either -artifact invalidates the admitted image. Retain the built image ID and artifact -manifest when reproducing an acceptance run. +A boot is started once. After a crash or a lost response, the worker observes +the domain and does not start it again. If it cannot show what happened, the +outcome is unknown and custody stays held. A reinstall creates a new blank disk +and a new receipt for the same allocation. A wipe deletes the disks of every +installation of the Device, not only the latest. -The guest firmware obtains DHCP configuration and an HTTP iPXE script, then -fetches the kernel and initrd from the guarded broker. Installer domain XML has -only network boot: no libvirt kernel/initrd or disk-boot shortcut. The guest -installer starts with an empty 2 GiB disk, partitions and formats it, -copies its Linux filesystem, installs GRUB, and writes the operation's random -receipt onto disk. A separate libvirt domain boot uses only that disk: no external -kernel, initrd or installer medium. Its one-shot init script checks that `/` is -`/dev/vda1` ext4, emits the retained receipt on serial, and powers off. Fleet -requires the exact serial line and domain disappearance. Installer exit alone, -QEMU running, an old receipt, or missing evidence never yields installed success. -There is no ongoing guest agent. The minimal guest deliberately powers off after -verification; this does not qualify a production distribution or workload. - -The installer also accepts `fleet.mode=wipe`, which zeroes and verifies the disk. -Only the [Redfish mode](redfish-lab.md) boots it; this harness never selects it, -and its install path is unchanged. - -Reinstall creates a new blank disk and a new receipt under the same allocation. -Prior incarnation disks remain private until cleanup; they are never booted or -exposed to another consumer. Cleanup deletes only retained disks for that exact -binding after verifying no matching domain exists, and verifies absence before -returning the full request-bound clean result. This is disposable-file deletion, -not a claim of physical media sanitization. - -The harness crashes the process after verified provider completion, before the -controller receives its result, then starts a new process to recover the same -Installation. It repeats install and reinstall to verify retries, then releases -and allocates the slot to the waiting consumer. Pending effects without sufficient -evidence remain unknown and require inspection; the adapter does not blindly -restart an installer after an ambiguous libvirt start. - -## Local PXE admission and trust boundary - -The executable now selects `pxe` durably in the journal. Journals from the earlier -direct-kernel prototype cannot silently replay under PXE; there is no automatic -migration or runtime direct-boot option. The accelerator remains separately bound. -Tests retain private direct-mode fixtures for the existing lifecycle regressions. - -A random 256-bit bearer capability is retained with the exact admitted operation, -request digest, asset, allocation, epoch, fence and ten-minute expiry before effects. -The HTTP broker reads the atomic journal on every request and permits only the -current `installer-started` operation with an open, unexpired admission. It serves -only its derived iPXE script and the two manifest-bound artifacts. Artifact bytes -and the manifest are rechecked before delivery. Unknown identity, wrong capability, -stale allocation/fence, closed/revoked/expired admission, unsupported paths and -unguarded artifacts are denied. No general file server is exposed. - -The DHCP boot URL contains a short operation locator and scoped capability; the -locator is deliberately short enough for the legacy BOOTP filename field. MAC/IP -are routing information, not authentication. Delivery over HTTP and DHCP trusts the -single-guest isolated lab and container operator. A tenant or hostile peer on this -network could steal the capability: this is **not production attestation**, TLS -bootstrap, or qualified multi-tenant PXE. The listener is reachable in the disposable -container network but no host port is published. The capability cannot select an -image, asset, operation, URL or arbitrary file beyond its retained admission. - -Expiry/revocation prevents new HTTP retrieval, not execution of a downloaded -installer. The provider first observes domain disappearance and the exact installer -receipt, then closes admission durably. It removes the isolated network before the -separate NIC-free disk boot. Missing observations remain Unknown with capacity held; -no timeout triggers a second installer start. Cleanup still requires every retained -domain absent before deleting disks. Network teardown is local test plumbing, not -NSO/IPAM or production fencing evidence. - -Raw runtime state and failed-run directories are private: the journal and network -XML contain capabilities, and kubeconfigs contain Kubernetes credentials. Successful -exports remove these credentials, scan for retained boot capabilities, and retain -only artifact names, byte counts, DHCP leases and exact non-secret receipts. - -## Evidence and limitations - -Successful output includes DHCP leases, guarded HTTP delivery receipts, live -closed-admission HTTP denial probes, sanitized provider journal, both serial logs and -rendered domain definitions per installation, public Installation status, phase -log, image ID and the final domain inventory. The journal binds receipts to exact -requests including allocation, epoch, fence and image. Readiness assurance is -local trusted-executor evidence, not hardware attestation. The local operator and -container root remain trusted. No remote API or production authorization is added. - -See the separately maintained [adversarial validation report](local-vm-adversarial-validation.md). -Actual execution results must be reported separately; a successful Go build or -synthetic simulator test is not evidence of an OS installation. - -## Execution record (2026-11-14) - -`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, -`hack/validate-doc-links.sh`, and `git diff --check` passed. The Linux executable -and installer image built. Two disposable runs reached real Kubernetes-backed -exclusive allocation and contention rejection. The first real KVM guest booted, -partitioned and formatted its blank disk, then failed during filesystem copying -because BusyBox selected its built-in tar. The installer now calls GNU tar by -absolute path, checks pipeline failures, enables ACPI, and disables automatic -libvirt restart on guest reboot/crash. - -The corrected second run was interrupted by the dedicated Colima VM rebooting -and Docker being gracefully stopped. Subsequent serial-console inspection found -that this reboot followed a nested-KVM host kernel panic, not merely an external -Docker stop. Its journal retained `installer-started` -with an `Unknown` result. The runtime contained only the four containers from -these two runs. One authorized Docker restart restored the internal daemon; -the workstation socket remained unavailable. Restarting the provider daemon -showed no libvirt domains. An attempt to recover the existing installation -exited 139. Subsequent inspection traced exit 139 to an executable truncated at -4,194,304 bytes, compared with the original 37,455,636-byte binary. Restoring that -exact original binary to a separate recovery path, verifying its SHA256, and -retrying the same Installation correctly returned Unknown. No operation was reset -and no disk was reformatted during recovery. -Both runs' resources and private state were retained for inspection. - -**The interrupted KVM attempts did not complete real OS disk boot, post-effect -crash recovery, reinstall, or cleanup/reuse.** The subsequent successful explicit -TCG acceptance is recorded below; it does not qualify this KVM environment. -The original local evidence directory is -`/tmp/fleet-local-evidence.ixHu29`; `summary.json`, `runtime-status.txt`, -`journal-sanitized.json`, `device.json`, and `SHA256SUMS` are safe diagnostic -artifacts. Its kubeconfig files and the raw container journals are private and -must not be published. The retained resource names are -`fleet-local-9c2ad625d67a` and `fleet-local-adcaca5a98e8`, each with a corresponding -`-control-plane` kind container. Inspect those exact resources before cleanup. - -### Follow-up runtime diagnosis +## Installer and artifacts -The dedicated `fleet-e2e-x86` runtime is itself an x86 VM emulated by QEMU TCG on -an Apple Silicon host. A fresh diagnostic run, `fleet-local-9d76bd454637`, reproduced -the host Linux panic at 20:50 CST on November 14, 2026: -`Kernel panic - not syncing: corrupted stack end detected inside scheduler`, -with `Comm: CPU 0/KVM`. The earlier 20:35 CST reboot has the same signature. -The fresh operation also remains `installer-started`/Unknown; its container, -disk, kind cluster and private credentials are retained. No further KVM guest -boots should be attempted in this runtime until the nested virtualization issue -is resolved. The daemon was started only to collect retained diagnostics, without -restarting any provider container or replaying an installer. +A pinned Debian base supplies a Linux kernel, BusyBox and GRUB. Package +resolution uses Debian repositories at image-build time, so rebuilding is **not +bit-reproducible**. The build emits `SHA256SUMS`. The site derives the admitted +image identity from that manifest, and the boot server rechecks the artifact +bytes and the manifest before each delivery. Changing either artifact +invalidates the admitted image. `hack/local-vm/Containerfile` builds the site +image from the `site` target, with the checksum-verified `fleet-multiplane` +binary. -Sanitized panic excerpts and sanitized journals are under -`/tmp/fleet-acceptance-recovery` (`nested-kvm-panic.txt`, -`prior-nested-kvm-panic.txt`, `journal-sanitized.json`, -`first-journal-sanitized.json`, and `diagnostic-journal-sanitized.json`). This -directory also contains private recovery files: share only the named sanitized -files, not the directory. A separate task-owned native arm64 Colima VZ runtime, -`fleet-acceptance-tcg`, was created with no host mounts and without switching the -active Docker context, for explicit TCG acceptance using the updated provider. - -### Successful explicit TCG acceptance (2026-11-14) - -The following command exited zero on November 14, 2026 at approximately 21:03 CST -(November 15, 03:03 UTC), using the parent-updated provider with durable directory -sync, accelerator binding, and lifecycle regression tests: - -```sh -DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh -``` - -The runtime has no `/dev/kvm`. Its native arm64 QEMU executed the real amd64 Linux -guest from the built installer, not a simulator or a preinstalled cloud disk. -The run verified Kubernetes-backed exclusive allocation and contention rejection; -partitioning, ext4 formatting, payload copying and GRUB installation onto a blank -2 GiB disk; a separate disk-only boot with the exact installation receipt; exit 75 -after the provider's durable success and recovery by a new process; exact retries; -a second real installation with a distinct receipt and blank disk; and verified -cleanup followed by exclusive allocation to the waiting consumer. - -The fresh resource `fleet-local-00cf3dc540bb` and its kind cluster were removed -after successful cleanup/reuse. Its credentials were removed from the evidence -directory. The new task-owned Colima runtime remains available, with no containers; -none of the three unknown KVM operations was reset, cleaned, or declared ready. - -Sanitized acceptance evidence is in `/tmp/fleet-local-evidence.gz8QaY`: - -- `summary.json`, `phases.log`, `accelerator`, and `runtime-architecture` record - the result and execution mode. -- `provider/journal.json` contains two succeeded installation operations and one - succeeded cleanup operation, with fences redacted and the allocation closed. -- The operation directories contain both installer and disk serial logs and XML; - the two disk-only boot receipts match their retained operations and differ from - each other. Neither disk domain XML contains a kernel, initrd, or network NIC. -- `provider/installations.json` records both public Installation statuses as Ready. -- `domains-after.txt` is empty, and no `disk.raw` remains in the copied provider state. -- `SHA256SUMS`, `binary-SHA256SUMS`, `source-SHA256SUMS`, and `image-id` identify - the exact tested artifacts. The runner image ID is - `sha256:5047968ca9404706a83199f3808eaf23f94ca7d2fb165dda1f1cd3dfa97ea24b`. - -An independent readback checked these journal, receipt, XML, retry, cleanup and -credential-removal assertions after the harness passed. -`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, ShellCheck on -`run.sh` and `start-libvirt`, documentation links, and `git diff --check` also passed. -The installer has an informational ShellCheck SC2013 diagnostic for intentionally -splitting `/proc/cmdline` into words. Docker reports an intentional fixed-platform -build warning because the installer must remain amd64 on an arm64 runner. - -**This is real OS-install/control-plane acceptance under explicit TCG, not KVM -qualification, production hardware attestation, or a production distribution -qualification.** KVM remains the default and must be qualified separately on a -reliable x86 virtualization host. - -### Successful firmware PXE acceptance (2026-11-14 CST / 2026-11-15 UTC) - -The same explicit TCG command above exited zero with the PXE implementation. -Sanitized evidence is `/tmp/fleet-local-evidence.A5KTID`; its `summary.json` was -produced by a separate readback of the exported artifacts. The runner image ID is -`sha256:2b2c1109b2e11068c03ef25239adec425108898a4299e06a50bce2414ed6e6c3`. -The native arm64 runtime executed amd64 SeaBIOS/e1000 iPXE firmware and Linux with -TCG. This is legacy BIOS PXE, not UEFI or KVM qualification. - -Both fresh blank-disk installations have DHCP leases and guarded requests for -`boot.ipxe`, the 8,234,944-byte kernel and 215,654,737-byte initrd. Readback verified -network-only installer XML with no direct kernel/initrd, real partition/format/ -payload-copy/GRUB logs, distinct exact receipts from separate NIC-free disk boots, -closed admissions, two succeeded installs, succeeded cleanup, no remaining disks -or domains, and allocation to the waiting consumer. The harness also exercised -exclusive contention, exit 75 after durable provider completion, new-process -recovery, repeated exact requests, and reinstall. Twelve live HTTP denials after -reinstall/cleanup cover closed predecessor scripts/artifacts, unknown identity, -unguarded paths and unsupported artifacts; the earlier post-install denial probe -also passed. Expired/revoked admission and cross-operation capabilities were tested -through HTTP against durable synthetic journals in `boot_test.go`, not by expiring -a real destructive guest mid-install. - -`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax, ShellCheck on -`run.sh` and `start-libvirt`, documentation links, and whitespace validation passed. -The successful harness checks exported credentials, XML boot paths, DHCP evidence, -artifact receipts and disk deletion. Its resource `fleet-local-7ad959c9bb50` and -corresponding kind cluster were removed. No production changes or KVM starts were -made. Base image and artifact checksums are retained; apt package resolution still -is not reproducible. - -Two diagnostic attempts remain in the task-owned TCG runtime, each with its -corresponding `-control-plane` kind container and private credentials/state: - -- `fleet-local-d4e060978d40`: the first DHCP URL exceeded the legacy BOOTP filename - capacity. DHCP succeeded but no HTTP request followed. The guest was explicitly - destroyed and absence observed; the operation remains `installer-started`/Unknown. - Private failure directory: `/tmp/fleet-local-evidence.Hs5F4y`. -- `fleet-local-482c67269d19`: after shortening the locator, real PXE install, - disk-only boot, post-effect recovery and exact retries passed. The harness then - stopped because a newly added probe was unsupported by its already-built binary. - Its single installation is Succeeded, no guest domain remains, and its allocated - disk is retained. Private failure directory: `/tmp/fleet-local-evidence.3W7DIL`. - -Only sanitized diagnostic journals and empty domain inventories are exported in -`/tmp/fleet-pxe-diagnostics`. The earlier three unknown KVM resource sets remain -untouched. Neither those nor the failed PXE operation was inferred clean or ready. -The final complete acceptance used a freshly built executable and a fresh resource. +The guest firmware obtains DHCP configuration and an HTTP iPXE script, then +fetches the kernel and initrd from the boot server. The installer domain has only +network boot, with no libvirt kernel, initrd or disk-boot shortcut in PXE mode. +The installer partitions and formats an empty 2 GiB disk, copies its Linux +filesystem, installs GRUB, and writes the operation's random receipt onto the +disk. A separate boot uses only that disk: no external kernel, initrd or +installer medium. Its one-shot init script checks that `/` is `/dev/vda1` ext4, +prints the receipt on the serial console, and powers off. Installer exit, +QEMU running, an old receipt, or missing evidence never counts as installed. +There is no ongoing guest agent. The installer also accepts `fleet.mode=wipe`, +which zeroes and verifies the disk. Only the [Redfish mode](redfish-lab.md) +boots it. + +## Boot admission and trust boundary + +A random 256-bit capability is stored with the operation's admission, at the +operation's fence, with a ten-minute expiry, before any boot. The boot server +reads the site store on every request. It serves a boot only while the +admission is open and unexpired, the token matches, and the fence equals the +Device's stored fence. A superseded operation can never boot the server. It +serves only its derived iPXE script and the two manifest-bound artifacts, and +no general files. Each delivery is logged as an attempt, and as `write-complete` +only when the response writer wrote the whole body without error. + +The DHCP boot URL carries a short operation locator and the capability. The +locator is short enough for the legacy BOOTP filename field. The MAC address and +IP address are routing information, not authentication. Delivery over HTTP and +DHCP trusts the single-guest isolated lab and its container operator. A hostile +peer on the network could take the capability. This is **not production +attestation**, TLS bootstrap, or qualified multi-tenant PXE. + +Expiry or revocation stops new retrievals. It does not stop an installer that has +already downloaded. The worker closes the admission only after it observes the +domain gone and the exact receipt. It then removes the isolated network before the +disk boot. Missing observations stay unknown, and no timeout starts a second +installer. + +## Limits + +- Guests use one e1000 NIC on an isolated libvirt bridge inside the runtime + container. Disk-boot guests have no NIC. Libvirt and dnsmasq are the only DHCP + and network authority. +- The accelerator is KVM or an explicit TCG. The multi-plane run uses TCG, with + an amd64 guest on a native arm64 runtime. TCG qualifies the installation and + control-plane path, not KVM. +- Boot is legacy BIOS PXE, not UEFI. +- Privilege is limited to the disposable container environment. It is not a + sandbox for untrusted users or guest images. +- NSO, Milo IAM and quota are synthetic. The guest has no managed network. + +Validation of earlier prototypes is described in the [adversarial validation +notes](local-vm-adversarial-validation.md). diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 63b70d23..7bcdfe81 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -1,36 +1,40 @@ # Local Milo, Karmada and PXE acceptance This opt-in harness runs native Milo project routing, actual Karmada delivery and -status reflection, and the local VM executor through the existing allocator and -installation lifecycle. On the selected cell, execution runs as Flux-owned -Kubernetes Deployments and kro-created per-operation Jobs; see [Kubernetes-native site execution](site-execution.md). +status reflection, and the [local VM site](local-vm.md) through the allocator and +[Device custody](../development/device-custody.md#cutover-increment-c). On the +selected cell, execution runs as Flux-owned Kubernetes Deployments and +kro-created per-assignment Jobs; see [Kubernetes-native site execution](site-execution.md). Every long-running service is installed by each cluster's own Flux from a source artifact built from the checkout; see [Flux-reconciled local environment](gitops.md). It is not enabled by the production manager or any production overlay. Production authority and deployment equivalence remain **unqualified**. +Status: the run on Device custody is **implemented**. Verification of the local VM +run and of the [Redfish run](redfish-lab.md) on custody is pending. The run +records under [Verification and remaining gaps](#verification-and-remaining-gaps) +were observed on the path before the cutover, with the Secret-backed coordinator, +and are not evidence for the custody path. + Read the [writer placement contract](../architecture/README.md#control-plane-placement-and-writers), [pinned design sources](../architecture/design.md#source-proposals), and -[local VM contract](local-vm.md) first. New multi-plane files implement this -composition. The shared lifecycle adds only the read-only -`Coordinator.ClaimReleased` custody query, and the executor interface documents -exact-request replay and its narrow not-found-plus-Unknown lookup contract. +[local VM site](local-vm.md) first. The [Redfish mode](redfish-lab.md) (`task multiplane:redfish-acceptance`) runs the -same composition with a Redfish executor. Its workers have no libvirt socket and -reach two persistent lab VMs only through the DMTF Redfish Interface Emulator. +same composition with the Redfish site workers. Its workers have no libvirt socket +and reach two persistent lab VMs only through the DMTF Redfish Interface Emulator. ## Topology and versions | Surface | Local implementation | Writer | | --- | --- | --- | -| Provider project | Milo v0.32.5 native `/projects/provider/control-plane` route; dedicated API Deployment and etcd StatefulSet with its own PVC on the platform kind cluster, reconciled by Flux | Bootstrap fixture supplies definitions and observations; allocator retains exclusive custody | +| Provider project | Milo v0.32.5 native `/projects/provider/control-plane` route; dedicated API Deployment and etcd StatefulSet with its own PVC on the platform kind cluster, reconciled by Flux. It holds the inventory and custody CRDs, the Devices, `DeviceCustody`, the operations and the MachineAllocations. It enforces the custody CRD rules. It registers no creator webhook. | Bootstrap fixture supplies definitions and observations. Each component has its own token: the custody coordinator (the only custody writer), the Metal provider (allocations and installations), the release controller (wipes), and a discovery identity (fixture discovery). | | Consumer A / B | Two independently restartable Milo v0.32.5 Deployments and etcds, one Flux Kustomization each; native project routes; both use namespace `default` and Machine name `allocation` | Separate customer credentials create/watch requests; management writes public status | -| Private allocation custody | `fleet-system-private` Secrets on the management host Kubernetes API | Shared lifecycle coordinator, with its own scoped credential | -| Coordination intent | Karmada v1.16.0 API (hub Flux `HelmRelease`), separate from the host Kubernetes API | Management credential creates immutable handoffs; cannot write status | +| Custody coordinator | A workstation process for the run, started by `hack/multiplane/coordinator.sh` | The coordinator's own token. It admits operations, delivers each assignment through Karmada, and accepts the cell's results by fence. | +| Coordination intent | Karmada v1.16.0 API (hub Flux `HelmRelease`), separate from the host Kubernetes API | The coordinator's credential creates immutable handoffs and labels them answered; it cannot write status | | Selected cell | Separate kind Kubernetes API running its own Flux, the Flux-owned shared site services, kro v0.9.4 and the `HandoffDispatcher` graph | Karmada delivers intent; the site observer ServiceAccount is the only local status writer | | Reflected results | Karmada interpreter aggregates each member's identity and observation | Karmada; management validates before projection | -| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG | One bounded kro-created worker Job per handoff invokes `executor.Client`; provider persists exact requests and boot evidence on a retained, Flux-owned PVC | +| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG | One bounded kro-created worker Job per assignment runs the site worker; the site store holds each Device's fence, journal and results, and the boot evidence, on a retained, Flux-owned PVC | The platform integration choices were discovered in these connected sources: @@ -67,9 +71,9 @@ bare Docker container. **This is still a local placement seam:** it is not the platform's complete root/ProjectControlPlane provisioning machinery, Kyverno orchestration, shared root IAM, or project retirement path. Milo's native project routing and project storage are real. Separate roots and etcds -prevent namespace-based isolation shortcuts. The management process runs on the -host, and its private storage shares host infrastructure with Karmada, while -using a distinct API endpoint, namespace and credential. +prevent namespace-based isolation shortcuts. The coordinator and the +management phases run on the host, each with its own credential, against the +provider project's API and the Karmada API. ## Run @@ -108,9 +112,10 @@ Preflight records `evidence/preflight.json`. Prerequisite checks cover tools, the exact Docker context socket, reachability, architecture, memory, CPUs, free disk, amd64 emulation, inotify, and concurrent Fleet runtimes. Readiness checks require the CLI subcommands and location-denial error the harness drives, then -run `go test -race -count=1 ./internal/coordination ./internal/multiplane -./internal/localvm ./cmd/fleet-multiplane`. Failing either blocks before any -resource is created. +run `go test -race -count=1 ./internal/coordination ./internal/custody +./internal/site/... ./internal/multiplane ./cmd/fleet-multiplane`, plus +`./internal/redfish` in Redfish mode. Failing either blocks before any resource is +created. Exit codes and `evidence/result.json` status: @@ -179,7 +184,11 @@ acceptance starts, the run does the following: [bootstrap boundary](gitops.md#bootstrap-boundary)). Flux then installs Milo, Karmada, host RBAC, the Karmada API configuration, kro, the site base and the graph in dependency order; -- enrolls credentials and seeds fixtures; +- enrolls credentials, including one token per provider-project component, and + seeds fixtures; +- starts the custody coordinator on the workstation (the `coordinator` phase, + `hack/multiplane/coordinator.sh`), which also writes fixture discovery through + its own discovery identity. Real BMC discovery is not part of this run; - publishes revision 2, which adds the shared site services and the `HandoffDispatcher` with dispatch disabled. `site.sh check` requires the following: @@ -210,13 +219,14 @@ The phases are then: another Device. It then removes the objects and the CRDs. Milo ignores admission policies stored in a project, so this proves the rules hold there. It sends nothing to any server. -2. **Contention.** Two consumers request one provider capacity. One binding - succeeds; `verify-contention` independently reads Bound for A and +2. **Contention.** Two consumers request one provider capacity. Custody grants one + allocation; `verify-contention` independently reads Bound for A and Pending/InsufficientCapacity for B. -3. **Retained admission before effects.** Installation admission retains core - authority and inputs, then immutable hub intent, before any effect. - `await-delivery` requires the following: - - exactly one Karmada-delivered handoff; +3. **Admission before effects.** The coordinator admits the `DeviceInstallation` + and raises the Device's fence, then writes one immutable hub handoff carrying + that exact assignment, before any effect. `await-delivery` requires the + following: + - exactly one Karmada-delivered assignment handoff; - kro reporting that handoff in `HandoffDispatcher.status.deliveredHandoffs`; - no cell status and no worker Job. 4. **Partition.** Suspend consumer A's Flux Kustomization, stop its API and pause @@ -224,8 +234,8 @@ The phases are then: The cell's own Flux reconciles it from the registry with no hub access. kro creates the per-operation ServiceAccount, Role, RoleBinding and Job from its local replica. -5. **Pod interruption.** `interrupt-pod` waits until the provider journal shows - the install `installer-started` *and* its libvirt domain running. It then +5. **Pod interruption.** `interrupt-pod` waits until the Device's journal shows + the install's installer boot requested *and* its libvirt domain running. It then force-deletes the worker Pod with no grace period. It requires: - no local result; - the Job controller to record the lost Pod and start a replacement in the @@ -235,8 +245,8 @@ The phases are then: the replacement exists, still mid-install. kro must recreate the Job under a new UID for the same operation. 7. **Exact resume.** `resume` requires the recreated Job to be `Complete` with - one succeeded Pod, and the observer to publish `Succeeded` from the journal. - The journal must hold exactly one install. Evidence later proves exactly one + one succeeded Pod, and the observer to publish the stored `Succeeded` result. + The Device's journal must show the installer boot requested exactly once. Evidence later proves exactly one firmware-network installer start followed by exactly one disk-only start. It uses libvirt's append-only QEMU log, plus one `sfdisk`, one installer receipt and one disk-boot receipt in the guest serial logs. `worker-rbac` @@ -251,16 +261,19 @@ The phases are then: 9. **Heal and project.** Restart the hub and the cell node; the cell restart recreates every site Pod from the retained volume. Flux on every cluster must return to Ready at the current revision. Karmada reflects the - result, and management validates the following before public projection: - - the exact selected cell, request and operation; - - allocation, asset, epoch and fence; - - input digest and observation freshness. + result, and the coordinator accepts it only if it is this cell's observation + of exactly the assignment carried, with: + - the assignment's digest, Device, operation and fence; + - a result at the active operation's fence; + - observation freshness. + + Public status then follows custody. Installation is repeated to confirm idempotent recovery. 10. **Pod and Job lifecycle.** `lifecycle` recreates the runtime, boot and observer Pods and deletes the completed install Job; kro recreates the Job, which replays a verified no-op. The following must be unchanged: - - journal bytes; + - the site store's state; - QEMU start count; - PVC/PV identity and `Retain` policy; - domains; @@ -276,43 +289,49 @@ The phases are then: - `flux-restart`: controllers restart without duplicate effects; - `flux-fail-closed`: a broken kro release blocks only the dispatcher layers; - - `flux-retention`: the journal volume is retained when its claim is + - `flux-retention`: the site volume is retained when its claim is removed from the source. See [acceptance coverage](gitops.md#acceptance-coverage). -11. **Invalid and stale results.** With the Karmada `HelmRelease` suspended and its controller stopped, bootstrap - credentials substitute one attribute of the real reflected result at a time: - wrong cell, stale, future, duplicate replicas, wrong intent digest, wrong input - digest, wrong operation ID, incomplete phase, and missing reflection. Management - must reject each. This is fault injection, not a replacement status relay. -12. **Cleanup and reuse.** Cleanup goes through the same federation path and - kro-created Jobs, with synthetic quota settlement. `release-status-a` - requires consumer A's Machine to be Released with Ready False, no - `currentInstallationRef`, and no Fleet finalizer. Consumer B then reuses the - capacity in epoch 2 and must show Bound. -13. **Delivery faults.** `delivery-faults` creates three cell-local handoffs - with cell bootstrap credentials: - - the epoch-1 install under a second name; - - a wrong-cell intent; - - a stale epoch-1 replay. - - Each kro-created Job must fail once with exit 65 by `podFailurePolicy`. - The journal must be unchanged, no status may appear, consumer B must stay - Bound, and kro must prune them once deleted. After B's release, - `release-status-b` repeats the released checks for B. +11. **Invalid and stale results.** With the Karmada `HelmRelease` suspended and its + controller stopped, the harness reopens the answered install handoff and + substitutes one attribute of the real reflected result at a time: wrong + cluster name, foreign observer, duplicate replicas, a future time, wrong + assignment digest, wrong Device, wrong operation, a stale fence, and missing + reflection. The coordinator must ignore each: custody stays unchanged and the + handoff stays unanswered. This is fault injection, not a replacement status + relay. +12. **Release and reuse.** Release creates a `DeviceWipe` through the release + controller. The wipe goes through the same federation path and kro-created + Jobs. `release-status-a` requires consumer A's Machine to be Released with + Ready False, no `currentInstallationRef`, and no Fleet finalizer, and its + Installation Released. Custody then names consumer B's allocation, and B + must show Bound under a higher fence. No mode here has Milo quota, so the quota + claim is not exercised. +13. **Delivery faults.** `delivery-faults` injects three faults with cell + bootstrap credentials: + - the install assignment under a second name, which the API refuses; + - an assignment naming another cell; + - an assignment replayed below the Device's stored fence. + + Each of the last two creates a kro Job that must fail once with exit 65 by + `podFailurePolicy`. The site store must be unchanged, no status may appear, + consumer B must stay Bound, and kro must prune them once deleted. After B + installs and is released, `release-status-b` repeats the released checks for + B. 14. **Wrong location.** With capacity free, the consumer A customer recreates its request with `locationRef: remote-elsewhere`. Allocation must fail with the - location-not-served error. Private custody Secret names/UIDs/resourceVersions, - the provider journal bytes, and the Machine's finalizers and status must be - unchanged. Free capacity rules out contention as the reason for denial. + location-not-served error. The custody records, the site store's state, and the + Machine's finalizers and status must be unchanged. Free capacity rules out contention as the reason for denial. 15. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the boot Service are denied after closure. Evidence requires all of: - - PXE mode, one install and two cleanups, epochs 1 and 2; + - PXE mode, one install and two wipes, each `Succeeded` at its own fence, with + the fences strictly increasing; - completed broker writes and a DHCP lease for the installer NIC; - network-only installer XML, and disk XML with no NIC or direct kernel; - closed boot admission, no remaining domain or disk; - kro-created, `Complete` worker Jobs for exactly the one install and two - cleanups, each with one successful Pod; + wipes, each with one successful Pod; - zero OOM kills. 16. **Final convergence and teardown.** `flux-final` requires all three clusters at the last revision with nothing suspended, and repeats the @@ -321,8 +340,8 @@ The phases are then: ### Failed or interrupted runs -Failures stop this run's exact containers (never delete them) and retain the full -private state; execution and custody are **Unknown**. `result.json` names the +Failures stop this run's coordinator process and its exact containers (never +delete them) and retain the full private state; execution and custody are **Unknown**. `result.json` names the failed phase and the retained containers. Stopping is not release evidence: ```sh @@ -348,62 +367,71 @@ result mapping, and effect-free teardown refusal. ## Implementation and trust boundaries -`internal/coordination.Hub` implements `executor.Client`. It creates an immutable -`MachineAllocationHandoff` under `coordination.fleet.datumapis.com/v1alpha1` and -returns Unknown until a valid reflected observation exists. The request is stored -as a JSON string so API-server normalization cannot reorder opaque input fields -and change the retained executor digest. `spec` is immutable through CRD CEL. -Names derive from the operation ID; a changed request under the same ID conflicts. +**The coordinator.** The custody coordinator (`fleet-multiplane coordinator`) is a +workstation process with its own token. Its loop (`internal/delivery`) reconciles +each Device's custody, builds the assignment for the active operation from custody +and the operation spec as admitted, creates its handoff, collects the cell's +results, and runs the retention sweep. The coordinator configuration names the +cell as the site serving each Device. It is the only custody writer. The Metal +provider creates allocations and installations, and the release controller +creates wipes, each with its own token. An operation's creator is the identity a +`SelfSubjectReview` reports. The local Milo enforces the custody CRD rules and +registers no creator webhook, so this run does not prove that rule. + +**Handoffs.** `internal/coordination.Hub` creates an immutable +`MachineAllocationHandoff` under `coordination.fleet.datumapis.com/v1alpha1`, +labelled with the cell and a role. An assignment handoff carries one assignment +(`spec.device` and `spec.assignmentJSON`). A report handoff has no assignment and +asks for a Device's fence report. The assignment is stored as a JSON string so +API-server normalization cannot reorder it and change its digest. `spec` is +immutable through CRD CEL. The name derives from the Device, the operation UID and +the fence, so a changed assignment under the same name conflicts. kro creates a +worker Job only for an assignment handoff. `internal/coordination.Cell` is split into two least-privilege roles. Both validate that the delivered handoff names this cell, that its name is derived -from the operation ID, and that the intent is valid before anything else. - -- **`Cell.Execute`** runs in the per-operation worker Job (`fleet-multiplane - site-worker`). It looks up the provider journal first, and a terminal - result is not re-executed. When lookup reports the operation not found and - Unknown, the worker re-sends the identical retained request under the same - operation ID. The local provider reports exactly this for a retained but - unfinished operation. The provider replays it against its digest-checked - journal and resumes observing an already-started installer instead of - starting another. Conflict, fencing, transport errors and a found-but-errored - lookup stop before any effect. `Execute` never writes status. +from its assignment, and that the assignment is valid before anything else. + +- **`Cell.Work`** runs in the per-assignment worker Job (`fleet-multiplane + site-worker`). It runs the assignment through the site runner, which fences, + checks and journals every step. A `DeviceRecovery` only raises the fence and + confirms the older worker stopped. An assignment below the Device's stored fence + is refused with exit 65. `Work` never writes status. - **`Cell.Publish`/`Cell.Observe`** run in the observer Deployment - (`fleet-multiplane site-observer`), which uses a read-only provider. Every 10 - seconds it lists this cell's handoffs and publishes an observation only for - a terminal journal result that passes `ValidateResult`. Unknown is never - published, and periodic refresh keeps observation timestamps fresh. + (`fleet-multiplane site-observer`), which reads the site store read-only. Every + 10 seconds it lists this cell's handoffs and publishes, for each, the Device's + seen and stopped fences and, for an assignment, its stored result. It deletes + the site's copy of a result once the coordinator has labelled the handoff + answered. Retries, Pod replacement and dependency ordering belong to the Job controller -and kro. Neither role holds a hub, consumer, provider-project or -private-custody credential. This proves recoverable operation completion, not -ongoing guest health or live production hardware attestation. +and kro. Neither role holds a hub, consumer or provider-project credential. The +coordinator accepts only this cell's observation of exactly the assignment the +handoff carries. This proves recoverable operation completion, not ongoing guest +health or live production hardware attestation. Allocation serves exactly one location, `local`, bound to the configured cell. -`Runner.request` rejects any other Machine `locationRef`, an empty `Config.Cell`, -or a hub client with a different cell. It returns `ErrLocationNotServed` before -claim custody, authority records, finalizers or allocation. The CLI treats this -rejection, conflicts, fencing and invalid requests as terminal instead of -retrying until timeout. - -Release projection runs only after verified cleanup made finalizer removal safe. -Each step is retry-safe. The referenced Installation is retired first (`Released`, -Ready False), then `currentInstallationRef` is cleared and the Machine is -published `Released` with Bound and Ready False. The Fleet finalizer is removed -last, from the server's fresh copy, so the removal is not reverted. Later requests -read terminal custody through `Coordinator.ClaimReleased` and never restore the -finalizer on a released claim. Reuse writes consumer B's Bound status only from -the coordinator's committed binding. The CRD types Installation `status.phase` as -a free-form string with no enum or CEL rule, so `Released` is schema-valid. -`release-status-a` reads it back from the real Milo API. - -`LocalAssetMapping` maps exactly one configured provider-scoped Device identity -to `localvm.AssetID`. It obtains the original retained request from the cell API, -validates the translated provider digest, and returns the original digest. -It never aliases by suffix or moves custody into the cell. This explicit -synthetic hardware enrollment is necessary because the local VM provider accepts -one fixed physical asset ID. No Device/capacity/allocation/Installation identity -is substituted for another. +`Runner.request` rejects any other Machine `locationRef` or an empty +`Config.Cell`. It returns `ErrLocationNotServed` before the quota claim, the +allocation or any finalizer. The CLI treats this rejection, conflicts, fencing +and invalid requests as terminal instead of retrying until timeout. + +Release projection runs only after the allocation is `Released`, which needs every +release gate closed and custody back at `None`, so finalizer removal is safe. Each step is +retry-safe. The referenced Installation is retired first (`Released`, Ready +False), then `currentInstallationRef` is cleared and the Machine is published +`Released` with Bound and Ready False. The Fleet finalizer is removed last, from +the server's fresh copy, so the removal is not reverted. Reuse writes consumer B's +Bound status only from the allocation custody committed. The CRD types +Installation `status.phase` as a free-form string with no enum or CEL rule, so +`Released` is schema-valid. `release-status-a` reads it back from the real Milo +API. + +The site enrolls each Device it serves. The local VM site's enrollment is +`config/site/base/enrollment.json`, and the Redfish site's is built by +`redfish-enroll`. Fixture access checks it against the admitted snapshot before +any effect. No Device, capacity, allocation or Installation identity is +substituted for another. Cell site identities are as follows: @@ -418,31 +446,40 @@ Cell site identities are as follows: per-operation shape. It has no Deployment, Service, volume, Secret or handoff spec/status write. -Management's hub Role grants intent create/get/list/watch but no status writes. -Karmada uses a separate member ServiceAccount with namespace-scoped intent -writes. It also has cluster-wide read/watch for handoffs, because its member -informer lists that resource across namespaces, and it can read -nodes/pods/namespaces and discovery/health endpoints. It has no Secret-reading -permission or local status-writing grant. Management and Karmada tokens are -24-hour local ServiceAccount tokens; the harness does not refresh them for -long-running deployments. Bootstrap administrator credentials remain on the -host. No cell credential leaves the cell: the cell kubeconfig export from the -previous design was removed. +The coordinator's hub Role grants handoff create, get, list, watch and patch (to +label a result answered, while the spec stays immutable), but no status writes. Karmada uses a separate member +ServiceAccount with namespace-scoped intent writes. It also has cluster-wide +read/watch for handoffs, because its member informer lists that resource across +namespaces, and it can read nodes/pods/namespaces and discovery/health endpoints. +It has no Secret-reading permission or local status-writing grant. Coordinator and +Karmada tokens are 24-hour local ServiceAccount tokens; the harness does not +refresh them for long-running deployments. Bootstrap administrator credentials +remain on the host. No cell credential leaves the cell. Milo static-token RBAC grants live in the native root RBAC store, where its RBAC -authorizer reads them. Customer tokens cannot write status or read Secrets. -Management uses separate project read/status roles. Tests also delete the cell -RoleBinding, verify denial, and restore that exact binding. These tests establish -Kubernetes RBAC behavior, not caller-preserving production Milo IAM. +authorizer reads them. Customer tokens cannot write status or read Secrets. The +coordinator, the Metal provider, the release controller and the discovery identity +each have a separate provider-project role (`hack/multiplane/milo.py`). The +management phases use separate project read/status roles. Tests also delete the +cell RoleBinding, verify denial, and restore that exact binding. These tests +establish Kubernetes RBAC behavior, not caller-preserving production Milo IAM. The local runner's catalog, publication, hardware observations, source-use -admission, quota holds and settlement are explicit synthetic fixtures. Concrete -synthetic contract records and the existing lifecycle custody are durable before -effects. Networking is deliberately empty; no NSO/IPAM/routing implementation is -substituted. Adoption and production service readiness are never enabled. +admission and fixture cleaning policy are explicit synthetic fixtures, and no +quota system serves the run. The MachineAllocation, custody and operation records +are durable before effects. Networking is deliberately empty; no NSO/IPAM/routing +implementation is substituted. Adoption and production service readiness are never +enabled. ## Verification and remaining gaps +The records below, up to [Offline checks](#offline-checks), were observed on the +path before the cutover to Device custody. They used the Secret-backed +coordinator, a site-wide provider journal and a single-writer `executor.Client`. +They show what the earlier composition proved, and the Flux, kro and Karmada +findings there still describe the same infrastructure. They are not evidence for +the custody path. Verification of the local VM run on custody is pending. + ### Flux-owned shared site acceptance (2026-11-16) This run verifies the current ownership split: the cell's Flux owns the shared @@ -867,79 +904,68 @@ were never treated as release evidence. go test -race -count=1 ./... go vet ./... task multiplane:test-harness # includes hack/multiplane/test-k8s-evidence.py -shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime +shellcheck -S warning hack/multiplane/*.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime git diff --check ``` -Deterministic Go tests cover these result faults: wrong-cell, stale/future, -duplicate, missing, wrong operation/digest/allocation/epoch/fence, and Unknown. -They also cover: - -- the worker/observer split: the worker never writes status, and the - observer never executes and never publishes Unknown, absent or mismatched - journal results; -- delivery faults fencing before effects, and cell-label selection; -- restart recovery and exact local asset mapping; -- boot-origin and libvirt-URI validation, and read-only providers; -- boot evidence kept outside the journal directory; -- NAT forwarding only for a remote boot Service; -- project identity collisions, concurrent allocation, and unknown cleanup - preventing capacity reuse. +Deterministic Go tests cover, among others: + +- allocation, installation, release and reuse on custody against a real API server + (`TestAllocateInstallReleaseReuse`, `TestConcurrentAllocatorsOneWinner`, + `TestAnAllocationThatLostItsDeviceIsReplaced`); +- the federation layer: an assignment's round trip, only this cell's observation + accepted, a stale fence report ignored, and a cell running only its own + assignments (`internal/coordination`); +- the local VM site: install then wipe, a resumed boot observed and not repeated, + and the boot server serving only an open admission at the stored fence + (`internal/site/vmwork`); +- the site framework's fences, journal, deadlines and results (`internal/site`); +- location rejection before allocation (`internal/multiplane`). They do not pretend to implement Karmada, kro or the Job controller in memory. Only the live command establishes federation, kro, Job and PXE acceptance. -A known shared-lifecycle diagnostic edge remains: contenders with identical -Machine UIDs in different projects can receive `ErrRecordInvalid` rather than -`InsufficientCapacity`. Tests accept either fail-closed outcome and require one -exclusive winner and no reuse after Unknown cleanup. This harness does not edit -shared core lifecycle code to change that behavior. - ### Known limitations of the local MVP -Independent review on 2026-11-15 found no blocking safety issue for this -disposable local MVP. It recorded these limits, which the harness does not hide: - -- **The provider journal is the sole fence.** The local provider's - `/var/lib/fleet-local/journal.json` alone binds operation IDs, allocation epoch, - fence and receipts to the physical asset. If provider state is deleted or - replaced and old handoffs are replayed, the provider admits them as new and can - re-image the disk. That is acceptable only because every site volume here is - disposable and created fresh per run. The volume uses `Retain` and is not - managed by kro, but nothing prevents an operator from deleting the PV. Never - reset, delete or replace a journal for a provider whose device or disk is - retained. +Independent review on 2026-11-15 found no blocking safety issue for the +disposable local MVP of the earlier composition. These limits still apply, and +the harness does not hide them: + +- **The site store is the fence.** Each Device's highest fence, the older-worker + stop confirmation and its journal live in the site store on the retained + volume. If the store is deleted or replaced, the site reports a lower fence than + the coordinator last admitted, and it no longer refuses older assignments. That + is acceptable only because every site volume here is disposable and created + fresh per run. The volume uses `Retain` and is not managed by kro, but nothing + prevents an operator from deleting the PV. Never reset, delete or replace the + store of a site whose Device or disk is retained. - **Location validation is local to this runner.** `ErrLocationNotServed` is enforced by `internal/multiplane.Runner.request` for its single `local` - location and configured cell. The shared allocator, the standalone runner and - the production manager do not implement location binding. -- **Some crash windows remain Unknown indefinitely.** These include an ambiguous - `virsh create` after `installer-started` or `disk-started` was retained, a crash - after disk creation but before `prepared` (exclusive creation then refuses to - overwrite), and a lost PXE network, lease or broker delivery. The provider will - not restart a possibly executed installer. Custody, capacity and diagnostics stay - retained. Do not reset the journal or retry under new authority to "unstick" it. - No automated operator resolution exists. Resolving such a run means discarding - the whole disposable topology after inspection (`teardown.sh --discard-unknown`). -- **Test coverage seams.** Deterministic tests use identical scoped and physical - asset IDs in places and exercise recovery through the non-PXE provider path. - The live run is therefore the evidence for real firmware PXE with in-flight - worker Pod and Job interruption, exact resume and a single installer start. + location and configured cell. The shared allocator and the production manager + do not implement location binding. +- **Some crash windows leave an operation unknown.** These include an ambiguous + `virsh create` after a boot step was journaled, a crash after disk creation but + before the step was recorded (exclusive creation then refuses to overwrite), and + a lost PXE network, lease or broker delivery. A worker does not start a possibly + executed boot again, and custody holds the Device. A person settles the hold + with a `DeviceRecovery`, which this run does not exercise. In the run, the only + resolution is to discard the whole disposable topology after inspection + (`teardown.sh --discard-unknown`). - **Single-node site.** The runtime, boot service, observer and workers share - one kind node and one `ReadWriteOnce` local-path volume; the journal lock + one kind node and one `ReadWriteOnce` local-path volume; the per-Device lock depends on that. Losing the runtime Pod stops any running guest; the - operation then stays Unknown. Multi-node or HA execution is not designed. + operation then stays unknown. Multi-node or HA execution is not designed. - **kro is a broad reader, and graph authors are trusted.** kro must read - delivered handoffs, including the fence token in `requestJSON`, to enumerate - them. Its informers need cluster-wide get/list/watch on every referenced - kind. Its writes are namespaced and admission-checked, but an admitted worker - still reaches root libvirtd and the journal; see the + delivered handoffs, including each assignment, to enumerate them. Its informers + need cluster-wide get/list/watch on every referenced kind. Its writes are + namespaced and admission-checked, but an admitted worker still reaches root + libvirtd and the site store; see the [trust model](site-execution.md#ownership-and-trust-model). Disabling `dispatch` or deleting a handoff prunes worker Jobs without cancelling effects. See [site execution](site-execution.md#lifecycle-and-retention). - **Shared-service revisions roll the runtime.** A services-layer change, such as a new site image, recreates the runtime Pod and stops any running guest. - The operation then stays Unknown. No migration from the earlier kro-owned + The operation then stays unknown. No migration from the earlier kro-owned composition is implemented. Retained historical Jobs also have immutable pod templates: changing the runtime-derived worker image may block kro dispatch. This upgrade risk has not been exercised; image upgrades require a fresh @@ -954,8 +980,12 @@ disposable local MVP. It recorded these limits, which the harness does not hide: External Secrets. The Karmada API is reconciled with its admin kubeconfig, and the three clusters share one VM. Revisions are staged from the checkout; nothing is published. See [what is not production](gitops.md#what-is-not-production). - The journal volume's Flux policy (`prune: disabled`, `ssa: IfNotPresent`) + The site volume's Flux policy (`prune: disabled`, `ssa: IfNotPresent`) protects it from reconciliation, but not from an operator deleting the PV. +- **No creator webhook, and no real BMC discovery.** The local Milo enforces the + custody CRD rules but registers no creator webhook. Fixture discovery writes + Device status through a separate discovery identity on the workstation; real + BMC discovery is not part of the run. - **Qualification scope.** A non-disposable provider, KVM, UEFI, real hardware/BMC, production Milo IAM, quota and networking remain out of scope. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 92edf39b..029fadc1 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -1,19 +1,28 @@ # Redfish-mode acceptance with the DMTF Redfish Interface Emulator This opt-in mode of the [multi-plane acceptance](multiplane.md) replaces the -cell worker's libvirt path with a Redfish executor. Workers reach two persistent -lab VMs only through the DMTF Redfish Interface Emulator and a small lab-only -adapter. Everything else is the existing pipeline: +cell worker's libvirt path with the Redfish site workers +(`internal/site/redfishwork`). Workers reach two persistent lab VMs only through +the DMTF Redfish Interface Emulator and a small lab-only adapter. Everything else +is the same pipeline: - native Milo project APIs; -- the shared allocator and installation lifecycle; +- the allocator and [Device custody](../development/device-custody.md#cutover-increment-c), + with the coordinator running on the workstation; - Karmada delivery and reflection; - kro-created per-operation Jobs; - Flux-owned shared services. +Status: the Redfish workers are **implemented and verified** by unit tests, +including against TLS BMC stubs. The multi-plane Redfish run on custody is +**implemented**, and its verification is pending. The execution records at the +end of this page describe runs on the path before the cutover. + It is a **local MVP proof**, not hardware qualification. No physical server, BMC, -vendor Redfish implementation, UEFI firmware, TLS or production secret store -was involved. See [what remains unqualified](#limitations-and-physical-hardware-readiness). +vendor Redfish implementation, UEFI firmware or production secret store was +involved. The lab BMC serves TLS with a key generated for each run, but that key +is not a vendor certificate. See [what remains +unqualified](#limitations-and-physical-hardware-readiness). ```sh task multiplane:redfish-acceptance @@ -45,7 +54,7 @@ digest and the archive provenance are recorded in `evidence/image-id` and `evidence/redfish-upstream.json`. **No OpenStack component is used.** The image contains no Sushy, sushy-tools, -Ironic or VirtualBMC. The Fleet executor's Redfish client is built on gofish +Ironic or VirtualBMC. Fleet's Redfish client is built on gofish ([BMC client library](#bmc-client-library)). `hack/multiplane/test-redfish.py` fails if any of these names appears in the lock file, adapter or image definition. @@ -68,6 +77,7 @@ does not fork or patch upstream files. | Concern | Served by | | --- | --- | | Service root, Systems collection and members, Chassis, Managers, ActionInfo, routing and JSON serialization | Upstream, unmodified | +| TLS on port 8443 with a certificate and key from a mounted Secret, generated for each run | Adapter | | HTTP Basic authentication against a mounted credential (the service root stays anonymous, per the Redfish specification) | Adapter | | `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | | `PowerState` read from libvirt on every System read | Adapter | @@ -87,22 +97,23 @@ upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. cell Flux layers (Redfish overlays of config/site) fleet-site-runtime (privileged) fleet-site-bmc (unprivileged, all caps dropped) libvirtd + QEMU TCG ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter - lab-target-a lab-target-b ▲ Redfish over HTTP, Basic auth - (persistent disks, serial capture) │ Service 10.96.0.81:8000 + lab-target-a lab-target-b ▲ Redfish over TLS (pinned key), Basic auth + (persistent disks, serial capture) │ Service 10.96.0.81:8443 │ firmware DHCP/iPXE (static) │ ▼ │ - fleet-site-boot (journal read-only) kro worker Job (per handoff, Redfish only) - per-MAC chain, artifacts journal rw, boot evidence ro, - console capture ro, BMC credential + fleet-site-boot (site store read-only) kro worker Job (per handoff, Redfish only) + per-MAC chain, artifacts site store rw, boot evidence ro, + console capture ro, per-Device credentials ``` | Component | Owner | Holds | | --- | --- | --- | | `fleet-site-runtime` Deployment | Flux `fleet-site-services` (Redfish overlay) | libvirtd and QEMU; creates the two 2 GiB target disks once on the retained volume (`lab-disks`) and the console capture directory (`lab-console`) | -| `fleet-site-bmc` Deployment and Service (fixed ClusterIP `10.96.0.81`) | Flux `fleet-site-services` | The emulator and adapter; the libvirt socket, NVRAM and audit (`bmc-state`), and the credential Secret | +| `fleet-site-bmc` Deployment and Service (fixed ClusterIP `10.96.0.81`, port 8443) | Flux `fleet-site-services` | The emulator and adapter; the libvirt socket, NVRAM and audit (`bmc-state`), the credential Secret and the TLS Secret | | `fleet-site-bmc` ServiceAccount | Flux `fleet-site-base` (Redfish overlay) | No API token | -| `fleet-site-bmc-credentials` Secret | Created by the harness in the `redfish-enroll` phase; in no source revision or Flux inventory | A synthetic username and a random 256-bit password per run | -| Boot service and observer | Flux, as before | The Redfish read-only provider; no credential | +| `fleet-site-bmc-credentials` and `fleet-site-bmc-tls` Secrets | Created by the harness in the `redfish-enroll` phase; in no source revision or Flux inventory | A synthetic username, a random 256-bit password and a TLS key and certificate generated per run | +| One credential Secret per Device in the `fleet-site-credentials` namespace, named `bmc-` and 20 hex digits of the Device's SHA-256, labelled `fleet.datumapis.com/bmc-credential` | The harness, in `redfish-enroll` | The same username and password, and `tlsPublicKeySHA256`, the digest of the run's BMC key: each Device's approved pin. This follows the [BMC discovery](bmc-discovery.md) contract. Each operation's worker may get only the Secret of the Device its assignment names. kro derives that name, no handoff field names it, and the worker cannot list, watch or get another's. The `worker-rbac` and `delivery-faults` phases check this. | +| Boot service and observer | Flux, as before | They read the site store; no credential | | `w-` Job, ServiceAccount, Role, RoleBinding | kro, as before | The Redfish worker; **no libvirt socket**, no lab disks | Flux selects the overlays with the same source revision: in Redfish mode the @@ -113,86 +124,77 @@ ownership audit covers the BMC Deployment, Service and ServiceAccount. ### Lab targets: identity before allocation -| Target | Redfish System | UUID | NIC MAC / lease | Fleet asset | Role | +| Target | Redfish System | UUID | NIC MAC / lease | Device | Role | | --- | --- | --- | --- | --- | --- | -| A | `System-1` | `7f3d0c2e-…-0a1b2c3d4e0a` | `52:54:00:77:01:0a` / `.10` | `…/Device/synthetic-device-central-01` | The only published capacity | -| B | `System-2` | `7f3d0c2e-…-0a1b2c3d4e0b` | `52:54:00:77:01:0b` / `.11` | `…/Device/synthetic-device-central-02` | Enrolled, never allocated; proves target isolation | +| A | `System-1` | `7f3d0c2e-…-0a1b2c3d4e0a` | `52:54:00:77:01:0a` / `.10` | `fleet-provider/synthetic-device-central-01` | The only published capacity | +| B | `System-2` | `7f3d0c2e-…-0a1b2c3d4e0b` | `52:54:00:77:01:0b` / `.11` | `fleet-provider/synthetic-device-central-02` | Enrolled at the site only, never a Device: it shares the lab BMC's key; proves target isolation | The disks, domain UUIDs and MACs exist before any allocation. Each installation or cleanup reuses target A's single persistent disk. The site enrollment is an -explicit asset-to-System mapping in the worker template, with each target's BMC +explicit Device-to-System mapping in the worker template, with each target's BMC endpoint, System Id, UUID, MAC, disk size and console capture name. The lab sets `"dhcp": "static"` because its dnsmasq leases are fixed; see -[Boot network](boot-network.md) for synchronized DHCP. The executor writes the -enrollment once into the journal directory and refuses a changed enrollment -later. - -## Redfish executor contract - -The [site framework for Device custody](../development/device-custody.md#site-execution-increment-b) -ports the install and wipe phases below to per-Device fencing, a per-Device -journal and per-Device credentials with the approved TLS pin. It is -implemented and inert. This lab still runs the executor described here until -the cutover. - -`internal/redfish` implements `executor.Client` behind the unchanged -`LocalAssetMapping`, coordination and lifecycle code. It has no process -execution, libvirt client or lab dependency. A Go test parses its imports to -enforce this. `Open` refuses a `FLEET_LIBVIRT_URI` and a mounted -`/run/fleet-libvirt`, so a Redfish worker has no hypervisor fallback. - -**Discovery (GETs only).** The executor walks the service root to the Systems -collection and reads every member. Exactly one member must carry the enrolled -UUID, and it must have the enrolled Id. A member with the enrolled Id and -another UUID is a renumbered or swapped target and is refused. The reset target -and ActionInfo must belong to that System. `On`, `ForceOff`, `Pxe` and `Hdd` must -be advertised, and `Once` too when the System advertises its enabled values. It -never follows redirects or `@odata.id` paths outside `/redfish/v1`. A rejected -credential, a missing capability or an identity mismatch leaves the operation -`admitted`, Unknown and effect-free. +[Boot network](boot-network.md) for synchronized DHCP. Before any request, the +worker checks the enrollment against the admitted snapshot. + +## Redfish worker contract + +The Redfish workers (`internal/site/redfishwork`) run on the [site framework for +Device custody](../development/device-custody.md#site-execution-increment-b). +The framework owns the per-Device fence, the journal, the credential lookup, the +TLS pin and identity checks, the deadline and result delivery. A worker has no +libvirt client or lab dependency. A Redfish site refuses a libvirt URI and a +mounted libvirt socket, so a Redfish worker has no hypervisor fallback. + +**Credential, pin and identity (GETs only).** Before any effect, the framework +reads the Device's own credential Secret and connects only to the key its +approved pin names. It walks the service root to the Systems collection and +reads every member. Exactly one member must carry the enrolled UUID, and it must +have the enrolled Id. A member with the enrolled Id and another UUID is a +renumbered or swapped target and is refused. The reset target and ActionInfo must +belong to that System. `On`, `ForceOff`, `Pxe` and `Hdd` must be advertised, and +`Once` too when the System advertises its enabled values. It never follows +redirects or `@odata.id` paths outside `/redfish/v1`. A rejected credential, a +missing capability or an identity mismatch sends nothing. **BMC client library.** See [BMC client library](#bmc-client-library) for which requests go through gofish and which helpers are deliberately not used. -**Exact inputs before effects.** The journal retains these before any Redfish -request, under the same lock and fencing rules as the libvirt provider: - -- the exact request and its digest; -- the enrolled target; -- a random receipt and boot capability, with a 20-minute boot window; -- allocation epoch, binding and fence. - -The discovered System is retained before the first effect. +**Exact inputs before effects.** The assignment carries the operation's inputs +exactly as admitted, with their digest, the fence and the snapshot. The framework +checks the digest, the fence and the enrollment, and journals each step before it +sends it. The worker records a boot admission with a random receipt and +capability and a 20-minute window, at the operation's fence. **Phases.** An install is a network-boot installer phase (`Pxe`) followed by a -disk-boot phase (`Hdd`). A cleanup is one network-boot wipe phase. Each phase -proceeds in order: +disk-boot phase (`Hdd`). A wipe is one network-boot phase. Each phase proceeds in +order: -1. Power off if needed. This is idempotent, because nothing of the phase has +1. Power off if needed. This is safe to repeat, because nothing of the phase has booted. -2. Arm a one-time override and read it back. -3. Retain `-requested`, then `POST Reset On`. -4. Observe until the phase may have started. -5. Wait for the exact receipt and power off. - -**Lost responses and recovery.** HTTP success is never evidence. Any sign of a -boot is treated as "may have run", and the phase is never requested again: - -- power not `Off`; -- the one-time override consumed; -- a boot delivery for the operation; -- a receipt. - -A repeated `On` is sent only when the target is still `Off`, still armed and -silent after a 45-second settle window, within three retained attempts. +2. Arm a one-time override. This is safe to repeat. +3. In synchronized DHCP mode, wait until DHCP applied the reservation. See [Boot + network](boot-network.md). +4. Journal `-power-on`, then `POST Reset On`. +5. Wait for exactly one console receipt, and for a network boot, the boot + server's delivery evidence, and power off. + +**Lost responses and recovery.** HTTP success is never evidence. Power-on is the +only step that is not sent again: after a crash or a lost response, a resumed +worker observes whether the boot began. Any sign of a boot counts: power not +`Off`, a consumed one-time override, a boot delivery for the operation, or a +receipt. With no sign, the outcome is unknown and nothing is sent again. The old +executor sent `On` again, up to a small budget, when the server was still off and +armed after a settle window; the workers do not. **Completion.** A phase completes only with exactly one console line `FLEET-INSTALLED:`, `FLEET-DISK-BOOT:` or `FLEET-WIPED::`, and power `Off`. A second identical receipt means a duplicate execution and fails rather than succeeding. The installer phase also requires completed boot deliveries of the script, kernel and initrd; -boot admission then closes durably. Worker exit codes and the -Job/observer/management split are unchanged: +boot admission then closes. Each verified phase is journaled, so a resumed +worker continues from the next phase. Worker exit codes and the +Job/observer/coordinator split are unchanged: [exit 0 never implies readiness](site-execution.md#authority-and-failure-contract). **Cleanup uses a booted environment.** The wipe environment is the same pinned @@ -210,9 +212,9 @@ or DCO areas, firmware caches or crypto-erase. newest release at adoption, BSD-3-Clause, no transitive module dependencies). It replaced the handwritten `net/http` request helper and the `map[string]any` decoding of the service root, Systems collection and ComputerSystem. The -provider (`provider.go`) is unchanged: it still owns validation, the journal, -sequencing, recovery and results, and calls the same `Discover`, `Observe`, -`SetBootOnce` and `Reset` methods. +Redfish workers call its `Discover`, `Identify`, `Observe`, `SetBootOnce` and +`Reset` methods. The site framework owns validation, the journal, sequencing, +recovery and results. **What gofish provides here:** @@ -232,11 +234,10 @@ sequencing, recovery and results, and calls the same `Discover`, `Observe`, query on a mutation, `OData-Version: 4.0`, and a 1 MiB response bound. A link returned by the BMC cannot send the credential elsewhere. Redirects are never followed. The environment proxy is not used, so the credential goes - only to the enrolled endpoint. The executor's TLS uses the system trust - store. `NewPinnedClient` verifies a BMC by the SHA-256 of its leaf public key - instead, through the same guard; [BMC discovery](bmc-discovery.md) uses it, - and the executor does not yet. The endpoint must still be a literal - `http(s)://IPv4:port`. + only to the enrolled endpoint. `NewPinnedClient` verifies a BMC by the SHA-256 of + its leaf public key instead of the system trust store, through the same guard. + [BMC discovery](bmc-discovery.md) and the site workers both use it, with the + Device's approved pin. The endpoint must still be a literal `http(s)://IPv4:port`. - **Identity and capability checks.** These are unchanged: one UUID match across all members with the enrolled Id, a reset target and ActionInfo on that System, and `On`, `ForceOff`, `Pxe`, `Hdd` and `Once` checked against @@ -279,7 +280,7 @@ newest release) was rejected for these reasons: - Its `bmc` power facade tries the next provider after an error. Its vendor providers (Dell, Supermicro, ASRockRack, OpenBMC, IPMI) target BIOS, -firmware and virtual-media work that this executor does not perform. **No +firmware and virtual-media work that the workers do not perform. **No vendor-specific compatibility is added by this change.** It reuses a maintained Redfish client and schema model. It also fixes collection paging and adds `If-Match` on the boot override. @@ -299,12 +300,16 @@ and adds `If-Match` on the boot override. These are documented lab seams, not production designs: -- **Credential.** HTTP Basic over plain HTTP on the cell network, with one - synthetic per-run credential shared by the adapter (server side) and Redfish - workers (client side). There is no TLS, rotation, vault or per-BMC account. - The Secret is never in Git, a source revision or evidence. The harness keeps - the password in a `.token` file so the evidence secret scan covers it. Worker - and harness logs print outcome classes only. +- **Credential and transport.** HTTP Basic over TLS. The harness generates one + synthetic username, password and TLS key for the run. The adapter serves that + key. Each Device has its own credential Secret, which holds the shared username + and password and the key's digest as its approved pin. A worker connects only to + that key, so a different key aborts the handshake before any credential is sent. + The lab seam is that one key and one account serve both targets. There is no + rotation, vault or per-BMC account. The Secrets are never in Git, a source + revision or evidence. The harness keeps the password in a `.token` file so the + evidence secret scan covers it. Worker and harness logs print outcome classes + only. - **Provisioning network.** The adapter defines one static libvirt network. dnsmasq gives each enrolled MAC a fixed address and the same boot file. That iPXE script chains to `/pxe/${net0/mac:hexhyp}/boot.ipxe`. The boot service @@ -316,7 +321,7 @@ These are documented lab seams, not production designs: as a stand-in for serial-over-LAN or an installer callback. It is observation, not control. - **Admission.** The Redfish overlay's admission policy limits kro worker Jobs - to the journal claim, `emptyDir` and the BMC credential. It denies a + to the site state claim, `emptyDir` and the per-Device credentials. It denies a `libvirt*` subPath, `/run/fleet-libvirt` or lab-disk mount and a `FLEET_LIBVIRT_URI`, and requires `FLEET_SITE_PROVIDER=redfish`. The `rbac` phase proves each denial as kro's identity, and evidence re-checks every real @@ -326,7 +331,8 @@ These are documented lab seams, not production designs: `hack/multiplane/acceptance-redfish.sh` runs every scenario of the [libvirt-mode sequence](multiplane.md#acceptance-phases) through the same -federation and kro path, with these differences. +federation and kro path, with these differences. The phase descriptions follow the +harness at this change; verification of the run on custody is pending. **Before topology:** @@ -335,7 +341,10 @@ federation and kro path, with these differences. - `bmc-self-test` runs the adapter self-test with no network. **Before Flux installs the shared services:** `redfish-enroll` creates the -synthetic credential Secret. +synthetic credential and TLS Secrets, one credential Secret per Device, and the +fixture enrollment. The coordinator runs on the workstation +(`hack/multiplane/coordinator.sh`), and a separate discovery identity writes +fixture discovery for the lab Devices. Real BMC discovery is not part of this run. **Redfish phases:** @@ -347,7 +356,7 @@ synthetic credential Secret. | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | | `resume` | The recreated Job completes the exact operation with one succeeded Pod | -| `install-b` | After verified cleanup and reuse, consumer B installs on the same physical target in epoch 2 with a new receipt | +| `install-b` | After the wipe and reuse, consumer B installs on the same physical target under a higher fence with a new receipt | | `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | | `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | @@ -374,24 +383,31 @@ Redfish-specific evidence files are `redfish-upstream.json`, ## Offline checks ```sh -go test -race -count=1 ./internal/redfish ./cmd/fleet-multiplane ./internal/multiplane +go test -race -count=1 ./internal/redfish ./internal/site/... ./cmd/fleet-multiplane ./internal/multiplane task multiplane:test-harness # includes hack/multiplane/test-redfish.py ``` -The Go tests use a fake BMC whose fake guest fetches its script and artifacts -from the real boot handler and writes console receipts. They cover: - -- install, disk boot, cleanup and reuse; -- exact replay; -- a rejected credential, unsupported reset and renumbered or swapped UUIDs, - each with no effect; -- a lost response after the effect, recovered without a repeat; -- a lost request repeated exactly once; -- duplicate receipts and identity change failing; -- changed-retry conflict, stale-epoch fencing and an unenrolled asset; -- journal-lock exclusion; -- boot scoping by MAC, capability, admission and fence; -- refusal of libvirt configuration, and the import-graph guard. +The Go tests in `internal/site/redfishwork` use a fake BMC whose fake guest +fetches its script and artifacts from the real boot handler and writes console +receipts. The site framework's tests in `internal/site` run against TLS stubs. +Together they cover: + +- an install with both phases and one power-on each, a wipe that checks the + enrolled disk, and a bootstrap reference refused at the site + (`TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, + `TestBootstrapIsRefusedAtTheSiteToo`); +- a worker interrupted in either phase that resumes without a second power-on + (`TestAnInterruptedWorkerResumesWithoutASecondOn`, + `TestAWorkerInterruptedInTheDiskPhaseResumes`); +- a server that never powers off ending the step + (`TestAServerThatNeverPowersOffEndsTheStep`); +- a boot admission open only at the current fence + (`TestOnlyTheCurrentFenceHasAnOpenBootAdmission`); +- synchronized DHCP following the open admission (`TestSyncedDHCPFollowsTheOpenAdmission`); +- a pin mismatch and an identity mismatch sending nothing + (`TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`), and a + rejected credential, unsupported reset and renumbered or swapped UUIDs, each + with no effect. `client_test.go` covers the gofish-backed client against a recording stub: @@ -409,7 +425,7 @@ from the real boot handler and writes console receipts. They cover: - no environment proxy; - no credential, response body or endpoint in any error. -The provider's fake BMC serves the emulator's string `"Required"` in +The workers' fake BMC serves the emulator's string `"Required"` in ActionInfo. `test-redfish.py` renders the overlays and a staged Redfish revision with @@ -425,6 +441,12 @@ kustomize and checks the following: ## Execution record +The records below describe runs on the path before the cutover to Device custody, +with the old executor, a site-wide journal and a shared credential over plain +HTTP. They show what the lab and the harness proved then. They are not evidence +for the Redfish workers. The multi-plane Redfish run on custody is implemented, +and its verification is pending. + ### Attempts before the first pass (2026-11-16) Every attempt below was a fresh topology owned by this task. Each failure was @@ -596,7 +618,7 @@ sanitization all remain `false` in `summary.json`. These differences from physical hardware are known and **not** addressed by this MVP. They are listed as an explicit qualification checklist: -1. **Real BMC.** Qualify the executor against at least one vendor Redfish +1. **Real BMC.** Qualify the Redfish workers against at least one vendor Redfish implementation. Check ActionInfo and inline `AllowableValues`, the actual reset semantics (some BMCs reject `On` while on, or report `PoweringOn`), and whether `Once` overrides are consumed at POST. Check ETag/`If-Match` @@ -608,10 +630,11 @@ MVP. They are listed as an explicit qualification checklist: order persistence. 3. **Receipts.** Replace the read-only console capture with serial-over-LAN or an authenticated installer callback, and decide its trust model. -4. **Credentials and transport.** Public-key pinning exists - (`NewPinnedClient`) but the executor does not use it. Per-BMC - accounts, a credential broker so workers never hold a long-lived password, - and rotation and revocation. +4. **Credentials and transport.** Workers read a per-Device credential Secret + and connect only to the approved pin, but the lab uses one account and one key + for both targets. Still open: per-BMC accounts, a credential broker so + workers never hold a long-lived password, and rotation and revocation of both + the credential and the pinned key. 5. **Provisioning network.** Synchronized DHCP reservations with served and withdrawn evidence are implemented and unit tested ([Boot network](boot-network.md)) but not exercised at a site. Still open: @@ -622,19 +645,22 @@ MVP. They are listed as an explicit qualification checklist: Distinguish it from this logical overwrite. 7. **Power semantics.** Physical power transitions take longer, may fail and may report intermediate states. Revisit the settle window, the outage tolerance - and the three-attempt `On` budget. Revisit installer and disk-boot power-off - as the completion signal; a real OS reboots and keeps running. -8. **Fencing and journal.** One site journal fences all targets with one - allocatable target. Per-asset fencing, journal durability and HA are not - designed. Never reset the journal of a retained target + and the five-minute power-off bound. A worker never sends `On` a second time; + it observes. Revisit installer and disk-boot power-off as the completion + signal; a real OS reboots and keeps running. +8. **Fencing and the site store.** Each Device has its own fence and journal on + one retained volume. Store durability across volume loss and HA are not + designed. Never reset the store of a retained target ([known limitations](multiplane.md#known-limitations-of-the-local-mvp)). -9. **Enrollment.** The asset-to-System mapping is a static source value. +9. **Enrollment.** The Device-to-System mapping is a static source value. Enrollment trust and attestation of the System identity (beyond Id and UUID) are open. Read-only [BMC discovery](bmc-discovery.md) reports observed identity into Device status but does not enroll. -10. **Operator recovery.** Unknown operations, for example a power-off without - a receipt or an exhausted `On` budget, have no automated resolution. The - only recovery is to discard the disposable topology after inspection. +10. **Operator recovery.** An unknown operation, for example a power-on with no + sign that the boot began, holds the Device. A person settles it with a + `DeviceRecovery`. Nothing retries it automatically, and the multi-plane run + does not exercise recovery. Its only resolution there is to discard the + disposable topology after inspection. The existing local-MVP limitations also apply: single node, trusted graph and service authors, and no image upgrade lifecycle. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 311c7d80..134e3035 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -1,7 +1,7 @@ # Kubernetes-native site execution The [multi-plane acceptance](multiplane.md) runs selected-cell execution as -ordinary Kubernetes workloads. The cell's Flux owns the long-lived site services +ordinary Kubernetes workloads, as a site of [Device custody](../development/device-custody.md#cutover-increment-c). The cell's Flux owns the long-lived site services directly, and an installed [kro](https://kro.run) controller creates only the per-operation worker Jobs and their RBAC. Before Kubernetes execution, a hand-written cell process was started with `docker exec` inside a privileged libvirt container. @@ -10,9 +10,10 @@ wrote status. Now Kubernetes controllers own scheduling, retries, Pod replacement and dependency ordering. Fleet code is left with only the parts that carry authority: -- exact-request replay against the provider journal; -- fencing; -- journal-derived observation. +- per-Device fences and a journal of each step, from the + [site framework](../development/device-custody.md#site-execution-increment-b); +- fenced, typed results; +- observation of what the site store holds. This is an **implemented local acceptance composition**, not a production deployment. The [PXE installation proposal](../enhancements/pxe-installation/README.md#location-execution) @@ -41,7 +42,7 @@ digest, and `flux-verify` checks the release history records that digest. See ▼ ▼ ▼ ▼ fleet-site-base fleet-site-services fleet-site-graph fleet-site-dispatch ns, Retain PVC, runtime, boot and ResourceGraphDefinition HandoffDispatcher/dispatcher -identities, RBAC, observer Deployments; fleet-handoff-dispatcher (cell, scoped asset, dispatch) +identities, RBAC, observer Deployments; fleet-handoff-dispatcher (cell, dispatch) kro grants, boot Service (fixed │ admission policy ClusterIP); policy param │ kro ▲ externalRef (read only, readiness-gated) ▼ @@ -50,23 +51,23 @@ Karmada ──delivers──▶ MachineAllocationHandoff ─ external collection (fleet-coordination, label-selected by cell) (resourceNames: that handoff, get), RoleBinding, bounded Job -VM runtime (libvirtd, privileged) ◀─ libvirt socket ─ worker Job ── replays one operation - └─ firmware DHCP/iPXE ─NAT─▶ boot Service ─▶ boot Deployment (journal read-only) -observer Deployment (journal read-only; only handoff status writer) +VM runtime (libvirtd, privileged) ◀─ libvirt socket ─ worker Job ── runs one assignment + └─ firmware DHCP/iPXE ─NAT─▶ boot Service ─▶ boot Deployment (site store read-only) +observer Deployment (site store read-only; only handoff status writer) ╲_____________ fleet-site-state PVC (Retain), Flux-owned __________╱ ``` | Resource | Owner (single writer) | Privileges | Volume subpaths | Role | | --- | --- | --- | --- | --- | -| `fleet-site` namespace, `fleet-site-retain` StorageClass, `fleet-site-state` PVC | Flux `fleet-site-base` (`config/site/base`; never pruned; class and claim created once) | — | — | Durable journal, disks, boot evidence, libvirt socket and QEMU logs. Never in any graph. | +| `fleet-site` namespace, `fleet-site-retain` StorageClass, `fleet-site-state` PVC | Flux `fleet-site-base` (`config/site/base`; never pruned; class and claim created once) | none | none | The site store (each Device's fence and journal, under the `journal` subpath), disks, boot evidence, libvirt socket and QEMU logs. Never in any graph. | | `fleet-site-runtime`, `fleet-site-boot`, `fleet-site-observer` ServiceAccounts; observer Role and RoleBinding | Flux `fleet-site-base` | Observer: get/list/watch handoffs; update handoff status | — | The observer is the only cell identity that writes handoff status | | `fleet-site-kro` ClusterRole, `fleet-site-kro-workers` and `fleet-site-kro-worker-rbac` Roles and bindings, two `ValidatingAdmissionPolicies` | Flux `fleet-site-base` | — | — | kro's narrowed grant and the shape of its writes ([trust model](#ownership-and-trust-model)) | | `fleet-site-runtime` Deployment | Flux `fleet-site-services` | **privileged** (bridge, dnsmasq, tap, iptables) | `journal` rw, `libvirt-socket` rw, `libvirt-log` rw, `boot-evidence` ro | libvirtd and QEMU only. No API token, no TCP listener. | | `fleet-site-boot` Service and Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem, no API token | `journal` **ro**, `boot-evidence` rw | Boot decision point and artifact delivery. The Service has a fixed ClusterIP (`10.96.0.80`). | -| `fleet-site-observer` Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem | `journal` **ro** | Publishes validated terminal journal results every 10 seconds | +| `fleet-site-observer` Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem | `journal` **ro** | Publishes each Device's stored fences, and the stored result of each assignment, every 10 seconds | | `fleet-site-worker-policy` ConfigMap | Flux `fleet-site-services` | — | — | Admission parameter: the image worker Jobs must run | | `fleet-handoff-dispatcher` ResourceGraphDefinition, `HandoffDispatcher/dispatcher` | Flux `fleet-site-graph`, `fleet-site-dispatch` (each a scoped identity; never pruned) | — | — | Orders per-operation work and projects non-authoritative status | -| `w-` ServiceAccount, Role, RoleBinding, Job | kro `forEach` over delivered handoffs | get on exactly one handoff; uid 0 with all capabilities dropped; read-only root filesystem | `journal` rw, `libvirt-socket` rw, `boot-evidence` ro | Executes or resumes that one retained operation | +| `w-` ServiceAccount, Role, RoleBinding, Job | kro `forEach` over delivered handoffs | get on exactly one handoff; uid 0 with all capabilities dropped; read-only root filesystem | `journal` rw, `libvirt-socket` rw, `boot-evidence` ro | Runs or resumes that one assignment | ## Ownership and trust model @@ -138,7 +139,7 @@ kro's own requests and pin those writes to the worker shape: by the services layer); - no privilege or added capability; - no host namespaces; -- only the journal claim and `emptyDir` volumes. +- only the site state claim and `emptyDir` volumes. A Role may grant only `get` on its own handoff, and a RoleBinding may bind only its own Role to its own ServiceAccount. The `rbac` phase proves this with real @@ -155,11 +156,11 @@ denials are not covered by the current probes. **What graph authors are still trusted with.** This is not a sandbox for untrusted graph revisions: -- A worker mounts the journal read-write and reaches root libvirtd through +- A worker mounts the site store read-write and reaches root libvirtd through its socket. A graph author who changes the worker command, within the - admitted image, can therefore drive the hypervisor and rewrite the journal. -- kro must read every delivered handoff, including the fence token in - `requestJSON`, to enumerate them. + admitted image, can therefore drive the hypervisor and rewrite the site store. +- kro must read every delivered handoff, including its assignment, to + enumerate them. - kro keeps cluster-wide CRD create/update/delete from its chart, so a compromised kro controller could alter or remove CRDs it does not own. - The services layer chooses the privileged runtime image and its @@ -192,7 +193,7 @@ objects. This sequence is proposed only. any guest. The operation then stays Unknown and capacity stays occupied. - **Workers reach libvirt through a Unix socket on the site volume** (`qemu:///system?socket=/run/fleet-libvirt/libvirt-sock`). They hold no - network credential, and nothing listens on TCP. The provider accepts only + network credential, and nothing listens on TCP. The local VM site accepts only that URI shape. This socket still grants broad control over root libvirtd, including domain definitions backed by paths in the runtime filesystem. Dropped Linux capabilities do not isolate workers from the runtime's power. @@ -209,12 +210,12 @@ objects. This sequence is proposed only. proves this. The runtime entrypoint adds a `mangle` chain: traffic from the bridge may reach only local addresses (DHCP), broadcast, and the boot Service port. Everything - else is dropped. The boot service reads the journal read-only and writes + else is dropped. The boot service reads the site store read-only and writes only its own delivery evidence in a separate subpath. Workers read that evidence when they verify network boot. - **One shared volume, separate subpaths and mount modes.** All site Pods run on the single kind node, so one `ReadWriteOnce` local-path volume serves - them. The journal `flock` is effective because every writer shares one + them. Each Device's run lock is effective because every writer shares one kernel and inode. - **The observer is a Deployment, not part of the Job.** Management requires reflected observations to be fresher than one minute. Refreshing them is a @@ -223,45 +224,46 @@ objects. This sequence is proposed only. ## Authority and failure contract -- **Exact operation before effect.** A worker reads only its handoff. It - checks the cell, checks that the name is derived from the operation ID, and - validates the intent. `LocalAssetMapping` re-reads the same handoff and - compares digests. The provider then replays the journal under the exact - operation ID. A digest conflict, fence mismatch, stale epoch, or an - unfinished prior operation stops before any effect. +- **Exact assignment before effect.** A worker reads only its handoff. It checks + that the handoff is an assignment for this cell, that its name is derived from + the assignment, and that the assignment is valid. The site framework then + checks the inputs against the admitted digest, the enrollment against the + snapshot, the fence against the Device's stored fence, and, for Redfish, the + Device's credential and TLS pin. Any failed check sends nothing. See [device + custody](../development/device-custody.md#site-execution-increment-b). - **Worker exit codes are the Job contract.** - - `0`: a terminal result was validated against the journal. - - `65`: fenced, conflicting or invalid authority. `podFailurePolicy` fails - the Job with no retry. - - `75`: Unknown or transport error. The Job controller retries, up to + - `0`: the assignment's result is stored, or another worker for the same + assignment holds the Device's run lock and owns the result. + - `65`: the handoff is not an assignment for this cell, or the assignment is + below the Device's stored fence. `podFailurePolicy` fails the Job with no + retry. + - `75`: any other error. The Job controller retries, up to `backoffLimit: 6` and `activeDeadlineSeconds: 3600`. Disruption-target Pod conditions are ignored, not counted. -- **The journal lock serializes effects.** `podReplacementPolicy: Failed` +- **Each Device's run lock serializes effects.** `podReplacementPolicy: Failed` delays ordinary replacement until the old Pod is terminal. Force deletion can remove its API object while the old process still runs, and Job recreation - can also overlap workers. The provider's non-blocking journal lock is the - actual execution guard in these cases; a contender exits 75. A recreated - worker replays the same retained operation. + can also overlap workers. A newer assignment raises the fence and waits for the + lock, and the older worker stops within a second. A redelivered assignment + that finds the same assignment running stores nothing. A recreated worker + resumes from the journal. - **Job Complete and kro Ready grant nothing.** The worker never writes - status. The observer publishes only a terminal journal result that passes - `ValidateResult`. Management accepts only the Karmada-reflected observation - that passes `ValidateReflection`, which checks: - - exact cell, operation and intent/input digests; - - freshness; - - a single replica. + status. The observer publishes only what the site store holds: the Device's + fences, and the stored result of the assignment. The coordinator accepts only + this cell's observation of exactly the assignment the handoff carries, by its + digest and fence, and then labels the handoff answered so the cell deletes its + copy. A result below the active operation's fence is rejected. The acceptance shows this directly: during the hub partition the install Job is `Complete` while public Machine `Ready` stays `False`. A failed Job leaves - the operation Unknown; it never releases capacity. -- **Delivery faults fail closed.** kro selects handoffs by cell label only for - convenience. A duplicate under another name, a wrong-cell intent and a - stale-epoch replay each get a Job. The acceptance injects these faults with - no pending operation: each fails once by policy without touching the journal. - While another operation is unfinished, the provider may reject a stale - request as Unknown before checking its fence. That worker exits 75 and may - exhaust its retry budget instead of failing once with exit 65; no effect is - authorized in either case. + the operation unknown; it never releases capacity. +- **Delivery faults fail closed.** kro selects assignment handoffs by cell label + only for convenience. The acceptance injects three faults: a duplicate handoff + under a second name, which the API refuses; an assignment naming another cell; + and an assignment replayed below the Device's stored fence. The last two each + get a Job that fails once at exit 65 by policy, with the site store unchanged + and no status written. ## Lifecycle and retention @@ -275,16 +277,17 @@ objects. This sequence is proposed only. `HandoffDispatcher` instance. kro removes only that handoff's Job, ServiceAccount, Role and RoleBinding. Every shared object keeps its UID, including the Deployments, Service, ServiceAccounts, RBAC, admission policies, - PVC and StorageClass. The journal, PV, guests and custody are unchanged, and + PVC and StorageClass. The site store, PV, guests and custody are unchanged, and the handoff keeps its terminal observation. Resuming lets Flux recreate the instance; kro recreates the workers and the Job replays a verified no-op. kro deletes Jobs without a propagation policy, so batch/v1 orphans their terminal Pods; the evidence lists them. -- **Never delete or replace the journal** of a provider whose disk or device - is retained. A fresh journal would admit replayed handoffs as new - operations; see [known limitations](multiplane.md#known-limitations-of-the-local-mvp). +- **Never delete or replace the site store** of a site whose disk or Device is + retained. It holds the fences that refuse older assignments, and a fresh store + would report a lower fence than the one the coordinator last admitted; see + [known limitations](multiplane.md#known-limitations-of-the-local-mvp). - After the installation is terminal, recreating the Flux-owned runtime, boot or - observer Pods does not change journal bytes, guest starts, volume identity or + observer Pods does not change the site store, guest starts, volume identity or public allocation. Neither does recreating a completed Job, which only replays a verified no-op. The `lifecycle` phase asserts all of this. @@ -293,7 +296,7 @@ objects. This sequence is proposed only. specify cascading deletion for pruned Jobs, so dependent worker Pods may be orphaned and continue to completion, as may their guests. The observer can still publish a completed result if its handoff exists. Re-enabling dispatch - can create a competing worker that exits 75 on the journal lock. The harness + can create a competing worker that waits on the Device's run lock. The harness does not exercise pruning an active Job; its explicit Job deletion uses background propagation. Neither dispatch nor object deletion is an authorized cancellation or fencing protocol. @@ -314,12 +317,15 @@ objects. This sequence is proposed only. - kro's controller is not in the authority path. If kro is down, no new worker is created, existing Jobs continue, and the Flux-owned shared services keep running and reconciling. Recovery is kro reconciliation followed by - journal replay. + replay from the journal. ## Secrets -The fence token remains inside the handoff's `requestJSON`; this is the existing -federation contract. Cell readers of handoffs are: +A handoff carries one assignment: the Device, the operation, the fence, the +admitted snapshot and the exact inputs. It holds no credential. A bootstrap +payload is refused, so none is carried. A Redfish worker reads each Device's own +BMC credential Secret in the site's cluster, never from a handoff. Cell readers +of handoffs are: - each worker, for its one handoff only; - the observer; @@ -327,27 +333,33 @@ federation contract. Cell readers of handoffs are: - kro, which must read handoffs to enumerate them. Job specs, Pod arguments, kro instance status and labels carry only handoff -names, the cell name and the scoped asset ID. Worker and observer logs print an -outcome class, never request bodies. The harness creates short-lived tokens for -RBAC probes with names ending in `.token`. It scans every evidence file against -all retained tokens, fences and boot capabilities. +names and the cell name. Worker and observer logs print an outcome class, never +request bodies. The harness creates short-lived tokens for RBAC probes with names +ending in `.token`. It scans every evidence file against all retained tokens and +boot capabilities. ## What replaced what | Removed | Replaced by | | --- | --- | | `fleet-multiplane cell` process launched with `docker exec`, its PID file and `kill` signalling | kro-created Jobs and the Job controller | -| `coordination.Cell.Run` list/watch loop and `Reconcile` (execute plus publish) | `Cell.Execute` (worker; no status writes) and `Cell.Publish`/`Cell.Observe` (observer; lookup only) | +| `coordination.Cell.Run` list/watch loop and `Reconcile` (execute plus publish) | `Cell.Work` (worker; no status writes) and `Cell.Publish`/`Cell.Observe` (observer; reads the site store only) | | `config/multiplane/cell-rbac.yaml` and an exported cell kubeconfig | Static observer RBAC and kro per-operation RBAC; no cell credential leaves the cell | | Dedicated privileged provider container and `docker exec` probes | Runtime, boot and observer Deployments; probes through the cell API | | kro-created runtime, boot and observer Deployments, boot Service and their ServiceAccounts (`FleetSite` graph), with a cluster-wide kro write grant | Flux layer `fleet-site-services` (scoped identity) and identities in `fleet-site-base`; the `HandoffDispatcher` graph references them; kro writes are namespaced and admission-checked | | `helm install` of kro, `kubectl apply` of the site base and RGD, a `kubectl patch` of `dispatch`, and `kind load` of the image | Cell Flux `HelmRelease`/Kustomizations from a pushed source revision; the image pulled by digest from the run registry ([details](gitops.md)) | -The single-plane [local VM harness](local-vm.md) still uses its own disposable -container and is unchanged. +The Increment C cutover also removed the site-wide provider journal, the +`requestJSON` handoff and the single-plane [local VM harness](local-vm.md). A +handoff now carries one assignment, and each Device has its own fence and +journal in the site store. ## Implemented versus proposed +Rows marked "exercised" were observed in runs on the path before the cutover to +Device custody. The same phases now run on custody. Verification of that run is +pending. + | Behavior | Status | | --- | --- | | Flux-owned shared site services and storage; kro-created per-operation RBAC and bounded worker Jobs on a real cell API | Implemented and exercised by `task multiplane:acceptance` | @@ -355,18 +367,19 @@ container and is unchanged. | Narrowed kro RBAC and admission policies on kro's writes | Implemented and exercised (`rbac`, `kro-rbac.json`); every dispatched Job and its RBAC passed them | | In-place migration of an existing site from kro-owned shared services | Proposed only ([trust model](#ownership-and-trust-model)) | | Pod loss and Job deletion mid-install resuming the same operation with one installer start | Implemented and exercised | -| Duplicate, wrong-cell and stale-epoch delivery failing by `podFailurePolicy` before effects | Implemented and exercised | -| Pod/Job lifecycle not changing journal, guest or allocation | Implemented and exercised | +| A duplicate handoff refused, and wrong-cell and below-fence assignments failing by `podFailurePolicy` before effects | Implemented; the earlier phase was exercised, and the current one awaits verification | +| Pod/Job lifecycle not changing the site store, guest or allocation | Implemented and exercised | | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | -| Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | -| Redfish execution Jobs with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md) for its run record | -| Synchronized DHCP boot reservations with served and withdrawn evidence | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | +| A credential broker so no worker holds a long-lived BMC credential | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | +| Redfish workers with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md). Verification of the run on custody is pending. | +| Synchronized DHCP boot reservations with served and withdrawn evidence, read from the site store | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | | Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | -| Per-Device fence store and journal, older-worker stop with a confirmation, worker deadlines, fenced typed results, per-Device credentials with the approved TLS pin, and the operation handoff payload ([device custody](../development/device-custody.md#site-execution-increment-b)) | Implemented and inert: unit tested, and nothing at the site runs it until the cutover. The site-wide journal above still drives this acceptance. | +| Per-Device fence store and journal, older-worker stop with a confirmation, worker deadlines, fenced typed results, per-Device credentials with the approved TLS pin, and the operation handoff payload ([device custody](../development/device-custody.md#site-execution-increment-b)) | Implemented: unit tested, and every site runs it since the cutover. The multi-plane run on it awaits verification. | ## Independent review of the recorded run -This review covered the run before Flux installation. The +This review covered a run before Flux installation and before the cutover to +Device custody, so it describes the retired provider journal and its lock. The [Flux-reconciled run](multiplane.md#flux-reconciled-acceptance-2026-11-15) re-established the same execution findings and has not yet been independently reviewed. diff --git a/docs/operations/standalone-smoke.md b/docs/operations/standalone-smoke.md index 0f7ccfd0..5a593110 100644 --- a/docs/operations/standalone-smoke.md +++ b/docs/operations/standalone-smoke.md @@ -2,36 +2,53 @@ [Operations guide](README.md) · [Troubleshooting](../troubleshooting/README.md) -This environment exercises Fleet's implemented local-scope lifecycle library -against the persistent provider simulator. It is a development smoke test, not -the Milo acceptance suite and not hardware qualification. +This environment exercises Fleet's implemented allocation lifecycle on [Device +custody](../development/device-custody.md#cutover-increment-c) in one kind +cluster. A Deployment runs the custody coordinator, and the simulator is the +only site. It is a development smoke test, not the Milo acceptance suite and not +hardware qualification. Status: **implemented and verified** by +`task standalone:test`. `fleet-project-a` and `fleet-project-b` are Kubernetes namespaces used only as project stand-ins. They do not model Milo routing, IAM, entitlement, quota, project deletion, or equal `default` namespaces in separate project API servers. -The fixture supplies synthetic admission and retains one exact Machine evidence -record with its Machine UID, location, hardware, and observation time. Later -phases fail closed if that record is missing, stale, or substituted. The -production `fleet-manager` remains fail-closed and performs no effects. +The fixture supplies synthetic admission. The capacity projector is not wired, +so the install and allocate phases write `Prepared`, `Healthy` and `Available` +on the capacity themselves. Custody, not those conditions, decides exclusivity. +The production `fleet-manager` remains fail-closed and performs no effects. + +Each component has its own identity, and the phases run as the Metal provider: + +| Identity | ServiceAccount | Writes | +| --- | --- | --- | +| Custody coordinator | `fleet-custody-coordinator` | Custody and operation status | +| Metal provider | `fleet-standalone-smoke` | MachineAllocations and DeviceInstallations | +| Release controller | `fleet-release-controller` | DeviceWipes | + +A ValidatingAdmissionPolicy (`config/standalone/site.yaml`) requires each +operation's `spec.creator` to be the caller that creates it: its username, and +its UID only when its credential carries one. The scenario has one `us-central-1` Machine with 24 physical CPU cores and -128Gi of memory. Both consumers request it. Project A binds first while project -B remains pending. Project A installs a digest-pinned synthetic Debian image. -The script restarts the simulator and reruns the install phase to recover the -same retained operation. A separate `debian-12-reinstall` Installation then names -`debian-12` as its expected predecessor and replaces it on the same allocation. -Another simulator restart and retry recover that exact successor operation. -Every install/reinstall run performs an authenticated simulator lookup and checks -the operation identity, terminal result, and digest of the exact retained request -(including allocation, epoch, fencing authority, and image inputs). Kubernetes -completion records alone cannot pass the restart persistence check. -Project B remains pending throughout. The scenario then releases project A, -verifies cleanup, and lets project B bind at a later executor epoch. - -Reinstall retries preserve the allocation binding and executor epoch. An unknown -executor result leaves the Machine's readiness unknown and retains custody; -neither retry nor release can expose that capacity before recovery and cleanup. -Tests exercise lost responses, concurrent retry, and stale predecessor rejection. +128Gi of memory, on one synthetic Device, `synthetic-device-central-01`. Both +consumers request it. Custody must be `Verified` first. Project A allocates +first, so one `MachineAllocation` exists and custody names it. Project B waits +with `InsufficientCapacity`. Power comes only from the manager's power +projector, which reads custody and fixture discovery. Project A installs a +digest-pinned synthetic Debian image through a `DeviceInstallation`. The script +restarts the simulator and reruns the install phase to recover the same retained +operation. A separate `debian-12-reinstall` Installation then names `debian-12` +as its expected predecessor and replaces it on the same allocation. Another +simulator restart and retry recover that exact successor operation. Kubernetes +completion records alone cannot pass the restart check. + +Project B remains pending throughout. The scenario then releases project A. The +release wipes the Device once through a `DeviceWipe`, under a fence above both +installations. Custody then names project B's new allocation, and project B +becomes `Ready`. Project A's allocation is `Released`. + +An unknown site result keeps the Machine's readiness unknown and holds custody. +Neither a retry nor a release can expose that capacity before recovery. No network interface is requested. The `NETWORK` and `ADDRESS` columns are therefore intentionally blank; this environment does not deploy or impersonate @@ -72,7 +89,7 @@ KUBECTL_CONTEXT=kind-fleet-core KIND_CLUSTER=fleet-core ./hack/standalone-smoke. The script refuses a cluster that already has Fleet APIs (including a prior standalone run), fixture namespaces, or a `fleet-manager`/`fleet-milo-manager` deployment. Use a fresh dedicated cluster for every run. This prevents another -controller, retained epoch, or old claim from making the evidence ambiguous. +controller, retained custody, or old claim from making the evidence ambiguous. It also refuses a context whose API server does not match `kind get kubeconfig` for the requested cluster. A differently named context is accepted only with `ALLOW_KIND_CONTEXT_ALIAS=true`, and must still target that exact kind cluster. @@ -89,9 +106,9 @@ commits therefore cannot silently reuse one local workload tag. It applies the CRDs first and waits for establishment before applying fixtures, then uses `kubectl wait`/rollout watches for phase completion. It never patches status, removes finalizers, or writes -lifecycle records itself. The -phase Job is the designated synthetic fixture and status writer; the lifecycle -library remains the only writer of custody, asset, and operation records. +custody or operation records itself. The phase Job is the designated synthetic +fixture and status writer. The coordinator Deployment is the only writer of +custody and operation status. After the allocation phase, expected output has one ready and one pending claim: @@ -106,19 +123,26 @@ pins from the exact fixture profile for both claims, including the one still waiting. `kubectl get machines -A -o wide` adds the profile and the allocated CPU and memory, which stay blank for the pending claim. -After release, only project B remains and reports the same hardware. The private -records remain in `fleet-system-private`; release does not erase recovery or -epoch history. +After release, only project B remains and reports the same hardware. The +released allocation, the installations and the wipe remain in the provider +namespace (`fleet-provider`), so the fence history is kept: + +```sh +kubectl -n fleet-provider get machineallocations,deviceinstallations,devicewipes,devicecustodies +``` ## Security and lifecycle limits -The simulator has a dedicated runtime token, a persistent volume, no admin -listener, an explicit non-root UID/GID, a read-only root filesystem, and no -Kubernetes API credentials. Its pod `fsGroup` makes only the state volume and -group-readable token usable by that identity. Both Dockerfile bases are pinned -by digest. Only the smoke service account can write private records; its public -access is restricted to the named fixture objects. The script checks every -sensitive Secret verb, named Secret reads, and out-of-scope fixture access. +The simulator site has a dedicated runtime token, a persistent volume for its +site store, no admin listener, an explicit non-root UID/GID, a read-only root +filesystem, and no Kubernetes API credentials beyond its fixture discovery. Its +pod `fsGroup` makes only the state volume and group-readable token usable by that +identity. Both Dockerfile bases are pinned by digest. The script checks that the +project stand-ins cannot read or write custody, operations or allocations and +cannot read the three token Secrets. It also checks that the Metal provider cannot +update custody or create wipes, that the release controller cannot create +installations, and that the smoke account's access to fixtures is limited to the +named objects. The synthetic phase worker deliberately does not reconstruct or claim an end user identity. Production still requires create-time caller capture, protected diff --git a/docs/troubleshooting/README.md b/docs/troubleshooting/README.md index 095a1433..51db5c1a 100644 --- a/docs/troubleshooting/README.md +++ b/docs/troubleshooting/README.md @@ -31,7 +31,7 @@ records, or mark occupied capacity as available to unblock a test or rollout. The [provider execution and recovery contract](../enhancements/machine-lifecycle/README.md#provider-execution-and-recovery) and [release contract](../enhancements/machine-lifecycle/README.md#release-and-project-lifecycle) describe the intended guarantees. Compare them with the -[implemented lifecycle library](../development/README.md#standalone-lifecycle-library) +[implemented allocation library](../development/README.md#allocation-on-device-custody) and [simulator limits](../development/README.md#explicit-gaps) before choosing a recovery action. Real-provider recovery procedures are not established by these fixtures. diff --git a/hack/local-vm/run.sh b/hack/local-vm/run.sh deleted file mode 100755 index 27e0e024..00000000 --- a/hack/local-vm/run.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env bash -# Creates only fresh disposable resources; retains failed state for recovery. -set -euo pipefail -cd "$(dirname "$0")/../.." -umask 077 -[[ $# == 0 ]] || { echo 'This local harness accepts no arguments' >&2; exit 1; } -export KIND_EXPERIMENTAL_PROVIDER=docker -accelerator=${FLEET_LOCAL_VM_ACCEL:-kvm} -case "$accelerator" in - kvm|tcg) ;; - *) echo 'FLEET_LOCAL_VM_ACCEL must be kvm or tcg' >&2; exit 1;; -esac -case $(docker context inspect --format '{{.Endpoints.docker.Host}}') in - unix://*) ;; - *) echo 'Local Unix Docker endpoint required; remote runtimes are not authorized' >&2; exit 1;; -esac -case $(docker info --format '{{.Architecture}}') in - x86_64|amd64) runtime_arch=amd64 ;; - aarch64|arm64) runtime_arch=arm64 ;; - *) echo 'Unsupported Docker runtime architecture' >&2; exit 1;; -esac -[[ $accelerator == tcg || $runtime_arch == amd64 ]] || { echo 'KVM requires an amd64 runtime for this guest' >&2; exit 1; } -run_id="fleet-local-$(python3 -c 'import uuid; print(uuid.uuid4().hex[:12])')" -evidence=$(mktemp -d /tmp/fleet-local-evidence.XXXXXX) -export KUBECONFIG="$evidence/kubeconfig" -printf '%s\n' "$run_id" > "$evidence/resource-name" -printf '%s\n' "$accelerator" > "$evidence/accelerator" -printf '%s\n' "$runtime_arch" > "$evidence/runtime-architecture" -printf 'Evidence: %s\n' "$evidence" -trap 'echo "Resources retained for inspection: $run_id; evidence: $evidence"' EXIT -python3 - "$evidence/source-SHA256SUMS" <<'PYHASH' -import hashlib,pathlib,sys -paths=[*pathlib.Path('internal/localvm').glob('*.go'),*pathlib.Path('cmd/fleet-local-vm').glob('*.go'),*pathlib.Path('hack/local-vm').glob('*')] -with open(sys.argv[1],'w') as out: - for p in sorted(paths): - if p.is_file(): out.write(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n') -PYHASH -CGO_ENABLED=0 GOOS=linux GOARCH="$runtime_arch" go build -o "$evidence/fleet-local-vm" ./cmd/fleet-local-vm -docker build --target "$accelerator" -t fleet-local-install -f hack/local-vm/Containerfile hack/local-vm -kind create cluster --name "$run_id" --kubeconfig "$KUBECONFIG" --image kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f --wait 120s -kubectl apply -f config/base/crd/metal.datumapis.com.yaml -kubectl wait --for=condition=Established crd --all --timeout=60s -for ns in fleet-system-private fleet-provider fleet-project-a fleet-project-b; do kubectl create namespace "$ns"; done -docker run -d --name "$run_id" --network kind --privileged --user root -e "FLEET_LOCAL_VM_ACCEL=$accelerator" --entrypoint /usr/local/bin/fleet-start-libvirt fleet-local-install -# No host filesystem mounts, host network, or host libvirt socket. -docker exec "$run_id" mkdir -p /run/fleet -binary_digest=$(python3 - "$evidence/fleet-local-vm" <<'PY' -import hashlib,sys -print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest()) -PY -) -printf '%s fleet-local-vm\n' "$binary_digest" > "$evidence/binary-SHA256SUMS" -docker cp "$evidence/fleet-local-vm" "$run_id:/usr/local/bin/fleet-local-vm.pending" -printf '%s /usr/local/bin/fleet-local-vm.pending\n' "$binary_digest" | docker exec -i "$run_id" sha256sum -c - -docker exec "$run_id" mv /usr/local/bin/fleet-local-vm.pending /usr/local/bin/fleet-local-vm -kind get kubeconfig --name "$run_id" --internal > "$evidence/internal-kubeconfig" -docker cp "$evidence/internal-kubeconfig" "$run_id:/run/fleet/kubeconfig" -docker exec -d "$run_id" fleet-local-vm boot-service -image=$(docker exec "$run_id" fleet-local-vm image) -docker cp "$run_id:/opt/fleet-local/artifacts/SHA256SUMS" "$evidence/SHA256SUMS" -python3 - "$image" > "$evidence/fixtures.yaml" <<'PY' -import sys -s=open('config/standalone/fixtures.yaml').read() -s=s.replace('cores: 24','cores: 2').replace('capacity: 128Gi','capacity: 2Gi') -s=s.replace('debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb',sys.argv[1]) -print(s) -PY -kubectl apply -f "$evidence/fixtures.yaml" -docker exec "$run_id" fleet-local-vm allocate | tee -a "$evidence/phases.log" -set +e -docker exec "$run_id" fleet-local-vm install-crash >> "$evidence/phases.log" 2>&1 -crash_status=$? -set -e -[[ $crash_status == 75 ]] || { echo "Expected post-effect crash 75; got $crash_status"; exit 1; } -printf "post-effect process crash verified (75)\n" >> "$evidence/phases.log" -for phase in install install boot-denials reinstall reinstall boot-denials release boot-denials evidence; do - docker exec "$run_id" fleet-local-vm "$phase" | tee -a "$evidence/phases.log" -done -docker cp "$run_id:/var/lib/fleet-local" "$evidence/provider" -docker exec "$run_id" virsh list --all --name > "$evidence/domains-after.txt" -docker image inspect fleet-local-install --format '{{.Id}}' > "$evidence/image-id" -# Retain receipts but omit fence tokens and all kubeconfigs from shareable evidence. -python3 - "$evidence/provider/journal.json" <<'PY' -import json,sys,pathlib -p=sys.argv[1];j=json.load(open(p));j.pop('fence',None) -tokens=[r.get('bootToken','') for r in j['operations'].values() if r.get('bootToken')] -for r in j['operations'].values(): - r['request'].pop('fenceToken',None) - r.pop('bootToken',None) -json.dump(j,open(p,'w'),indent=2) -root=pathlib.Path(p).parent -(root/'network-private.xml').unlink(missing_ok=True) -for file in root.rglob('*'): - if file.is_file() and any(token.encode() in file.read_bytes() for token in tokens): - raise SystemExit('credential found in exported evidence') -assert j['bootMode']=='pxe' -for r in j['operations'].values(): - if r['request']['kind']!='install': continue - import hashlib - d=root/hashlib.sha256(r['request']['id'].encode()).hexdigest() - installer=(d/'installer.xml').read_text(); disk=(d/'disk.xml').read_text() - assert '' not in installer and '' not in installer and "boot dev='network'" in installer - assert '' not in disk and '' not in disk - assert r['bootClosed'] - for name in ['boot.ipxe','kernel','installer.gz']: assert 'write-complete '+name+' bytes=' in (d/'boot-delivery.log').read_text() - assert '52:54:00:77:00:02' in (d/'dhcp-leases.txt').read_text() - assert 'FLEET-DISK-BOOT:'+r['receipt'] in (d/'disk.log').read_text() - assert not (d/'disk.raw').exists() -PY -rm -f "$evidence/provider/network-private.xml" -docker rm -f "$run_id" -kind delete cluster --name "$run_id" -rm -f "$evidence/kubeconfig" "$evidence/internal-kubeconfig" "$evidence/fleet-local-vm" -trap - EXIT -printf 'PASS: real local installation, retry, reinstall, cleanup and reuse; evidence %s\n' "$evidence" diff --git a/hack/multiplane/coordinator.sh b/hack/multiplane/coordinator.sh new file mode 100755 index 00000000..3e77ed76 --- /dev/null +++ b/hack/multiplane/coordinator.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Start or stop this run's custody coordinator: the reconciling process that +# admits operations, delivers them through Karmada and accepts the cell's +# results. It runs on the workstation with the coordinator's own token, and +# logs to the private state directory. +set -euo pipefail +action=${1:?start or stop} +state=${2:?private run state directory required} +pidfile="$state/coordinator.pid" +case $action in + start) + if [[ -f $pidfile ]] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then + echo "coordinator: already running" + exit 0 + fi + nohup "$state/fleet-multiplane-host" coordinator --config "$state/acceptance.json" >>"$state/coordinator.log" 2>&1 "$pidfile" + sleep 2 + kill -0 "$(cat "$pidfile")" || { echo 'coordinator: exited at start; see coordinator.log in the state directory' >&2; exit 1; } + echo "coordinator: running" + ;; + stop) + if [[ -f $pidfile ]]; then + pid=$(cat "$pidfile") + if kill -0 "$pid" 2>/dev/null; then + kill "$pid" + for _ in $(seq 1 30); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done + fi + rm -f "$pidfile" + fi + echo "coordinator: stopped" + ;; + *) echo 'usage: coordinator.sh start|stop STATE' >&2; exit 64 ;; +esac diff --git a/hack/multiplane/custody_crd_rules.py b/hack/multiplane/custody_crd_rules.py index 013133df..5de1a16b 100644 --- a/hack/multiplane/custody_crd_rules.py +++ b/hack/multiplane/custody_crd_rules.py @@ -3,20 +3,20 @@ Milo v0.32.5 ignores admission policies stored in a project, so the custody contract rests on the CRD schema and CEL rules the project API server itself -evaluates. This phase installs only the device-operations CRDs into the -provider project, tries each forbidden change against synthetic objects, and -requires the API server to refuse it. It then removes the objects and the -CRDs, so no later phase sees them. It sends nothing to any BMC. +evaluates. The provider project serves the device-operations CRDs for the +whole run. This phase tries each forbidden change against synthetic objects +in the fleet-rules namespace, which the coordinator never reads, requires +the API server to refuse it, and removes the objects. It sends nothing to +any BMC. """ import json, pathlib, subprocess, sys state = pathlib.Path(sys.argv[1]).resolve() config = state / 'provider' / 'bootstrap-project.json' -crds = 'config/components/device-operations/crds/fleet.datumapis.com.yaml' -# The provider namespace the fixture bootstrap creates. The phase creates no -# namespace, because a project API may not run a namespace controller to -# finish deleting one. -namespace = 'fleet-provider' +# The namespace the fixture bootstrap creates for this check. The phase +# creates no namespace, because a project API may not run a namespace +# controller to finish deleting one. +namespace = 'fleet-rules' objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001')) names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries') @@ -51,11 +51,10 @@ def status(kind, name, phase): checks = [] removed = False try: - kubectl('apply', '-f', crds) for name in names: kubectl('wait', '--for=condition=Established', 'crd/%s.fleet.datumapis.com' % name, '--timeout=90s') envelope = {'creator': {'username': 'staff-example', 'uid': 'staff-example-uid'}, - 'deviceRef': {'name': 'server-example-001', 'uid': '00000000-0000-4000-8000-000000000001'}, + 'deviceRef': {'name': 'server-example-001'}, 'authority': {'serviceRequest': {'reason': 'synthetic rule check'}}} recovery = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceRecovery', 'metadata': {'name': 'rules-recovery', 'namespace': namespace}, @@ -93,15 +92,16 @@ def status(kind, name, phase): mismatch['metadata']['namespace'] = namespace refused('custody has the same name as its Device', 'create', '-f', '-', stdin=json.dumps(mismatch)) finally: - cleared = all(kubectl('-n', namespace, 'delete', kind, name, '--ignore-not-found', '--wait=true', '--timeout=120s', check=False).returncode == 0 + # The rule-check custody carries no finalizer: nothing reconciles this + # namespace, so it is deleted at once. + removed = all(kubectl('-n', namespace, 'delete', kind, name, '--ignore-not-found', '--wait=true', '--timeout=120s', check=False).returncode == 0 for kind, name in objects) - removed = cleared and kubectl('delete', '-f', crds, '--ignore-not-found', '--wait=true', '--timeout=120s', check=False).returncode == 0 if not removed: - raise SystemExit('custody-crd-rules: the rule-check objects or CRDs could not be removed') + raise SystemExit('custody-crd-rules: the rule-check objects could not be removed') evidence = state / 'evidence' evidence.mkdir(mode=0o700, exist_ok=True) path = evidence / 'custody-crd-rules.json' -path.write_text(json.dumps({'checks': checks, 'crdsRemoved': removed}, indent=1) + '\n') +path.write_text(json.dumps({'checks': checks, 'objectsRemoved': removed}, indent=1) + '\n') path.chmod(0o600) -print('custody-crd-rules: the provider project API refused every forbidden custody and operation write (%d rules); CRDs removed' % len(checks), flush=True) +print('custody-crd-rules: the provider project API refused every forbidden custody and operation write (%d rules); objects removed' % len(checks), flush=True) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 80c35ce9..318f0767 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -14,6 +14,9 @@ import sys import tarfile +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout, provider custody) + s = pathlib.Path(sys.argv[1]) prefix = (s / 'prefix').read_text().strip() ev = s / 'evidence' @@ -70,69 +73,134 @@ def copy_out(source, destination): fail('missing independent native project create/watch evidence') custody_rules = json.loads((ev / 'custody-crd-rules.json').read_text()) -if not custody_rules.get('crdsRemoved') or len(custody_rules.get('checks', [])) != 8 or not all(c.get('refused') for c in custody_rules['checks']): +if not custody_rules.get('objectsRemoved') or len(custody_rules.get('checks', [])) != 8 or not all(c.get('refused') for c in custody_rules['checks']): fail('the provider project API did not refuse every forbidden custody write') phases = (s / 'phases.log').read_text() +REFLECTION_FAULTS = ('wrong-cell', 'foreign-observer', 'duplicate', 'future', 'wrong-assignment', 'wrong-device', 'wrong-operation', 'stale-fence', 'missing') markers = ('custody-crd-rules: the provider project API refused every forbidden custody and operation write', 'Verified forbidden observer/project/hub writes', 'allocate: verified', 'contention: consumer-a Bound', 'delivery: Karmada delivered exactly one', 'kro created the worker Job and per-operation RBAC', 'worker-rbac: per-operation ServiceAccount', 'interrupt-pod: worker Pod force-deleted', 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', - 'delivery-faults: duplicate, wrong-cell and stale-epoch', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine Released', + 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine Released', 'wrong-location: denied before allocation', 'Flux restored the binding', 'flux-verify: 3 clusters Ready', 'cell Flux applied the dispatch revision', 'Flux restored consumer-a', 'Flux on every cluster Ready at the current revision', 'flux-drift: helm-controller restored kro', 'recreated the shared boot Service at its fixed ClusterIP and restored the observer', 'flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects', 'kro RBAC and admission confine it to per-operation objects', 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', - 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in ( - 'wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing')) + 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in REFLECTION_FAULTS) if REDFISH: markers += ('bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified', 'bmc-self-test: upstream emulator and lab adapter self-test passed', - 'redfish-enroll: synthetic BMC credential Secret created', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', + 'redfish-enroll: synthetic per-Device BMC credentials', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', 'redfish-lost-response: On took effect but its response was lost', 'redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install', 'install-b: verified', 'redfish-isolation: target B never started') for marker in markers: if marker not in phases: fail('missing acceptance phase: ' + marker) +def site_operations(raw): + """The Device's journaled operations from the copied site store, matched to + the provider project's operations by site key: kind, name and fence. Expected order: consumer A's + install, A's release wipe, (Redfish: consumer B's install,) B's release + wipe, with strictly increasing fences, each Succeeded at its fence.""" + store = json.loads((raw / 'site' / 'devices' / harness.device_dir().rsplit('/', 1)[1] / 'state.json').read_text()) + journaled = harness.sanitized_operations(store, redfish=REDFISH) + # Operations by site key; custody and allocations by kind and name. + provider = {(i['kind'] + '/' + i['metadata']['name'] if i['kind'] in ('DeviceCustody', 'MachineAllocation') else harness.provider_key(i)): i for i in harness.custody(s)} + ops = [] + for o in journaled: + p = provider.get(o['operation']) + if not p or p['kind'] != o['kind'] or not o['done']: + fail('journaled operation %s is not a finished provider %s' % (o['operation'], o['kind'])) + st = p.get('status', {}) + if st.get('phase') != 'Succeeded' or st.get('fence') != o['fence']: + fail('%s %s is %s at fence %s, journaled at fence %s' % (p['kind'], p['metadata']['name'], st.get('phase'), st.get('fence'), o['fence'])) + ops.append(dict(o, name=p['metadata']['name'], allocation=p['spec']['authority']['allocationRef']['name'], phase=st['phase'])) + fences = [o['fence'] for o in ops] + if fences != sorted(set(fences)): + fail('operation fences are not strictly increasing: %s' % fences) + return store, ops, provider + + +def check_sequence(ops, interrupt): + """Consumer A's allocation holds the interrupted install; the other is B's.""" + a = next((o['allocation'] for o in ops if o['operation'] == interrupt['operationID']), None) + b = next((o['allocation'] for o in ops if o['allocation'] != a), None) + want = [('DeviceInstallation', a), ('DeviceWipe', a)] + ([('DeviceInstallation', b)] if REDFISH else []) + [('DeviceWipe', b)] + if not a or not b or [(o['kind'], o['allocation']) for o in ops] != want: + fail('expected %s, got %s' % (want, [(o['kind'], o['allocation']) for o in ops])) + if any(o['kind'] == 'DeviceWipe' and o['name'] != o['allocation'] + '-wipe-1' for o in ops): + fail('a release wiped the Device other than with its first wipe step') + stage = 'installer-power-on' if REDFISH else 'installer-start' + if interrupt['stageAtInterrupt'] != stage or not interrupt['domainRunningAtInterrupt'] or interrupt['fence'] != ops[0]['fence']: + fail('interrupt evidence does not identify the retained install operation mid-installer') + return a, b + + +def custody_evidence(store, ops, provider, a, b): + """Final provider custody: the Device returned Verified to no holder, both + allocations Released, and the site's fence equal to custody's.""" + custody = next((i for i in provider.values() if i['kind'] == 'DeviceCustody' and i['metadata']['name'] == harness.DEVICE.split('/')[1]), None) + allocations = {i['metadata']['name']: i for i in provider.values() if i['kind'] == 'MachineAllocation'} + if not custody or a not in allocations or b not in allocations: + fail('missing the Device custody or a consumer allocation in the provider project') + spec = custody['spec'] + if spec.get('state') != 'Verified' or spec.get('holder', {}).get('type') != 'None' or spec.get('activeOperation') or spec.get('recoveryHold'): + fail('final custody is not Verified with no holder, operation or hold: %s' % {k: spec.get(k) for k in ('state', 'holder', 'activeOperation', 'recoveryHold')}) + if spec.get('fence') != ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: + fail('custody fence %s, site fence %s/%s and the last operation fence %s differ' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) + if any(i['kind'] == 'DeviceRecovery' for i in provider.values()): + fail('a DeviceRecovery exists after an uninterrupted lifecycle') + record = {'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'device': harness.DEVICE, + 'custody': {'state': spec['state'], 'holder': spec['holder'], 'fence': spec['fence'], 'activeOperation': None, 'recoveryHold': None, + 'rejectedResults': spec.get('rejectedResults')}, + 'siteFence': {'seen': store['fence'], 'stopped': store['stopped']}, 'allocations': {}} + for consumer, name in (('consumerA', a), ('consumerB', b)): + m = allocations[name] + if m.get('status', {}).get('phase') != 'Released' or m['spec']['deviceRef']['name'] != harness.DEVICE.split('/')[1]: + fail('%s allocation %s is not Released for the Device' % (consumer, name)) + record['allocations'][consumer] = {'name': name, 'phase': 'Released', 'consumer': m['spec']['consumerRef'], 'machine': {k: m['spec']['machineRef'].get(k) for k in ('namespace', 'name')}, + 'wipe': m['status'].get('wipe')} + record['operations'] = [{k: o[k] for k in ('kind', 'name', 'operation', 'allocation', 'fence', 'phase')} for o in ops] + (ev / 'custody.json').write_text(json.dumps(record, indent=2, sort_keys=True) + '\n') + return record + + +def boot_record(raw, collection, name): + p = raw / 'site' / 'devices' / harness.device_dir().rsplit('/', 1)[1] / collection / (name + '.json') + return json.loads(p.read_text()) if p.exists() else {} + + def libvirt_provider(): raw = s / 'provider-private' raw.mkdir(mode=0o700, exist_ok=True) copy_out('/var/lib/fleet-local', raw) copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') - j = json.loads((raw / 'journal.json').read_text()) - ops = list(j['operations'].values()) - installs = [o for o in ops if o['request']['kind'] == 'install'] - cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] - if j.get('bootMode') != 'pxe' or len(installs) != 1 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): - fail('expected PXE mode, exactly one install and two verified cleanups') - if not j.get('closed'): - fail('allocation epoch is not closed after final cleanup') - epochs = sorted({o['request']['epoch'] for o in ops}) - if epochs != [1, 2]: - fail('expected allocation epochs 1 and 2, got %s' % epochs) - + store, ops, provider = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) - if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: - fail('interrupt evidence does not identify the retained install operation mid-installer') - - logs = list(raw.rglob('boot-delivery.log')) - written = '\n'.join(p.read_text() for p in logs) - for name in ('boot.ipxe', 'kernel', 'installer.gz'): - if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): - fail('missing completed broker write for ' + name) + a, b = check_sequence(ops, interrupt) + installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] + wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] receipts, starts = [], {} for o in installs: - op_id = o['request']['id'] - directory = raw / hashlib.sha256(op_id.encode()).hexdigest() + uid = o['operation'] + directory = raw / 'vm' / harness.key(harness.DEVICE) / harness.key(uid) + boot = boot_record(raw, 'vmboot', harness.key(uid)) + if not boot.get('closed') or boot.get('open') or boot.get('fence') != o['fence']: + fail('boot admission not closed at the install fence') + log = raw / 'boot-evidence' / harness.key(uid) / 'boot-delivery.log' + written = log.read_text() if log.exists() else '' + for name in ('boot.ipxe', 'kernel', 'installer.gz'): + if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): + fail('missing completed broker write for ' + name) for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): p = directory / filename lines = [line.strip() for line in p.read_text(errors='replace').splitlines()] if p.exists() else [] - if lines.count(marker + o['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: + if lines.count(marker + boot['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: fail('expected exactly one exact guest receipt in ' + filename) - receipts.append({'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) + receipts.append({'operation': uid, 'fence': o['fence'], 'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) if sum(1 for l in (directory / 'installer.log').read_text(errors='replace').splitlines() if re.match(r'^\+ sfdisk /dev/vda', l.strip())) != 1: fail('installer partitioned the disk other than exactly once') installer, disk = (directory / 'installer.xml').read_text(), (directory / 'disk.xml').read_text() @@ -142,27 +210,26 @@ def libvirt_provider(): fail('disk-only boot has a NIC or direct kernel') if '52:54:00:77:00:02' not in (directory / 'dhcp-leases.txt').read_text(): fail('missing DHCP lease for the installer NIC') - if not o.get('bootClosed'): - fail('boot admission not closed') - if (directory / 'disk.raw').exists(): - fail('cleaned allocation still has a guest disk') # libvirt appends one 'starting up' block per QEMU start. Independent of the # journal, this proves one firmware-network installer start and one disk start. - qemu = (raw / 'libvirt-qemu' / ('fleet-local-' + hashlib.sha256(op_id.encode()).hexdigest()[:24] + '.log')).read_text(errors='replace') + qemu = (raw / 'libvirt-qemu' / (harness.domain_name(uid) + '.log')).read_text(errors='replace') blocks = [b for b in re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:]] network = [b for b in blocks if '-netdev' in b and '52:54:00:77:00:02' in b] disk_only = [b for b in blocks if '-netdev' not in b and 'virtio-disk0' in b] - starts[op_id] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} + starts[uid] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} if len(blocks) != 2 or len(network) != 1 or len(disk_only) != 1 or blocks.index(network[0]) != 0: - fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[op_id]) - + fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[uid]) + # The release wipes deleted every installation disk of the Device. + if list((raw / 'vm').rglob('disk.raw')): + fail('a wiped Device still has an installation disk') domains = runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--all', '--name').strip() if domains: - fail('provider domain remains after cleanup') + fail('provider domain remains after the wipes') denials = (s / 'boot-denials.txt').read_text().strip() if (s / 'boot-denials.txt').exists() else '' if not denials.startswith('PASS'): fail('missing live closed-boot HTTP denial evidence') - return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + custody = custody_evidence(store, ops, provider, a, b) + return ops, installs, wipes, custody, interrupt, receipts, starts, denials def redfish_provider(): @@ -175,40 +242,33 @@ def redfish_provider(): copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') copy_out('/var/lib/fleet-lab-console', raw / 'lab-console') - j = json.loads((raw / 'journal.json').read_text()) - ops = sorted(j['operations'].values(), key=lambda o: o['result']['createdAt']) - installs = [o for o in ops if o['request']['kind'] == 'install'] - cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] - if j.get('provider') != 'redfish' or len(installs) != 2 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): - fail('expected the Redfish provider, two installs and two verified cleanups') - if [o['request']['kind'] for o in ops] != ['install', 'cleanup', 'install', 'cleanup'] or not j.get('closed'): - fail('expected install, cleanup, reinstall, cleanup with the final epoch closed') - epochs = sorted({o['request']['epoch'] for o in ops}) - if epochs != [1, 2]: - fail('expected allocation epochs 1 and 2, got %s' % epochs) - enrolled = json.loads((raw / 'enrollment.json').read_text()) - a = next(t for t in enrolled['targets'] if t['systemID'] == 'System-1') - for o in ops: - if o['target'] != a or o['system']['path'] != '/redfish/v1/Systems/System-1' or o['system']['uuid'] != a['systemUUID'] or not o.get('bootClosed'): - fail('an operation did not retain the exact enrolled target A System with closed boot admission') + store, ops, provider = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) - if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: - fail('interrupt evidence does not identify the retained install operation mid-installer') + a_alloc, b_alloc = check_sequence(ops, interrupt) + installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] + wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] + enrollment = json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]) + a = next(t for t in enrollment['targets'] if t['device'] == harness.DEVICE) + if a['systemID'] != 'System-1' or a['console'] != 'target-a.log': + fail('the allocated Device is not enrolled as lab target A') console = [l.strip() for l in (raw / 'lab-console' / 'target-a.log').read_text(errors='replace').splitlines()] expected, receipts = [], [] for o in ops: - want = ['FLEET-INSTALLED:' + o['receipt'], 'FLEET-DISK-BOOT:' + o['receipt']] if o['request']['kind'] == 'install' else ['FLEET-WIPED:%s:%d' % (o['receipt'], a['diskBytes'])] + boot = boot_record(raw, 'boot', o['operation']) + if not boot.get('closed') or boot.get('phase') or boot.get('fence') != o['fence'] or boot.get('mac') != a['mac'].lower(): + fail('an operation did not keep a closed boot admission for target A at its fence') + want = ['FLEET-INSTALLED:' + boot['receipt'], 'FLEET-DISK-BOOT:' + boot['receipt']] if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] for line in want: if console.count(line) != 1: - fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['request']['kind'])) + fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['kind'])) expected.append(console.index(line)) - receipts.append({'operation': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], - 'receipts': [line.split(':')[0] for line in want], 'receiptSHA256': hashlib.sha256(o['receipt'].encode()).hexdigest()}) - log = raw / 'boot-evidence' / hashlib.sha256(o['request']['id'].encode()).hexdigest() / 'boot-delivery.log' + receipts.append({'operation': o['operation'], 'kind': o['kind'], 'fence': o['fence'], + 'receipts': [line.split(':')[0] for line in want], 'receiptSHA256': hashlib.sha256(boot['receipt'].encode()).hexdigest()}) + log = raw / 'boot-evidence' / harness.key(o['operation']) / 'boot-delivery.log' written = log.read_text() if log.exists() else '' for name in ('boot.ipxe', 'kernel', 'installer.gz'): if 'write-complete ' + name + ' bytes=' not in written: - fail('missing completed boot delivery of %s for %s' % (name, o['request']['kind'])) + fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): fail('console receipts are out of order or include another operation') if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 2: @@ -229,14 +289,20 @@ def network(block): fail('expected exactly six effective On requests, all to System-1, and no other target effect') if sum(1 for e in ons if e.get('fault') == 'drop-response-after-effect') != 1: fail('the lost-response fault did not fire exactly once') + # Each boot was requested once: one journaled power-on step per phase. + powered = sum(1 for o in ops for n, st in o['steps'] if n.endswith('-power-on') and st == 'Done') + if powered != len(ons): + fail('journaled %d power-on steps for %d effective On requests' % (powered, len(ons))) if runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--name').strip(): fail('a lab target is still running') admission = json.loads((ev / 'kro-rbac.json').read_text())['admission'] - for case in ('Redfish worker mounting the libvirt socket', 'Redfish worker mounting the lab disks', 'Redfish worker with a libvirt URI', 'worker selecting the libvirt provider'): + for case in ('Redfish worker mounting the libvirt socket', 'Redfish worker mounting the lab disks', 'Redfish worker with a libvirt URI', 'worker selecting the libvirt provider', + 'Redfish worker mounting a credential Secret'): if admission.get(case, {}).get('deniedBy') != 'ValidatingAdmissionPolicy': fail('kro admission did not deny: ' + case) - if not admission.get('Redfish worker Job with the BMC credential', {}).get('admitted'): - fail('kro admission did not admit the Redfish worker shape') + for case in ('Redfish worker Job', 'worker credential Role'): + if not admission.get(case, {}).get('admitted'): + fail('kro admission did not admit: ' + case) for name in ('redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', 'redfish-bmc-interrupt.json', 'redfish-isolation.json'): if not (ev / name).exists(): fail('missing Redfish evidence ' + name) @@ -244,11 +310,12 @@ def network(block): if not denials.startswith('PASS'): fail('missing live closed-boot HTTP denial evidence') starts['redfishEffects'] = [{k: e.get(k) for k in ('method', 'path', 'status', 'resetType', 'boot', 'effect', 'fault')} for e in effects] - return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + custody = custody_evidence(store, ops, provider, a_alloc, b_alloc) + return ops, installs, wipes, custody, interrupt, receipts, starts, denials raw = s / 'provider-private' -ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = (redfish_provider if REDFISH else libvirt_provider)() +ops, installs, wipes, custody, interrupt, receipts, starts, denials = (redfish_provider if REDFISH else libvirt_provider)() # Kubernetes execution: what actually ran, as names, UIDs, phases and conditions. kro = kget('-n', 'kro-system', 'get', 'deployment')['items'] @@ -258,7 +325,7 @@ def network(block): if rgd['status'].get('state') != 'Active' or instance['status'].get('state') != 'ACTIVE': fail('kro RGD or HandoffDispatcher instance not active') jobs = kget('-n', 'fleet-site', 'get', 'jobs', '-l', 'app.kubernetes.io/name=fleet-site-worker')['items'] -handoffs = {h['metadata']['name']: json.loads(h['spec']['requestJSON']) for h in kget('-n', 'fleet-coordination', 'get', 'machineallocationhandoffs')['items']} +handoffs = {h['metadata']['name']: json.loads(h['spec']['assignmentJSON']) for h in kget('-n', 'fleet-coordination', 'get', 'machineallocationhandoffs', '-l', 'coordination.fleet.datumapis.com/role=assignment')['items']} worker_jobs = [] for job in jobs: handoff = job['metadata']['labels']['fleet.datumapis.com/handoff'] @@ -269,8 +336,9 @@ def network(block): exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in job_pods] if exits.count(0) != 1: fail('worker Job without exactly one successful Pod: ' + job['metadata']['name']) - worker_jobs.append({'job': job['metadata']['name'], 'uid': job['metadata']['uid'], 'operationID': handoffs[handoff]['id'], 'kind': handoffs[handoff]['kind'], - 'epoch': handoffs[handoff]['epoch'], 'conditions': conditions, 'succeeded': job['status'].get('succeeded', 0), 'failed': job['status'].get('failed', 0), + operation = handoffs[handoff]['operation'] + 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'), @@ -284,9 +352,9 @@ def network(block): mounts = [m.get('subPath', '') + ':' + m['mountPath'] for m in c.get('volumeMounts', [])] if env.get('FLEET_SITE_PROVIDER') != 'redfish' or 'FLEET_LIBVIRT_URI' in env or any('libvirt' in m or 'lab-disks' in m for m in mounts) or any('hostPath' in v for v in pod.get('volumes', [])): fail('a Redfish worker Job had a hypervisor path: ' + job['metadata']['name']) -expected_jobs = ['cleanup', 'cleanup', 'install', 'install'] if REDFISH else ['cleanup', 'cleanup', 'install'] -if sorted(j['kind'] for j in worker_jobs) != expected_jobs or any(j['createdBy'] != 'workers' for j in worker_jobs): - fail('expected kro-created worker Jobs for exactly one install and two cleanups, got %s' % [(j['kind'], j['createdBy']) for j in worker_jobs]) +# One kro-created worker Job per admitted operation, at that operation's fence. +if sorted((j['operationID'], j['fence']) for j in worker_jobs) != sorted((o['operation'], o['fence']) for o in ops) 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']) deployments = {d['metadata']['name']: {'uid': d['metadata']['uid'], 'availableReplicas': d['status'].get('availableReplicas', 0), @@ -311,7 +379,7 @@ def network(block): 'interruptions': json.loads((ev / 'interrupt.json').read_text()), 'lifecycle': json.loads((ev / 'lifecycle.json').read_text()), 'deliveryFaults': json.loads((ev / 'delivery-faults.json').read_text()), - 'authority': 'Job Complete, Flux Ready and kro Ready are execution facts only; management validated Karmada-reflected, journal-derived observations before any projection', + 'authority': 'Job Complete, Flux Ready and kro Ready are execution facts only; the custody coordinator accepted only Karmada-reflected results the site stored at each fence', } if execution['kro']['helmReleaseOwner'] != 'kro': fail('kro controller is not owned by the Flux HelmRelease') @@ -349,15 +417,17 @@ def network(block): 'gitops': {'sourceRevisions': [{k: r[k] for k in ('revision', 'digest', 'purpose', 'gitHead', 'contentSumsSHA256', 'files')} for r in flux_revisions], 'evidence': list(flux_files), 'siteImage': write_env['siteImage']}, 'installerStarts': starts, - 'reflectionRejections': ['wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing'], + 'reflectionRejections': list(REFLECTION_FAULTS), 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), 'custodyCRDRules': custody_rules, 'releasedProjection': {'consumerA': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer', 'installation': 'Released, Ready False'}, 'consumerB': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer'}}, - 'cleanupAndReuse': {'epochs': epochs, 'cleanups': len(cleanups), 'domainsAfterCleanup': [], 'disksAfterCleanup': 0}, + 'wipeAndReuse': {'fences': [o['fence'] for o in ops], 'wipes': [o['name'] for o in wipes], 'domainsAfterWipe': [], 'disksAfterWipe': 0}, + 'custody': 'custody.json', 'closedBootDenials': denials, }, - 'operations': [{'id': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], 'phase': o['result']['phase'], 'result': o['result']['result'], 'inputDigest': o['result']['inputDigest']} for o in ops], + 'operations': [{'operation': o['operation'], 'kind': o['kind'], 'name': o['name'], 'allocation': o['allocation'], 'fence': o['fence'], 'phase': o['phase'], + 'inputDigest': next((h['inputDigest'] for h in handoffs.values() if harness.operation_key(h['operation']['kind'], h['operation']['name'], h['fence']) == o['operation']), None)} for o in ops], 'projectRouting': routing, 'brokerWriteCompletion': True, 'guestEvidence': receipts, 'runtimePodMemoryEvents': {key: int(value) for key, value in memory_events.items()}, 'cellNodeMemoryEvents': {key: int(value) for key, value in node_memory_events.items()}, @@ -371,20 +441,20 @@ def network(block): 'privateArtifacts': 'state directory outside evidence/ contains authority; do not publish', } if REDFISH: - summary['qualification'].update(redfishExecutor=True, dmtfRedfishInterfaceEmulator='1.2.2 (unmodified) + lab-only libvirt adapter', bootedCleanupEnvironment=True, - physicalHardware=False, physicalBMC=False, vendorRedfishQualified=False, bmcTLS=False, mediaSanitization=False) - summary['scenarios']['cleanupAndReuse'] = {'epochs': epochs, 'installs': len(installs), 'cleanups': len(cleanups), 'reinstallOnReusedTarget': True, - 'cleanup': 'PXE-booted wipe environment zeroed and read back the whole 2 GiB virtual disk; the harness hashed the disk file as all zeroes. Logical test cleanup, not media sanitization.'} + summary['qualification'].update(redfishExecutor=True, dmtfRedfishInterfaceEmulator='1.2.2 (unmodified) + lab-only libvirt adapter', bootedWipeEnvironment=True, + physicalHardware=False, physicalBMC=False, vendorRedfishQualified=False, bmcTLS=True, mediaSanitization=False) + summary['scenarios']['wipeAndReuse'] = {'fences': [o['fence'] for o in ops], 'installs': len(installs), 'wipes': [o['name'] for o in wipes], 'reinstallOnReusedTarget': True, + 'wipe': 'PXE-booted wipe environment zeroed and read back the whole 2 GiB virtual disk; the harness hashed the disk file as all zeroes. Logical test wipe, not media sanitization.'} summary['scenarios']['redfish'] = {'evidence': ['redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', 'redfish-bmc-interrupt.json', 'redfish-isolation.json', 'redfish-audit.jsonl'], 'bootOrderTargetA': starts['targetA'], 'targetBStarts': starts['targetB'], 'effects': starts['redfishEffects']} summary['seams'] = [x for x in summary['seams'] if 'root libvirtd' not in x] + [ 'DMTF Redfish Interface Emulator with a lab-only adapter in place of a physical BMC; libvirt/QEMU TCG VMs in place of servers', - 'plain-HTTP Basic authentication with a synthetic per-run credential Secret enrolled by the harness (no TLS, rotation or vault)', + 'Basic authentication over TLS pinned to a lab key generated per run, with synthetic per-Device credential Secrets enrolled by the harness (no rotation or vault)', 'static lab provisioning network (libvirt dnsmasq) with MAC-chained iPXE; MAC is routing, not authentication', 'installation receipts read from a read-only serial-console capture (stand-in for SOL or an installer callback)', - 'trusted graph authors: worker Jobs hold the synthetic BMC credential; only the runtime and the lab BMC hold the libvirt socket', - 'one site journal fences every lab target (one allocatable target)'] + 'trusted graph authors: worker Jobs list the site BMC credential Secrets; only the runtime and the lab BMC hold the libvirt socket', + 'one allocatable lab target; the site store fences each Device separately'] (ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') for name in ('source-SHA256SUMS', 'sysctl.json'): if (s / name).exists(): diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 1766e672..75177d56 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -58,13 +58,13 @@ # Expected Flux Kustomizations per cluster (namespace/name), besides the root. EXPECTED = { 'platform': ['flux-system/milo-provider', 'flux-system/milo-consumer-a', 'flux-system/milo-consumer-b'], - 'hub': ['flux-system/karmada', 'flux-system/fleet-host', 'karmada-system/fleet-karmada-coordination', + 'hub': ['flux-system/karmada', 'karmada-system/fleet-karmada-coordination', 'karmada-system/fleet-karmada-api', 'karmada-system/fleet-karmada-members'], 'cell': ['flux-system/fleet-coordination', 'flux-system/fleet-federation', 'flux-system/kro', 'flux-system/fleet-site-base', 'flux-system/fleet-site-graph'], } HELMRELEASES = {'hub': ['flux-system/karmada'], 'cell': ['flux-system/kro']} -# Cell site layers present once the scoped asset is known (revision 2 onwards). +# Cell site layers present from revision 2 onwards. SITE_LAYERS = ['flux-system/fleet-site-services', 'flux-system/fleet-site-dispatch'] # A fixed ClusterIP in the static band (first 256 addresses) of kind's default # 10.96.0.0/16 Service range, so a recreated boot Service keeps its origin. @@ -185,10 +185,7 @@ def tools(args): def environment(state): s = pathlib.Path(state) - env = json.loads((s / 'gitops-environment.json').read_text()) - if (s / 'scoped-asset').exists(): - env['scopedAsset'] = (s / 'scoped-asset').read_text().strip() - return env + return json.loads((s / 'gitops-environment.json').read_text()) def sync_objects(cluster, url): @@ -274,7 +271,7 @@ def stage(args): data.update(FLEET_BMC_IMAGE=env['bmcImage'], FLEET_BMC_SERVICE_IP=BMC_SERVICE_IP) if args.site != 'absent': resources.insert(2, '../../config/multiplane/clusters/cell-site') - data.update(FLEET_SCOPED_ASSET=env['scopedAsset'], FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, + data.update(FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false') if args.bad_kro_chart: patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, @@ -678,7 +675,7 @@ def verify(args): for cluster, kind, ns, name in (('cell', 'namespace', None, 'fleet-site'), ('cell', 'namespace', None, 'fleet-coordination'), ('cell', 'crd', None, 'machineallocationhandoffs.coordination.fleet.datumapis.com'), ('cell', 'resourcegraphdefinition', None, RGD), ('cell', DISPATCHER[0], SITE, DISPATCHER[1]), - ('cell', 'storageclass', None, 'fleet-site-retain'), ('hub', 'namespace', None, 'fleet-system-private')): + ('cell', 'storageclass', None, 'fleet-site-retain')): o = kget(s, cluster, *(['-n', ns] if ns else []), 'get', kind, name) value = o['metadata'].get('annotations', {}).get('kustomize.toolkit.fluxcd.io/prune') protected['%s/%s/%s' % (cluster, kind, name)] = value @@ -728,12 +725,13 @@ def site_facts(state): jobs = sorted((j['metadata']['name'], j['metadata']['uid']) for j in kget(s, 'cell', '-n', 'fleet-site', 'get', 'jobs')['items']) pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') pv = kget(s, 'cell', 'get', 'pv', pvc['spec']['volumeName']) - journal = kubectl(s, 'cell', '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/lib/fleet-local/journal.json').stdout - secrets = kget(s, 'hub', '-n', 'fleet-system-private', 'get', 'secrets')['items'] - custody = hashlib.sha256(json.dumps(sorted((i['metadata']['name'], i['metadata']['uid'], i['metadata']['resourceVersion']) for i in secrets)).encode()).hexdigest() + # The provider project's custody and the site store's state for the + # Device (its fences and journal). + records, custody = harness.custody_digest(s) + store = kubectl(s, 'cell', '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', harness.STATE_PATH).stdout return {'jobs': jobs, 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvPhase': pv['status'].get('phase'), - 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'journalSHA256': hashlib.sha256(journal.encode()).hexdigest(), - 'custodyRecords': len(secrets), 'custodyDigest': custody} + 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'siteStoreSHA256': hashlib.sha256(store.encode()).hexdigest(), + 'custodyRecords': records, 'custodyDigest': custody} def same_facts(before, after, what): @@ -862,6 +860,29 @@ def worker_objects(state): for o in kget(s, 'cell', '-n', ns, 'get', kind)['items'] if o['metadata']['name'].startswith('w-op-')) +def handoff_outcome(s, handoff): + """The install handoff's outcome on the cell. Once the coordinator + accepted the result it labels the handoff answered and the cell deletes + its copy, so an answered handoff counts as Succeeded only when the + provider project's operation for it succeeded.""" + obj = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff) + result = obj.get('status', {}).get('observation', {}).get('result') + if result: + return result.get('phase') + if obj['metadata'].get('labels', {}).get('coordination.fleet.datumapis.com/answered') != 'true': + return None + operation = json.loads(obj['spec']['assignmentJSON'])['operation'] + kind = {'DeviceInstallation': 'deviceinstallation', 'DeviceWipe': 'devicewipe'}[operation['kind']] + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'provider' / 'bootstrap-project.json'), '-n', 'fleet-provider', 'get', kind, operation['name'], '-o', 'json'], text=True, capture_output=True) + if r.returncode != 0: + return None + current = json.loads(r.stdout) + # The operation admitted at the handoff's fence; a same-name operation + # created later has another fence. + status = current.get('status', {}) + return status.get('phase') if status.get('fence') == json.loads(obj['spec']['assignmentJSON'])['fence'] else None + + def graph_lifecycle(args): """Deleting the dispatcher instance removes only kro's per-operation objects. @@ -879,7 +900,7 @@ def graph_lifecycle(args): if sorted(k for k, n, _ in worker_objects(s) if n == 'w-' + handoff) != want: die('expected one kro-written Job, ServiceAccount, Role and RoleBinding for the install handoff: %s' % worker_objects(s)) before, uids, workers = site_facts(s), shared_uids(s), worker_objects(s) - status = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + status = handoff_outcome(s, handoff) if status != 'Succeeded': die('install handoff is not terminal before the graph lifecycle: %s' % status) old = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) @@ -920,7 +941,7 @@ def replayed(): owners_after, problems = ownership(s, snaps) if problems: die('ownership after the graph lifecycle:\n ' + '\n '.join(problems)) - status_after = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + status_after = handoff_outcome(s, handoff) if status_after != 'Succeeded': die('install handoff lost its terminal observation across the graph lifecycle: %s' % status_after) # kro deletes Jobs without a propagation policy, so batch/v1 orphans their diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index 19cbb231..a7d01022 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -26,15 +26,34 @@ DEBIAN = 'debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc' # Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', - 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) -READINESS_PACKAGES = ('./internal/coordination', './internal/multiplane', './internal/localvm', './cmd/fleet-multiplane') + 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) +READINESS_PACKAGES = ('./internal/coordination', './internal/custody', './internal/site/...', './internal/multiplane', './cmd/fleet-multiplane') # Redfish mode (run.sh --redfish) adds its executor and probe to the readiness gate. PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') if PROVIDER == 'redfish': - REQUIRED_SOURCE_MARKERS += ('"redfish-probe"', '"install-b"', 'redfish.Open()') + REQUIRED_SOURCE_MARKERS += ('"redfish-probe"', '"install-b"', 'redfish.NewPinnedClient') READINESS_PACKAGES += ('./internal/redfish',) -# Lab targets behind the Redfish emulator: System Id -> persistent libvirt domain. -LAB_DOMAINS = {'System-1': 'fleet-lab-target-a', 'System-2': 'fleet-lab-target-b'} +# The one Device the acceptance allocates, as the site store names it. In +# Redfish mode it is enrolled as lab target A (System-1), a persistent domain. +DEVICE = 'fleet-provider/synthetic-device-central-01' +LAB_DOMAIN = 'fleet-lab-target-a' +# The site store on the cell's retained volume (internal/site/store.go): one +# directory per Device, named by the first 16 bytes of the Device's SHA-256. +SITE_STORE = '/var/lib/fleet-local/site' + + +def device_dir(device=DEVICE): + return SITE_STORE + '/devices/' + hashlib.sha256(device.encode()).hexdigest()[:32] + + +STATE_PATH = device_dir() + '/state.json' +RESULTS_DIR = device_dir() + '/results' +# The journaled step that ends each kind, in either mode (internal/site/vmwork +# and internal/site/redfishwork). +FINAL_STEPS = {'DeviceInstallation': ('disk-verified',), 'DeviceWipe': ('wipe', 'wipe-verified')} +# Provider-project custody records, read with the provider's bootstrap credential. +CUSTODY_KINDS = ('devicecustodies.fleet.datumapis.com', 'deviceinstallations.fleet.datumapis.com', 'devicewipes.fleet.datumapis.com', + 'devicerecoveries.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') def now(): @@ -256,11 +275,25 @@ def runtime_exec(state, *command, timeout=20): 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command], timeout) -def journal(state): - code, out, err = runtime_exec(state, 'cat', '/var/lib/fleet-local/journal.json') +def read_site_store(run): + """The Device's site store state and its stored results, or (None, []). + run(*command) runs a read-only command in the runtime Pod and returns + (exit code, stdout).""" + code, out = run('cat', STATE_PATH) if code != 0: - return None - return json.loads(out) + return None, [] + store = json.loads(out) + code, out = run('sh', '-c', 'for f in %s/*.json; do [ -f "$f" ] && cat "$f" && echo; done; true' % RESULTS_DIR) + return store, [json.loads(l) for l in out.splitlines() if l.strip()] if code == 0 else [] + + +def site_store(state): + return read_site_store(lambda *command: runtime_exec(state, *command)[:2]) + + +def journal(state): + store, results = site_store(state) + return None if store is None else sanitized_operations(store, results) def domains(state): @@ -269,18 +302,72 @@ def domains(state): return out.split() if code == 0 else None -def domain_name(operation_id): - return 'fleet-local-' + hashlib.sha256(operation_id.encode()).hexdigest()[:24] +def key(operation_uid): + """An operation's 16-character key in domain, disk and boot evidence names.""" + return hashlib.sha256(operation_uid.encode()).hexdigest()[:16] + + +def domain_name(operation_uid): + return 'fleet-local-' + key(operation_uid) + + +def operation_kind(steps): + return 'DeviceWipe' if any(s == 'wipe' or s.startswith('wipe-') for s in steps) else 'DeviceInstallation' + +def operation_key(kind, name, fence): + """The site's key for one admission of an operation, as + custody.OperationKey builds it: no object UID is in any spec.""" + key = '%s.%s.%d' % (kind.lower(), name, fence) + if len(key) <= 128: + return key + return '%s.%s.%d' % (kind.lower(), hashlib.sha256(name.encode()).hexdigest()[:32], fence) -def sanitized_operations(j): - """Only non-secret fields: no fence, boot capability or receipt.""" - ops = [] - for r in (j or {}).get('operations', {}).values(): - ops.append({'id': r['request']['id'], 'kind': r['request']['kind'], 'epoch': r['request']['epoch'], - 'stage': r.get('stage'), 'phase': r.get('result', {}).get('phase'), 'bootClosed': r.get('bootClosed', False), - 'domain': LAB_DOMAINS.get(r.get('target', {}).get('systemID'), '?') if (j or {}).get('provider') == 'redfish' else domain_name(r['request']['id'])}) - return ops + +def provider_key(item): + """A provider-project operation's site key, from its admitted fence.""" + return operation_key(item['kind'], item['metadata']['name'], item.get('status', {}).get('fence', 0)) + + +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.""" + redfish = PROVIDER == 'redfish' if redfish is None else redfish + ops = {} + for e in (store or {}).get('journal') or []: + 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} + out = [] + for o in ops.values(): + kind = operation_kind([n for n, _ in o['steps']]) + o.update(kind=kind, stage=o['steps'][-1][0], stageState=o['steps'][-1][1], + done=any(n in FINAL_STEPS[kind] and st == 'Done' for n, st in o['steps']), + phase=phases.get((o['operation'], o['fence'])), domain=LAB_DOMAIN if redfish else domain_name(o['operation'])) + out.append(o) + return out + + +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']) + + +def custody(state): + """The provider project's custody, operations and allocations.""" + config = pathlib.Path(state) / 'provider' / 'bootstrap-project.json' + code, out, err = capture(['kubectl', '--kubeconfig', str(config), '--request-timeout=15s', '-n', 'fleet-provider', 'get', ','.join(CUSTODY_KINDS), '-o', 'json'], 30) + if code != 0: + raise SystemExit('provider custody unreadable: ' + err.strip()[-200:]) + return json.loads(out)['items'] + + +def custody_digest(state): + """Count and digest of the custody facts: spec, phase and fence of each record.""" + rows = sorted((i['kind'], i['metadata']['name'], i['metadata']['uid'], json.dumps(i.get('spec'), sort_keys=True), + i.get('status', {}).get('phase'), i.get('status', {}).get('fence')) for i in custody(state)) + return len(rows), hashlib.sha256(json.dumps(rows).encode()).hexdigest() def wait_stage(args): @@ -288,14 +375,13 @@ def wait_stage(args): deadline = time.monotonic() + args.timeout last = None while time.monotonic() < deadline: - ops = sanitized_operations(journal(args.state)) - installs = [o for o in ops if o['kind'] == 'install'] + installs = [o for o in journal(args.state) or [] if o['kind'] == 'DeviceInstallation'] running = domains(args.state) or [] last = {'installs': installs, 'runningDomains': len(running)} if len(installs) > 1: print(json.dumps({'error': 'more than one install operation', **last})) return EXIT_FAILED - if installs and installs[0]['stage'] in ('installer-verified', 'disk-armed', 'disk-requested', 'disk-started', 'disk-verified', 'done'): + if installs and past_installer(installs[0]): print(json.dumps({'error': 'installer completed before the interrupt window', **last})) return EXIT_FAILED if installs and installs[0]['stage'] == args.stage and installs[0]['domain'] in running: @@ -307,7 +393,12 @@ def wait_stage(args): def journal_cmd(args): - print(json.dumps(sanitized_operations(journal(args.state)), sort_keys=True)) + print(json.dumps(journal(args.state) or [], sort_keys=True)) + return 0 + + +def custody_cmd(args): + print('%d %s' % custody_digest(args.state)) return 0 @@ -332,17 +423,12 @@ def secrets(state): found.update(line.split(',')[0] for line in text.splitlines() if line.count(',') >= 2) for m in TOKEN.finditer(text): found.add(m.group(1)) - if p.name == 'journal.json': + # Copied site store boot admissions carry the one-time boot capability. + if p.suffix == '.json' and p.parent.name in ('vmboot', 'boot'): try: - j = json.loads(text) - except ValueError: - continue - if j.get('fence'): - found.add(j['fence']) - for r in j.get('operations', {}).values(): - for value in (r.get('bootToken'), r.get('request', {}).get('fenceToken')): - if value: - found.add(value) + found.add(json.loads(text).get('token') or '') + except (ValueError, AttributeError): + pass for m in re.finditer(r'-----BEGIN [A-Z ]*PRIVATE KEY-----[^-]+', text): found.add(m.group(0)[40:100]) return {s for s in found if s and len(s) >= 16} @@ -411,6 +497,8 @@ def main(): s.add_argument('--interval', type=float, default=1.0) s = sub.add_parser('journal') s.add_argument('--state', required=True) + s = sub.add_parser('custody-digest') + s.add_argument('--state', required=True) s = sub.add_parser('scan') s.add_argument('--state', required=True) s.add_argument('--extra', nargs='*') @@ -423,7 +511,7 @@ def main(): a.command = a.command[1:] if not a.command or not re.match(r'^[a-z0-9-]+$', a.name): return EXIT_USAGE - return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, + return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, 'custody-digest': custody_cmd, 'scan': scan, 'result': result}[a.cmd](a) diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 0cc3c4d6..73f8eea4 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -2,8 +2,8 @@ """Kubernetes site observation, fault injection and sanitized execution records. Every call goes through the selected cell's API with its bootstrap kubeconfig. -Records keep names, UIDs, phases, exit codes and conditions only: never handoff -specs, journal records, fences, boot capabilities or tokens. +Records keep names, UIDs, fences, phases, exit codes and conditions only: never +assignment inputs, journal payloads, boot capabilities or tokens. """ import datetime import hashlib @@ -13,9 +13,13 @@ import subprocess import sys -NS, SITE = 'fleet-coordination', 'fleet-site' +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout) + +NS, SITE, CREDENTIALS = 'fleet-coordination', 'fleet-site', 'fleet-site-credentials' LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' REDFISH = os.environ.get('FLEET_SITE_PROVIDER') == 'redfish' +CELL_LABEL, ROLE_LABEL = 'coordination.fleet.datumapis.com/cell', 'coordination.fleet.datumapis.com/role' def now(): @@ -76,7 +80,26 @@ def write(path, value): def installs(path): - return [o for o in json.loads(pathlib.Path(path).read_text()) if o['kind'] == 'install'] + return [o for o in json.loads(pathlib.Path(path).read_text()) if o['kind'] == 'DeviceInstallation'] + + +def assignment_name(assignment): + """internal/coordination.AssignmentName: the only name an assignment's handoff may have.""" + key = harness.operation_key(assignment['operation']['kind'], assignment['operation']['name'], assignment['fence']) + return 'op-' + hashlib.sha256(('%s/%s' % (assignment['device'], key)).encode()).hexdigest()[:40] + + +def observation(state, name): + return (get(state, '-n', NS, 'get', 'machineallocationhandoff', name).get('status') or {}).get('observation') + + +DEVICE = 'fleet-provider/synthetic-device-central-01' +OTHER_DEVICE = 'fleet-provider/synthetic-device-central-02' + + +def credential_name(device): + """The only name a Device's credential Secret may have at the site.""" + return 'bmc-' + hashlib.sha256(device.encode()).hexdigest()[:20] def worker_rbac(state, name): @@ -94,15 +117,36 @@ def worker_rbac(state, name): for args in (('-n', NS, 'get', 'machineallocationhandoff', 'op-other-operation'), ('-n', NS, 'get', 'machineallocationhandoffs'), ('-n', NS, 'patch', 'machineallocationhandoff', name, '--subresource=status', '--type=merge', '-p', '{"status":{}}'), ('-n', NS, 'patch', 'machineallocationhandoff', name, '--type=merge', '-p', '{"spec":{"cell":"other"}}'), - ('-n', NS, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs')): + ('-n', NS, 'get', 'secrets'), ('-n', SITE, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs'), + # Another Device's credential, and listing or watching them, are + # denied in both modes. + ('-n', CREDENTIALS, 'get', 'secret', credential_name(OTHER_DEVICE)), ('-n', CREDENTIALS, 'get', 'secrets'), + ('-n', CREDENTIALS, 'get', 'secrets', '--watch', '--request-timeout=5s'), + *((('-n', CREDENTIALS, 'get', 'secret', credential_name(DEVICE)),) if not REDFISH else ())): r = kubectl(state, *args, check=False, config='worker-kubeconfig.json') if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): raise SystemExit('worker credential allowed: ' + ' '.join(args[:4]) + ' ' + r.stderr[:200]) - denied.append(' '.join(args[2:4]) + (' (status)' if '--subresource=status' in args else '')) + denied.append(args[1] + ' ' + ' '.join(args[2:4]) + (' (status)' if '--subresource=status' in args else '')) + record = {'observedAt': now(), 'serviceAccount': 'w-' + name, 'ownHandoffReadable': True, 'forbidden': denied} role = get(state, '-n', NS, 'get', 'role', 'w-' + name) - write(s / 'k8s-worker-rbac.json', {'observedAt': now(), 'serviceAccount': 'w-' + name, 'roleRules': role['rules'], - 'ownHandoffReadable': True, 'forbidden': denied, 'roleCreatedBy': role['metadata'].get('labels', {}).get('kro.run/node-id')}) - print('worker-rbac: per-operation ServiceAccount reads only its own handoff; list, other names, status, spec, Secrets and site writes forbidden') + record.update(roleRules=role['rules'], roleCreatedBy=role['metadata'].get('labels', {}).get('kro.run/node-id')) + if REDFISH: + # A Redfish worker may get exactly the credential Secret of the Device + # its assignment names, and nothing else. No handoff field names it. + spec = get(state, '-n', NS, 'get', 'machineallocationhandoff', name)['spec'] + if 'credential' in spec: + raise SystemExit('the handoff names a credential Secret: %s' % spec['credential']) + own = credential_name(json.loads(spec['assignmentJSON'])['device']) + mine = kubectl(state, '-n', CREDENTIALS, 'get', 'secret', own, '-o', 'name', check=False, config='worker-kubeconfig.json') + if mine.returncode: + raise SystemExit("Redfish worker cannot get its own Device's credential: " + mine.stderr[:200]) + creds = get(state, '-n', CREDENTIALS, 'get', 'role', 'w-' + name) + if creds['rules'] != [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': [own], 'verbs': ['get']}]: + raise SystemExit('Redfish worker credential Role is not get on its one Secret: %s' % creds['rules']) + record.update(ownCredentialReadable=True, credentialRoleRules=creds['rules']) + write(s / 'k8s-worker-rbac.json', record) + print('worker-rbac: per-operation ServiceAccount reads only its own handoff; list, other names, status, spec, Secrets and site writes forbidden' + + ("; it gets only its own Device's BMC credential Secret, never another's, and lists none" if REDFISH else '')) def record_pod_interrupt(state, before, after): @@ -111,12 +155,12 @@ def record_pod_interrupt(state, before, after): after_ops = installs(s / 'interrupt-after.json') jb = json.loads((s / 'interrupt-job-before-pod.json').read_text()) ja = json.loads((s / 'interrupt-job-after-pod.json').read_text()) - if len(after_ops) != 1 or after_ops[0]['id'] != seen['operation']['id'] or after_ops[0]['stage'] == 'done': - raise SystemExit('interrupted operation is not the same unfinished operation') + if len(after_ops) != 1 or after_ops[0]['operation'] != seen['operation']['operation'] or after_ops[0]['done'] or after_ops[0]['phase']: + raise SystemExit('interrupted operation is not the same unfinished operation without a result') if jb['uid'] != ja['uid'] or ja['failed'] < 1: raise SystemExit('Job controller did not account and replace the lost Pod in the same Job: %s' % ja) write(evidence(state) / 'interrupt.json', { - 'observedAt': now(), 'operationID': seen['operation']['id'], 'domain': seen['operation']['domain'], + 'observedAt': now(), 'operationID': seen['operation']['operation'], 'fence': seen['operation']['fence'], 'domain': seen['operation']['domain'], 'stageAtInterrupt': seen['operation']['stage'], 'domainRunningAtInterrupt': seen['domainRunning'], 'podInterruption': {'method': 'worker Pod force-deleted with grace period 0', 'deletedPodUID': before, 'replacementPodUID': after, 'jobUID': jb['uid'], 'jobFailedPodsBefore': jb['failed'], 'jobFailedPodsAfter': ja['failed'], 'replacedBy': 'Job controller'}, @@ -127,9 +171,9 @@ def record_job_interrupt(state, old, new, pod_before, pod_after): s = pathlib.Path(state) i = interrupt_record(state) before, after = installs(s / 'interrupt-job-before.json'), installs(s / 'interrupt-job-after.json') - if len(before) != 1 or before[0]['stage'] == 'done': + if len(before) != 1 or before[0]['done']: raise SystemExit('install finished before the Job could be deleted mid-operation') - if len(after) != 1 or after[0]['id'] != i['operationID']: + if len(after) != 1 or after[0]['operation'] != i['operationID'] or after[0]['fence'] != i['fence']: raise SystemExit('Job recreation created another install operation') i['jobRecreation'] = {'deletedJobUID': old, 'recreatedJobUID': new, 'recreatedBy': 'kro collection reconciliation', 'podBeforeUID': pod_before, 'podAfterUID': pod_after, 'stageAtDeletion': before[0]['stage'], 'stageAfterRecreation': after[0]['stage']} @@ -140,20 +184,25 @@ def record_resume(state, name): s = pathlib.Path(state) i = interrupt_record(state) done = installs(s / 'resume-after.json') - if len(done) != 1 or done[0]['id'] != i['operationID'] or done[0]['stage'] != 'done' or done[0]['phase'] != 'Succeeded': + if len(done) != 1 or done[0]['operation'] != i['operationID'] or done[0]['fence'] != i['fence'] or not done[0]['done']: raise SystemExit('replacement workers did not complete the exact interrupted operation') + # The observer published the stored result for exactly that assignment. + result = (observation(state, name) or {}).get('result') or {} + operation = result.get('operation', {}) + if result.get('phase') != 'Succeeded' or harness.operation_key(operation.get('kind', ''), operation.get('name', ''), result.get('fence', 0)) != i['operationID'] or result.get('fence') != i['fence']: + raise SystemExit('the observed result is not the interrupted operation Succeeded at its fence') j, ps = job(state, name), pods(state, name) if j['uid'] != i['jobRecreation']['recreatedJobUID'] or ['Complete', 'True', 'CompletionsReached'] not in j['conditions']: raise SystemExit('recreated Job did not complete: %s' % j) if [p['exitCode'] for p in ps if p['phase'] == 'Succeeded'] != [0]: raise SystemExit('expected exactly one succeeded worker Pod in the recreated Job: %s' % ps) - i.update(resumedStage=done[0]['stage'], resumedPhase=done[0]['phase'], installOperations=len(done), completedJob=j, completedJobPods=ps) + i.update(resumedStage=done[0]['stage'], resumedPhase=result['phase'], installOperations=len(done), completedJob=j, completedJobPods=ps) write(evidence(state) / 'interrupt.json', i) def qemu_starts(state, operation): # Redfish mode: the persistent lab target A carries every operation. - domain = 'fleet-lab-target-a' if REDFISH else 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] + domain = harness.LAB_DOMAIN if REDFISH else harness.domain_name(operation) r = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/log/libvirt/qemu/' + domain + '.log', check=False) return r.stdout.count(': starting up ') if r.returncode == 0 else None @@ -167,7 +216,7 @@ def lifecycle_snapshot(state, name): conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} site_pods = {d: [p['metadata']['uid'] for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=' + d)['items']] for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')} - print(json.dumps({'observedAt': now(), 'journalSHA256': hashlib.sha256(runtime(state, 'cat', '/var/lib/fleet-local/journal.json').encode()).hexdigest(), + print(json.dumps({'observedAt': now(), 'siteStoreSHA256': hashlib.sha256(runtime(state, 'cat', harness.STATE_PATH).encode()).hexdigest(), 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', *([] if REDFISH else ['--all'])).split(), 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvReclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'machineA': {'phase': machine.get('status', {}).get('phase'), 'bound': conds.get('Bound'), 'ready': conds.get('Ready')}, @@ -177,7 +226,7 @@ def lifecycle_snapshot(state, name): def record_lifecycle(state, old, new): s = pathlib.Path(state) a, b = json.loads((s / 'lifecycle-before.json').read_text()), json.loads((s / 'lifecycle-after.json').read_text()) - for key in ('journalSHA256', 'qemuStarts', 'pvcUID', 'pvUID', 'pvReclaimPolicy', 'domains', 'machineA'): + 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': @@ -191,65 +240,118 @@ def record_lifecycle(state, old, new): raise SystemExit('recreated completed Job did not finish with one verified no-op replay: %s' % replay) write(evidence(state) / 'lifecycle.json', {'observedAt': now(), 'recreated': ['fleet-site-runtime Pod', 'fleet-site-boot Pod', 'fleet-site-observer Pod', 'completed install Job'], 'completedJobUIDBefore': old, 'completedJobUIDAfter': new, 'replayPods': replay, - 'unchanged': ['provider journal bytes', 'QEMU starts (2)', 'PVC/PV identity', 'Retain reclaim policy', 'no domains', 'consumer-a Machine Ready/Bound'], - 'journalSHA256': a['journalSHA256'], 'observerRepublished': True, 'before': a, 'after': b}) + 'unchanged': ['site store state bytes', 'QEMU starts (2)', 'PVC/PV identity', 'Retain reclaim policy', 'no domains', 'consumer-a Machine Ready/Bound'], + 'siteStoreSHA256': a['siteStoreSHA256'], 'observerRepublished': True, 'before': a, 'after': b}) + + +FAULTS = ('duplicate', 'wrong-cell', 'stale-fence') +# Faults delivered to the cell; the duplicate never exists. +JOB_FAULTS = ('wrong-cell', 'stale-fence', 'device-mismatch') -FAULTS = ('duplicate', 'wrong-cell', 'stale-epoch') +def handoff(name, cell, spec, fault): + return {'apiVersion': 'coordination.fleet.datumapis.com/v1alpha1', 'kind': 'MachineAllocationHandoff', + 'metadata': {'name': name, 'namespace': NS, 'labels': {CELL_LABEL: cell, ROLE_LABEL: 'assignment', 'fleet.datumapis.com/fault': fault}}, 'spec': spec} def delivery_faults(state, action): + """Each fault derives from the latest delivered assignment, whose fence is + the Device's stored fence: a duplicate of it, the same assignment for + another cell, the same operation below that fence, a handoff that names + another Device's credential Secret, and a handoff whose assignment names + another Device than the handoff does.""" s = pathlib.Path(state) cell = (s / 'prefix').read_text().strip() + '-cell' + private = s / 'fault-handoffs.json' if action == 'create': - handoffs = get(state, '-n', NS, 'get', 'machineallocationhandoffs', '-l', 'coordination.fleet.datumapis.com/cell=' + cell)['items'] - source = [h for h in handoffs if json.loads(h['spec']['requestJSON'])['kind'] == 'install' and json.loads(h['spec']['requestJSON'])['epoch'] == 1] - if len(source) != 1: - raise SystemExit('expected exactly one epoch-1 install handoff to derive faults from') - spec = source[0]['spec'] - request = json.loads(spec['requestJSON']) - objects = {} - # Same retained intent under a second name: name/operation binding fails. - objects['duplicate'] = ('op-fault-duplicate-' + hashlib.sha256(spec['requestJSON'].encode()).hexdigest()[:12], dict(spec)) - # Selected by the cell label, but the intent names another cell. - wrong = dict(request, id=request['id'] + '-fault-wrong-cell') - objects['wrong-cell'] = ('op-' + hashlib.sha256(wrong['id'].encode()).hexdigest()[:40], {'cell': 'remote-elsewhere-cell', 'requestJSON': json.dumps(wrong, separators=(',', ':'))}) - # Well-formed for this cell, but replays the superseded epoch-1 fence. - stale = dict(request, id=request['id'] + '-fault-stale-epoch') - objects['stale-epoch'] = ('op-' + hashlib.sha256(stale['id'].encode()).hexdigest()[:40], {'cell': cell, 'requestJSON': json.dumps(stale, separators=(',', ':'))}) - if request['epoch'] != 1: - raise SystemExit('stale-epoch fault requires the epoch-1 install handoff') - for fault in FAULTS: - name, body = objects[fault] - obj = {'apiVersion': 'coordination.fleet.datumapis.com/v1alpha1', 'kind': 'MachineAllocationHandoff', - 'metadata': {'name': name, 'namespace': NS, 'labels': {'coordination.fleet.datumapis.com/cell': cell, 'fleet.datumapis.com/fault': fault}}, 'spec': body} - kubectl(state, 'create', '-f', '-', input=json.dumps(obj)) - (s / ('fault-%s-job' % fault)).write_text('w-' + name + '\n') - (s / ('fault-%s-handoff' % fault)).write_text(name + '\n') + handoffs = get(state, '-n', NS, 'get', 'machineallocationhandoffs', '-l', '%s=%s,%s=assignment' % (CELL_LABEL, cell, ROLE_LABEL))['items'] + if not handoffs: + raise SystemExit('no delivered assignment to derive faults from') + source = max(handoffs, key=lambda h: json.loads(h['spec']['assignmentJSON'])['fence']) + assignment = json.loads(source['spec']['assignmentJSON']) + if source['metadata']['name'] != assignment_name(assignment) or assignment['fence'] < 2: + raise SystemExit('the stale-fence fault needs a delivered assignment under its own name with a fence of at least 2') + faults = {} + # The same assignment again: its name is fixed by its contents, so the API refuses it. + dup = handoff(source['metadata']['name'], cell, source['spec'], 'duplicate') + r = kubectl(state, 'create', '-f', '-', input=json.dumps(dup), check=False) + if r.returncode == 0 or 'AlreadyExists' not in r.stderr: + raise SystemExit('a duplicate assignment was not refused as AlreadyExists: ' + r.stderr[:200]) + faults['duplicate'] = {'handoff': source['metadata']['name'], 'refused': 'AlreadyExists'} + # Selected by the cell label, but the handoff names another cell. + wrong = dict(assignment, operation=dict(assignment['operation'], name=assignment['operation']['name'] + '-fault-wrong-cell')) + faults['wrong-cell'] = {'handoff': assignment_name(wrong), 'spec': {'cell': 'remote-elsewhere-cell', 'device': assignment['device'], + 'assignmentJSON': json.dumps(wrong, separators=(',', ':'))}} + # Well-formed for this cell under its own name, but below the stored fence. + stale = dict(assignment, fence=assignment['fence'] - 1) + faults['stale-fence'] = {'handoff': assignment_name(stale), 'operation': harness.operation_key(stale['operation']['kind'], stale['operation']['name'], stale['fence']), 'fence': stale['fence'], + 'spec': {'cell': cell, 'device': assignment['device'], 'assignmentJSON': json.dumps(stale, separators=(',', ':'))}} + # The handoff names this Device, but its assignment names another, below + # the stored fence. Its worker refuses it, and it gets no credential + # Role, so neither Device's Secret is granted for it. + mismatched = dict(assignment, device=OTHER_DEVICE, fence=assignment['fence'] - 1, + operation=dict(assignment['operation'], name=assignment['operation']['name'] + '-fault-device')) + faults['device-mismatch'] = {'handoff': assignment_name(mismatched), 'spec': {'cell': cell, 'device': assignment['device'], + 'assignmentJSON': json.dumps(mismatched, separators=(',', ':'))}} + for fault in JOB_FAULTS: + f = faults[fault] + kubectl(state, 'create', '-f', '-', input=json.dumps(handoff(f['handoff'], cell, f.pop('spec'), fault))) + (s / ('fault-%s-job' % fault)).write_text('w-' + f['handoff'] + '\n') + # A forged handoff naming another Device's credential Secret. No handoff + # field may name a Secret, so the API refuses it, and no Role on that + # Secret is ever created. + foreign = dict(assignment, fence=assignment['fence'] - 1, operation=dict(assignment['operation'], name=assignment['operation']['name'] + '-fault-credential')) + forged = handoff(assignment_name(foreign), cell, {'cell': cell, 'device': assignment['device'], 'assignmentJSON': json.dumps(foreign, separators=(',', ':')), + 'credential': credential_name(OTHER_DEVICE)}, 'foreign-credential') + r = kubectl(state, 'create', '--validate=strict', '-f', '-', input=json.dumps(forged), check=False) + if r.returncode == 0: + raise SystemExit('a handoff naming another Device\'s credential Secret was accepted') + if 'unknown field' not in r.stderr or 'credential' not in r.stderr: + raise SystemExit('a handoff naming a credential Secret was refused for another reason: ' + r.stderr[:200]) + if kubectl(state, '-n', NS, 'get', 'machineallocationhandoff', assignment_name(foreign), check=False).returncode == 0: + raise SystemExit('the refused credential handoff exists') + faults['foreign-credential'] = {'handoff': assignment_name(foreign), 'refused': 'unknown field spec.credential'} + faults['source'] = {'handoff': source['metadata']['name'], 'operation': assignment['operation'], 'fence': assignment['fence']} + write(private, faults) return - names = {f: (s / ('fault-%s-handoff' % f)).read_text().strip() for f in FAULTS} + faults = json.loads(private.read_text()) if action == 'verify': - record = {'observedAt': now(), 'faults': {}} - for fault, name in names.items(): + record = {'observedAt': now(), 'source': faults['source'], 'faults': {'duplicate': faults['duplicate'], 'foreign-credential': faults['foreign-credential']}} + # No Role at the site grants any Secret but the one of the Device its + # own assignment names; another Device's credential is never granted. + for role in get(state, '-n', CREDENTIALS, 'get', 'roles')['items']: + names = [n for rule in role.get('rules', []) for n in rule.get('resourceNames', [])] + if credential_name(OTHER_DEVICE) in names: + raise SystemExit('Role %s grants another Device\'s credential Secret' % role['metadata']['name']) + for fault in JOB_FAULTS: + name = faults[fault]['handoff'] j, ps = job(state, name), pods(state, name) if ['Failed', 'True', 'PodFailurePolicy'] not in j['conditions'] or j['succeeded'] or [p['exitCode'] for p in ps] != [65]: raise SystemExit('%s fault Job did not fail once by podFailurePolicy exit 65: %s %s' % (fault, j, ps)) - h = get(state, '-n', NS, 'get', 'machineallocationhandoff', name) - if h.get('status'): - raise SystemExit(fault + ' fault handoff gained a status observation') - record['faults'][fault] = {'handoff': name, 'job': j, 'pods': ps, 'status': None} + seen = observation(state, name) + if fault == 'wrong-cell' and seen: + raise SystemExit('the wrong-cell handoff gained an observation') + if fault == 'stale-fence' and (seen or {}).get('result'): + raise SystemExit('the stale-fence handoff gained a result') + if fault == 'device-mismatch' and kubectl(state, '-n', CREDENTIALS, 'get', 'role', 'w-' + name, check=False).returncode == 0: + raise SystemExit('the device-mismatch handoff was granted a credential Role') + record['faults'][fault] = {'handoff': name, 'job': j, 'pods': ps, 'observedFence': (seen or {}).get('fence'), 'result': None} + stored = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'test', '-e', + '%s/%s.json' % (harness.RESULTS_DIR, faults['stale-fence']['operation']), check=False) + if stored.returncode == 0: + raise SystemExit('the site stored a result for the stale-fence assignment') machine = get(state, '-n', 'default', 'get', 'machine', 'allocation', config='consumer-b/management-project.json') conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} if machine.get('status', {}).get('phase') != 'Bound' or conds.get('Bound') != 'True': raise SystemExit('failed fault Jobs changed consumer-b allocation: %s' % machine.get('status')) - record['providerJournalUnchanged'] = True - record['consumerBStillBound'] = True + record.update(siteStoreUnchanged=True, staleResultStored=False, consumerBStillBound=True) write(evidence(state) / 'delivery-faults.json', record) return - for name in names.values(): + names = [faults[f]['handoff'] for f in JOB_FAULTS] + for name in names: kubectl(state, '-n', NS, 'delete', 'machineallocationhandoff', name, '--wait=true') for _ in range(120): - left = [n for n in names.values() if kubectl(state, '-n', SITE, 'get', 'job', 'w-' + n, check=False).returncode == 0] + left = [n for n in names if kubectl(state, '-n', SITE, 'get', 'job', 'w-' + n, check=False).returncode == 0] if not left: break subprocess.run(['sleep', '1']) diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 0e3dc5e6..5e5ee1c2 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -8,8 +8,12 @@ - credential enrollment: per-API static tokens and a self-signed serving key, written as the milo-apiserver-private Secret (local credential seam); - tenant fixture bootstrap through each API: the Project, static-token RBAC - grants and the metal CRDs inside the project. Production uses Milo's own - project provisioning, service catalog and IAM; this is not that machinery. + grants and the metal CRDs inside the project, and in the provider project + the inventory and Device custody CRDs. The provider project's Fleet + components each get their own token: the Metal provider (management), the + custody coordinator, the release controller and fixture discovery. + Production uses Milo's own project provisioning, service catalog and IAM; + this is not that machinery. """ import argparse, base64, json, os, pathlib, secrets, subprocess, time p=argparse.ArgumentParser();p.add_argument('state');p.add_argument('prefix');a=p.parse_args() @@ -34,7 +38,8 @@ def wait(fn,seconds,what): d=root/role;ns='milo-'+role if not d.exists(): d.mkdir(mode=0o700) - tokens={r:secrets.token_hex(32) for r in ('bootstrap','management','customer')} + who=('bootstrap','management','customer')+(('coordinator','release','discovery') 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) for f in ('tokens.csv','tls.key','tls.crt'):(d/f).chmod(0o600) @@ -73,6 +78,28 @@ def wait(fn,seconds,what): ns='fleet-provider' if role=='provider' else 'default' apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations'],'verbs':['get','list','watch']}] + if role=='provider': + for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml'): + kubectl(config,'apply','-f',crds,stdout=subprocess.DEVNULL) + kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) + # The CRD rule check writes its synthetic objects here, away from the + # 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. + 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']}] + components={ + 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries'],'verbs':['get','list','watch','delete']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, + {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], + 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], + 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}]} + for who,component in components.items(): + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-'+who},'rules':component}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-'+who},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-'+who},'subjects':[{'kind':'User','name':who}]}) if role!='provider':rules += [{'apiGroups':['metal.datumapis.com'],'resources':['machines'],'verbs':['update']},{'apiGroups':['metal.datumapis.com'],'resources':['machines/status','installations/status'],'verbs':['update','patch']}] apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-management'},'rules':rules}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index b6ec0ffc..a0aa3941 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -3,8 +3,8 @@ Every observation goes through the selected cell's API. Lab faults are written only through the lab BMC adapter's fault file (bounded, one-shot) and are -recorded. Evidence records methods, paths, outcome classes, UIDs and digests, -never the BMC credential, fences, boot capabilities or request bodies. +recorded. Evidence records methods, paths, outcome classes, UIDs, fences and digests, +never the BMC credential, boot capabilities or request bodies. enroll create the synthetic BMC credential Secret (never in Git) baseline snapshot target B and the BMC audit before any operation @@ -12,8 +12,8 @@ credentials, identity mismatch and a hidden ResetType arm-lost-response one-shot: withhold the response to target A's second effective On (the disk boot of the first install) - lost-response the worker lost the On response after the effect; - recovery observed the target instead of repeating it + lost-response stop the worker while that On awaits its response; + the replacement observed the target instead of repeating it bmc-interrupt delete the BMC Pod mid-installer; the guest keeps running isolation target B untouched, target A disk verifiably zeroed """ @@ -27,12 +27,18 @@ import sys import time +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout) + SITE = 'fleet-site' TARGET_A = {'system': 'System-1', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a', 'domain': 'fleet-lab-target-a', 'disk': '/var/lib/fleet-lab/disks/target-a.raw'} TARGET_B = {'system': 'System-2', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b', 'domain': 'fleet-lab-target-b', 'disk': '/var/lib/fleet-lab/disks/target-b.raw'} DISK_BYTES = 2 << 30 LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' SECRET = 'fleet-site-bmc-credentials' +TLS_SECRET = 'fleet-site-bmc-tls' +CREDENTIALS = 'fleet-site-credentials' +BMC_IP = '10.96.0.81' def now(): @@ -75,20 +81,29 @@ def mutating(entries, system=None): return [e for e in entries if e['method'] not in ('GET', 'HEAD') and (system is None or e['path'].rstrip('/').startswith('/redfish/v1/Systems/' + system))] -def journal(s): - return json.loads(runtime(s, 'cat', '/var/lib/fleet-local/journal.json').stdout) +def journal(s, pending_ok=False): + """The Device's journaled operations, sanitized: UID, fence, kind and steps.""" + # pending_ok: before the first worker raises the fence there is no state yet. + def run(*command): + r = runtime(s, *command, check=False) + return r.returncode, r.stdout + store, results = harness.read_site_store(run) + if store is None and not pending_ok: + die('the site store holds no state for the Device') + return harness.sanitized_operations(store, results, redfish=True) def installs(s, pending_ok=False): - # pending_ok: before the first worker retains its operation there is no journal yet. - if pending_ok: - r = runtime(s, 'cat', '/var/lib/fleet-local/journal.json', check=False) - if r.returncode: - return [] - ops = json.loads(r.stdout)['operations'].values() - else: - ops = journal(s)['operations'].values() - return [o for o in ops if o['request']['kind'] == 'install'] + return [o for o in journal(s, pending_ok) if o['kind'] == 'DeviceInstallation'] + + +def done(op, step): + return [step, 'Done'] in op['steps'] + + +def power_ons(op): + """Journaled power-on steps by phase. The journal holds one entry per step.""" + return {n[:-len('-power-on')]: st for n, st in op['steps'] if n.endswith('-power-on')} def qemu_starts(s, domain): @@ -109,23 +124,59 @@ def running(s): return runtime(s, 'virsh', '--connect', LIBVIRT, 'list', '--name').stdout.split() +def credential_name(device): + """The only name a Device's credential Secret may have at the site.""" + return 'bmc-' + hashlib.sha256(device.encode()).hexdigest()[:20] + + def enroll(s): d = s / 'redfish' d.mkdir(mode=0o700, exist_ok=True) (d / 'bmc-username').write_text('fleet-lab-operator\n') # The .token suffix enrolls the value in the harness secret scan. (d / 'bmc-password.token').write_text(secrets.token_hex(32) + '\n') + # The lab BMC's TLS key is generated per run and never committed. Workers + # connect only to this key: its digest is each Device's approved pin. + subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'bmc-tls.key'), + '-out', str(d / 'bmc-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-bmc', '-addext', 'subjectAltName=IP:%s' % BMC_IP], + check=True, capture_output=True) + spki = subprocess.run(['openssl', 'x509', '-in', str(d / 'bmc-tls.crt'), '-pubkey', '-noout'], check=True, capture_output=True).stdout + der = subprocess.run(['openssl', 'pkey', '-pubin', '-outform', 'der'], input=spki, check=True, capture_output=True).stdout + pin = hashlib.sha256(der).hexdigest() + (d / 'bmc-pin').write_text(pin + '\n') for p in d.iterdir(): p.chmod(0o600) kubectl(s, '-n', SITE, 'create', 'secret', 'generic', SECRET, '--from-file=username=%s' % (d / 'bmc-username'), '--from-file=password=%s' % (d / 'bmc-password.token')) + kubectl(s, '-n', SITE, 'create', 'secret', 'tls', TLS_SECRET, '--cert=%s' % (d / 'bmc-tls.crt'), '--key=%s' % (d / 'bmc-tls.key')) + # One credential Secret per Device, by the BMC discovery contract. + if kubectl(s, 'get', 'namespace', CREDENTIALS, check=False).returncode != 0: + kubectl(s, 'create', 'namespace', CREDENTIALS) + enrollment = json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]) + fixture = {} + for target in enrollment['targets']: + namespace, name = target['device'].split('/') + # The Secret's name derives from the Device (site.CredentialSecretName), + # so each worker can be granted get on exactly its Device's. + secret = {'apiVersion': 'v1', 'kind': 'Secret', 'metadata': {'name': credential_name(target['device']), 'namespace': CREDENTIALS, 'labels': {'fleet.datumapis.com/bmc-credential': 'true'}, + 'annotations': {'fleet.datumapis.com/device-project': 'provider', 'fleet.datumapis.com/device-namespace': namespace, 'fleet.datumapis.com/device-name': name}}, + 'stringData': {'username': (d / 'bmc-username').read_text().strip(), 'password': (d / 'bmc-password.token').read_text().strip(), 'tlsPublicKeySHA256': pin}} + kubectl(s, 'apply', '-f', '-', input=json.dumps(secret)) + # Only target A is a Fleet Device. Target B is enrolled at the site to + # prove isolation and is never inventory: the lab serves both targets + # from one BMC with one TLS key, and custody refuses a key that + # another active Device also records. + if target['device'] == 'fleet-provider/synthetic-device-central-01': + fixture[target['device']] = {'bmcEndpoint': target['endpoint'], 'systemUUID': target['systemUUID'], 'bootMACAddress': target['mac'], 'bmcPublicKeySHA256': pin, 'disks': ['disk-0']} + write(d / 'fixture-enrollment.json', fixture) write(s / 'evidence' / 'redfish-enrollment.json', { - 'observedAt': now(), 'credentialSecret': SITE + '/' + SECRET, 'username': 'fleet-lab-operator', + 'observedAt': now(), 'credentialSecrets': [CREDENTIALS + '/' + credential_name(t['device']) for t in enrollment['targets']], 'username': 'fleet-lab-operator', 'password': 'synthetic random 256-bit value generated per run; never recorded or committed', - 'transport': 'plain HTTP Basic on the cell network to the fixed BMC Service 10.96.0.81:8000 (lab seam)', - 'readers': ['lab BMC adapter (server side)', 'per-operation Redfish worker Pods (client side)'], - 'enrollment': json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]), + 'transport': 'Redfish over TLS to the fixed BMC Service %s:8443, pinned to a key generated per run (lab seam: one key for both lab targets)' % BMC_IP, + 'pin': pin, + 'readers': ['lab BMC adapter (server side)', 'per-operation Redfish worker Pods (client side, own Device only)'], + 'enrollment': enrollment, 'labTargets': json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())}) - print('redfish-enroll: synthetic BMC credential Secret created in the cell; not part of any source revision') + print('redfish-enroll: synthetic per-Device BMC credentials and the lab BMC TLS key created in the cell; not part of any source revision') def baseline(s): @@ -150,7 +201,7 @@ def port_forward(s): sock.bind(('127.0.0.1', 0)) port = sock.getsockname()[1] sock.close() - p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', SITE, 'port-forward', 'svc/fleet-site-bmc', '%d:8000' % port], + p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', SITE, 'port-forward', 'svc/fleet-site-bmc', '%d:8443' % port], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(60): try: @@ -174,8 +225,8 @@ def discovery_faults(s): cases = [] try: def probe(name, creds, system, uuid, want): - r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'http://127.0.0.1:%d' % port, '--credentials', str(creds), - '--system', system, '--uuid', uuid], text=True, capture_output=True, timeout=120) + r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'https://127.0.0.1:%d' % port, '--credentials', str(creds), + '--system', system, '--uuid', uuid, '--pin', (d / 'bmc-pin').read_text().strip()], text=True, capture_output=True, timeout=120) line = (r.stdout.strip().splitlines() or [''])[-1] cases.append({'case': name, 'system': system, 'exitCode': r.returncode, 'outcome': line}) if r.returncode != want: @@ -216,47 +267,66 @@ def arm_lost_response(s): def lost_response(s): + # The site journals disk-power-on before it sends On. While that step is + # only Intended and the BMC withholds the On response, the worker Pod is + # stopped: it stores no result, and its replacement must observe that the + # boot began instead of sending On again. A worker whose request timed out + # first stores OutcomeUnknown, which this step reports as a failure. name = (s / 'install-handoff').read_text().strip() deadline = time.monotonic() + 900 record = None while time.monotonic() < deadline: + ops = installs(s) + if len(ops) == 1 and ops[0]['phase']: + die('the install stored result %s before its worker could be stopped mid-request' % ops[0]['phase']) + if len(ops) == 1 and done(ops[0], 'disk-power-on'): + die('the disk boot On completed before its worker could be stopped mid-request') + if len(ops) == 1 and ['disk-power-on', 'Intended'] in ops[0]['steps']: + live = [p for p in kget(s, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items'] + if p['status'].get('phase') == 'Running' and not p['metadata'].get('deletionTimestamp')] + if len(live) == 1: + kubectl(s, '-n', SITE, 'delete', 'pod', live[0]['metadata']['name'], '--wait=false') + record = {'stoppedAt': now(), 'stoppedPodUID': live[0]['metadata']['uid'], 'journaledAtStop': 'disk-power-on Intended', + 'stop': 'worker Pod deleted (SIGTERM) while its On request awaited the withheld response'} + break + time.sleep(0.5) + if not record: + die('the disk boot On was never in flight with one running worker') + fired = [] + for _ in range(120): fired = [e for e in audit(s) if e.get('fault') == 'drop-response-after-effect'] - pods = kget(s, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items'] - exits = [c['state']['terminated']['exitCode'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] - if fired and 75 in exits: - failed = next(p for p in pods for c in p['status'].get('containerStatuses', []) if c.get('state', {}).get('terminated', {}).get('exitCode') == 75) - log = kubectl(s, '-n', SITE, 'logs', failed['metadata']['name'], '-c', 'worker', check=False).stdout - # The audit entry is written after the withheld response. - record = {'faultRecordedAt': fired[0]['at'], 'faultedRequest': {k: fired[0].get(k) for k in ('method', 'path', 'resetType', 'effect', 'status')}, - 'failedPodUID': failed['metadata']['uid'], 'failedPodExitCode': 75, - 'workerOutcomeClass': 'outcome unknown' if 'outcome unknown' in log else log.strip()[-160:]} + if fired: break time.sleep(2) - if not record: - die('lost-response fault did not fire and fail one worker with exit 75') + if len(fired) != 1: + die('the lost-response fault did not fire exactly once') + record.update(faultRecordedAt=fired[0]['at'], faultedRequest={k: fired[0].get(k) for k in ('method', 'path', 'resetType', 'effect', 'status')}) + # The replacement worker found disk-power-on journaled but not done and + # observed the boot instead of sending On again. for _ in range(300): ops = installs(s) - if len(ops) == 1 and ops[0]['stage'] in ('disk-started', 'disk-verified', 'done'): + if len(ops) == 1 and done(ops[0], 'disk-power-on'): break time.sleep(2) ops = installs(s) - ons = [e for e in mutating(audit(s), TARGET_A['system']) if e.get('resetType') == 'On'] - if len(ops) != 1 or ops[0]['stage'] not in ('disk-started', 'disk-verified', 'done') or len(ons) != 2 or ops[0].get('powerOnRequests') != {'installer': 1, 'disk': 1}: - die('recovery after the lost response repeated or did not observe the boot: %d On requests, %s' % (len(ons), ops[0].get('stage') if ops else None)) - record.update(observedAt=now(), operationID=ops[0]['request']['id'], stageAfterRecovery=ops[0]['stage'], phase='disk boot', powerOnRequests=ops[0]['powerOnRequests'], + ons = [e for e in mutating(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)) + record.update(observedAt=now(), operationID=ops[0]['operation'], fence=ops[0]['fence'], stageAfterRecovery=ops[0]['stage'], phase='disk boot', journaledPowerOn=journaled, onRequestsToTargetA=len(ons), runningDomains=running(s), recovery='replacement worker observed PowerState and the consumed one-time override; it did not repeat On') write(s / 'evidence' / 'redfish-lost-response.json', record) - print('redfish-lost-response: On took effect but its response was lost; the worker exited 75 Unknown; its replacement observed the running target and did not repeat the effect') + print('redfish-lost-response: On took effect but its response was lost; the worker was stopped with the step journaled Intended and stored no result; its replacement observed the running target and did not repeat the effect') def bmc_interrupt(s): ops = [] for _ in range(600): ops = installs(s, pending_ok=True) - if len(ops) == 1 and ops[0]['stage'] == 'installer-started' and TARGET_A['domain'] in running(s): + if len(ops) == 1 and ops[0]['stage'] == 'installer-power-on' and TARGET_A['domain'] in running(s): break - if len(ops) == 1 and ops[0]['stage'] not in ('admitted', 'discovered', 'installer-armed', 'installer-requested', 'installer-started'): + if len(ops) == 1 and harness.past_installer(ops[0]): die('the installer finished before the BMC could be interrupted: %s' % ops[0]['stage']) time.sleep(0.5) else: @@ -274,10 +344,10 @@ def bmc_interrupt(s): if not new: die('BMC Pod was not replaced') after = installs(s) - if TARGET_A['domain'] not in running(s) and after[0]['stage'] == 'installer-started': + if TARGET_A['domain'] not in running(s) and not harness.past_installer(after[0]): die('the guest stopped when the BMC was interrupted') write(s / 'evidence' / 'redfish-bmc-interrupt.json', {'observedAt': now(), 'deletedBMCPodUIDs': [o['metadata']['uid'] for o in old], 'replacementBMCPodUID': new['metadata']['uid'], - 'operationID': ops[0]['request']['id'], 'stageAtInterrupt': 'installer-started', 'stageAfter': after[0]['stage'], + 'operationID': ops[0]['operation'], 'fence': ops[0]['fence'], 'stageAtInterrupt': ops[0]['stage'], 'stageAfter': after[0]['stage'], 'guestRunningAfter': TARGET_A['domain'] in running(s), 'note': 'the BMC adapter re-reads NVRAM and libvirt state; the worker tolerates a bounded BMC outage while observing'}) print('redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install and replaced; the guest kept running and the operation stayed unfinished') diff --git a/hack/multiplane/reflection-faults.py b/hack/multiplane/reflection-faults.py index 48873a2f..580b68e7 100755 --- a/hack/multiplane/reflection-faults.py +++ b/hack/multiplane/reflection-faults.py @@ -1,12 +1,26 @@ #!/usr/bin/env python3 -"""Explicit test-only hub status fault injection; no simulated federation relay.""" -import copy,json,pathlib,subprocess,sys +"""Explicit test-only hub status fault injection; no simulated federation relay. + +The install's result is already accepted, so the coordinator answered its +handoff and the cell deleted its copy. With Karmada stopped, the harness +reopens that handoff (removes its answered label) and reflects one forged +result at a time, each wrong in exactly one attribute. The custody +coordinator must ignore every one: custody stays unchanged and the handoff +stays unanswered. The label and the real status are restored afterwards. +""" +import copy,datetime,json,pathlib,subprocess,sys,time +sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (provider custody digest) s=pathlib.Path(sys.argv[1]);hub=s/'hub-admin.yaml';host=s/'host.yaml' +ANSWERED='coordination.fleet.datumapis.com/answered' def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=20s',*args],input=input,text=True,capture_output=True,check=True).stdout -items=json.loads(k(hub,'-n','fleet-coordination','get','machineallocationhandoffs','-o','json'))['items'] -if len(items)!=1:raise SystemExit('run reflection faults after install and before cleanup') +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'] +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 len((original or {}).get('reflected',[]))!=1:raise SystemExit('no real reflected result to test') +if obj['metadata'].get('labels',{}).get(ANSWERED)!='true':raise SystemExit('the install result is not answered yet') +if len((original or {}).get('reflected',[]))!=1:raise SystemExit('no real reflected observation to test') +assignment=json.loads(obj['spec']['assignmentJSON']) # Explicit ownership transfer: suspend the Flux HelmRelease before stopping the # controller, so Flux and the harness are never concurrent writers. k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":true}}') @@ -18,28 +32,36 @@ def guard(mode): def patch(status): p=s/'status-fault.json';p.write_text(json.dumps({'status':status}));p.chmod(0o600) k(hub,'-n','fleet-coordination','patch','machineallocationhandoff',name,'--subresource=status','--type=merge','--patch-file',str(p)) +before=harness.custody_digest(s) try: - # Each mode changes exactly one attribute of the real reflected result. - for mode in ('wrong-cell','stale','duplicate','future','wrong-intent','wrong-digest','wrong-operation','incomplete','missing'): - status=copy.deepcopy(original);o=status['reflected'][0]['observation'] + k(hub,'-n','fleet-coordination','label','machineallocationhandoff',name,ANSWERED+'-') + # A result the coordinator would otherwise accept for exactly this assignment. + base=copy.deepcopy(original);o=base['reflected'][0]['observation'] + o['observedAt']=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + o['result']={'site':o['cell'],'device':assignment['device'].split('/',1)[1],'operation':assignment['operation'],'fence':assignment['fence'], + 'phase':'Failed','reason':'FaultInjection','message':'forged by the acceptance harness'} + for mode in ('wrong-cell','foreign-observer','duplicate','future','wrong-assignment','wrong-device','wrong-operation','stale-fence','missing'): + status=copy.deepcopy(base);o=status['reflected'][0]['observation'];result=o['result'] if mode=='wrong-cell':status['reflected'][0]['clusterName']='wrong-cell' - elif mode=='stale':o['observedAt']='2000-01-01T00:00:00Z' + elif mode=='foreign-observer':o['cell']='wrong-cell' elif mode=='duplicate':status['reflected'].append(copy.deepcopy(status['reflected'][0])) elif mode=='future':o['observedAt']='2999-01-01T00:00:00Z' - elif mode=='wrong-intent':o['intentDigest']='0'*64 - elif mode=='wrong-digest':o['result']['inputDigest']='0'*64 - elif mode=='wrong-operation':o['result']['id']=o['result']['id']+'-other' - elif mode=='incomplete':o['result']['phase']='Unknown' + elif mode=='wrong-assignment':o['assignmentDigest']='0'*64 + elif mode=='wrong-device':result['device']=result['device']+'-other' + elif mode=='wrong-operation':result['operation']=dict(result['operation'],name=result['operation']['name']+'-other') + elif mode=='stale-fence':result['fence']=result['fence']-1 else:status={'reflected':[]} guard('check') patch(status) - result=subprocess.run([str(s/'fleet-multiplane-host'),'install','--once','--config',str(s/'acceptance.json')],text=True,capture_output=True) - if result.returncode==0:raise SystemExit(mode+' incorrectly accepted') - if 'unknown' not in result.stderr.lower():raise SystemExit(mode+' did not reach result validation: '+result.stderr[:200]) + # The coordinator passes every second; give it several passes. + time.sleep(8) + if handoff()['metadata'].get('labels',{}).get(ANSWERED)=='true':raise SystemExit(mode+' was answered by the coordinator') + if harness.custody_digest(s)!=before:raise SystemExit(mode+' changed custody') print(mode+': management rejected reflected evidence') finally: guard('check') patch(original) + k(hub,'-n','fleet-coordination','label','--overwrite','machineallocationhandoff',name,ANSWERED+'=true') k(host,'-n','karmada-system','scale','deployment/karmada-controller-manager','--replicas=1') k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":false}}') k(host,'-n','karmada-system','wait','--for=condition=Available','deployment/karmada-controller-manager','--timeout=180s') diff --git a/hack/multiplane/roles.py b/hack/multiplane/roles.py index 65141651..bc79a8a1 100755 --- a/hack/multiplane/roles.py +++ b/hack/multiplane/roles.py @@ -35,7 +35,6 @@ def credentials(config,ns,name,dest,internal=None,server=None): k(hub,'config','set-cluster',entry,'--server=https://127.0.0.1:%d'%env['karmadaPort']) # CA verification is retained; the chart includes localhost in its serving SANs. credentials(hub,ns,'fleet-management',state/'management-hub.json') -credentials(host,'fleet-system-private','fleet-custodian',state/'private.json') # Cell execution credentials are Kubernetes ServiceAccounts inside the cell # site; no cell credential is exported to the host. token,ca=credentials(cell,ns,'fleet-federation',state/'federation-cell.json',env['cellEndpoint']) @@ -46,4 +45,4 @@ def credentials(config,ns,name,dest,internal=None,server=None): wait(hub,'cluster/'+env['cell']) k(hub,'wait','--for=condition=Ready','cluster/'+env['cell'],'--timeout=300s') k(host,'-n','karmada-system','wait','--for=condition=Ready','kustomization/fleet-karmada-members','--timeout=300s') -print('Karmada member enrolled; separate management/custodian/cell credentials minted for Flux-created identities') +print('Karmada member enrolled; separate management and cell credentials minted for Flux-created identities') diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 73111d06..46e1e226 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -94,13 +94,17 @@ ph flux-platform 1800 "${flux[@]}" wait "$state" --cluster cell --cluster hub -- ph milo-bootstrap 1200 python3 hack/multiplane/milo.py "$state" "$prefix" ph flux-milo 900 "${flux[@]}" wait "$state" --cluster platform --timeout 600 ph federation-enrollment 600 python3 hack/multiplane/roles.py "$state" -python3 - "$state" <<'PY' +# Redfish mode enrolls the per-Device BMC credentials and the lab BMC's TLS +# key first: fixture discovery reports that key's digest. +[[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" +python3 - "$state" "$provider" <<'PY' import json,pathlib,sys -s=pathlib.Path(sys.argv[1]).resolve();c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'PrivateKubeconfig':str(s/'private.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip()};(s/'acceptance.json').write_text(json.dumps(c)) +s=pathlib.Path(sys.argv[1]).resolve() +enrollment=json.loads((s/'redfish'/'fixture-enrollment.json').read_text() if sys.argv[2]=='redfish' else pathlib.Path('config/site/base/enrollment.json').read_text()) +c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment};(s/'acceptance.json').write_text(json.dumps(c)) PY ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" -ph scoped-asset 120 sh -c '"$1/fleet-multiplane-host" asset --config "$1/acceptance.json" > "$1/scoped-asset" && echo "scoped asset recorded"' sh "$state" -[[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" +ph coordinator 120 bash hack/multiplane/coordinator.sh start "$state" # Revision 2: the Flux-owned shared site services and the HandoffDispatcher # instance, dispatch disabled. ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index e6c07852..6af24770 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -31,19 +31,22 @@ wait_api() { done echo "API did not recover: $(basename "$1")" >&2; return 1 } -local_phase() { cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].status.observation.result.phase}'; } -# Private custody digest: names, UIDs and resourceVersions only; data never leaves memory. -custody_digest() { - k "$state/host.yaml" -n fleet-system-private get secrets -o json | python3 -c ' -import hashlib,json,sys -items=sorted((i["metadata"]["name"],i["metadata"]["uid"],i["metadata"]["resourceVersion"]) for i in json.load(sys.stdin)["items"]) -print(len(items), hashlib.sha256(json.dumps(items).encode()).hexdigest())' -} +assignments=coordination.fleet.datumapis.com/role=assignment +# 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}'; } +# 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"; } +# The Device's site store state: its fences and journal. +store_state=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import harness; print(harness.STATE_PATH)') journal_digest() { - runtime cat /var/lib/fleet-local/journal.json | python3 -c ' + runtime cat "$store_state" | python3 -c ' import hashlib,sys print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' } +# The step the install has journaled once its installer boot was requested. +installer_step=installer-start +[[ $(cat "$state/site-provider" 2>/dev/null) != redfish ]] || installer_step=installer-power-on wait_running_pod() { for _ in $(seq 1 "${2:-120}"); do uid=$(py running-pod "$state" "$1") @@ -63,17 +66,17 @@ case "$step" in ;; await-delivery) for _ in $(seq 1 120); do - names=$(cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].metadata.name}') + names=$(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o jsonpath='{.items[*].metadata.name}') [[ -z $names ]] || break sleep 1 done [[ -n $names ]] || { echo 'Karmada did not deliver retained intent' >&2; exit 1; } - [[ $(wc -w <<<"$names") -eq 1 ]] || { echo 'more than one delivered handoff' >&2; exit 1; } + [[ $(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 [[ -z $(site get jobs -o name) ]] || { echo 'worker Job exists before dispatch' >&2; exit 1; } - printf 'delivery: Karmada delivered exactly one retained handoff; kro observed it; no worker Job before dispatch\n' + printf 'delivery: Karmada delivered exactly one retained assignment; kro observed it; no worker Job before dispatch\n' ;; partition) # Consumer A's API is Flux-managed: suspend its Kustomization, then stop it. @@ -102,7 +105,7 @@ case "$step" in ;; interrupt-pod) name=$(cat "$state/install-handoff") - "${harness[@]}" wait-stage --state "$state" --stage installer-started --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" + "${harness[@]}" wait-stage --state "$state" --stage "$installer_step" --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" before=$(wait_running_pod "$name" 30) py job "$state" "$name" > "$state/interrupt-job-before-pod.json" # Abrupt Pod loss with no grace period. The guest runs under the runtime Pod, @@ -119,7 +122,7 @@ case "$step" in py job "$state" "$name" > "$state/interrupt-job-after-pod.json" "${harness[@]}" journal --state "$state" > "$state/interrupt-after.json" py record-pod-interrupt "$state" "$before" "$after" - printf 'interrupt-pod: worker Pod force-deleted while installer-started with its domain running; Job controller replaced it; no local result\n' + printf 'interrupt-pod: worker Pod force-deleted after the installer boot was journaled with its domain running; Job controller replaced it; no local result\n' ;; interrupt-job) name=$(cat "$state/install-handoff") @@ -150,7 +153,7 @@ case "$step" in cell -n "$ns" wait --for=jsonpath='{.status.observation.result.phase}'=Succeeded machineallocationhandoff "$name" --timeout=5m >/dev/null "${harness[@]}" journal --state "$state" > "$state/resume-after.json" py record-resume "$state" "$name" - printf 'resume: replacement worker completed the exact interrupted operation; one install operation; observer published from the journal\n' + printf 'resume: replacement worker completed the exact interrupted operation at its fence; one install operation; observer published the stored result\n' ;; partition-readiness) # The platform's root sync must apply r3 (pushed during the partition) with @@ -219,19 +222,20 @@ case "$step" in ;; delivery-faults) # Cell-local delivery faults injected with cell bootstrap credentials: a - # duplicate under another name, a wrong-cell intent, and a stale-epoch replay. + # duplicate the API refuses, an assignment naming another cell, and a + # replay of an admitted operation below the Device's stored fence. before=$(journal_digest) py delivery-faults "$state" create - for fault in duplicate wrong-cell stale-epoch; do + for fault in wrong-cell stale-fence; do job=$(cat "$state/fault-$fault-job") for _ in $(seq 1 120); do site get job "$job" >/dev/null 2>&1 && break; sleep 1; done site wait --for=condition=Failed "job/$job" --timeout=300s >/dev/null done after=$(journal_digest) - [[ $before == "$after" ]] || { echo 'provider journal changed during delivery faults' >&2; exit 1; } + [[ $before == "$after" ]] || { echo 'site store changed during delivery faults' >&2; exit 1; } py delivery-faults "$state" verify py delivery-faults "$state" delete - printf 'delivery-faults: duplicate, wrong-cell and stale-epoch deliveries failed their Jobs by podFailurePolicy before effects; journal unchanged; kro pruned them\n' + printf 'delivery-faults: duplicate refused by the API; wrong-cell and stale-fence deliveries failed their Jobs by podFailurePolicy before effects; site store unchanged; kro pruned them\n' ;; release-status-a|release-status-b) # Released claims must not keep public readiness or an installation reference. @@ -248,10 +252,10 @@ case "$step" in reuse-status) b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}') [[ $b == Bound/True ]] || { echo "reused consumer-b status: $b" >&2; exit 1; } - printf 'reuse-status: consumer-b Bound after verified cleanup\n' + printf 'reuse-status: consumer-b Bound after the verified wipe\n' ;; wrong-location) - # Runs after both verified cleanups, so capacity is free: denial cannot be + # Runs after both releases, so capacity is free: denial cannot be # explained by contention. The customer recreates its request elsewhere. before_custody=$(custody_digest); before_journal=$(journal_digest) customer="$state/consumer-a/customer-project.json" @@ -266,19 +270,19 @@ JSON [[ $code -ne 0 ]] || { echo 'wrong-location Machine was allocated' >&2; exit 1; } grep -q 'not served by the configured cell' "$state/wrong-location.err" || { echo "allocation failed for another reason: $(tail -c 300 "$state/wrong-location.err")" >&2; exit 1; } after_custody=$(custody_digest); after_journal=$(journal_digest) - [[ $before_custody == "$after_custody" ]] || { echo 'private custody changed during wrong-location attempt' >&2; exit 1; } - [[ $before_journal == "$after_journal" ]] || { echo 'provider journal changed during wrong-location attempt' >&2; exit 1; } + [[ $before_custody == "$after_custody" ]] || { echo 'custody changed during wrong-location attempt' >&2; exit 1; } + [[ $before_journal == "$after_journal" ]] || { echo 'site store changed during wrong-location attempt' >&2; exit 1; } k "$state/consumer-a/management-project.json" -n default get machine allocation -o json > "$state/wrong-location-machine.json" python3 - "$state" "$code" "$before_custody" <<'PY' import json,sys,pathlib,datetime m=json.loads((pathlib.Path(sys.argv[1])/'wrong-location-machine.json').read_text()) if m['metadata'].get('finalizers') or m.get('status'): raise SystemExit('wrong-location Machine gained finalizers or status') record={'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'requestedLocation':m['spec']['locationRef']['name'],'servedLocation':'local', - 'capacityFree':True,'exitCode':int(sys.argv[2]),'error':'ErrLocationNotServed','privateCustodyUnchanged':True,'privateCustodyRecords':int(sys.argv[3].split()[0]), - 'providerJournalUnchanged':True,'machineFinalizers':[],'machineStatus':None} + 'capacityFree':True,'exitCode':int(sys.argv[2]),'error':'ErrLocationNotServed','custodyUnchanged':True,'custodyRecords':int(sys.argv[3].split()[0]), + 'siteStoreUnchanged':True,'machineFinalizers':[],'machineStatus':None} (pathlib.Path(sys.argv[1])/'evidence'/'wrong-location.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') PY - printf 'wrong-location: denied before allocation with free capacity; private custody and provider journal unchanged\n' + printf 'wrong-location: denied before allocation with free capacity; custody and site store unchanged\n' ;; boot-denials) # Probe the boot Service from the runtime Pod: the same path firmware uses. diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh index f0fe3677..96ef7fb3 100755 --- a/hack/multiplane/stop.sh +++ b/hack/multiplane/stop.sh @@ -4,6 +4,8 @@ set -euo pipefail state=${1:?private run state directory required} prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || exit 1 +# The coordinator is a workstation process: stop it before its clusters. +bash hack/multiplane/coordinator.sh stop "$state" >/dev/null export DOCKER_CONTEXT=colima-fleet-acceptance-tcg # The cell node holds the site runtime, journal volume, kro and worker Jobs; the # platform node holds the Milo APIs and their etcd volumes; the registry holds diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index 009d4033..8d2ec172 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -12,6 +12,8 @@ mode=${2:-passed} [[ $mode == passed || $mode == --discard-unknown ]] || { echo 'usage: teardown.sh STATE [--discard-unknown]' >&2; exit 64; } prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo 'unexpected prefix' >&2; exit 1; } +# The coordinator is a workstation process: stop it before its clusters. +bash hack/multiplane/coordinator.sh stop "$state" >/dev/null export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker if [[ $mode == passed ]]; then python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="passed")' "$state/evidence/summary.json" 2>/dev/null || { @@ -50,7 +52,7 @@ rm -f "$state/kind-delete.kubeconfig" if [[ $mode == passed ]]; then # Credentials and raw journals are no longer needed once the run has passed. rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" "$state/redfish" - rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/private.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ + rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ "$state"/status-fault.json "$state"/acceptance.json "$state"/fleet-multiplane "$state"/fleet-multiplane-host rm -rf "$state/site-bin" "$state/kro-chart" "$state/flux-tools/flux" "$state"/flux-tools/*.tar.gz fi diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index c9fcd115..de101577 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -98,7 +98,6 @@ def meta(name, **kw): 'cellEndpoint': 'https://fleet-mp-0000abcd-cell-control-plane:6443', 'siteImage': 'fleet-mp-0000abcd-registry:5000/fleet-site@sha256:' + 'a' * 64, 'siteImageDigest': 'sha256:' + 'a' * 64} (s / 'gitops-environment.json').write_text(json.dumps(env)) - (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') def ns(**kw): base = dict(state=str(s), root=str(root), revision=1, site='absent', bad_kro_chart=False, drop_site_volume=False, purpose='test', cluster=[], timeout=5) @@ -119,7 +118,7 @@ def render(rev, cluster): check('hub environment beside the Karmada kubeconfig', 'name: fleet-environment\n namespace: karmada-system' in hub1 and 'name: fleet-environment\n namespace: flux-system' in hub1) check('stage dispatch revision', flux.stage(ns(revision=3, site='dispatch')) == 0) cell3 = render(3, 'cell') - check('dispatch revision carries the site', 'FLEET_SITE_DISPATCH: "true"' in cell3 and 'path: ./config/site/instance' in cell3 and 'FLEET_SCOPED_ASSET' in cell3 + check('dispatch revision carries the site', 'FLEET_SITE_DISPATCH: "true"' in cell3 and 'path: ./config/site/instance' in cell3 and 'FLEET_SCOPED_ASSET' not in cell3 and 'path: ./config/site/services' in cell3 and ('FLEET_BOOT_SERVICE_IP: %s\n' % flux.BOOT_SERVICE_IP) in cell3.replace('"', '')) # Flux replaces an undefined variable with an empty string, which would give # the boot Service a random ClusterIP: every substituted variable must be defined. diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 5f486440..244f8f04 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -3,7 +3,7 @@ # and go executables; never contacts a container runtime or cluster. set -eu root=$(CDPATH='' cd -- "$(dirname "$0")/../.." && pwd) -for f in "$root"/hack/multiplane/*.sh "$root"/hack/local-vm/run.sh; do bash -n "$f"; done +for f in "$root"/hack/multiplane/*.sh; do bash -n "$f"; done python3 -m py_compile "$root"/hack/multiplane/*.py python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" python3 "$root"/hack/multiplane/test-redfish.py "$root" @@ -36,13 +36,15 @@ if tool == 'docker': if a[:1] == ['run']: print('x86_64'); sys.exit(0) if tool == 'kubectl' and 'exec' in a and 'deploy/fleet-site-runtime' in a: - if 'journal.json' in a[-1]: - stage = os.environ.get('FAKE_STAGE', 'installer-started') - print(json.dumps({'fence': 'F' * 32, 'operations': {'op': {'request': {'id': 'install-op-1', 'kind': 'install', 'epoch': 1, 'fenceToken': 'T' * 32}, - 'stage': stage, 'bootToken': 'B' * 64, 'receipt': 'R' * 64, 'result': {'phase': 'Unknown'}, 'bootClosed': False}}})); sys.exit(0) + if a[-1].endswith('/state.json'): + stage = os.environ.get('FAKE_STAGE', 'installer-start') + 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 'virsh' in a: import hashlib - print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:24]); sys.exit(0) + print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:16]); sys.exit(0) if tool == 'colima': if 'df' in a[-1]: print('/dev/vdb1 41000000 20000000 %d 50%% /var/lib/docker' % (int(os.environ.get('FAKE_FREE_KB', '20000000')))) elif 'inotify' in a[-1]: print(os.environ.get('FAKE_INOTIFY', '1024')) @@ -66,7 +68,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', 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] + markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed') bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) (bad_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers)) @@ -124,17 +126,20 @@ with tempfile.TemporaryDirectory() as tmp: check(name + ' timeout', r.returncode == 4, r.stdout + r.stderr) check(name + ' bounded', time.monotonic() - started < 8) - # Provider observation never exposes fence, capability or receipt. + # Provider observation reads the site store's journal, never step payloads. obs = state() - r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5']) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-start', '--timeout', '5']) check('wait-stage observes running installer', r.returncode == 0, r.stdout) - check('wait-stage sanitized', not any(x in r.stdout for x in ('B' * 64, 'R' * 64, 'T' * 32, 'F' * 32)), r.stdout) - r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5'], {'FAKE_STAGE': 'disk-started'}) + seen = json.loads(r.stdout) if r.returncode == 0 else {} + check('wait-stage names the operation and its fence', seen.get('operation', {}).get('operation') == 'install-op-1' and seen['operation'].get('fence') == 3 + and seen['operation'].get('kind') == 'DeviceInstallation', r.stdout) + check('wait-stage sanitized', 'R' * 64 not in r.stdout, r.stdout) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-start', '--timeout', '5'], {'FAKE_STAGE': 'disk-start'}) check('wait-stage rejects missed window', r.returncode == 1, r.stdout) - r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '2'], {'FAKE_STAGE': 'prepared'}) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-start', '--timeout', '2'], {'FAKE_STAGE': 'prepared'}) check('wait-stage bounded', r.returncode == 4, r.stdout) out = run(['journal', '--state', str(obs)]).stdout - check('journal sanitized', 'B' * 64 not in out and 'install-op-1' in out, out) + check('journal sanitized', 'R' * 64 not in out and 'install-op-1' in out, out) calls = [json.loads(l) for l in trace.read_text().splitlines()] check('provider observation only through the cell API', not any(c[0] == 'docker' and 'exec' in c for c in calls) and any(c[0] == 'kubectl' and 'exec' in c and 'deploy/fleet-site-runtime' in c for c in calls)) @@ -143,12 +148,13 @@ with tempfile.TemporaryDirectory() as tmp: s = state(); (s / 'evidence').mkdir() (s / 'provider').mkdir(); (s / 'provider/tokens.csv').write_text('a' * 64 + ',bootstrap,bootstrap,system:masters\n') (s / 'hub.json').write_text(json.dumps({'users': [{'user': {'token': 'k' * 40}}]})) - (s / 'provider-private').mkdir(); (s / 'provider-private/journal.json').write_text(json.dumps({'fence': 'f' * 32, 'operations': {'x': {'bootToken': 'b' * 64, 'request': {'fenceToken': 't' * 32}}}})) + boot = s / 'provider-private/site/devices/0123/vmboot'; boot.mkdir(parents=True) + (boot / 'k.json').write_text(json.dumps({'operation': 'x', 'fence': 1, 'receipt': 'r' * 64, 'token': 'b' * 64})) (s / 'host.yaml').write_text('users:\n- user:\n client-key-data: ' + 'K' * 48 + '\n') (s / 'evidence/clean.json').write_text('{"ok":true}') check('scan clean', run(['scan', '--state', str(s)]).returncode == 0) (s / 'worker.token').write_text('w' * 40 + '\n') - for secret in ('a' * 64, 'k' * 40, 'f' * 32, 'b' * 64, 't' * 32, 'K' * 48, 'w' * 40): + for secret in ('a' * 64, 'k' * 40, 'b' * 64, 'K' * 48, 'w' * 40): (s / 'evidence/leak.json').write_text('{"v":"%s"}' % secret) check('scan detects ' + secret[0], run(['scan', '--state', str(s)]).returncode == 1) check('scan redacts ' + secret[0], secret not in (s / 'evidence/leak.json').read_text()) @@ -195,13 +201,14 @@ with tempfile.TemporaryDirectory() as tmp: continue check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) - # The custody CRD rule phase proves the project API enforces the CEL - # rules, then removes everything it installed, in both modes. + # The custody CRD rule phase proves the provider project API enforces the + # CEL rules in its own namespace, then deletes every object it created, in + # both modes. The CRDs belong to the provider project; it installs none. rules = (root / 'hack/multiplane/custody_crd_rules.py').read_text() redfish_sequence = (root / 'hack/multiplane/acceptance-redfish.sh').read_text() check('custody CRD rules run in both modes', 'ph custody-crd-rules ' in sequence and 'ph custody-crd-rules ' in redfish_sequence) - check('custody CRD rules install only the component CRDs and remove them', rules.count('config/components/device-operations/crds/fleet.datumapis.com.yaml') == 1 - and "'delete', '-f', crds" in rules and "'delete', kind, name" in rules and "'Namespace'" not in rules) + check('custody CRD rules install nothing and remove what they create', 'crds' not in rules + and "'delete', kind, name" in rules and "'Namespace'" not in rules and "namespace = 'fleet-rules'" in rules) check('custody CRD rules evidence is checked', "custody-crd-rules.json" in evidence and 'custody-crd-rules: the provider project API refused' in evidence) # The kro graph and the worker exit-code contract must agree. kro owns only @@ -262,7 +269,7 @@ with tempfile.TemporaryDirectory() as tmp: check('fault injection suspends Flux first', 'suspend milo-consumer-a true' in steps and '"suspend":true' in (root / 'hack/multiplane/reflection-faults.py').read_text()) check('RBAC revocation repaired by Flux, not the harness', "'apply'" not in (root / 'hack/multiplane/verify-rbac.py').read_text()) for path in ('config/site/base/site.yaml', 'config/site/graph/rgd.yaml', 'config/site/instance/dispatcher.yaml', 'config/multiplane/coordination/crd.yaml', - 'config/multiplane/host/custody.yaml', 'config/multiplane/karmada/karmada.yaml', 'config/multiplane/karmada-members/members.yaml'): + 'config/multiplane/karmada/karmada.yaml', 'config/multiplane/karmada-members/members.yaml'): check('prune-protected: ' + path, 'kustomize.toolkit.fluxcd.io/prune: disabled' in (root / path).read_text()) check('site volume is create-once', base.count('kustomize.toolkit.fluxcd.io/ssa: IfNotPresent') == 2) check('graph has no Flux substitution', 'postBuild' not in (root / 'config/multiplane/clusters/cell/cell.yaml').read_text().split('name: fleet-site-graph')[1]) diff --git a/hack/multiplane/test-k8s-evidence.py b/hack/multiplane/test-k8s-evidence.py index 18fd90a1..d599e979 100644 --- a/hack/multiplane/test-k8s-evidence.py +++ b/hack/multiplane/test-k8s-evidence.py @@ -5,6 +5,7 @@ path and on representative failure paths, so call-signature and data-shape mistakes fail here instead of mid-run. Never contacts a cluster. """ +import hashlib import json import os import pathlib @@ -40,12 +41,19 @@ def emit(v): print(json.dumps(v)); sys.exit(0) emit({'clusters': [{'cluster': {}}], 'contexts': [{'context': {}}], 'users': []}) if 'exec' in args: cmd = args[args.index('--') + 1:] - if cmd[:1] == ['cat'] and cmd[1].endswith('journal.json'): print(world['journal']); sys.exit(0) + if cmd[:1] == ['cat'] and cmd[1].endswith('/state.json'): print(world['store']); sys.exit(0) + if cmd[:1] == ['test']: sys.exit(0 if cmd[-1].rsplit('/', 1)[1] in world.get('results', []) else 1) if cmd[:1] == ['cat'] and '/qemu/' in cmd[1]: print(world['qemu']); sys.exit(0) if cmd[:1] == ['virsh']: print(''); sys.exit(0) sys.exit(1) if args[:1] == ['create']: - obj = json.loads(sys.stdin.read()); world.setdefault('created', []).append(obj['metadata']['name']) + obj = json.loads(sys.stdin.read()) + # The API refuses a handoff field it does not define. + if 'credential' in obj.get('spec', {}) and not world.get('acceptCredential'): + print('Error from server (BadRequest): strict decoding error: unknown field "spec.credential"', file=sys.stderr); sys.exit(1) + if obj['metadata']['name'] in [h['metadata']['name'] for h in world['handoffs']] + world.get('created', []): + print('Error from server (AlreadyExists): exists', file=sys.stderr); sys.exit(1) + world.setdefault('created', []).append(obj['metadata']['name']) json.dump(world, open(os.environ['FAKE_WORLD'], 'w')); sys.exit(0) if 'delete' in args: name = args[args.index('delete') + 2] @@ -64,9 +72,14 @@ def emit(v): print(json.dumps(v)); sys.exit(0) if kind == 'pv': emit({'metadata': {'uid': 'pv-uid'}, 'spec': {'persistentVolumeReclaimPolicy': 'Retain'}}) if kind == 'machine': emit(world['machines'][config.split('/')[-2]]) +if kind == 'role' and ns() == 'fleet-site-credentials' and name not in world.get('credentialRoles', []): + print('NotFound', file=sys.stderr); sys.exit(1) if kind == 'role': emit({'metadata': {'labels': {'kro.run/node-id': 'workerRoles'}}, 'rules': [{'resourceNames': [world['handoff']], 'verbs': ['get']}]}) if kind == 'machineallocationhandoffs': emit({'items': world['handoffs']}) -if kind == 'machineallocationhandoff': emit({'metadata': {'name': name}, 'spec': {}}) +if kind == 'roles': emit({'items': world.get('roles', [])}) +if kind == 'machineallocationhandoff' and name not in [h['metadata']['name'] for h in world['handoffs']] + world.get('created', []) + [world['handoff']]: + print('NotFound', file=sys.stderr); sys.exit(1) +if kind == 'machineallocationhandoff': emit({'metadata': {'name': name}, 'spec': {}, 'status': world.get('statuses', {}).get(name)}) sys.exit(1) '''.replace('#!PYTHON', '#!' + sys.executable) @@ -92,13 +105,22 @@ def pod(name, uid, handoff, job_uid, phase, exit_code=None, app=None): (state / 'prefix').write_text('fleet-mp-1234abcd\n') h = 'op-' + 'a' * 40 (state / 'install-handoff').write_text(h + '\n') - request = {'id': 'install-1', 'kind': 'install', 'assetID': 'x', 'bindingID': 'b', 'epoch': 1, 'fenceToken': 'F' * 32} - world = {'handoff': h, 'journal': '{"operations":{}}', 'qemu': 'x: starting up a\nx: starting up b\n', + device = 'fleet-provider/synthetic-device-central-01' + # The latest delivered assignment: the release wipe at fence 2. + wipe = {'device': device, 'operation': {'kind': 'DeviceWipe', 'name': 'alloc-0123456789abcdef-wipe-1'}, 'fence': 2, + 'admittedAt': '2026-01-01T00:00:00Z', 'deadline': '2026-01-01T01:00:00Z', 'snapshot': {}, 'inputDigest': 'sha256:' + '0' * 64, 'inputs': {}} + wipe_name = 'op-' + hashlib.sha256(('%s/devicewipe.alloc-0123456789abcdef-wipe-1.2' % device).encode()).hexdigest()[:40] + install = dict(wipe, operation={'kind': 'DeviceInstallation', 'name': 'alloc-0123456789abcdef-install-0123456789ab'}, fence=1) + install_key = 'deviceinstallation.alloc-0123456789abcdef-install-0123456789ab.1' + store = {'device': device, 'fence': 2, 'stopped': 2, 'journal': [{'operation': install_key, 'fence': 1, 'step': 'prepare-disk', 'state': 'Done', 'at': 'x'}]} + world = {'handoff': h, 'store': json.dumps(store), 'qemu': 'x: starting up a\nx: starting up b\n', 'jobs': {'w-' + h: job('w-' + h, 'job-2', [('Complete', 'CompletionsReached')], succeeded=1)}, 'pods': [pod('p2', 'pod-2', h, 'job-2', 'Succeeded', 0)] + [pod(d, d + '-uid', None, '', 'Running', app=d) for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')], 'machines': {'consumer-a': {'status': {'phase': 'Ready', 'conditions': [{'type': 'Bound', 'status': 'True'}, {'type': 'Ready', 'status': 'True'}]}}, 'consumer-b': {'status': {'phase': 'Bound', 'conditions': [{'type': 'Bound', 'status': 'True'}]}}}, - 'handoffs': [{'metadata': {'name': h}, 'spec': {'cell': 'fleet-mp-1234abcd-cell', 'requestJSON': json.dumps(request)}}]} + 'statuses': {h: {'observation': {'cell': 'fleet-mp-1234abcd-cell', 'result': {'phase': 'Succeeded', 'operation': install['operation'], 'fence': 1}}}}, + 'handoffs': [{'metadata': {'name': h}, 'spec': {'cell': 'fleet-mp-1234abcd-cell', 'device': device, 'assignmentJSON': json.dumps(install)}}, + {'metadata': {'name': wipe_name}, 'spec': {'cell': 'fleet-mp-1234abcd-cell', 'device': device, 'assignmentJSON': json.dumps(wipe)}}]} wpath = tmp / 'world.json' env = dict(os.environ, PATH=str(bindir) + os.pathsep + os.environ['PATH'], FAKE_WORLD=str(wpath)) @@ -119,24 +141,28 @@ def run(*args): check('job record', r.returncode == 0 and json.loads(r.stdout)['uid'] == 'job-2', r.stderr) # Interruption records. - ops = lambda stage: json.dumps([{'id': 'install-1', 'kind': 'install', 'stage': stage, 'phase': 'Unknown' if stage != 'done' else 'Succeeded'}]) - (state / 'interrupt-observed.json').write_text(json.dumps({'operation': {'id': 'install-1', 'stage': 'installer-started', 'domain': 'd'}, 'domainRunning': True})) - (state / 'interrupt-after.json').write_text(ops('installer-started')) + ops = lambda stage: json.dumps([{'operation': install_key, 'fence': 1, 'kind': 'DeviceInstallation', 'stage': stage, 'stageState': 'Done', + 'done': stage == 'disk-verified', 'phase': 'Succeeded' if stage == 'disk-verified' else None, 'steps': [[stage, 'Done']]}]) + (state / 'interrupt-observed.json').write_text(json.dumps({'operation': {'operation': install_key, 'fence': 1, 'stage': 'installer-start', 'domain': 'd'}, 'domainRunning': True})) + (state / 'interrupt-after.json').write_text(ops('installer-start')) (state / 'interrupt-job-before-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 0})) (state / 'interrupt-job-after-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 1})) r = run('record-pod-interrupt', 'pod-0', 'pod-1') check('record-pod-interrupt', r.returncode == 0, r.stderr) (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) - (state / 'interrupt-job-after.json').write_text(ops('disk-started')) + (state / 'interrupt-job-after.json').write_text(ops('disk-start')) r = run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') check('record-job-interrupt', r.returncode == 0, r.stderr) - (state / 'interrupt-job-before.json').write_text(ops('done')) + (state / 'interrupt-job-before.json').write_text(ops('disk-verified')) check('record-job-interrupt rejects finished install', run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2').returncode != 0) (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') - (state / 'resume-after.json').write_text(ops('done')) + (state / 'resume-after.json').write_text(ops('disk-verified')) r = run('record-resume', h) check('record-resume', r.returncode == 0, r.stderr) + world['statuses'][h]['observation']['result']['fence'] = 2 + check('record-resume rejects a result at another fence', run('record-resume', h).returncode != 0) + world['statuses'][h]['observation']['result']['fence'] = 1 # Lifecycle: snapshot, replace site Pods and the Job, record. r = run('lifecycle-snapshot', h) @@ -148,9 +174,9 @@ def run(*args): (state / 'lifecycle-after.json').write_text(r.stdout) r = run('record-lifecycle', 'job-2', 'job-3') check('record-lifecycle', r.returncode == 0 and (state / 'evidence/lifecycle.json').exists(), r.stderr) - world['journal'] = '{"operations":{"changed":true}}' + world['store'] = json.dumps(dict(store, journal=store['journal'] + [{'operation': install_key, 'fence': 1, 'step': 'installer-start', 'state': 'Intended', 'at': 'y'}])) (state / 'lifecycle-after.json').write_text(run('lifecycle-snapshot', h).stdout) - check('record-lifecycle rejects journal change', run('record-lifecycle', 'job-2', 'job-3').returncode != 0) + check('record-lifecycle rejects a site store change', run('record-lifecycle', 'job-2', 'job-3').returncode != 0) # Worker RBAC probes. (state / 'worker.token').write_text('w' * 40) @@ -158,15 +184,45 @@ def run(*args): check('worker-rbac', r.returncode == 0 and (state / 'k8s-worker-rbac.json').exists(), r.stderr) # Delivery faults: create, verify failure by policy, prune. + # Before the fix the handoff defined a credential field, so the API took a + # forged one and kro granted that Secret. The fault refuses that state. + world['acceptCredential'] = True + check('delivery-faults fails when the API takes a handoff naming a credential', run('delivery-faults', 'create').returncode != 0) + world['acceptCredential'] = False + world['created'] = [] r = run('delivery-faults', 'create') check('delivery-faults create', r.returncode == 0 and len(world.get('created', [])) == 3, r.stderr) - for fault in ('duplicate', 'wrong-cell', 'stale-epoch'): - name = (state / ('fault-%s-handoff' % fault)).read_text().strip() - check('fault name fits worker names: ' + fault, len('w-' + name) <= 63, name) + faults = json.loads((state / 'fault-handoffs.json').read_text()) + check('duplicate refused by the API', faults['duplicate'] == {'handoff': wipe_name, 'refused': 'AlreadyExists'}, str(faults['duplicate'])) + check('a handoff naming another Device\'s credential is refused by the API', faults['foreign-credential']['refused'] == 'unknown field spec.credential', str(faults['foreign-credential'])) + stale = faults['stale-fence'] + check('stale fault is the same operation below the fence under its own name', stale['operation'] == 'devicewipe.alloc-0123456789abcdef-wipe-1.1' and stale['fence'] == 1 + and stale['handoff'] == 'op-' + hashlib.sha256(('%s/devicewipe.alloc-0123456789abcdef-wipe-1.1' % device).encode()).hexdigest()[:40], str(stale)) + check('faults derive from the latest assignment', faults['source']['handoff'] == wipe_name and faults['source']['fence'] == 2) + mismatch = faults['device-mismatch'] + check('the device-mismatch fault names another Device in its assignment', mismatch['handoff'].startswith('op-') and mismatch['handoff'] != faults['stale-fence']['handoff'], str(mismatch)) + for fault in ('wrong-cell', 'stale-fence', 'device-mismatch'): + name = faults[fault]['handoff'] + check('fault name fits worker names: ' + fault, len('w-' + name) <= 63 and (state / ('fault-%s-job' % fault)).read_text().strip() == 'w-' + name, name) world['jobs']['w-' + name] = job('w-' + name, fault, [('Failed', 'PodFailurePolicy')], failed=1) world['pods'].append(pod('f-' + fault, 'f-' + fault, name, fault, 'Failed', 65)) + world['statuses'][stale['handoff']] = {'observation': {'cell': 'fleet-mp-1234abcd-cell', 'fence': {'seen': 2, 'stopped': 2}}} r = run('delivery-faults', 'verify') check('delivery-faults verify', r.returncode == 0, r.stderr) + other = 'bmc-' + hashlib.sha256(b'fleet-provider/synthetic-device-central-02').hexdigest()[:20] + world['roles'] = [{'metadata': {'name': 'w-op-forged'}, 'rules': [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': [other], 'verbs': ['get']}]}] + check('delivery-faults rejects a Role on another Device\'s credential', run('delivery-faults', 'verify').returncode != 0) + world['roles'] = [] + world['credentialRoles'] = ['w-' + faults['device-mismatch']['handoff']] + check('delivery-faults rejects a credential Role for a handoff whose Device is not its assignment\'s', run('delivery-faults', 'verify').returncode != 0) + world['credentialRoles'] = [] + world['results'] = ['devicewipe.alloc-0123456789abcdef-wipe-1.1.json'] + check('delivery-faults rejects a stored stale result', run('delivery-faults', 'verify').returncode != 0) + world['results'] = [] + world['statuses'][faults['wrong-cell']['handoff']] = {'observation': {'cell': 'fleet-mp-1234abcd-cell'}} + check('delivery-faults rejects a wrong-cell observation', run('delivery-faults', 'verify').returncode != 0) + del world['statuses'][faults['wrong-cell']['handoff']] + run('delivery-faults', 'verify') r = run('delivery-faults', 'delete') check('delivery-faults delete', r.returncode == 0 and json.loads((state / 'evidence/delivery-faults.json').read_text()).get('prunedByKro'), r.stderr) world['pods'][-1]['status']['containerStatuses'][0]['state']['terminated']['exitCode'] = 75 diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index d8bd1f38..846eb322 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -57,8 +57,20 @@ def build(path): check('Redfish worker selects the Redfish provider', env.get('FLEET_SITE_PROVIDER') == 'redfish' and 'FLEET_LIBVIRT_URI' not in env, str(env.keys())) check('Redfish worker has no libvirt socket or lab disk mount', not any('libvirt' in m.get('subPath', '') + m['mountPath'] or 'lab-disks' in m.get('subPath', '') for m in mounts), str(mounts)) check('Redfish worker console capture is read-only', any(m.get('subPath') == 'lab-console' and m.get('readOnly') for m in mounts)) -check('Redfish worker credential is the BMC Secret only', [v['secret']['secretName'] for v in worker.get('volumes', []) if 'secret' in v] == ['fleet-site-bmc-credentials'] - and not any('hostPath' in v for v in worker.get('volumes', []))) +check('Redfish worker mounts no credential and no host path', not any('secret' in v or 'hostPath' in v for v in worker.get('volumes', [])), str(worker.get('volumes'))) +check('Redfish worker reads per-Device credentials from the credential namespace', env.get('FLEET_SITE_CREDENTIALS_NAMESPACE') == 'fleet-site-credentials' + and env.get('FLEET_SITE_PROJECT') == 'provider', str(env.keys())) +creds = resources.get('workerCredentialRoles', {}).get('template', {}) +check("per-operation credential Role gets only the Secret of the Device its assignment names, in the credential namespace", creds.get('metadata', {}).get('namespace') == 'fleet-site-credentials' + and creds.get('rules') == [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': ["${'bmc-' + '%x'.format([hash.sha256(json.unmarshal(handoff.spec.assignmentJSON).device)]).substring(0, 20)}"], 'verbs': ['get']}], json.dumps(creds)[:300]) +consistent = "${handoffs.filter(h, h.spec.device == json.unmarshal(h.spec.assignmentJSON).device)}" +check('only a handoff whose Device is its assignment\'s gets a credential Role or binding', + all(resources.get(r, {}).get('forEach') == [{'handoff': consistent}] for r in ('workerCredentialRoles', 'workerCredentialBindings')), + json.dumps([resources.get(r, {}).get('forEach') for r in ('workerCredentialRoles', 'workerCredentialBindings')])) +binding = resources.get('workerCredentialBindings', {}).get('template', {}) +check('per-operation credential RoleBinding binds its own Role to its own ServiceAccount', binding.get('metadata', {}).get('namespace') == 'fleet-site-credentials' + and binding.get('roleRef', {}).get('name') == '${"w-" + handoff.metadata.name}' + and binding.get('subjects') == [{'kind': 'ServiceAccount', 'name': '${"w-" + handoff.metadata.name}', 'namespace': 'fleet-site'}], json.dumps(binding)[:300]) check('Redfish worker waits for the Flux-owned BMC', 'bmc' in resources and resources['bmc'].get('externalRef', {}).get('metadata', {}).get('name') == 'fleet-site-bmc' and '${bmc.metadata.name}' in json.dumps(resources.get('workers', {}))) check('graph ids still valid for kro', all(re.fullmatch(r'[a-z][a-zA-Z0-9]*', i) for i in resources) and 'runtime' not in resources, str(list(resources))) @@ -67,12 +79,13 @@ def build(path): enrollment = json.loads(env.get('FLEET_REDFISH_ENROLLMENT', '{}')) targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) by_system = {t['system']: t for t in targets} -check('every enrolled BMC endpoint is the fixed BMC Service', enrollment.get('targets') and all(t.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP for t in enrollment['targets'])) +check('every enrolled BMC endpoint is the fixed BMC Service', enrollment.get('targets') and all(t.get('endpoint') == 'https://%s:8443' % flux.BMC_SERVICE_IP for t in enrollment['targets'])) check('lab DHCP is static: no provisioning attachment published', enrollment.get('dhcp') == 'static' and not any('provisioning' in t for t in enrollment.get('targets', []))) check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['mac'] == t['mac'] and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) -check('only target A is the published capacity Device', enrollment['targets'][0]['assetID'].endswith('/synthetic-device-central-01') if enrollment.get('targets') else False) +check('only target A is the published capacity Device', [t.get('device') for t in enrollment.get('targets', [])][:1] == ['fleet-provider/synthetic-device-central-01'] + and enrollment['targets'][0].get('systemID') == 'System-1') services = build(root / 'config/site/redfish/services') deployments = {d['metadata']['name']: d for d in services if d.get('kind') == 'Deployment'} @@ -90,7 +103,14 @@ def build(path): base = build(root / 'config/site/redfish/base') policy = next((d for d in base if d.get('kind') == 'ValidatingAdmissionPolicy' and d['metadata']['name'] == 'fleet-site-kro-worker-jobs'), {}) text = json.dumps(policy) -check('admission denies libvirt mounts and URIs for kro worker Jobs', "startsWith('/run/fleet-libvirt')" in text and "FLEET_LIBVIRT_URI" in text and 'fleet-site-bmc-credentials' in text) +check('admission denies libvirt mounts and URIs for kro worker Jobs', "startsWith('/run/fleet-libvirt')" in text and "FLEET_LIBVIRT_URI" in text) +identity = json.dumps(next((d for d in base if d.get('kind') == 'ValidatingAdmissionPolicy' and d['metadata']['name'] == 'fleet-site-kro-worker-identity'), {})) +handoff_crd = documents((root / 'config/multiplane/coordination/crd.yaml').read_text())[0] +handoff_spec = handoff_crd['spec']['versions'][0]['schema']['openAPIV3Schema']['properties']['spec'] +check('no handoff field names a credential Secret, so a forged one is refused', 'credential' not in handoff_spec.get('properties', {}) + and not handoff_spec.get('x-kubernetes-preserve-unknown-fields'), json.dumps(handoff_spec)[:300]) +check('admission confines credential Roles to get on one named Secret', 'fleet-site-credentials' in identity and "r.verbs == ['get']" in identity and 'size(r.resourceNames) == 1' in identity + and "r.verbs == ['list']" not in identity) check('BMC identity in the base', any(d.get('kind') == 'ServiceAccount' and d['metadata']['name'] == 'fleet-site-bmc' for d in base)) check('no Secret in any Redfish overlay', not any(d.get('kind') == 'Secret' for d in base + services + graph)) @@ -111,7 +131,6 @@ def build(path): (s / 'gitops-environment.json').write_text(json.dumps({'registryHost': 'fleet-mp-0000abcd-registry', 'registryPort': 5555, 'karmadaPort': 1, 'cell': 'fleet-mp-0000abcd-cell', 'cellEndpoint': 'https://x:6443', 'siteImage': 'r/fleet-site@sha256:' + 'a' * 64, 'siteImageDigest': 'sha256:' + 'a' * 64, 'bmcImage': 'r/fleet-bmc@sha256:' + 'b' * 64, 'bmcImageDigest': 'sha256:' + 'b' * 64})) - (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') args = argparse.Namespace(state=str(s), root=str(root), revision=2, site='off', bad_kro_chart=False, drop_site_volume=True, purpose='test', cluster=[], timeout=5) check('stage a Redfish revision', flux.stage(args) == 0) cell = subprocess.run(['kustomize', 'build', str(s / 'gitops/r2/environment/cell')], text=True, capture_output=True).stdout @@ -138,9 +157,9 @@ def build(path): 'reuse', 'delivery-faults', 'install-b', 'release-b', 'boot-denials', 'isolation', 'evidence'] positions = [sequence.find(' ' + n + ' ') for n in order] check('Redfish phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) -for name in ('internal/redfish/client.go', 'internal/redfish/provider.go', 'internal/redfish/boot.go'): - src = (root / name).read_text() - check('no lab fault hook in production code: ' + name, not re.search(r'\bfaults?\b|drop-response|hide-reset', src, re.I)) +for path in sorted(list((root / 'internal/redfish').glob('*.go')) + list((root / 'internal/site/redfishwork').glob('*.go'))): + if not path.name.endswith('_test.go'): + check('no lab fault hook in production code: ' + path.name, not re.search(r'\bfaults?\b|drop-response|hide-reset', path.read_text(), re.I)) adapter = (root / 'hack/redfish-lab/fleet_lab_adapter.py').read_text() check('adapter keeps upstream unmodified (imports it)', 'import emulator' in adapter and 'COPY --from=upstream . /opt/redfish-emulator' in (root / 'hack/redfish-lab/Containerfile').read_text()) check('upstream source pinned by digest and commit', re.search(r'sha256=[0-9a-f]{64}', (root / 'hack/redfish-lab/upstream.sh').read_text()) is not None diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 1c733932..6998a8b8 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -56,10 +56,16 @@ def can(*args): return r.stdout.strip()=='yes' allowed=[('create','jobs','-n',site),('create','serviceaccounts','-n',site),('create','roles','-n',ns),('create','rolebindings','-n',ns), ('list','deployments','-A'),('list','services','-A'),('watch',h,'-A'),('get','persistentvolumeclaims','-n',site)] +redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish';creds_ns='fleet-site-credentials' +if redfish: + # Redfish mode: kro creates each worker's Role to get its one BMC credential + # Secret, so it holds get there and nothing more; it cannot list or watch. + allowed+=[('create','roles','-n',creds_ns),('create','rolebindings','-n',creds_ns),('get','secrets','-n',creds_ns)] denied=[('create','deployments','-n',site),('patch','deployments','-n',site),('create','services','-n',site),('delete','services','-n',site), ('delete','persistentvolumeclaims','-n',site),('patch','configmaps','-n',site),('create','jobs','-n','default'),('create','jobs','-n','kube-system'), ('create','roles','-n',site),('create','rolebindings','-n','kube-system'),('create','clusterroles'),('get','secrets','-n',site), - ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')] + ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')]+( + [('list','secrets','-n',creds_ns),('create','secrets','-n',creds_ns),('watch','secrets','-n',creds_ns)] if redfish else []) bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] if bad:raise SystemExit('kro RBAC is not the narrowed grant: '+'; '.join(bad)) # Grants the kro chart keeps because kro needs them: it creates the CRD for each @@ -67,7 +73,6 @@ def can(*args): retained=[('create','customresourcedefinitions'),('delete','customresourcedefinitions'),('update','leases','-n','kro-system')] retained={' '.join(a):can(*a) for a in retained} image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] -redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish' def job(**change): c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} if redfish:c['env']=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'}] @@ -75,11 +80,11 @@ def job(**change): for k,v in change.items(): (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v return {'apiVersion':'batch/v1','kind':'Job','metadata':{'name':'w-op-admission-probe','namespace':site,'labels':{'fleet.datumapis.com/handoff':'op-admission-probe'}},'spec':{'template':{'spec':spec}}} -role=lambda rules:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'w-op-admission-probe','namespace':ns},'rules':rules} +role=lambda rules,namespace=ns:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'w-op-admission-probe','namespace':namespace},'rules':rules} own=[{'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationhandoffs'],'resourceNames':['op-admission-probe'],'verbs':['get']}] # RBAC resolves a binding's Role before admission runs, so the probe binds an # existing Role that kro fully holds; a dry run cannot create w- first. -binding=lambda name,sa,ref:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':name,'namespace':ns}, +binding=lambda name,sa,ref,namespace=ns:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':name,'namespace':namespace}, 'subjects':[{'kind':'ServiceAccount','name':sa,'namespace':site}],'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':ref}} sa=lambda name:{'apiVersion':'v1','kind':'ServiceAccount','metadata':{'name':name,'namespace':site}} cases={'admitted':{'worker Job':job(),'worker Role':role(own),'worker ServiceAccount':sa('w-op-admission-probe')}, @@ -89,14 +94,23 @@ def job(**change): 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} if redfish: # Redfish workers have no hypervisor path: the libvirt socket, the lab disks - # and a libvirt URI are denied by policy; only the BMC credential is added. - creds=[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'credentials','secret':{'secretName':'fleet-site-bmc-credentials'}}] - cases['admitted']['Redfish worker Job with the BMC credential']=job(volumes=creds) + # and a libvirt URI are denied by policy. They mount no credential: each gets + # its Device's credential Secret, by name, through a per-operation Role. + named=[{'apiGroups':[''],'resources':['secrets'],'resourceNames':['bmc-'+'0'*20],'verbs':['get']}] + listing=[{'apiGroups':[''],'resources':['secrets'],'verbs':['list']}] + cases['admitted'].update({'Redfish worker Job':job(),'worker credential Role':role(named,creds_ns)}) cases['denied'].update({'Redfish worker mounting the libvirt socket':job(volumeMounts=[{'name':'state','mountPath':'/run/fleet-libvirt','subPath':'libvirt-socket'}]), 'Redfish worker mounting the lab disks':job(volumeMounts=[{'name':'state','mountPath':'/var/lib/fleet-lab/disks','subPath':'lab-disks'}]), 'Redfish worker with a libvirt URI':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'},{'name':'FLEET_LIBVIRT_URI','value':'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock'}]), 'worker selecting the libvirt provider':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'libvirt'}]), - 'Redfish worker mounting another Secret':job(volumes=[{'name':'other','secret':{'secretName':'fleet-site-other'}}])}) + 'Redfish worker mounting a credential Secret':job(volumes=[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'credentials','secret':{'secretName':'bmc-synthetic-device-central-01'}}]), + # Shapes within kro's own grant, so the policy, not RBAC escalation, denies them. + 'credential Role with a second rule':role(named+own,creds_ns), + 'credential Role listing Secrets':role(listing,creds_ns), + 'credential Role getting every Secret':role([dict(named[0],resourceNames=[])],creds_ns), + 'credential Role getting two Secrets':role([dict(named[0],resourceNames=['bmc-'+'0'*20,'bmc-'+'1'*20])],creds_ns), + 'credential Role naming a Secret outside the rule':role([dict(named[0],resourceNames=['fleet-site-bmc-credentials'])],creds_ns), + 'credential RoleBinding to another Role':binding('w-op-admission-probe','w-op-admission-probe','fleet-site-kro-worker-credentials',creds_ns)}) record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} for outcome,objs in cases.items(): for name,obj in objs.items(): @@ -106,8 +120,13 @@ def job(**change): if (outcome=='admitted')!=ok or (not ok and not by_policy and 'forbidden' not in r.stderr.lower()): raise SystemExit('kro admission %s for %s: %s'%('denied' if not ok else 'admitted',name,r.stderr[:300])) record['admission'][name]={'expected':outcome,'admitted':ok,'deniedBy':None if ok else ('ValidatingAdmissionPolicy' if by_policy else 'RBAC')} -if any(v['deniedBy']!='ValidatingAdmissionPolicy' for v in record['admission'].values() if not v['admitted']): - raise SystemExit('expected the admission policies, not RBAC, to deny in-namespace shape violations: %s'%record['admission']) +# A credential Role that lists Secrets is outside kro's own grant: kro holds +# only get there, so RBAC escalation refuses it before admission. Every other +# shape is within kro's grant and must be refused by the policies. +outside_grant={'credential Role listing Secrets'} +wrong=[n for n,v in record['admission'].items() if not v['admitted'] and v['deniedBy']!=('RBAC' if n in outside_grant else 'ValidatingAdmissionPolicy')] +if wrong: + raise SystemExit('a shape was refused by the wrong layer (%s): %s'%(', '.join(wrong),record['admission'])) (s/'evidence'/'kro-rbac.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') print('Verified kro RBAC and admission confine it to per-operation objects: %d allowed, %d denied verbs; %d shapes admitted, %d denied by policy'%( len(allowed),len(denied),len(cases['admitted']),len(cases['denied']))) diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 3798d5e1..3782e009 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -38,7 +38,10 @@ CREDENTIALS = os.environ.get('FLEET_BMC_CREDENTIALS', '/etc/fleet-bmc-credentials') LIBVIRT_URI = os.environ.get('FLEET_LIBVIRT_URI', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock') VIRSH = os.environ.get('FLEET_VIRSH', 'virsh') -PORT = int(os.environ.get('FLEET_BMC_PORT', '8000')) +PORT = int(os.environ.get('FLEET_BMC_PORT', '8443')) +# The lab BMC serves TLS with a key the harness generates per run, so Fleet +# workers reach it only over a connection pinned to that key. +TLS_DIR = os.environ.get('FLEET_BMC_TLS', '/etc/fleet-bmc-tls') RESET_TYPES = ('On', 'ForceOff', 'ForceRestart') BOOT_TARGETS = ('None', 'Pxe', 'Hdd') BOOT_ENABLED = ('Disabled', 'Once') @@ -376,7 +379,8 @@ def main(): boot_ip = os.environ.get('FLEET_BOOT_IP', '') if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', boot_ip): raise SystemExit('FLEET_BOOT_IP must be the boot Service IPv4 address') - create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True) + tls = (os.path.join(TLS_DIR, 'tls.crt'), os.path.join(TLS_DIR, 'tls.key')) + create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True, ssl_context=tls) elif sys.argv[1:2] == ['fault']: fault_cli(sys.argv[2:]) else: diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 9eaed6f2..dfdd281b 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -40,7 +40,7 @@ done </dev/null 2>&1; then echo "fixed namespace $namespace already exists; use a fresh dedicated kind cluster" >&2 exit 1 @@ -52,20 +52,32 @@ for crd in installations machineallocations machinecapacities machineclasses mac exit 1 fi done -for object in clusterrole/fleet-standalone-fixture-reader clusterrolebinding/fleet-standalone-fixture-reader; do +for crd in devices devicecustodies deviceinstallations devicewipes devicerecoveries; do + if kubectl --context "$context" get crd "$crd.fleet.datumapis.com" >/dev/null 2>&1; then + echo "fixed Fleet CRD $crd already exists; use a fresh dedicated kind cluster" >&2 + exit 1 + fi +done +for object in clusterrole/fleet-standalone-fixture-reader clusterrolebinding/fleet-standalone-fixture-reader clusterrole/fleet-custody-coordinator-devices clusterrolebinding/fleet-custody-coordinator-devices validatingadmissionpolicy/fleet-operation-creator validatingadmissionpolicybinding/fleet-operation-creator; do if kubectl --context "$context" get "$object" >/dev/null 2>&1; then echo "fixed cluster object $object already exists; use a fresh dedicated kind cluster" >&2 exit 1 fi done -# The five required namespaces are absent, which also proves every fixed +# The four required namespaces are absent, which also proves every fixed # namespaced ServiceAccount, Role, binding, Secret, workload, Job, and fixture # name is absent. No ownership label or ConfigMap is accepted as resume proof. docker build -f build/simulator.Dockerfile -t "$simulator_image" . docker build -f build/standalone-smoke.Dockerfile -t "$smoke_image" . kind load docker-image --name "$cluster" "$simulator_image" "$smoke_image" -kustomize build config/base/crd >"$rendered" +{ + kustomize build config/base/crd + echo --- + kustomize build config/components/inventory/crds + echo --- + kustomize build config/components/device-operations/crds +} >"$rendered" kubectl --context "$context" apply -f "$rendered" kubectl --context "$context" wait --for=condition=Established --timeout=60s -f "$rendered" kustomize build config/standalone | @@ -76,6 +88,7 @@ if grep -q 'standalone-local' "$rendered"; then fi kubectl --context "$context" apply -f "$rendered" kubectl --context "$context" -n fleet-system rollout status statefulset/fleet-simulator --timeout=120s +kubectl --context "$context" -n fleet-system rollout status deployment/fleet-custody-coordinator --timeout=120s simulator_pod=$(kubectl --context "$context" -n fleet-system get pod -l app.kubernetes.io/name=fleet-simulator -o jsonpath='{.items[0].metadata.name}') test "$(kubectl --context "$context" -n fleet-system get pod "$simulator_pod" -o jsonpath='{.spec.containers[0].image}')" = "$simulator_image" test "$(kubectl --context "$context" -n fleet-system get pod "$simulator_pod" -o jsonpath='{.spec.containers[0].imagePullPolicy}')" = "Never" @@ -99,6 +112,13 @@ test "$(kubectl --context "$context" -n fleet-project-a get machine -o name)" = test "$(kubectl --context "$context" -n fleet-project-b get machine -o name)" = "machine.metal.datumapis.com/allocation" test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.phase}')" = "Ready" test "$(kubectl --context "$context" -n fleet-project-b get machine allocation -o jsonpath='{.status.phase}')" = "Pending" +# Custody decided the contention: one allocation exists, and custody names it. +test "$(kubectl --context "$context" -n fleet-provider get machineallocations -o name | wc -l | tr -d ' ')" = "1" +winner=$(kubectl --context "$context" -n fleet-provider get machineallocations -o jsonpath='{.items[0].metadata.name}') +test "$(kubectl --context "$context" -n fleet-provider get devicecustody synthetic-device-central-01 -o jsonpath='{.spec.state}/{.spec.holder.type}/{.spec.holder.allocationRef.name}')" = "Verified/Allocation/$winner" +# Power comes only from the manager's power projector, which reads custody +# and fixture discovery. +test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.power.state}')" = "Off" # Requested hardware is pinned from the exact profile for both claims, # including the one still waiting for capacity. for project in fleet-project-a fleet-project-b; do @@ -123,21 +143,26 @@ test "$(kubectl --context "$context" -n fleet-project-b get machine allocation - for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" - for verb in get list watch create update patch delete; do - if [ "$(kubectl --context "$context" auth can-i "$verb" secrets --as="$subject" -n fleet-system-private)" != "no" ]; then - echo "$subject unexpectedly has $verb access to private records" >&2 + for resource in devicecustodies deviceinstallations devicewipes devicerecoveries machineallocations; do + for verb in get list watch create update patch delete; do + if [ "$(kubectl --context "$context" auth can-i "$verb" "$resource" --as="$subject" -n fleet-provider)" != "no" ]; then + echo "$subject unexpectedly has $verb access to $resource" >&2 + exit 1 + fi + done + done + for secret in fleet-simulator-runtime fleet-custody-coordinator-token fleet-release-controller-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 fi done - if [ "$(kubectl --context "$context" auth can-i get secret/fleet-claim-forbidden --as="$subject" -n fleet-system-private)" != "no" ]; then - echo "$subject unexpectedly has named private-record access" >&2 - exit 1 - fi - if [ "$(kubectl --context "$context" auth can-i get secret/fleet-simulator-runtime --as="$subject" -n fleet-system)" != "no" ]; then - echo "$subject unexpectedly has simulator credential access" >&2 - exit 1 - fi done +# Only the custody coordinator writes custody; the Metal provider only reads it. +provider_subject=system:serviceaccount:fleet-system:fleet-standalone-smoke +test "$(kubectl --context "$context" auth can-i update devicecustodies --as="$provider_subject" -n fleet-provider)" = "no" +test "$(kubectl --context "$context" auth can-i create devicewipes --as="$provider_subject" -n fleet-provider)" = "no" +test "$(kubectl --context "$context" auth can-i create deviceinstallations --as=system:serviceaccount:fleet-system:fleet-release-controller -n fleet-provider)" = "no" smoke_subject=system:serviceaccount:fleet-system:fleet-standalone-smoke test "$(kubectl --context "$context" auth can-i get machine/other-machine --as="$smoke_subject" -n fleet-provider)" = "no" test "$(kubectl --context "$context" auth can-i update machineclass/standard-metal --as="$smoke_subject")" = "no" @@ -151,3 +176,17 @@ if kubectl --context "$context" -n fleet-project-a get machine allocation >/dev/ fi test "$(kubectl --context "$context" -n fleet-project-b get machine -o name)" = "machine.metal.datumapis.com/allocation" test "$(kubectl --context "$context" -n fleet-project-b get machine allocation -o jsonpath='{.status.phase}')" = "Ready" +# The release wiped the Device once, under a fence above both installations, +# and custody now names the reusing consumer's allocation. +kubectl --context "$context" -n fleet-provider get machineallocations,deviceinstallations,devicewipes,devicecustodies +test "$(kubectl --context "$context" -n fleet-provider get devicewipes -o jsonpath='{range .items[*]}{.status.phase}{"\n"}{end}')" = "Succeeded" +test "$(kubectl --context "$context" -n fleet-provider get deviceinstallations -o jsonpath='{range .items[*]}{.status.phase}{"\n"}{end}' | sort -u)" = "Succeeded" +wipe_fence=$(kubectl --context "$context" -n fleet-provider get devicewipes -o jsonpath='{.items[0].status.fence}') +for fence in $(kubectl --context "$context" -n fleet-provider get deviceinstallations -o jsonpath='{.items[*].status.fence}'); do + test "$fence" -lt "$wipe_fence" +done +released=$(kubectl --context "$context" -n fleet-provider get machineallocations -o jsonpath='{range .items[?(@.status.phase=="Released")]}{.metadata.name}{"\n"}{end}') +reused=$(kubectl --context "$context" -n fleet-provider get machineallocations -o jsonpath='{range .items[?(@.status.phase=="Active")]}{.metadata.name}{"\n"}{end}') +test "$released" = "$winner" +test -n "$reused" && test "$reused" != "$winner" +test "$(kubectl --context "$context" -n fleet-provider get devicecustody synthetic-device-central-01 -o jsonpath='{.spec.holder.type}/{.spec.holder.allocationRef.name}')" = "Allocation/$reused" diff --git a/hack/synthetic-staging-validator.go b/hack/synthetic-staging-validator.go index 7720ed7d..b0db3a32 100644 --- a/hack/synthetic-staging-validator.go +++ b/hack/synthetic-staging-validator.go @@ -77,7 +77,10 @@ func main() { } require(has(m.Args, "--synthetic-provider-url=http://"+service.Name+"."+service.Namespace+".svc:8090"), "manager must use provider Service DNS") require(has(m.Args, "--synthetic-provider-token-file=/var/run/fleet/provider/token") && has(p.Args, "--runtime-token-file=/var/run/fleet/provider/token"), "both processes need the dedicated runtime credential") - require(has(p.Args, "--listen-address=0.0.0.0:8090") && has(p.Args, "--state-file=/var/lib/fleet/state.json"), "provider runtime and persistent state paths must match mounts") + require(has(p.Args, "--listen-address=0.0.0.0:8090") && has(p.Args, "--state-dir=/var/lib/fleet/site"), "provider runtime and persistent store paths must match mounts") + require(!has(p.Args, "--discover"), "the provider site has no Kubernetes API credential, so it must not run discovery") + require(has(m.Args, "--synthetic-site-enrollment-file=/etc/fleet/enrollment/enrollment.json") && has(p.Args, "--enrollment-file=/etc/fleet/enrollment/enrollment.json"), "the manager and the site must read the same enrollment") + require(has(m.Args, "--synthetic-coordinator-client-cert-dir=/var/run/fleet/coordinator") && has(m.Args, "--synthetic-release-client-cert-dir=/var/run/fleet/release"), "the coordinator and release controller need their own Milo client certificates") for _, arg := range p.Args { require(!strings.HasPrefix(arg, "--admin-"), "provider must not expose an admin listener") } @@ -100,6 +103,36 @@ func main() { } require(mounted, "runtime token mount must resolve to the external Secret") } + // Each component's credential is an external Secret, and both + // processes mount the one enrollment ConfigMap. + mountsSecret := func(pod core.PodSpec, path, secret string) bool { + for _, mount := range pod.Containers[0].VolumeMounts { + if mount.MountPath != path || !mount.ReadOnly || mount.SubPath != "" { + continue + } + for _, volume := range pod.Volumes { + if volume.Name == mount.Name && volume.Secret != nil && volume.Secret.SecretName == secret { + return true + } + } + } + return false + } + 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") + var enrollment core.ConfigMap + read("ConfigMap/fleet-synthetic-site-enrollment", &enrollment) + for _, pod := range []core.PodSpec{manager.Spec.Template.Spec, provider.Spec.Template.Spec} { + mounted := false + for _, mount := range pod.Containers[0].VolumeMounts { + for _, volume := range pod.Volumes { + if mount.MountPath == "/etc/fleet/enrollment" && mount.ReadOnly && volume.Name == mount.Name && volume.ConfigMap != nil && volume.ConfigMap.Name == enrollment.Name { + mounted = true + } + } + } + require(mounted, "the enrollment mount must resolve to the shared ConfigMap") + } persistent := false for _, mount := range p.VolumeMounts { if mount.MountPath != "/var/lib/fleet" { diff --git a/hack/test-standalone-preflight.sh b/hack/test-standalone-preflight.sh index 5edbc741..9ff24368 100755 --- a/hack/test-standalone-preflight.sh +++ b/hack/test-standalone-preflight.sh @@ -64,7 +64,12 @@ cat >"$temporary/kustomize" <<'EOF' #!/bin/sh set -eu case "$*" in - 'build config/base/crd') echo 'kind: CustomResourceDefinition' ;; + # The smoke installs the Metal, inventory and Device custody CRDs + # together, and every one must be Established before any fixture. + 'build config/base/crd' | 'build config/components/inventory/crds' | 'build config/components/device-operations/crds') + touch "$ORDER_DIRECTORY/built-$(echo "$2" | tr / -)" + echo 'kind: CustomResourceDefinition' + ;; 'build config/standalone') test -f "$ORDER_DIRECTORY/established" echo 'kind: Installation' @@ -82,6 +87,9 @@ case " $* " in *" apply -f "*) for argument do manifest=$argument; done if grep -q 'CustomResourceDefinition' "$manifest"; then + for crds in config-base-crd config-components-inventory-crds config-components-device-operations-crds; do + test -f "$ORDER_DIRECTORY/built-$crds" + done touch "$ORDER_DIRECTORY/crds-applied" else test -f "$ORDER_DIRECTORY/established" diff --git a/hack/validate-standalone-render.sh b/hack/validate-standalone-render.sh index cba9052c..e61d758c 100755 --- a/hack/validate-standalone-render.sh +++ b/hack/validate-standalone-render.sh @@ -15,11 +15,11 @@ require_count() { fi } -require_count 5 'runAsUser: 65532' -require_count 5 'runAsGroup: 65532' -require_count 5 'fsGroup: 65532' -require_count 5 'defaultMode: 288' -require_count 5 'imagePullPolicy: Never' +require_count 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 1 'name: fleet-smoke-reinstall' require_count 1 '--phase=reinstall' diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go new file mode 100644 index 00000000..9285255d --- /dev/null +++ b/internal/allocation/allocator.go @@ -0,0 +1,458 @@ +// Package allocation allocates a Device to a Machine, installs it, and +// releases it, on Device custody. Every mode uses it: synthetic staging, the +// standalone smoke test and the multi-plane acceptance. +// +// An allocation is a MachineAllocation in the provider project, named from +// its Machine. The allocator writes in the order the custody design fixes: +// quota claim, then MachineAllocation, then custody. The conditional custody +// update decides which Machine wins a Device; the capacity conditions only +// pick candidates. +package allocation + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + "sort" + "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" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/tenancy" +) + +var ( + // ErrInsufficientCapacity means no eligible Device could be claimed. + ErrInsufficientCapacity = errors.New("no eligible capacity is free") + // ErrConflict means the allocation name belongs to another Machine. + ErrConflict = errors.New("the allocation belongs to another Machine") + // ErrReleased means the Machine's allocation is releasing or released. + ErrReleased = errors.New("the allocation is releasing or released") + // ErrCustodyLost means an active allocation no longer holds its Device. + // Fleet does not repair it: an operator resolves the custody conflict. + ErrCustodyLost = errors.New("the allocation no longer holds its Device") + // ErrPredecessor means an Installation does not follow the current one. + ErrPredecessor = errors.New("the installation does not name the current installation as its predecessor") + // ErrUnsupported means a request Fleet does not implement, such as a + // bootstrap payload. + ErrUnsupported = errors.New("unsupported request") +) + +// Machine names one Machine incarnation in one consumer incarnation. +type Machine struct { + // Consumer is the consumer's typed reference, as recorded in the + // allocation's consumerRef. + Consumer fleetv1.TypedReference + // ConsumerUID is the consumer's incarnation. It goes into the + // allocation's name and labels, never its spec. + ConsumerUID types.UID + Namespace string + Name string + UID types.UID +} + +// MachineOf is a resolved consumer's Machine. +func MachineOf(consumer tenancy.Consumer, machine *fleetv1.Machine) Machine { + return Machine{Consumer: consumer.Ref, ConsumerUID: consumer.UID, Namespace: machine.Namespace, Name: machine.Name, UID: machine.UID} +} + +func (m Machine) Valid() bool { + return tenancy.Supported(m.Consumer) == nil && m.ConsumerUID != "" && m.Namespace != "" && m.Name != "" && m.UID != "" +} + +func (m Machine) reference() fleetv1.AllocatedMachineReference { + return fleetv1.AllocatedMachineReference{Namespace: m.Namespace, Name: m.Name} +} + +// labels pin the Machine and consumer incarnations. No spec holds an object +// UID; the allocation's name hashes both, and these labels confirm them. +func (m Machine) labels() map[string]string { + return map[string]string{fleetv1.LabelMachineUID: string(m.UID), fleetv1.LabelConsumerUID: string(m.ConsumerUID)} +} + +// Name is the only name a Machine's allocation may have. It derives from the +// Machine UID within its consumer, so a retried create collides and equal +// UIDs in two consumers never share an allocation. +func Name(machine Machine) string { + sum := sha256.Sum256([]byte(string(machine.ConsumerUID) + "/" + string(machine.UID))) + return "alloc-" + hex.EncodeToString(sum[:])[:16] +} + +// Quota reserves and releases the consumer's quota for one Machine. Both are +// idempotent and name the claim from the Machine, so a claim reserved before +// a crash, or before capacity was found, is released by the Machine alone. +type Quota interface { + Acquire(ctx context.Context, machine Machine) (string, error) + // Release returns nil once the Machine's claim no longer exists. + Release(ctx context.Context, machine Machine) error +} + +// CleaningPolicies resolves a MachineCapacity's cleaning policy reference +// to the digest of the policy record pinned at allocation. +type CleaningPolicies func(name string) (string, error) + +// Request is one Machine's allocation request, already admitted. +type Request struct { + Machine Machine + // Class and Profile are the provider's source class and profile. + Class *fleetv1.MachineClass + Profile *fleetv1.MachineProfile + Authority fleetv1.AllocationAuthority +} + +// Allocator allocates, installs and releases on custody. +type Allocator struct { + // Provider is the Metal provider's client to the provider project. It + // must read through to the API server. It creates MachineAllocations + // and DeviceInstallations. + Provider client.Client + ProviderCreator ops.Creator + // Releaser is the release controller's client. It creates DeviceWipes. + Releaser client.Client + ReleaseCreator ops.Creator + Custody *custody.Coordinator + // Namespace is the Devices' namespace. Capacities and allocations live + // in it too. + Namespace string + Quota Quota + Cleaning CleaningPolicies + // BootInterface and TargetDisks are pinned on each allocation. + BootInterface string + TargetDisks []string +} + +// Get returns the Machine's allocation, or nil. +func (a *Allocator) Get(ctx context.Context, machine Machine) (*fleetv1.MachineAllocation, error) { + allocation := &fleetv1.MachineAllocation{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: Name(machine)}, allocation); apierrors.IsNotFound(err) { + return nil, nil + } else if err != nil { + return nil, err + } + // A same-name Machine or consumer never inherits the allocation. + if allocation.Spec.ConsumerRef != machine.Consumer || allocation.Spec.MachineRef != machine.reference() || allocation.Labels[fleetv1.LabelMachineUID] != string(machine.UID) || allocation.Labels[fleetv1.LabelConsumerUID] != string(machine.ConsumerUID) { + return nil, ErrConflict + } + return allocation, nil +} + +// Allocate gives the Machine one Device and returns its active allocation. +// A retry after a lost response finds the same allocation by name and never +// claims a second Device. +func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.MachineAllocation, error) { + if err := tenancy.Supported(request.Machine.Consumer); err != nil { + return nil, err + } + if !request.Machine.Valid() || request.Class == nil || request.Profile == nil || request.Class.Spec.Capacity == nil { + return nil, errors.New("allocation: an exact Machine, class and profile are required") + } + // No spec holds an object UID: the allocation's name and labels carry + // the incarnations, so the authority names its decision by name. + for _, uid := range []types.UID{request.Machine.UID, request.Machine.ConsumerUID} { + if strings.Contains(request.Authority.Principal, string(uid)) || strings.Contains(request.Authority.Decision, string(uid)) { + return nil, fmt.Errorf("%w: the allocation authority records an object UID", ErrUnsupported) + } + } + if request.Class.Spec.Capacity.MachineCapacities.Namespace != a.Namespace { + return nil, errors.New("allocation: the class selects capacity outside the Device namespace") + } + var claim string + if a.Quota != nil { + var err error + if claim, err = a.Quota.Acquire(ctx, request.Machine); err != nil { + return nil, fmt.Errorf("reserve quota: %w", err) + } + } + tried := map[string]bool{} + for { + allocation, err := a.Get(ctx, request.Machine) + if err != nil { + return nil, err + } + if allocation != nil { + done, err := a.claim(ctx, allocation) + if err != nil || done { + return allocation, err + } + tried[allocation.Spec.MachineCapacityRef.Name] = true + continue + } + candidate, device, err := a.candidate(ctx, request, tried) + if err != nil { + return nil, err + } + tried[candidate.Name] = true + allocation, err = a.newAllocation(request, candidate, device, claim) + if err != nil { + return nil, err + } + if err := a.Provider.Create(ctx, allocation); err != nil && !apierrors.IsAlreadyExists(err) { + return nil, err + } + } +} + +// claim claims custody for an existing allocation. It returns true when the +// allocation holds its Device. An allocation that never held it is deleted +// when another holder took the Device, so the caller selects again. +func (a *Allocator) claim(ctx context.Context, allocation *fleetv1.MachineAllocation) (bool, error) { + switch allocation.Status.Phase { + case fleetv1.AllocationReleasing, fleetv1.AllocationReleased: + return false, ErrReleased + } + err := a.Custody.Claim(ctx, allocation.Spec.DeviceRef.Name, types.UID(allocation.Labels[fleetv1.LabelDeviceUID]), allocation.Name) + switch { + case err == nil: + return true, a.setPhase(ctx, allocation, fleetv1.AllocationActive) + case !errors.Is(err, custody.ErrUnavailable): + return false, err + case allocation.Status.Phase == fleetv1.AllocationActive: + return false, ErrCustodyLost + } + // No effect ran under this allocation: it never held the Device. + uid, version := allocation.UID, allocation.ResourceVersion + if err := a.Provider.Delete(ctx, allocation, client.Preconditions{UID: &uid, ResourceVersion: &version}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return false, err + } + 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) { + selector, err := metav1.LabelSelectorAsSelector(&request.Class.Spec.Capacity.MachineCapacities.Selector) + if err != nil { + return nil, nil, 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 + } + sort.Slice(capacities.Items, func(i, j int) bool { return capacities.Items[i].Name < capacities.Items[j].Name }) + for index := range capacities.Items { + capacity := &capacities.Items[index] + if tried[capacity.Name] || !Eligible(capacity, request.Profile.Spec) || !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 + } + 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 + } + 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 + } + } + return matches(profile, capacity.Status.Hardware) +} + +// Free reports whether custody shows the Device free: Verified, for this +// Device incarnation, holder None, no hold and no active operation. +func Free(state *ops.DeviceCustody, device *inventory.Device) bool { + spec := state.Spec + return state.DeletionTimestamp.IsZero() && state.Labels[ops.LabelDeviceUID] == string(device.UID) && spec.State == ops.CustodyVerified && spec.Holder.Type == ops.HolderNone && + 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) { + if a.Cleaning == nil { + return nil, errors.New("allocation: no cleaning policy resolver") + } + digest, err := a.Cleaning(capacity.Spec.CleaningPolicyRef.Name) + if err != nil { + return nil, fmt.Errorf("resolve cleaning policy: %w", err) + } + classDigest, err := custody.SpecDigest(request.Class.Spec) + if err != nil { + return nil, err + } + profileDigest, err := custody.SpecDigest(request.Profile.Spec) + if err != nil { + return nil, err + } + labels := request.Machine.labels() + labels[fleetv1.LabelDeviceUID] = string(device.UID) + allocation := &fleetv1.MachineAllocation{ + ObjectMeta: metav1.ObjectMeta{Name: Name(request.Machine), Namespace: a.Namespace, Labels: labels}, + Spec: fleetv1.MachineAllocationSpec{ + ConsumerRef: request.Machine.Consumer, + MachineRef: request.Machine.reference(), + MachineCapacityRef: fleetv1.NamespacedReference{Namespace: capacity.Namespace, Name: capacity.Name}, + DeviceRef: fleetv1.AllocatedDeviceReference{Name: device.Name}, + Accepted: fleetv1.AcceptedContract{ + MachineClassRef: fleetv1.ContentReference{Name: request.Class.Name, Generation: request.Class.Generation, Digest: classDigest}, + MachineProfileRef: fleetv1.ContentReference{Name: request.Profile.Name, Generation: request.Profile.Generation, Digest: profileDigest}, + CPU: request.Profile.Spec.CPU, + Memory: request.Profile.Spec.Memory, + }, + Hardware: capacity.Status.Hardware, + Authority: request.Authority, + CleaningPolicyDigest: digest, + BootInterface: a.BootInterface, + TargetDisks: slices.Clone(a.TargetDisks), + }, + } + if claim != "" { + allocation.Spec.QuotaClaimRef = &fleetv1.LocalReference{Name: claim} + } + return allocation, nil +} + +// setPhase writes the allocation's phase with the resourceVersion read. +func (a *Allocator) setPhase(ctx context.Context, allocation *fleetv1.MachineAllocation, phase string) error { + if allocation.Status.Phase == phase { + return nil + } + allocation.Status.Phase = phase + return a.Provider.Status().Update(ctx, allocation) +} + +// Installation is one Installation an allocation's Machine requested. +type Installation struct { + Installation *fleetv1.Installation + // Current is the Machine's current installation, or empty. + Current string +} + +// ParseImage splits an image reference into its name and digest. Fleet +// installs only images pinned by digest. +func ParseImage(reference string) (ops.ImageInput, error) { + name, digest, ok := strings.Cut(reference, "@") + hexDigest, sha := strings.CutPrefix(digest, "sha256:") + if !ok || name == "" || !sha || len(hexDigest) != 64 || strings.Trim(hexDigest, "0123456789abcdef") != "" { + return ops.ImageInput{}, fmt.Errorf("%w: the image must be name@sha256:<64 hex>", ErrUnsupported) + } + return ops.ImageInput{Name: name, Digest: digest}, nil +} + +// Install creates the DeviceInstallation for an Installation. It is +// create-only: a retry finds the same operation by name. +func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllocation, request Installation) (*ops.DeviceInstallation, error) { + installation := request.Installation + if allocation.Status.Phase != fleetv1.AllocationActive { + return nil, ErrReleased + } + if installation.Spec.BootstrapConfigRef != nil { + return nil, fmt.Errorf("%w: bootstrap payloads need the sealed store, which is not implemented", ErrUnsupported) + } + predecessor := installation.Spec.ExpectedPredecessor + if (request.Current == "" && predecessor.Type != "None") || (request.Current != "" && (predecessor.Type != "Installation" || predecessor.Name != request.Current)) { + return nil, ErrPredecessor + } + image, err := ParseImage(installation.Spec.ImageRef.Name) + if err != nil { + return nil, err + } + labels := operationLabels(allocation) + labels[ops.LabelInstallationUID] = string(installation.UID) + operation := &ops.DeviceInstallation{ + ObjectMeta: metav1.ObjectMeta{Name: custody.InstallationName(allocation.Name, string(installation.UID)), Namespace: a.Namespace, Labels: labels}, + Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: a.envelope(allocation, a.ProviderCreator), + Image: image, + BootInterface: allocation.Spec.BootInterface, + TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + }, + } + return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) +} + +func (a *Allocator) envelope(allocation *fleetv1.MachineAllocation, creator ops.Creator) ops.OperationEnvelope { + return ops.OperationEnvelope{ + Creator: creator, + DeviceRef: ops.DeviceReference{Name: allocation.Spec.DeviceRef.Name}, + Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: allocation.Name}}, + } +} + +// operationLabels carries the allocation's Device incarnation onto an +// operation, where admission compares it with the Device. +func operationLabels(allocation *fleetv1.MachineAllocation) map[string]string { + return map[string]string{ops.LabelDeviceUID: allocation.Labels[fleetv1.LabelDeviceUID]} +} + +// createOnce creates an operation, or reads the existing one and requires it +// to carry the same spec and the same incarnation labels, so an operation for +// a same-name Device or Installation is never taken for this one. +func (a *Allocator) createOnce(ctx context.Context, api client.Client, operation ops.Operation, existing ops.Operation) error { + if err := api.Create(ctx, operation); err == nil || !apierrors.IsAlreadyExists(err) { + return err + } + if err := api.Get(ctx, client.ObjectKeyFromObject(operation), existing); err != nil { + return err + } + want, err := specDigest(operation) + if err != nil { + return err + } + got, err := specDigest(existing) + if err != nil { + return err + } + if want != got { + return fmt.Errorf("%w: %s exists with other inputs", ErrConflict, operation.GetName()) + } + for key, value := range operation.GetLabels() { + if existing.GetLabels()[key] != value { + return fmt.Errorf("%w: %s exists for another %s", ErrConflict, operation.GetName(), key) + } + } + data, err := json.Marshal(existing) + if err != nil { + return err + } + return json.Unmarshal(data, operation) +} + +func specDigest(operation ops.Operation) (string, error) { + var object struct { + Spec json.RawMessage `json:"spec"` + } + data, err := json.Marshal(operation) + if err != nil { + return "", err + } + if err := json.Unmarshal(data, &object); err != nil { + return "", err + } + sum := sha256.Sum256(object.Spec) + return hex.EncodeToString(sum[:]), nil +} diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go new file mode 100644 index 00000000..bd2815ec --- /dev/null +++ b/internal/allocation/flow_test.go @@ -0,0 +1,188 @@ +package allocation + +import ( + "errors" + "sync" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site/simwork" +) + +// TestAllocateInstallReleaseReuse runs one Device through a whole lifecycle +// on custody: allocation, a losing contender, a retried allocation, +// installation, reinstallation, release with a wipe, and reuse by the +// contender under a higher fence. +func TestAllocateInstallReleaseReuse(t *testing.T) { + e := startEnv(t) + device := e.server(1) + + first, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + if first.Name != Name(machine(1)) || first.Status.Phase != fleetv1.AllocationActive || first.Labels[fleetv1.LabelDeviceUID] != string(device.UID) { + t.Fatalf("allocation = %s %s %+v", first.Name, first.Status.Phase, first.Spec.DeviceRef) + } + state := e.custody(device.Name) + if state.Spec.Holder.Type != ops.HolderAllocation || state.Spec.Holder.AllocationRef.Name != first.Name { + t.Fatalf("holder = %+v", state.Spec.Holder) + } + + // The contender loses: custody already names the first allocation, and + // its own allocation never remains. + if _, err := e.allocator.Allocate(e.ctx, e.request(2)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("contender err = %v", err) + } + if found, err := e.allocator.Get(e.ctx, machine(2)); err != nil || found != nil { + t.Fatalf("contender allocation = %v, %v", found, err) + } + // A retry after a lost response finds the same allocation. + again, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil || again.UID != first.UID { + t.Fatalf("retry = %v, %v", again, err) + } + + install := func(allocation *fleetv1.MachineAllocation, installation *fleetv1.Installation, current string) *ops.DeviceInstallation { + t.Helper() + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Current: current}) + if err != nil { + t.Fatal(err) + } + e.until("the installation succeeds", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + if operation.Status.Phase.Ended() && operation.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s: %s", operation.Status.Phase, operation.Status.Message) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + return operation + } + initial := install(first, e.installation(1, "debian-12", ""), "") + if initial.Name != custody.InstallationName(first.Name, uid(701)) { + t.Fatalf("installation name = %s", initial.Name) + } + server, err := simwork.ReadServer(e.store, namespace+"/"+device.Name) + if err != nil || server.Booted != initial.Spec.Image.Digest { + t.Fatalf("server = %+v, %v", server, err) + } + // A reinstall must name the current installation. + if _, err := e.allocator.Install(e.ctx, first, Installation{Installation: e.installation(2, "debian-12-reinstall", "elsewhere"), Current: "debian-12"}); !errors.Is(err, ErrPredecessor) { + t.Fatalf("stale predecessor err = %v", err) + } + reinstall := install(first, e.installation(2, "debian-12-reinstall", "debian-12"), "debian-12") + if reinstall.Status.Fence <= initial.Status.Fence { + t.Fatalf("reinstall fence %d, initial %d", reinstall.Status.Fence, initial.Status.Fence) + } + + e.release(first, machine(1)) + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(first.Name, 1)}, wipe); err != nil || wipe.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe = %+v, %v", wipe.Status, err) + } + if server, err := simwork.ReadServer(e.store, namespace+"/"+device.Name); err != nil || server != (simwork.Server{}) { + t.Fatalf("server after wipe = %+v, %v", server, err) + } + state = e.custody(device.Name) + if state.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("holder after release = %+v", state.Spec.Holder) + } + // A released allocation never allocates again. + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrReleased) { + t.Fatalf("released allocate err = %v", err) + } + + second, err := e.allocator.Allocate(e.ctx, e.request(2)) + if err != nil || second.Spec.DeviceRef.Name != device.Name { + t.Fatalf("reuse = %v, %v", second, err) + } + // A holder change does not raise the fence; the next admission does. + if next := install(second, e.installation(3, "debian-12", ""), ""); next.Status.Fence <= wipe.Status.Fence { + t.Fatalf("reused Device's installation fence %d is not above the wipe's %d", next.Status.Fence, wipe.Status.Fence) + } +} + +// TestConcurrentAllocatorsOneWinner races allocators for different Machines +// at one Device. Exactly one allocation remains and custody names it. +func TestConcurrentAllocatorsOneWinner(t *testing.T) { + e := startEnv(t) + device := e.server(1) + const contenders = 6 + var wg sync.WaitGroup + results := make([]error, contenders) + for index := range contenders { + wg.Add(1) + go func() { + defer wg.Done() + _, results[index] = e.allocator.Allocate(e.ctx, e.request(index+1)) + }() + } + wg.Wait() + winners := 0 + for index, err := range results { + switch { + case err == nil: + winners++ + case !errors.Is(err, ErrInsufficientCapacity): + t.Fatalf("contender %d: %v", index, err) + } + } + var allocations fleetv1.MachineAllocationList + if err := e.admin.List(e.ctx, &allocations, client.InNamespace(namespace)); err != nil { + t.Fatal(err) + } + if winners != 1 || len(allocations.Items) != 1 { + t.Fatalf("winners = %d, allocations = %d", winners, len(allocations.Items)) + } + if holder := e.custody(device.Name).Spec.Holder; holder.AllocationRef == nil || holder.AllocationRef.Name != allocations.Items[0].Name { + t.Fatalf("holder = %+v, allocation %s", holder, allocations.Items[0].Name) + } +} + +// TestAnAllocationThatLostItsDeviceIsReplaced covers the write order: an +// allocation created for a Device another holder then took is deleted and +// the allocator selects again. +func TestAnAllocationThatLostItsDeviceIsReplaced(t *testing.T) { + e := startEnv(t) + taken := e.server(1) + free := e.server(2) + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); err != nil { + t.Fatal(err) + } + if holder := e.custody(taken.Name).Spec.Holder; holder.Type != ops.HolderAllocation { + t.Fatalf("first allocation took %+v", holder) + } + // 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, "") + if err != nil { + t.Fatal(err) + } + e.create(stale) + second, err := e.allocator.Allocate(e.ctx, e.request(2)) + if err != nil { + t.Fatal(err) + } + if second.UID == stale.UID || second.Spec.DeviceRef.Name != free.Name { + t.Fatalf("second allocation = %s on %s", second.UID, second.Spec.DeviceRef.Name) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(stale), &fleetv1.MachineAllocation{}); err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } +} + +func (e *env) capacity(device string) *fleetv1.MachineCapacity { + e.t.Helper() + capacity := &fleetv1.MachineCapacity{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: "capacity-" + device}, capacity); err != nil { + e.t.Fatal(err) + } + return capacity +} diff --git a/internal/allocation/hardware.go b/internal/allocation/hardware.go new file mode 100644 index 00000000..2b8443f9 --- /dev/null +++ b/internal/allocation/hardware.go @@ -0,0 +1,116 @@ +package allocation + +import ( + "slices" + + "k8s.io/apimachinery/pkg/api/resource" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" +) + +func matches(profile fleetv1.MachineProfileSpec, hardware fleetv1.Hardware) bool { + // CPU and memory are exact requests. An inexact profile fails closed, and + // capacity matches only when its observed cores and installed memory equal + // the request; larger machines are not silently substituted. + if controller.ValidateExactHardware(profile) != nil || profile.CPU.Architecture != hardware.CPU.Architecture || profile.CPU.Cores != hardware.CPU.Cores || !sameMemory(profile.Memory.Capacity, hardware.Memory.Capacity) { + return false + } + var gpuCount int64 + for _, gpu := range hardware.GPUs { + if profile.GPUs != nil && (profile.GPUs.Vendor == "" || profile.GPUs.Vendor == gpu.Vendor) && (len(profile.GPUs.Models) == 0 || slices.Contains(profile.GPUs.Models, gpu.Model)) && matchesQuantity(profile.GPUs.MemoryPerDevice, gpu.Memory) { + gpuCount++ + } + } + if profile.GPUs != nil && !matchesCount(profile.GPUs.Count, gpuCount) { + return false + } + used := make([]bool, len(hardware.Disks)) + for _, group := range profile.Disks { + var candidates []int + for i, disk := range hardware.Disks { + if !used[i] && (group.Media == "" || group.Media == disk.Media) && (group.Interface == "" || group.Interface == disk.Interface) && matchesQuantity(group.Capacity, disk.Capacity) { + candidates = append(candidates, i) + } + } + if !matchesCount(group.Count, int64(len(candidates))) { + return false + } + count := requiredCount(group.Count) + // A disk group always requires at least one distinct device when no + // explicit minimum or exact count is supplied. Fail closed on malformed + // negative counts and on groups with too few candidates before slicing. + if count < 0 || int64(len(candidates)) < count { + return false + } + for _, index := range candidates[:count] { + used[index] = true + } + } + usedInterfaces := make([]bool, len(hardware.Interfaces)) + for _, requirement := range profile.Interfaces { + found := false + for i, iface := range hardware.Interfaces { + if !usedInterfaces[i] && (requirement.Type == "" || requirement.Type == iface.Type) && matchesQuantity(requirement.Speed, iface.Speed) { + usedInterfaces[i] = true + found = true + break + } + } + if !found { + return false + } + } + return true +} + +func requiredCount(c fleetv1.Constraint) int64 { + if c.Exact != nil { + return *c.Exact + } + if c.Min != nil { + return *c.Min + } + return 1 +} +func matchesCount(c fleetv1.Constraint, value int64) bool { + if c.Exact != nil { + return value == *c.Exact + } + return (c.Min == nil || value >= *c.Min) && (c.Max == nil || value <= *c.Max) +} +func matchesQuantity(c fleetv1.QuantityConstraint, value string) bool { + if c.Min == "" && c.Max == "" && c.Exact == "" { + return true + } + v, err := resource.ParseQuantity(value) + if err != nil { + return false + } + if c.Exact != "" { + q, err := resource.ParseQuantity(c.Exact) + return err == nil && v.Cmp(q) == 0 + } + if c.Min != "" { + q, err := resource.ParseQuantity(c.Min) + if err != nil || v.Cmp(q) < 0 { + return false + } + } + if c.Max != "" { + q, err := resource.ParseQuantity(c.Max) + if err != nil || v.Cmp(q) > 0 { + return false + } + } + return true +} + +func sameMemory(requested, observed string) bool { + want, err := resource.ParseQuantity(requested) + if err != nil { + return false + } + got, err := resource.ParseQuantity(observed) + return err == nil && want.Cmp(got) == 0 +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go new file mode 100644 index 00000000..0079bf7e --- /dev/null +++ b/internal/allocation/harness_test.go @@ -0,0 +1,233 @@ +package allocation + +import ( + "context" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" + 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/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + + 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" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/simwork" + "go.datum.net/fleet/internal/site/siteapi" + "go.datum.net/fleet/internal/tenancy" +) + +const ( + namespace = "fleet-provider" + providerUser = "system:serviceaccount:fleet-system:metal-provider" + releaseUser = "system:serviceaccount:fleet-system:release-controller" + siteName = "site-example-a" + siteToken = "synthetic-site-token" + keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" +) + +func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } + +// env is a real API server with the metal, inventory and custody CRDs, one +// simulator site behind its HTTP API, and the coordinator loop. +type env struct { + t *testing.T + ctx context.Context + admin client.Client + allocator *Allocator + loop *delivery.Loop + store *site.Store + enrollment fixture.Enrollment + class *fleetv1.MachineClass + profile *fleetv1.MachineProfile +} + +func scheme(t *testing.T) *runtime.Scheme { + s := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, fleetv1.AddToScheme, ops.AddToScheme} { + if err := add(s); err != nil { + t.Fatal(err) + } + } + return s +} + +func startEnv(t *testing.T) *env { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{ + filepath.Join(root, "config", "base", "crd"), + filepath.Join(root, "config", "components", "inventory", "crds"), + filepath.Join(root, "config", "components", "device-operations", "crds"), + }, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + admin, err := client.New(config, client.Options{Scheme: scheme(t)}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + e := &env{t: t, ctx: ctx, admin: admin, enrollment: fixture.Enrollment{}} + e.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}) + + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + e.store, err = site.OpenStore(dir, nil) + if err != nil { + 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} + 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() }) + remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + registry, err := custody.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ + custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, + }}} + e.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: namespace, + 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 }, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + } + 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"}}} + e.create(e.profile) + return e +} + +func (e *env) create(object client.Object) { + e.t.Helper() + if err := e.admin.Create(e.ctx, object); err != nil { + e.t.Fatal(err) + } +} + +// server adds a synthetic Device, its enrollment at the site, its capacity +// and fixture discovery. +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{ + 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}}, + }} + 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.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) + } + e.until("custody is Verified", func() bool { + state := e.custody(name) + return state != nil && state.Spec.State == ops.CustodyVerified + }) + return device +} + +// until runs coordinator passes until done holds. +func (e *env) until(what string, done func() bool) { + e.t.Helper() + deadline := time.Now().Add(30 * time.Second) + for !done() { + if time.Now().After(deadline) { + e.t.Fatalf("timed out waiting until %s", what) + } + if err := e.loop.Pass(e.ctx); err != nil { + e.t.Logf("pass: %v", err) + } + time.Sleep(20 * time.Millisecond) + } +} + +func (e *env) custody(name string) *ops.DeviceCustody { + state := &ops.DeviceCustody{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: name}, state); err != nil { + return nil + } + return state +} + +func machine(n int) Machine { + return Machine{Consumer: tenancy.Project(fmt.Sprintf("consumer-%d", n)), ConsumerUID: types.UID(uid(500 + n)), Namespace: "default", Name: "allocation", UID: types.UID(uid(600 + n))} +} + +func (e *env) request(n int) Request { + return Request{Machine: machine(n), Class: e.class, Profile: e.profile, Authority: fleetv1.AllocationAuthority{Principal: "fixture", Decision: fmt.Sprintf("fixture-%d", n)}} +} + +func (e *env) installation(n int, name, predecessor string) *fleetv1.Installation { + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID(uid(700 + n))}, + Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: "allocation"}, ImageRef: fleetv1.LocalReference{Name: imageRef}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} + if predecessor != "" { + installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "Installation", Name: predecessor} + } + return installation +} + +// release repeats Release while the coordinator runs, until it is Released. +func (e *env) release(allocation *fleetv1.MachineAllocation, owner Machine) { + e.t.Helper() + e.until("the allocation is Released", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + e.t.Fatal(err) + } + released, err := e.allocator.Release(e.ctx, allocation, owner) + if err != nil { + e.t.Logf("release: %v", err) + } + return released + }) +} diff --git a/internal/allocation/identity.go b/internal/allocation/identity.go new file mode 100644 index 00000000..4d46b042 --- /dev/null +++ b/internal/allocation/identity.go @@ -0,0 +1,36 @@ +package allocation + +import ( + "context" + "errors" + + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// MachineFinalizer keeps a Machine until its allocation is Released. +const MachineFinalizer = "fleet.datumapis.com/machine-protection" + +// Creator asks the API server who the credential authenticates as. An +// operation's creator must be that identity: the creator rule refuses any +// other, so it is never configured. The username identifies the caller; the +// UID is kept when the API server reports one. +func Creator(ctx context.Context, config *rest.Config) (ops.Creator, error) { + clients, err := kubernetes.NewForConfig(config) + if err != nil { + return ops.Creator{}, err + } + review, err := clients.AuthenticationV1().SelfSubjectReviews().Create(ctx, &authenticationv1.SelfSubjectReview{}, metav1.CreateOptions{}) + if err != nil { + return ops.Creator{}, err + } + user := review.Status.UserInfo + if user.Username == "" { + return ops.Creator{}, errors.New("allocation: the credential has no username") + } + return ops.Creator{Username: user.Username, UID: user.UID}, nil +} diff --git a/internal/allocation/identity_test.go b/internal/allocation/identity_test.go new file mode 100644 index 00000000..1cc25fab --- /dev/null +++ b/internal/allocation/identity_test.go @@ -0,0 +1,54 @@ +package allocation + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + authenticationv1 "k8s.io/api/authentication/v1" + "k8s.io/client-go/rest" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// reviewer answers every SelfSubjectReview with user. +func reviewer(t *testing.T, user authenticationv1.UserInfo) *rest.Config { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/apis/authentication.k8s.io/v1/selfsubjectreviews" { + http.NotFound(w, r) + return + } + review := authenticationv1.SelfSubjectReview{Status: authenticationv1.SelfSubjectReviewStatus{UserInfo: user}} + review.APIVersion, review.Kind = "authentication.k8s.io/v1", "SelfSubjectReview" + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(review) + })) + t.Cleanup(server.Close) + return &rest.Config{Host: server.URL} +} + +func TestCreatorIdentifiesTheCallerByUsername(t *testing.T) { + cases := map[string]struct { + user authenticationv1.UserInfo + want ops.Creator + }{ + "a credential with a UID": {authenticationv1.UserInfo{Username: "svc-example", UID: "svc-example-uid"}, ops.Creator{Username: "svc-example", UID: "svc-example-uid"}}, + "a credential without a UID": {authenticationv1.UserInfo{Username: "svc-example"}, ops.Creator{Username: "svc-example"}}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + got, err := Creator(context.Background(), reviewer(t, test.user)) + if err != nil || got != test.want { + t.Fatalf("Creator = %+v, %v; want %+v", got, err, test.want) + } + }) + } + t.Run("a credential without a username is refused", func(t *testing.T) { + if _, err := Creator(context.Background(), reviewer(t, authenticationv1.UserInfo{UID: "uid-only"})); err == nil { + t.Fatal("an anonymous credential was accepted") + } + }) +} diff --git a/internal/allocation/incarnation_test.go b/internal/allocation/incarnation_test.go new file mode 100644 index 00000000..2f968b53 --- /dev/null +++ b/internal/allocation/incarnation_test.go @@ -0,0 +1,267 @@ +package allocation + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" +) + +// No spec holds an object UID, so these tests pin each same-name +// recreation guard: an object recreated under the same name never inherits +// what was recorded for the incarnation before it. + +// TestAnAllocationForAnotherMachineIncarnationIsAConflict covers a Machine +// and a consumer project recreated under the same names: the allocation's +// labels name the incarnation it was made for. +func TestAnAllocationForAnotherMachineIncarnationIsAConflict(t *testing.T) { + e := startEnv(t) + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + for label, name := range map[string]string{fleetv1.LabelMachineUID: "Machine", fleetv1.LabelConsumerUID: "consumer"} { + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + t.Fatal(err) + } + original := stored.Labels[label] + stored.Labels[label] = uid(999) + if err := e.admin.Update(e.ctx, stored); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Get(e.ctx, machine(1)); !errors.Is(err, ErrConflict) { + t.Fatalf("an allocation for another %s incarnation: %v", name, err) + } + stored.Labels[label] = original + if err := e.admin.Update(e.ctx, stored); err != nil { + t.Fatal(err) + } + } + if found, err := e.allocator.Get(e.ctx, machine(1)); err != nil || found == nil { + t.Fatalf("the allocation's own Machine: %v, %v", found, err) + } +} + +// TestAnOperationForAnotherDeviceIncarnationIsAConflict covers a Device +// recreated under the same name: an existing operation with the same name +// and spec, recorded for the earlier Device, is never taken for a new one. +func TestAnOperationForAnotherDeviceIncarnationIsAConflict(t *testing.T) { + e := startEnv(t) + device := e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + installation := e.installation(1, "first", "") + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}) + if err != nil { + t.Fatal(err) + } + stored := &ops.DeviceInstallation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), stored); err != nil { + t.Fatal(err) + } + stored.Labels[ops.LabelDeviceUID] = uid(998) + if err := e.admin.Update(e.ctx, stored); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, ErrConflict) { + t.Fatalf("an operation recorded for another Device incarnation: %v", err) + } + if stored.Spec.DeviceRef.Name != device.Name { + t.Fatalf("operation names %s", stored.Spec.DeviceRef.Name) + } +} + +// TestCustodyForAnotherDeviceIncarnationIsNotFree covers a Device recreated +// under the same name: custody recorded for the earlier Device is not free +// capacity for the new one. +func TestCustodyForAnotherDeviceIncarnationIsNotFree(t *testing.T) { + e := startEnv(t) + device := e.server(1) + state := e.custody(device.Name) + if !Free(state, device) { + t.Fatalf("custody of the Device's own incarnation is not free: %+v", state.Spec) + } + recreated := *device + recreated.UID = types.UID(uid(997)) + if Free(state, &recreated) { + t.Fatal("custody of an earlier Device incarnation is free for a recreated Device") + } +} + +// TestAnAllocationForAnotherConsumerIsAConflict covers a consumer of another +// kind or name whose Machine shares the UIDs: the allocation's consumerRef +// names the consumer it was made for. +func TestAnAllocationForAnotherConsumerIsAConflict(t *testing.T) { + e := startEnv(t) + e.server(1) + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); err != nil { + t.Fatal(err) + } + for _, consumer := range []fleetv1.TypedReference{tenancy.Project("consumer-other"), tenancy.Namespace("consumer-1")} { + other := machine(1) + other.Consumer = consumer + if _, err := e.allocator.Get(e.ctx, other); !errors.Is(err, ErrConflict) { + t.Fatalf("an allocation for %+v: %v", consumer, err) + } + } +} + +// TestOnlyAProjectOrANamespaceConsumes refuses any other consumer kind, in +// the allocator before quota or capacity and at the API. +func TestOnlyAProjectOrANamespaceConsumes(t *testing.T) { + e := startEnv(t) + e.server(1) + for _, consumer := range []fleetv1.TypedReference{ + {APIGroup: "apps", Kind: "Deployment", Name: "consumer-1"}, + {APIGroup: "resourcemanager.miloapis.com", Kind: "Organization", Name: "consumer-1"}, + {Kind: "Project", Name: "consumer-1"}, + {APIGroup: "resourcemanager.miloapis.com", Kind: "Namespace", Name: "consumer-1"}, + } { + request := e.request(1) + request.Machine.Consumer = consumer + if _, err := e.allocator.Allocate(e.ctx, request); !errors.Is(err, tenancy.ErrUnsupportedConsumer) { + t.Fatalf("allocate for %+v: %v", consumer, err) + } + } + var allocations fleetv1.MachineAllocationList + if err := e.admin.List(e.ctx, &allocations); err != nil || len(allocations.Items) != 0 { + t.Fatalf("allocations = %d, %v", len(allocations.Items), err) + } + request := e.request(1) + request.Machine.Consumer = tenancy.Namespace("consumer-1") + allocation, err := e.allocator.Allocate(e.ctx, request) + if err != nil { + t.Fatalf("allocate for a Namespace consumer: %v", err) + } + refused := allocation.DeepCopyObject().(*fleetv1.MachineAllocation) + refused.ObjectMeta = metav1.ObjectMeta{Name: "alloc-refused", Namespace: allocation.Namespace} + refused.Spec.ConsumerRef = fleetv1.TypedReference{APIGroup: "apps", Kind: "Deployment", Name: "consumer-1"} + if err := e.admin.Create(e.ctx, refused); !apierrors.IsInvalid(err) { + t.Fatalf("the API took a Deployment consumer: %v", err) + } +} + +// recreatingProvider recreates the Device after the allocator selected it +// and created the allocation, before the allocator claims custody, and +// verifies custody for the new Device as an operator's resolve would. +type recreatingProvider struct { + client.Client + e *env + done bool +} + +func (p *recreatingProvider) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + if err := p.Client.Create(ctx, object, options...); err != nil { + return err + } + allocation, ok := object.(*fleetv1.MachineAllocation) + if !ok || p.done { + return nil + } + p.done = true + e := p.e + device := &inventory.Device{} + if err := e.admin.Get(ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Spec.DeviceRef.Name}, device); err != nil { + return err + } + device.Finalizers = nil + if err := e.admin.Update(ctx, device); err != nil { + return err + } + if err := e.admin.Delete(ctx, device); err != nil { + return err + } + recreated := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: namespace, Labels: device.Labels}, Spec: device.Spec} + for { + if err := e.admin.Create(ctx, recreated); err == nil { + break + } else if !apierrors.IsAlreadyExists(err) { + return err + } + time.Sleep(20 * time.Millisecond) + } + state := e.custody(device.Name) + state.Labels[ops.LabelDeviceUID] = string(recreated.UID) + return e.admin.Update(ctx, state) +} + +// TestARecreatedDeviceIsNeverClaimedForTheEarlierIncarnation recreates the +// selected Device between selection and the custody claim. The claim +// requires the Device incarnation the allocation names, so the allocator +// selects again, and the allocation that holds custody names its live +// Device. +func TestARecreatedDeviceIsNeverClaimedForTheEarlierIncarnation(t *testing.T) { + e := startEnv(t) + original := e.server(1) + e.server(2) + e.allocator.Provider = &recreatingProvider{Client: e.admin, e: e} + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + recreated := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(original), recreated); err != nil || recreated.UID == original.UID { + t.Fatalf("the selected Device was not recreated: %v", err) + } + live := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Spec.DeviceRef.Name}, live); err != nil { + t.Fatal(err) + } + if got := allocation.Labels[fleetv1.LabelDeviceUID]; got != string(live.UID) { + t.Fatalf("custody of %s was claimed for an allocation made against Device %s, the live Device is %s", live.Name, got, live.UID) + } + if holder := e.custody(live.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != allocation.Name { + t.Fatalf("holder = %+v", holder) + } + if holder := e.custody(original.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("the recreated Device's holder = %+v", holder) + } +} + +// TestTheAllocationAuthorityNamesNoIncarnation refuses an authority that +// records the Machine or consumer UID, so the allocation spec holds no +// object UID, and accepts one that names the decision by name. +func TestTheAllocationAuthorityNamesNoIncarnation(t *testing.T) { + e := startEnv(t) + e.server(1) + request := e.request(1) + for _, authority := range []fleetv1.AllocationAuthority{ + {Principal: "fixture", Decision: "fixture:" + string(request.Machine.UID)}, + {Principal: "fixture:" + string(request.Machine.ConsumerUID), Decision: "fixture"}, + } { + request.Authority = authority + if _, err := e.allocator.Allocate(e.ctx, request); !errors.Is(err, ErrUnsupported) { + t.Fatalf("authority %+v: %v", authority, err) + } + } + request.Authority = fleetv1.AllocationAuthority{Principal: "fixture:consumer-1", Decision: "fixture:default/allocation"} + allocation, err := e.allocator.Allocate(e.ctx, request) + if err != nil { + t.Fatal(err) + } + data, err := json.Marshal(allocation.Spec) + if err != nil { + t.Fatal(err) + } + for _, uid := range []types.UID{request.Machine.UID, request.Machine.ConsumerUID, types.UID(allocation.Labels[fleetv1.LabelDeviceUID])} { + if strings.Contains(string(data), string(uid)) { + t.Fatalf("the allocation spec records %s: %s", uid, data) + } + } +} diff --git a/internal/allocation/release.go b/internal/allocation/release.go new file mode 100644 index 00000000..7b60b25f --- /dev/null +++ b/internal/allocation/release.go @@ -0,0 +1,188 @@ +package allocation + +import ( + "context" + "errors" + "fmt" + "slices" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// maxWipeSteps bounds the wipes one release creates after wipes that ended +// Failed, which sent nothing. A wipe whose outcome is unknown is never +// repeated without a DeviceRecovery Retry. +const maxWipeSteps = 3 + +// ErrWipeFailed means the release created its last wipe step and it failed. +// The Cleaning gate stays open, and the Device stays in Release. +var ErrWipeFailed = errors.New("every wipe step of the release failed") + +// Release advances the release of an allocation by one step and reports +// whether it is Released. Callers repeat it while the custody coordinator +// runs. The holder moves to Release, the release controller closes each +// gate with evidence, the coordinator returns the Device to None, and only +// then is the allocation Released. +func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllocation, machine Machine) (bool, error) { + if allocation.Status.Phase == fleetv1.AllocationReleased { + return true, nil + } + state := &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil && !apierrors.IsNotFound(err) { + return false, err + } + holder := state.Spec.Holder + ours := holder.AllocationRef != nil && holder.AllocationRef.Name == allocation.Name && (holder.Type == ops.HolderAllocation || holder.Type == ops.HolderRelease) + if !ours { + switch { + case allocation.Status.Phase != fleetv1.AllocationActive && allocation.Status.Phase != fleetv1.AllocationReleasing: + // The allocation never held the Device: nothing ran under it. + case state.Spec.State == ops.CustodyVerified && allocation.Status.Phase == fleetv1.AllocationReleasing: + // Custody returned the Device after every gate closed. + default: + // Unverified custody waits for an operator to resolve it. + return false, nil + } + if err := a.releaseQuota(ctx, allocation, machine); err != nil { + return false, err + } + return true, a.setPhase(ctx, allocation, fleetv1.AllocationReleased) + } + if err := a.setPhase(ctx, allocation, fleetv1.AllocationReleasing); err != nil { + return false, err + } + if holder.Type == ops.HolderAllocation { + return false, a.Custody.BeginRelease(ctx, state.Name, allocation.Name) + } + // No mode provisions access, networks or addresses for a Machine, so + // those gates have nothing to release. + for _, gate := range []ops.ReleaseGate{ops.GateAccess, ops.GateNetwork, ops.GateAddress} { + if slices.Contains(holder.OpenGates, gate) { + return false, a.Custody.CloseGate(ctx, state.Name, allocation.Name, gate) + } + } + if slices.Contains(holder.OpenGates, ops.GateOperations) { + running, err := a.installing(ctx, state, allocation) + if err != nil || running { + return false, err + } + return false, a.Custody.CloseGate(ctx, state.Name, allocation.Name, ops.GateOperations) + } + if slices.Contains(holder.OpenGates, ops.GateCleaning) { + cleaned, err := a.clean(ctx, state, allocation) + if err != nil || !cleaned { + return false, err + } + return false, a.Custody.CloseGate(ctx, state.Name, allocation.Name, ops.GateCleaning) + } + if slices.Contains(holder.OpenGates, ops.GateQuota) { + if err := a.releaseQuota(ctx, allocation, machine); err != nil { + return false, err + } + return false, a.Custody.CloseGate(ctx, state.Name, allocation.Name, ops.GateQuota) + } + return false, nil +} + +func (a *Allocator) releaseQuota(ctx context.Context, _ *fleetv1.MachineAllocation, machine Machine) error { + if a.Quota == nil { + return nil + } + return a.Quota.Release(ctx, machine) +} + +// ReleaseMachine releases whatever a deleted Machine holds and reports +// whether nothing remains. A Machine deleted before its allocation existed, +// such as one still waiting for capacity, may hold a quota claim; it is +// released by the Machine's name for it. +func (a *Allocator) ReleaseMachine(ctx context.Context, machine Machine) (bool, error) { + current, err := a.Get(ctx, machine) + if err != nil { + return false, err + } + if current == nil { + return true, a.releaseQuota(ctx, nil, machine) + } + return a.Release(ctx, current, machine) +} + +// installing reports whether an installation of this allocation is active +// or has not ended. A pending one ends once admission refuses it, because +// installations are admitted only while the allocation holds the Device. +func (a *Allocator) installing(ctx context.Context, state *ops.DeviceCustody, allocation *fleetv1.MachineAllocation) (bool, error) { + if active := state.Spec.ActiveOperation; active != nil && active.Kind == "DeviceInstallation" { + return true, nil + } + var installations ops.DeviceInstallationList + if err := a.Provider.List(ctx, &installations, client.InNamespace(a.Namespace)); err != nil { + return false, err + } + for _, installation := range installations.Items { + reference := installation.Spec.Authority.AllocationRef + if reference != nil && reference.Name == allocation.Name && !installation.Status.Phase.Ended() { + return true, nil + } + } + return false, nil +} + +// clean drives the release's wipes and reports whether one succeeded. A +// wipe that ended Failed sent nothing, so a new step follows, up to +// maxWipeSteps. A wipe whose outcome is unknown is held: the next one is +// created only after staff authorize a Retry, under the name custody gives. +func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocation *fleetv1.MachineAllocation) (bool, error) { + current := allocation.Status.Wipe + if current == nil { + return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, 1), Step: 1}) + } + wipe := &ops.DeviceWipe{} + if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: current.Name}, wipe); apierrors.IsNotFound(err) { + // The status was written but the create was lost. + return false, a.wipe(ctx, allocation, *current) + } else if err != nil { + return false, err + } + switch wipe.Status.Phase { + case ops.PhaseSucceeded: + return true, nil + case ops.PhaseFailed, ops.PhaseCancelled: + if current.Step >= maxWipeSteps { + return false, fmt.Errorf("%w: %s: %s", ErrWipeFailed, wipe.Status.Reason, wipe.Status.Message) + } + step := current.Step + 1 + return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, step), Step: step}) + case ops.PhaseOutcomeUnknown: + hold := state.Spec.RecoveryHold + if hold != nil && hold.Kind == "DeviceWipe" && hold.Name == current.Name && hold.RetryName != "" { + return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: hold.RetryName, Step: current.Step + 1}) + } + } + return false, nil +} + +// wipe records the wipe in status, then creates it, so a crash between the +// two creates the same wipe again. +func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocation, reference fleetv1.WipeReference) error { + if current := allocation.Status.Wipe; current == nil || *current != reference { + allocation.Status.Wipe = &reference + if err := a.Provider.Status().Update(ctx, allocation); err != nil { + return err + } + } + wipe := &ops.DeviceWipe{ + ObjectMeta: metav1.ObjectMeta{Name: reference.Name, Namespace: a.Namespace, Labels: operationLabels(allocation)}, + Spec: ops.DeviceWipeSpec{ + OperationEnvelope: a.envelope(allocation, a.ReleaseCreator), + Step: reference.Step, + CleaningPolicyDigest: allocation.Spec.CleaningPolicyDigest, + TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + }, + } + return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) +} diff --git a/internal/allocation/release_test.go b/internal/allocation/release_test.go new file mode 100644 index 00000000..018fee80 --- /dev/null +++ b/internal/allocation/release_test.go @@ -0,0 +1,145 @@ +package allocation + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// quota records reservations by Machine. +type quota struct { + mu sync.Mutex + held map[string]bool +} + +func (q *quota) Acquire(_ context.Context, machine Machine) (string, error) { + q.mu.Lock() + defer q.mu.Unlock() + if q.held == nil { + q.held = map[string]bool{} + } + q.held[string(machine.UID)] = true + return "fleet-machine-" + string(machine.UID)[len(machine.UID)-3:], nil +} + +func (q *quota) Release(_ context.Context, machine Machine) error { + q.mu.Lock() + defer q.mu.Unlock() + delete(q.held, string(machine.UID)) + return nil +} + +func (q *quota) holds(machine Machine) bool { + q.mu.Lock() + defer q.mu.Unlock() + return q.held[string(machine.UID)] +} + +// TestAMachineDeletedWhileWaitingReleasesItsQuota covers the window between +// the quota claim and the allocation: a Machine that reserved quota but +// found no capacity still releases its claim when it is deleted. +func TestAMachineDeletedWhileWaitingReleasesItsQuota(t *testing.T) { + e := startEnv(t) + q := "a{} + e.allocator.Quota = q + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("allocate without capacity = %v", err) + } + if !q.holds(machine(1)) { + t.Fatal("the quota claim was not reserved before the allocation") + } + released, err := e.allocator.ReleaseMachine(e.ctx, machine(1)) + if err != nil || !released || q.holds(machine(1)) { + t.Fatalf("release = %v, %v; quota still held %v", released, err, q.holds(machine(1))) + } +} + +// TestAnAllocationThatNeverHeldItsDeviceIsReleased releases an allocation a +// crash left before it claimed custody, without touching custody. +func TestAnAllocationThatNeverHeldItsDeviceIsReleased(t *testing.T) { + e := startEnv(t) + q := "a{} + e.allocator.Quota = q + device := e.server(1) + 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") + if err != nil { + t.Fatal(err) + } + e.create(orphan) + before := e.custody(device.Name) + released, err := e.allocator.ReleaseMachine(e.ctx, machine(1)) + if err != nil || !released { + t.Fatalf("release = %v, %v", released, err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(orphan), orphan); err != nil || orphan.Status.Phase != fleetv1.AllocationReleased { + t.Fatalf("allocation = %+v, %v", orphan.Status, err) + } + if after := e.custody(device.Name); after.ResourceVersion != before.ResourceVersion || q.holds(machine(1)) { + t.Fatalf("custody changed (%s -> %s) or quota held %v", before.ResourceVersion, after.ResourceVersion, q.holds(machine(1))) + } +} + +// TestAFailingWipeGetsNewStepsThenStops gives a wipe that ends Failed, which +// sent nothing, a new step up to the bound, then stops the release with the +// Cleaning gate open and the Device still in Release. +func TestAFailingWipeGetsNewStepsThenStops(t *testing.T) { + e := startEnv(t) + device := e.server(1) + // The site enrolls disk-0; a wipe of disk-1 is refused before anything + // is sent. + e.allocator.TargetDisks = []string{"disk-1"} + held, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(45 * time.Second) + for { + if err := e.loop.Pass(e.ctx); err != nil { + t.Logf("pass: %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(held), held); err != nil { + t.Fatal(err) + } + _, err := e.allocator.Release(e.ctx, held, machine(1)) + if errors.Is(err, ErrWipeFailed) { + break + } + if time.Now().After(deadline) { + t.Fatalf("the release did not stop at the last wipe step: %v", err) + } + time.Sleep(20 * time.Millisecond) + } + for step := int32(1); step <= maxWipeSteps; step++ { + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(held.Name, step)}, wipe); err != nil || wipe.Status.Phase != ops.PhaseFailed || wipe.Status.Reason != custody.ReasonTargetDisks { + t.Fatalf("wipe step %d = %+v, %v", step, wipe.Status, err) + } + } + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(held.Name, maxWipeSteps+1)}, &ops.DeviceWipe{}); err == nil { + t.Fatal("a wipe step past the bound was created") + } + state := e.custody(device.Name) + if state.Spec.Holder.Type != ops.HolderRelease || !containsGate(state.Spec.Holder.OpenGates, ops.GateCleaning) || held.Status.Phase != fleetv1.AllocationReleasing { + t.Fatalf("holder = %+v, allocation %s", state.Spec.Holder, held.Status.Phase) + } +} + +func containsGate(gates []ops.ReleaseGate, gate ops.ReleaseGate) bool { + for _, g := range gates { + if g == gate { + return true + } + } + return false +} diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index fa0efa32..815171f7 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -243,9 +243,17 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { } } -// TestComponentIsInert proves Increment A wires nothing: no root includes the -// component, and the test-only kinds ship nowhere. -func TestComponentIsInert(t *testing.T) { +// TestComponentRoots pins where the component ships. The production Milo +// root includes all of it, the creator webhook included; the synthetic Milo +// root, which installs no webhook, includes the kinds, ProtectedResources and +// roles; the standalone cluster includes only the CRDs. No other root +// includes any of it, and the test-only kinds ship nowhere. +func TestComponentRoots(t *testing.T) { + want := map[string][]string{ + filepath.Join(configRoot, "milo", "kustomization.yaml"): {"../components/device-operations"}, + filepath.Join(configRoot, "milo-synthetic", "kustomization.yaml"): {"../components/device-operations/crds", "../components/device-operations/protected-resources", "../components/device-operations/roles"}, + filepath.Join(configRoot, "standalone", "kustomization.yaml"): {"../components/device-operations/crds"}, + } err := filepath.WalkDir(configRoot, func(path string, entry fs.DirEntry, err error) error { if err != nil { return err @@ -257,8 +265,16 @@ func TestComponentIsInert(t *testing.T) { if err != nil { return err } - if filepath.Base(path) == "kustomization.yaml" && strings.Contains(string(data), "device-operations") { - t.Errorf("%s includes the device-operations component", path) + if filepath.Base(path) == "kustomization.yaml" { + var included []string + for _, line := range strings.Split(string(data), "\n") { + if entry := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "- ")); strings.Contains(entry, "device-operations") && !strings.HasPrefix(entry, "#") { + included = append(included, entry) + } + } + if !slices.Equal(included, want[path]) { + t.Errorf("%s includes %v of the device-operations component, want %v", path, included, want[path]) + } } if strings.Contains(string(data), "DeviceTest") || strings.Contains(string(data), "devicetest") { t.Errorf("%s ships a test-only kind", path) diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index de825e1c..704d277f 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -80,11 +80,22 @@ type DeviceCustodySpec struct { RejectedResults *RejectedResults `json:"rejectedResults,omitempty"` } +// DeviceReference names the Device. No spec holds an object UID: the Device +// incarnation is in the LabelDeviceUID label of the operation or custody, +// which the coordinator compares with the Device's UID. type DeviceReference struct { Name string `json:"name"` - UID string `json:"uid"` } +// LabelDeviceUID records the Device incarnation an operation or custody +// record is for. It is the same label the Metal provider puts on a +// MachineAllocation. +const LabelDeviceUID = "fleet.datumapis.com/device-uid" + +// LabelInstallationUID records the Installation a DeviceInstallation +// fulfills. The operation's name hashes it, and admission checks the name. +const LabelInstallationUID = "fleet.datumapis.com/installation-uid" + type LocalReference struct { Name string `json:"name"` } @@ -97,11 +108,13 @@ type Holder struct { OpenGates []ReleaseGate `json:"openGates,omitempty"` } -// OperationReference names one operation incarnation. +// OperationReference names an operation by kind and name. Custody always +// records it with the fence it was admitted at, which identifies the +// admission uniquely: a same-name operation created later is admitted at a +// higher fence. type OperationReference struct { Kind string `json:"kind"` Name string `json:"name"` - UID string `json:"uid"` } // ActiveOperation is the one admitted operation. Custody retains its exact @@ -117,7 +130,7 @@ type ActiveOperation struct { Snapshot DeviceSnapshot `json:"snapshot"` Creator Creator `json:"creator"` // Settles names the recovery hold this operation was admitted to settle. - Settles *OperationReference `json:"settles,omitempty"` + Settles *HeldOperationReference `json:"settles,omitempty"` } // DeviceSnapshot is what admission captured about the Device. The site @@ -158,9 +171,10 @@ type RecoveryHold struct { Deadline *metav1.Time `json:"deadline,omitempty"` // Snapshot is the Device snapshot the held operation was admitted with. Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` - // RetryAuthorizedBy names the DeviceRecovery with Retry that lets the - // held operation's requester create one settling operation. - RetryAuthorizedBy *OperationReference `json:"retryAuthorizedBy,omitempty"` + // RetryAuthorizedBy names the DeviceRecovery with Retry, and the fence it + // was admitted at, that lets the held operation's requester create one + // settling operation. + RetryAuthorizedBy *HeldOperationReference `json:"retryAuthorizedBy,omitempty"` // Retries counts the DeviceRecovery Retry decisions for the held // operation. An operation created after a Retry is named RetryName (the // held operation's name when empty) plus "-retry-" and this count. @@ -213,10 +227,11 @@ func (p Phase) Running() bool { } // Creator is the authenticated caller that created an operation. A -// validating webhook rejects any other value and any change. +// validating webhook rejects any other value and any change. UID is set only +// when the caller's credential carries one. type Creator struct { Username string `json:"username"` - UID string `json:"uid"` + UID string `json:"uid,omitempty"` } // Authority is why an operation may act. Exactly one field is set. @@ -240,19 +255,29 @@ type OperationEnvelope struct { // OperationStatus is the status every operation kind shares. The coordinator // copies it from custody. type OperationStatus struct { - Phase Phase `json:"phase,omitempty"` - Reason string `json:"reason,omitempty"` - Message string `json:"message,omitempty"` - Fence int64 `json:"fence,omitempty"` - AdmittedAt *metav1.Time `json:"admittedAt,omitempty"` - Deadline *metav1.Time `json:"deadline,omitempty"` - FinishedAt *metav1.Time `json:"finishedAt,omitempty"` - InputDigest string `json:"inputDigest,omitempty"` - Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` + // Admission is the coordinator's record that it admitted this object. + // It is written before custody names the operation, so custody matches + // an operation only by its name and this fence; a same-name object + // created later has none. + Admission *OperationAdmission `json:"admission,omitempty"` + Phase Phase `json:"phase,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + Fence int64 `json:"fence,omitempty"` + AdmittedAt *metav1.Time `json:"admittedAt,omitempty"` + Deadline *metav1.Time `json:"deadline,omitempty"` + FinishedAt *metav1.Time `json:"finishedAt,omitempty"` + InputDigest string `json:"inputDigest,omitempty"` + Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` // Evidence is the kind's typed result evidence, as recorded in custody. Evidence *runtime.RawExtension `json:"evidence,omitempty"` } +// OperationAdmission records the fence custody admitted an operation at. +type OperationAdmission struct { + Fence int64 `json:"fence"` +} + // Operation is implemented by every operation kind. type Operation interface { runtime.Object @@ -272,9 +297,9 @@ type DeviceInstallation struct { type DeviceInstallationSpec struct { OperationEnvelope `json:",inline"` - // RequestUID is the UID of the Installation this fulfills. The name is - // derived from it, so a retried create collides. - RequestUID string `json:"requestUID"` + // The Installation this fulfills is in the name, which hashes the + // Installation's UID, so a retried create collides and a same-name + // Installation gets a new operation. Image ImageInput `json:"image"` Bootstrap *SealedInput `json:"bootstrap,omitempty"` BootInterface string `json:"bootInterface"` @@ -363,6 +388,8 @@ type DeviceRecoverySpec struct { Resolve *ResolveInput `json:"resolve,omitempty"` } +// HeldOperationReference names an operation and the fence it was admitted +// at. type HeldOperationReference struct { Kind string `json:"kind"` Name string `json:"name"` diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index 91daf9e6..ac4bc000 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -23,9 +23,12 @@ type AccessPolicy struct { ConsoleModes []string `json:"consoleModes,omitempty"` PowerControl bool `json:"powerControl,omitempty"` } + +// SourceReference names the provider class a published class copies: the +// provider that publishes it, as a typed reference, and the class's name. type SourceReference struct { - Project string `json:"project"` - Name string `json:"name"` + PublisherRef TypedReference `json:"publisherRef"` + Name string `json:"name"` } type ProfilePolicy struct { AllowedProfiles []LocalReference `json:"allowedProfiles,omitempty"` @@ -335,24 +338,115 @@ type InstallationStatus struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } -// MachineAllocation is a protected, service-owned record. Its generated name is -// the allocation identity. The spec is immutable and release is terminal. +// MachineAllocation is a protected, service-owned record in the provider +// project, in the namespace of its Device. It holds an allocation's private +// facts: which Machine holds which Device, the contract Fleet accepted, the +// hardware it saw, and the authority it acted on. Nothing secret is on it. +// Its name derives from the Machine's UID, so each Machine gets one +// allocation. Fleet writes the spec once and the API server keeps it +// immutable; status carries the lifecycle, and release is terminal. type MachineAllocationSpec struct { - MachineRef ProjectNamespacedReference `json:"machineRef"` - MachineCapacityRef NamespacedReference `json:"machineCapacityRef"` + // ConsumerRef is the consumer the Machine belongs to: a Milo Project, or + // a Namespace in standalone mode. It stays in spec because release needs + // it after the consumer is deleted. + ConsumerRef TypedReference `json:"consumerRef"` + MachineRef AllocatedMachineReference `json:"machineRef"` + MachineCapacityRef NamespacedReference `json:"machineCapacityRef"` + DeviceRef AllocatedDeviceReference `json:"deviceRef"` + Accepted AcceptedContract `json:"accepted"` + // Hardware is the capacity's hardware when Fleet allocated it. + Hardware Hardware `json:"hardware"` + Authority AllocationAuthority `json:"authority"` + // QuotaClaimRef names the quota claim Fleet reserved before the + // allocation, in the Machine's namespace. It is absent where no quota + // system serves the consumer. + QuotaClaimRef *LocalReference `json:"quotaClaimRef,omitempty"` + // CleaningPolicyDigest pins the cleaning policy record the release + // wipes under. + CleaningPolicyDigest string `json:"cleaningPolicyDigest"` + // BootInterface and TargetDisks are what installations and wipes for + // this allocation use. + BootInterface string `json:"bootInterface"` + TargetDisks []string `json:"targetDisks"` } -type ProjectNamespacedReference struct { - Project string `json:"project"` +// Labels that pin the object incarnations a MachineAllocation was made for. +// No spec holds an object UID: the allocation's name hashes the consumer +// project and Machine UIDs, and these labels let a reader confirm them, so a +// same-name Machine, project or Device never inherits the allocation. +const ( + LabelMachineUID = "fleet.datumapis.com/machine-uid" + LabelConsumerUID = "fleet.datumapis.com/consumer-uid" + LabelDeviceUID = "fleet.datumapis.com/device-uid" +) + +// TypedReference names an object by API group, kind and name, with no UID, +// in the shape of Milo's ResourceClaim consumerRef. An empty APIGroup is the +// core group. +type TypedReference struct { + APIGroup string `json:"apiGroup"` + Kind string `json:"kind"` + Name string `json:"name"` +} + +// AllocatedMachineReference names the Machine within its consumer. The +// incarnation is in the allocation's name and labels. +type AllocatedMachineReference struct { Namespace string `json:"namespace"` Name string `json:"name"` } +// AllocatedDeviceReference names the Device in the allocation's namespace. +// The incarnation is in the allocation's device-uid label. +type AllocatedDeviceReference struct { + Name string `json:"name"` +} + +// AcceptedContract is the class and profile Fleet accepted, with the exact +// CPU and memory it allocated against. +type AcceptedContract struct { + MachineClassRef ContentReference `json:"machineClassRef"` + MachineProfileRef ContentReference `json:"machineProfileRef"` + CPU CPURequirement `json:"cpu"` + Memory MemoryRequirement `json:"memory"` +} + +// ContentReference pins an object's content by its generation and a digest +// of its spec, which also tells same-name recreations apart. +type ContentReference struct { + Name string `json:"name"` + Generation int64 `json:"generation"` + // Digest is "sha256:" over the object's complete spec. + Digest string `json:"digest"` +} + +// AllocationAuthority is the admission decision Fleet acted on. +type AllocationAuthority struct { + Principal string `json:"principal"` + Decision string `json:"decision"` +} + +// MachineAllocation phases. +const ( + AllocationPending = "Pending" + AllocationActive = "Active" + AllocationReleasing = "Releasing" + AllocationReleased = "Released" +) + type MachineAllocationStatus struct { - Phase string `json:"phase,omitempty"` + Phase string `json:"phase,omitempty"` + // Wipe is the latest DeviceWipe the release created. + Wipe *WipeReference `json:"wipe,omitempty"` Conditions []metav1.Condition `json:"conditions,omitempty"` } +// WipeReference names a release's DeviceWipe and its step. +type WipeReference struct { + Name string `json:"name"` + Step int32 `json:"step"` +} + type MachineAllocation struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` diff --git a/internal/controller/authority.go b/internal/controller/authority.go index a027bd3f..bf43f371 100644 --- a/internal/controller/authority.go +++ b/internal/controller/authority.go @@ -21,50 +21,3 @@ func (p ProjectIdentity) Valid() bool { func (p ProjectIdentity) SameLifetime(other ProjectIdentity) bool { return p.AuthorityID == other.AuthorityID && p.UID == other.UID } - -// ClaimScope prevents equal claim UIDs from independent project API servers -// from sharing private lifecycle custody. Standalone callers use an explicit -// local authority with the namespace lifetime as the project key. -type ClaimScope struct { - AuthorityID string `json:"authorityID"` - ProjectUID types.UID `json:"projectUID"` -} - -func (s ClaimScope) Valid() bool { - return strings.TrimSpace(s.AuthorityID) != "" && s.ProjectUID != "" -} - -func ProjectClaimScope(project ProjectIdentity) ClaimScope { - return ClaimScope{AuthorityID: project.AuthorityID, ProjectUID: project.UID} -} - -func LocalClaimScope(namespaceUID types.UID) ClaimScope { - return ClaimScope{AuthorityID: "local", ProjectUID: namespaceUID} -} - -// AuthorityRef points at a service-controlled authority record. ContractDigest -// commits to its immutable admission inputs; the mutable record advances through -// quota and release recovery states under compare-and-swap updates. -type AuthorityRef struct { - Provider string `json:"provider"` - RecordName string `json:"recordName"` - RecordID string `json:"recordID"` - ContractDigest string `json:"contractDigest"` -} - -func (r AuthorityRef) Valid() bool { - return strings.TrimSpace(r.Provider) != "" && strings.TrimSpace(r.RecordName) != "" && strings.TrimSpace(r.RecordID) != "" && strings.TrimSpace(r.ContractDigest) != "" -} - -// ExternalHoldRef identifies an allocation hold whose owner must explicitly -// acknowledge settlement before Fleet releases custody. -type ExternalHoldRef struct { - Provider string `json:"provider"` - Namespace string `json:"namespace"` - Name string `json:"name"` - UID types.UID `json:"uid"` -} - -func (r ExternalHoldRef) Valid() bool { - return strings.TrimSpace(r.Provider) != "" && strings.TrimSpace(r.Namespace) != "" && strings.TrimSpace(r.Name) != "" && r.UID != "" -} diff --git a/internal/controller/authority_test.go b/internal/controller/authority_test.go deleted file mode 100644 index b46f6be7..00000000 --- a/internal/controller/authority_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package controller - -import ( - "context" - "errors" - "strings" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" -) - -func TestExternalAuthorityScopesAssetAndGatesRelease(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("milo") - consumer := ProjectIdentity{AuthorityID: "milo-a", RouteName: "consumer", UID: "consumer-uid"} - provider := ProjectIdentity{AuthorityID: "milo-a", RouteName: "provider", UID: "provider-uid"} - authority := AuthorityRef{Provider: "milo", RecordName: "record", RecordID: "record-id", ContractDigest: "digest"} - hold := ExternalHoldRef{Provider: "milo", Namespace: request.Claim.Namespace, Name: "quota", UID: "quota-uid"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission, consumer); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainClaimAuthority(ctx, request.Claim.UID, consumer, provider, authority); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainAllocationAuthority(ctx, request.Claim.UID, consumer, provider, authority, hold); err != nil { - t.Fatal(err) - } - request.ConsumerProject, request.ProviderProject = consumer, provider - request.Authority, request.ExternalHold = authority, hold - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - if !strings.HasPrefix(asset.AssetID, "milo-a/provider-uid/") { - t.Fatalf("asset ID %q is not provider lifetime scoped", asset.AssetID) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || result.State != AssetCleanupVerified || result.SafeToRemoveFinalizer || !result.ExternalSettlementRequired { - t.Fatalf("release = %#v, %v", result, err) - } - wrong := hold - wrong.UID = "replacement" - if _, err := f.coordinator.CompleteExternalRelease(ctx, request.Claim.UID, authority, wrong); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("wrong hold error = %v", err) - } - result, err = f.coordinator.CompleteExternalRelease(ctx, request.Claim.UID, authority, hold) - if err != nil || !result.SafeToRemoveFinalizer || result.State != AssetReleased { - t.Fatalf("completion = %#v, %v", result, err) - } -} - -func TestInstallRejectsCustodyAssetCorruptionBeforeEffects(t *testing.T) { - mutations := map[string]func(*ClaimCustodyRecord){ - "released": func(record *ClaimCustodyRecord) { record.State = CustodyReleased }, - "unbound": func(record *ClaimCustodyRecord) { - record.State, record.AssetID, record.ProposedAsset = CustodyUnbound, "", nil - }, - "wrong asset": func(record *ClaimCustodyRecord) { record.AssetID = "replacement-asset" }, - "authority": func(record *ClaimCustodyRecord) { record.Authority.RecordID = "replacement-record" }, - "hold": func(record *ClaimCustodyRecord) { record.ExternalHold.UID = "replacement-hold" }, - } - for name, mutate := range mutations { - t.Run(name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - resolver := &countingResolver{} - f.coordinator.images = resolver - request := f.request("claim-uid") - consumer := ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "consumer-uid"} - provider := ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "provider-uid"} - authority := AuthorityRef{Provider: "milo", RecordName: "record", RecordID: "record-id", ContractDigest: "digest"} - hold := ExternalHoldRef{Provider: "milo", Namespace: request.Claim.Namespace, Name: "quota", UID: "hold-uid"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission, consumer); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainClaimAuthority(ctx, request.Claim.UID, consumer, provider, authority); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainAllocationAuthority(ctx, request.Claim.UID, consumer, provider, authority, hold); err != nil { - t.Fatal(err) - } - request.ConsumerProject, request.ProviderProject, request.Authority, request.ExternalHold = consumer, provider, authority, hold - if _, err := f.coordinator.Allocate(ctx, request); err != nil { - t.Fatal(err) - } - custody, secret, err := f.coordinator.getCustodyScoped(ctx, ProjectClaimScope(consumer), request.Claim.UID) - if err != nil { - t.Fatal(err) - } - mutate(custody) - if err := encodeRecord(secret, custody, "custody"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Update(ctx, secret); err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "installation-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - _, err = f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, ClaimScope: ProjectClaimScope(consumer), ConsumerProject: consumer, Admission: installAdmission()}) - if !errors.Is(err, ErrRecordInvalid) || resolver.calls != 0 || len(f.executor.requests) != 0 { - t.Fatalf("Install error=%v image=%d executor=%d", err, resolver.calls, len(f.executor.requests)) - } - var secrets corev1.SecretList - if err := f.coordinator.client.List(ctx, &secrets); err != nil { - t.Fatal(err) - } - for i := range secrets.Items { - if secrets.Items[i].Labels[recordTypeLabel] == "installation" { - t.Fatalf("installation operation created: %s", secrets.Items[i].Name) - } - } - }) - } -} - -func TestSettledUnboundHoldCanBeClearedButNotSubstituted(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("unbound") - consumer := ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "consumer"} - provider := ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "provider"} - authority := AuthorityRef{Provider: "milo", RecordName: "record", RecordID: "id", ContractDigest: "digest"} - hold := ExternalHoldRef{Provider: "milo", Namespace: "default", Name: "hold", UID: "hold-uid"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission, consumer); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainClaimAuthority(ctx, request.Claim.UID, consumer, provider, authority); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainAllocationAuthority(ctx, request.Claim.UID, consumer, provider, authority, hold); err != nil { - t.Fatal(err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.ExternalSettlementRequired || result.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", result, err) - } - wrong := authority - wrong.RecordID = "other" - if err := f.coordinator.ClearSettledExternalHold(ctx, request.Claim.UID, wrong, hold); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("wrong authority error = %v", err) - } - if err := f.coordinator.ClearSettledExternalHold(ctx, request.Claim.UID, authority, hold); err != nil { - t.Fatal(err) - } -} - -func TestClaimCustodyIsScopedAcrossProjectAPIsWithEqualUIDs(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - left := f.request("left") - right := f.request("right") - right.Claim.UID = left.Claim.UID - leftProject := ProjectIdentity{AuthorityID: "milo", RouteName: "left", UID: "left-project"} - rightProject := ProjectIdentity{AuthorityID: "milo", RouteName: "right", UID: "right-project"} - if err := f.coordinator.EnsureClaimCustody(ctx, left.Claim, left.NamespaceUID, left.Admission, leftProject); err != nil { - t.Fatal(err) - } - if err := f.coordinator.EnsureClaimCustody(ctx, right.Claim, right.NamespaceUID, right.Admission, rightProject); err != nil { - t.Fatal(err) - } - leftRecord, leftSecret, err := f.coordinator.getCustodyScoped(ctx, ProjectClaimScope(leftProject), left.Claim.UID) - if err != nil { - t.Fatal(err) - } - rightRecord, rightSecret, err := f.coordinator.getCustodyScoped(ctx, ProjectClaimScope(rightProject), right.Claim.UID) - if err != nil { - t.Fatal(err) - } - if leftSecret.Name == rightSecret.Name || leftRecord.Scope == rightRecord.Scope { - t.Fatalf("colliding custody: %q %#v / %q %#v", leftSecret.Name, leftRecord.Scope, rightSecret.Name, rightRecord.Scope) - } - if _, _, err := f.coordinator.getCustody(ctx, left.Claim.UID); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("unscoped collision was not rejected: %v", err) - } -} - -func TestInstallationsAreScopedAcrossProjectAPIsWithEqualClaimUIDs(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - type projectCase struct { - name string - consumer ProjectIdentity - provider ProjectIdentity - } - cases := []projectCase{ - {name: "left", consumer: ProjectIdentity{AuthorityID: "milo", RouteName: "left-consumer", UID: "left-consumer"}, provider: ProjectIdentity{AuthorityID: "milo", RouteName: "left-provider", UID: "left-provider"}}, - {name: "right", consumer: ProjectIdentity{AuthorityID: "milo", RouteName: "right-consumer", UID: "right-consumer"}, provider: ProjectIdentity{AuthorityID: "milo", RouteName: "right-provider", UID: "right-provider"}}, - } - var operationNames []string - for _, tc := range cases { - request := f.request("shared-claim-uid") - request.NamespaceUID = types.UID(tc.name + "-namespace-uid") - authority := AuthorityRef{Provider: "milo", RecordName: tc.name + "-record", RecordID: tc.name + "-record-id", ContractDigest: tc.name + "-digest"} - hold := ExternalHoldRef{Provider: "milo", Namespace: request.Claim.Namespace, Name: tc.name + "-quota", UID: types.UID(tc.name + "-hold-uid")} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission, tc.consumer); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainClaimAuthority(ctx, request.Claim.UID, tc.consumer, tc.provider, authority); err != nil { - t.Fatal(err) - } - if err := f.coordinator.RetainAllocationAuthority(ctx, request.Claim.UID, tc.consumer, tc.provider, authority, hold); err != nil { - t.Fatal(err) - } - request.ConsumerProject, request.ProviderProject, request.Authority, request.ExternalHold = tc.consumer, tc.provider, authority, hold - if _, err := f.coordinator.Allocate(ctx, request); err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: types.UID(tc.name + "-installation")}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - result, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, ClaimScope: ProjectClaimScope(tc.consumer), ConsumerProject: tc.consumer, Admission: installAdmission()}) - if err != nil || result.Record.ClaimScope != ProjectClaimScope(tc.consumer) || result.Record.ConsumerProject != tc.consumer { - t.Fatalf("%s installation = %#v, %v", tc.name, result, err) - } - operationNames = append(operationNames, operationRecordName(result.Record.ClaimScope, result.Record.ClaimUID, result.Record.Predecessor)) - } - if operationNames[0] == operationNames[1] || len(f.executor.requests) != 2 { - t.Fatalf("operation collision: names=%v requests=%d", operationNames, len(f.executor.requests)) - } -} diff --git a/internal/controller/evidence_adversarial_test.go b/internal/controller/evidence_adversarial_test.go deleted file mode 100644 index affd3f71..00000000 --- a/internal/controller/evidence_adversarial_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package controller - -import ( - "context" - "errors" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -// Return a valid terminal result for the same operation name but a different -// physical target. Exercise both direct completion and lost-response recovery. -type substitutedCleanupExecutor struct { - result simulator.OperationResult - lost bool -} - -func (e *substitutedCleanupExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - request.AssetID += "-different-physical-asset" - digest, err := simulator.RequestDigest(request) - if err != nil { - return simulator.OperationResult{}, err - } - now := time.Now() - e.result = simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CompletedAt: &now} - if e.lost { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - return e.result, nil -} - -func (e *substitutedCleanupExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return e.result, true, nil -} - -func TestAdversarialCleanupEvidenceCannotReleaseAnotherAsset(t *testing.T) { - for _, lost := range []bool{false, true} { - name := "direct" - if lost { - name = "recovered" - } - t.Run(name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - owner, waiter := f.request("owner"), f.request("waiter") - for _, request := range []AllocationRequest{owner, waiter} { - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - } - if _, err := f.coordinator.Allocate(ctx, owner); err != nil { - t.Fatal(err) - } - f.coordinator.executor = &substitutedCleanupExecutor{lost: lost} - result, err := f.coordinator.Release(ctx, owner.Claim.UID) - if !errors.Is(err, executor.ErrOutcomeUnknown) || result.SafeToRemoveFinalizer { - t.Errorf("wrong-asset cleanup authorized release: result=%+v err=%v", result, err) - } - if _, err := f.coordinator.Allocate(ctx, waiter); !errors.Is(err, ErrInsufficientCapacity) { - t.Errorf("wrong-asset cleanup exposed occupied capacity: %v", err) - } - }) - } -} diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go deleted file mode 100644 index f5f4e9b7..00000000 --- a/internal/controller/lifecycle.go +++ /dev/null @@ -1,2196 +0,0 @@ -package controller - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "sort" - "strings" - "time" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - apiMeta "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/util/retry" - "sigs.k8s.io/controller-runtime/pkg/client" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/executor" - fleetnetwork "go.datum.net/fleet/internal/network" - "go.datum.net/fleet/internal/simulator" -) - -const ( - MachineFinalizer = "fleet.datumapis.com/machine-protection" - recordSchemaVersion = 1 - // Installation records carry retained public routing identities. Any - // other schema version is invalid. - installationRecordSchemaVersion = 2 - assetRecordPrefix = "fleet-asset-" - custodyRecordPrefix = "fleet-claim-" - operationPrefix = "fleet-install-" - recordDataKey = "record.json" - recordTypeLabel = "fleet.datumapis.com/private-record" - claimUIDLabel = "fleet.datumapis.com/claim-uid" -) - -type CustodyState string - -const ( - CustodyUnbound CustodyState = "Unbound" - CustodySelecting CustodyState = "Selecting" - CustodyBound CustodyState = "Bound" - CustodyReleased CustodyState = "Released" -) - -// ClaimCustodyRecord is independent proof of whether a claim lifetime ever -// acquired an asset. A missing asset record is safe only while this record is -// Unbound; Bound custody without matching asset authority fails closed. -type ClaimCustodyRecord struct { - SchemaVersion int `json:"schemaVersion"` - State CustodyState `json:"state"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - NamespaceUID types.UID `json:"namespaceUID"` - Scope ClaimScope `json:"scope"` - Admission AdmissionAuthority `json:"admission"` - ConsumerProject ProjectIdentity `json:"consumerProject,omitempty"` - ProviderProject ProjectIdentity `json:"providerProject,omitempty"` - Authority AuthorityRef `json:"authority,omitempty"` - ExternalHold ExternalHoldRef `json:"externalHold,omitempty"` - AssetID string `json:"assetID,omitempty"` - ProposedAsset *AssetRecord `json:"proposedAsset,omitempty"` -} - -type AdmissionAuthority struct { - PrincipalUID string `json:"principalUID"` - DecisionID string `json:"decisionID"` -} - -func (a AdmissionAuthority) valid() bool { - return strings.TrimSpace(a.PrincipalUID) != "" && strings.TrimSpace(a.DecisionID) != "" -} - -var ( - ErrUnsupported = errors.New("requested integration is unavailable") - ErrInsufficientCapacity = errors.New("no eligible clean machine is available") - ErrRecordInvalid = errors.New("retained private lifecycle record is invalid") - ErrClaimAlreadyReleased = errors.New("claim allocation was already released") - ErrPredecessorConflict = errors.New("installation predecessor was already consumed") - ErrOperationActive = errors.New("an admitted installation operation is not settled") -) - -type AssetState string - -const ( - AssetPreparing AssetState = "Preparing" - AssetCommitted AssetState = "Committed" - AssetReleasing AssetState = "Releasing" - AssetCleanupVerified AssetState = "CleanupVerified" - AssetReleased AssetState = "Released" -) - -type OperationState string - -const ( - OperationAdmitted OperationState = "Admitted" - OperationSucceeded OperationState = "Succeeded" -) - -// AssetRecord is private coordination state. It is deliberately retained after -// release so the next allocation can advance the executor epoch without -// reconstructing authority from public status. -type AssetRecord struct { - SchemaVersion int `json:"schemaVersion"` - State AssetState `json:"state"` - AssetID string `json:"assetID"` - MachineNamespace string `json:"machineNamespace"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - ClaimScope ClaimScope `json:"claimScope"` - ClassUID types.UID `json:"classUID"` - ProfileUID types.UID `json:"profileUID"` - LocalClassUID types.UID `json:"localClassUID"` - LocalProfileUID types.UID `json:"localProfileUID"` - ConsumerProject ProjectIdentity `json:"consumerProject,omitempty"` - ProviderProject ProjectIdentity `json:"providerProject,omitempty"` - Authority AuthorityRef `json:"authority,omitempty"` - ExternalHold ExternalHoldRef `json:"externalHold,omitempty"` - BindingID string `json:"bindingID"` - Epoch int64 `json:"epoch"` - FenceToken string `json:"fenceToken"` - CurrentInstallationName string `json:"currentInstallationName"` - ActiveOperationID string `json:"activeOperationID,omitempty"` - AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` - Hardware fleetv1.Hardware `json:"hardware"` - Network *NetworkRecord `json:"network,omitempty"` -} - -type ResolvedImage struct { - Name string `json:"name"` - UID types.UID `json:"uid,omitempty"` - Digest string `json:"digest"` - CatalogAuthority string `json:"catalogAuthority"` - CatalogRevision string `json:"catalogRevision"` - ImageDecisionID string `json:"imageDecisionID"` -} - -func (i ResolvedImage) Reference() string { return i.Name + "@" + i.Digest } - -func (i ResolvedImage) Validate() error { - if strings.TrimSpace(i.Name) == "" || strings.Contains(i.Name, "@") { - return errors.New("resolved image name must be nonempty and exclude a digest") - } - if !validSHA256(i.Digest) { - return errors.New("resolved image digest must be canonical sha256 with 64 lowercase hex digits") - } - if strings.TrimSpace(i.CatalogAuthority) == "" || strings.TrimSpace(i.CatalogRevision) == "" || strings.TrimSpace(i.ImageDecisionID) == "" { - return errors.New("resolved image authority is required") - } - return nil -} - -type ImageRequest struct { - NamespaceUID types.UID - ClaimUID types.UID - InstallationUID types.UID - ImageName string -} - -type ImageResolver interface { - ResolveImage(context.Context, ImageRequest) (ResolvedImage, error) -} - -// LocalDigestImageResolver is test-only. Production must resolve image -// authority through an authenticated catalog and retain its lifetime identity. -type LocalDigestImageResolver struct{} - -func (LocalDigestImageResolver) ResolveImage(_ context.Context, request ImageRequest) (ResolvedImage, error) { - name, digest, ok := strings.Cut(request.ImageName, "@") - image := ResolvedImage{Name: name, Digest: digest, CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + digest} - if !ok || image.Validate() != nil { - return ResolvedImage{}, errors.New("local digest resolver requires name@sha256:<64 lowercase hex digits>") - } - return image, nil -} - -type InstallationRecord struct { - SchemaVersion int `json:"schemaVersion"` - State OperationState `json:"state"` - OperationID string `json:"operationID"` - InstallationNamespace string `json:"installationNamespace"` - InstallationName string `json:"installationName"` - InstallationUID types.UID `json:"installationUID"` - NamespaceUID types.UID `json:"namespaceUID"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - ClaimScope ClaimScope `json:"claimScope"` - ConsumerProject ProjectIdentity `json:"consumerProject,omitempty"` - AssetID string `json:"assetID"` - BindingID string `json:"bindingID"` - Epoch int64 `json:"epoch"` - Predecessor string `json:"predecessor"` - ResultRevision string `json:"resultRevision"` - Image ResolvedImage `json:"image"` - ImageName string `json:"imageName"` - Admission InstallationAdmissionAuthority `json:"admission"` - NetworkInputs *fleetnetwork.Observation `json:"networkInputs,omitempty"` -} - -type InstallationAdmissionAuthority struct { - PrincipalUID string `json:"principalUID"` - DecisionID string `json:"decisionID"` - CatalogAuthority string `json:"catalogAuthority"` - CatalogRevision string `json:"catalogRevision"` - ImageDecisionID string `json:"imageDecisionID"` -} - -func (a InstallationAdmissionAuthority) valid() bool { - return strings.TrimSpace(a.PrincipalUID) != "" && strings.TrimSpace(a.DecisionID) != "" && strings.TrimSpace(a.CatalogAuthority) != "" && strings.TrimSpace(a.CatalogRevision) != "" && strings.TrimSpace(a.ImageDecisionID) != "" -} - -type Coordinator struct { - client client.Client - namespace string - executor executor.Client - images ImageResolver - networks fleetnetwork.Lifecycle - maxEvidenceAge time.Duration - now func() time.Time - newID func() (string, error) -} - -func NewCoordinator(kube client.Client, privateNamespace string, provider executor.Client, images ImageResolver, networks fleetnetwork.Lifecycle, maxEvidenceAge time.Duration) (*Coordinator, error) { - if kube == nil || provider == nil || images == nil || privateNamespace == "" || maxEvidenceAge <= 0 { - return nil, errors.New("client, private namespace, executor, image resolver, and positive evidence age are required") - } - return &Coordinator{client: kube, namespace: privateNamespace, executor: provider, images: images, networks: networks, maxEvidenceAge: maxEvidenceAge, now: time.Now, newID: randomID}, nil -} - -type AllocationRequest struct { - Claim *fleetv1.Machine - Class *fleetv1.MachineClass - Profile *fleetv1.MachineProfile - MachineCapacities []fleetv1.MachineCapacity - EvidenceObservedAt map[types.UID]time.Time - NamespaceUID types.UID - Admission AdmissionAuthority - LocalClassName string - LocalClassUID types.UID - LocalProfileName string - LocalProfileUID types.UID - ConsumerProject ProjectIdentity - ProviderProject ProjectIdentity - Authority AuthorityRef - ExternalHold ExternalHoldRef - Location fleetnetwork.LocationAuthority - networkPlan *fleetnetwork.Plan -} - -func allocationClaimScope(request AllocationRequest) ClaimScope { - if request.ConsumerProject.Valid() { - return ProjectClaimScope(request.ConsumerProject) - } - return LocalClaimScope(request.NamespaceUID) -} - -// EnsureClaimCustody must be called before a claim finalizer is installed. It -// is idempotent for the exact claim lifetime and rejects deterministic-name -// squatting or reuse with a different identity. -func (c *Coordinator) EnsureClaimCustody(ctx context.Context, claim *fleetv1.Machine, namespaceUID types.UID, admission AdmissionAuthority, project ...ProjectIdentity) error { - if claim == nil || claim.Namespace == "" || claim.Name == "" || claim.UID == "" || namespaceUID == "" || !admission.valid() { - return errors.New("claim lifetime identity is required") - } - ctx = withUndecodableReporting(ctx) - scope := LocalClaimScope(namespaceUID) - if len(project) > 1 || len(project) == 1 && !project[0].Valid() { - return ErrRecordInvalid - } - if len(project) == 1 { - scope = ProjectClaimScope(project[0]) - } - name := custodyRecordName(scope, claim.UID) - var secret corev1.Secret - err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) - if err == nil { - record, err := decodeCustodySecret(ctx, &secret) - if err != nil { - return err - } - if record.ClaimNamespace != claim.Namespace || record.ClaimName != claim.Name || record.ClaimUID != claim.UID || record.NamespaceUID != namespaceUID || record.Admission != admission { - return fmt.Errorf("%w: custody lifetime does not match claim", ErrRecordInvalid) - } - return nil - } - if !apierrors.IsNotFound(err) { - return err - } - record := &ClaimCustodyRecord{SchemaVersion: recordSchemaVersion, State: CustodyUnbound, ClaimNamespace: claim.Namespace, ClaimName: claim.Name, ClaimUID: claim.UID, NamespaceUID: namespaceUID, Scope: scope, Admission: admission} - secret = corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: c.namespace}} - if err := encodeRecord(&secret, record, "custody"); err != nil { - return err - } - if err := c.client.Create(ctx, &secret); apierrors.IsAlreadyExists(err) { - return c.EnsureClaimCustody(ctx, claim, namespaceUID, admission, project...) - } else { - return err - } -} - -// RetainClaimAuthority links finalizer custody to a protected authority record -// before any external hold or provider effect is requested. -func (c *Coordinator) RetainClaimAuthority(ctx context.Context, claimUID types.UID, consumer, provider ProjectIdentity, authority AuthorityRef) error { - if claimUID == "" || !consumer.Valid() || !provider.Valid() || !authority.Valid() { - return errors.New("exact project and authority lifetimes are required") - } - return retry.RetryOnConflict(retry.DefaultRetry, func() error { - record, secret, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) - if err != nil { - return err - } - if record.Authority.Valid() { - if record.ConsumerProject == consumer && record.ProviderProject == provider && record.Authority == authority { - return nil - } - return ErrRecordInvalid - } - if record.State != CustodyUnbound || record.ExternalHold.Valid() { - return ErrRecordInvalid - } - record.ConsumerProject, record.ProviderProject, record.Authority = consumer, provider, authority - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) - }) -} - -// VerifyAllocationAuthority proves that the exact claim lifetime is still -// unbound before an external quota owner is allowed to create a hold. A -// released custody record is terminal and must never be reopened by a racing -// allocation. -func (c *Coordinator) VerifyAllocationAuthority(ctx context.Context, claimUID types.UID, consumer, provider ProjectIdentity, authority AuthorityRef) error { - if claimUID == "" || !consumer.Valid() || !provider.Valid() || !authority.Valid() { - return errors.New("exact project and authority lifetimes are required") - } - record, _, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) - if err != nil { - return err - } - if record.State != CustodyUnbound || record.ExternalHold.Valid() || record.ConsumerProject != consumer || record.ProviderProject != provider || record.Authority != authority { - return ErrRecordInvalid - } - return nil -} - -// RetainAllocationAuthority attaches cross-project authority and an exact -// external hold to unbound custody before allocation. It is idempotent for the -// same authority and rejects recovery with a substituted project or hold lifetime. -func (c *Coordinator) RetainAllocationAuthority(ctx context.Context, claimUID types.UID, consumer, provider ProjectIdentity, authority AuthorityRef, hold ExternalHoldRef) error { - if claimUID == "" || !consumer.Valid() || !provider.Valid() || !authority.Valid() || !hold.Valid() { - return errors.New("exact project, authority, and hold lifetimes are required") - } - return retry.RetryOnConflict(retry.DefaultRetry, func() error { - record, secret, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) - if err != nil { - return err - } - if record.State != CustodyUnbound || record.ExternalHold.Valid() { - if record.ConsumerProject == consumer && record.ProviderProject == provider && record.Authority == authority && record.ExternalHold == hold { - return nil - } - return ErrRecordInvalid - } - if record.ConsumerProject != consumer || record.ProviderProject != provider || record.Authority != authority { - return ErrRecordInvalid - } - record.ExternalHold = hold - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) - }) -} - -// ClearSettledExternalHold permits a new allocation attempt only after the -// exact hold owner has acknowledged settlement and custody is still unbound. -func (c *Coordinator) ClearSettledExternalHold(ctx context.Context, claimUID types.UID, authority AuthorityRef, hold ExternalHoldRef, project ...ProjectIdentity) error { - return retry.RetryOnConflict(retry.DefaultRetry, func() error { - var record *ClaimCustodyRecord - var secret *corev1.Secret - var err error - if len(project) == 1 && project[0].Valid() { - record, secret, err = c.getCustodyScoped(ctx, ProjectClaimScope(project[0]), claimUID) - } else if len(project) == 0 { - record, secret, err = c.getCustody(ctx, claimUID) - } else { - return ErrRecordInvalid - } - if err != nil { - return err - } - if record.State != CustodyUnbound || record.AssetID != "" || record.Authority != authority { - return ErrRecordInvalid - } - if !record.ExternalHold.Valid() { - return nil - } - if record.ExternalHold != hold { - return ErrRecordInvalid - } - record.ExternalHold = ExternalHoldRef{} - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) - }) -} - -func (c *Coordinator) Allocate(ctx context.Context, request AllocationRequest) (*AssetRecord, error) { - ctx = withUndecodableReporting(ctx) - if err := validateAllocationRequest(request); err != nil { - return nil, err - } - if request.Class.Spec.Source != nil { - return nil, fmt.Errorf("%w: sourced classes must be resolved by an authority adapter", ErrUnsupported) - } - if request.Claim.DeletionTimestamp != nil || !contains(request.Claim.Finalizers, MachineFinalizer) { - return nil, errors.New("claim must be live and carry the Fleet finalizer before allocation") - } - scope := allocationClaimScope(request) - custody, _, err := c.getCustodyScoped(ctx, scope, request.Claim.UID) - if err != nil { - return nil, fmt.Errorf("claim custody must exist before allocation: %w", err) - } - if custody.ClaimNamespace != request.Claim.Namespace || custody.ClaimName != request.Claim.Name || custody.NamespaceUID != request.NamespaceUID || custody.Admission != request.Admission || custody.State == CustodyReleased || !allocationAuthorityMatches(custody, request) { - return nil, fmt.Errorf("%w: claim custody does not authorize allocation", ErrRecordInvalid) - } - existing, err := c.recordsForClaimScoped(ctx, request.Claim.UID, custody.ConsumerProject) - if err != nil { - return nil, err - } - if len(existing) > 1 { - return nil, fmt.Errorf("%w: claim has duplicate asset records", ErrRecordInvalid) - } - if len(existing) == 1 { - record := existing[0] - if err := validateAssetForRequest(record, request); err != nil { - return nil, err - } - if custody.State == CustodySelecting && custody.AssetID == record.AssetID && record.State == AssetPreparing { - if !c.recordCandidateEligible(record, request) { - return nil, ErrInsufficientCapacity - } - if err := c.bindCustody(ctx, request.Claim, record.AssetID, scope); err != nil { - return nil, err - } - } else if custody.State != CustodyBound || custody.AssetID != record.AssetID { - return nil, fmt.Errorf("%w: custody and asset authority disagree", ErrRecordInvalid) - } - if record.State == AssetReleased || record.State == AssetReleasing { - return nil, ErrClaimAlreadyReleased - } - return c.commitPrepared(ctx, record.AssetID, request.Claim.UID) - } - if len(request.Claim.Spec.NetworkInterfaces) != 0 { - if c.networks == nil || !request.Location.Valid() || request.Location.Name != request.Claim.Spec.LocationRef.Name { - return nil, fleetnetwork.ErrAuthorizationUnavailable - } - interfaces, err := networkRequests(request) - if err != nil { - return nil, err - } - plan, err := c.networks.Preflight(ctx, fleetnetwork.PreflightRequest{ClaimNamespace: request.Claim.Namespace, ClaimUID: request.Claim.UID, NamespaceUID: request.NamespaceUID, PrincipalUID: request.Admission.PrincipalUID, Location: request.Location, Interfaces: interfaces}) - if err != nil { - return nil, err - } - request.networkPlan = &plan - } - - selector, err := metav1.LabelSelectorAsSelector(&request.Class.Spec.Capacity.MachineCapacities.Selector) - if err != nil { - return nil, fmt.Errorf("invalid MachineClass selector: %w", err) - } - candidates := append([]fleetv1.MachineCapacity(nil), request.MachineCapacities...) - sort.Slice(candidates, func(i, j int) bool { - return candidates[i].Namespace+"/"+candidates[i].Name < candidates[j].Namespace+"/"+candidates[j].Name - }) - for i := range candidates { - machine := &candidates[i] - if machine.Namespace != request.Class.Spec.Capacity.MachineCapacities.Namespace || !selector.Matches(labels.Set(machine.Labels)) || !machineEligible(machine, request.EvidenceObservedAt[machine.UID], c.now(), c.maxEvidenceAge) || !matches(request.Profile.Spec, machine.Status.Hardware) { - continue - } - candidateID := machineAssetID(machine, request.ProviderProject) - if custody.State == CustodySelecting && custody.AssetID != candidateID { - continue - } - if custody.State == CustodyUnbound { - proposal, reusable, err := c.proposeAsset(ctx, request, machine) - if err != nil { - return nil, err - } - if !reusable { - continue - } - if err := c.selectCustody(ctx, request, proposal); err != nil { - return nil, err - } - custody.State, custody.AssetID, custody.ProposedAsset = CustodySelecting, candidateID, proposal - } - prepared, won, err := c.prepareAsset(ctx, request, machine) - if err != nil { - return nil, err - } - if !won { - if custody.State == CustodySelecting && custody.AssetID == candidateID { - if err := c.clearSelection(ctx, request.Claim.UID, candidateID, scope); err != nil { - return nil, err - } - custody.State, custody.AssetID = CustodyUnbound, "" - } - continue - } - if err := c.bindCustody(ctx, request.Claim, prepared.AssetID, scope); err != nil { - return nil, err - } - return c.commitPrepared(ctx, prepared.AssetID, request.Claim.UID) - } - return nil, ErrInsufficientCapacity -} - -func machineAssetID(machine *fleetv1.MachineCapacity, provider ProjectIdentity) string { - asset := fmt.Sprintf("%s/%s/%s/%s", machine.Namespace, "fleet.datumapis.com", "Device", machine.Spec.DeviceRef.Name) - if provider.Valid() { - return fmt.Sprintf("%s/%s/%s", provider.AuthorityID, provider.UID, asset) - } - return asset -} - -func (c *Coordinator) recordCandidateEligible(record *AssetRecord, request AllocationRequest) bool { - selector, err := metav1.LabelSelectorAsSelector(&request.Class.Spec.Capacity.MachineCapacities.Selector) - if err != nil { - return false - } - for i := range request.MachineCapacities { - m := &request.MachineCapacities[i] - if machineAssetID(m, request.ProviderProject) == record.AssetID && m.UID == record.MachineUID && m.Namespace == record.MachineNamespace && m.Name == record.MachineName && m.Namespace == request.Class.Spec.Capacity.MachineCapacities.Namespace && selector.Matches(labels.Set(m.Labels)) && machineEligible(m, request.EvidenceObservedAt[m.UID], c.now(), c.maxEvidenceAge) && matches(request.Profile.Spec, m.Status.Hardware) { - return true - } - } - return false -} - -func validateAssetForRequest(record *AssetRecord, request AllocationRequest) error { - // Specs contain slices, so compare their canonical JSON rather than - // allowing a recovered Preparing record to drift across retries. - got, _ := json.Marshal(record.AcceptedRequirements) - want, _ := json.Marshal(request.Profile.Spec) - if record.ClaimNamespace != request.Claim.Namespace || record.ClaimName != request.Claim.Name || record.ClaimUID != request.Claim.UID || record.ClassUID != request.Class.UID || record.ProfileUID != request.Profile.UID || record.LocalClassUID != localClassUID(request) || record.LocalProfileUID != localProfileUID(request) || record.ConsumerProject != request.ConsumerProject || record.ProviderProject != request.ProviderProject || record.Authority != request.Authority || record.ExternalHold != request.ExternalHold || string(got) != string(want) { - return fmt.Errorf("%w: retained asset inputs differ from allocation retry", ErrRecordInvalid) - } - interfaces, err := networkRequests(request) - if err != nil { - return err - } - digest, err := fleetnetwork.DigestRequests(interfaces) - if err != nil { - return err - } - if (record.Network == nil) != (len(interfaces) == 0) || record.Network != nil && (record.Network.Plan.RequestDigest != digest || record.Network.Plan.Location.Name != request.Claim.Spec.LocationRef.Name) { - return fmt.Errorf("%w: retained network inputs differ from allocation retry", ErrRecordInvalid) - } - return nil -} - -func networkRequests(request AllocationRequest) ([]fleetnetwork.InterfaceRequest, error) { - slots := map[string]bool{} - for _, iface := range request.Profile.Spec.Interfaces { - slots[iface.Name] = true - } - seen := map[string]bool{} - result := make([]fleetnetwork.InterfaceRequest, 0, len(request.Claim.Spec.NetworkInterfaces)) - for _, requested := range request.Claim.Spec.NetworkInterfaces { - if requested.Name == "" || seen[requested.Name] || !slots[requested.Name] || requested.Network.Name == "" { - return nil, fmt.Errorf("%w: network interface does not name one unique profile slot", ErrRecordInvalid) - } - seen[requested.Name] = true - reclaim, ok := fleetnetwork.NormalizeReclaimPolicy(requested.ReclaimPolicy) - if !ok { - return nil, fmt.Errorf("%w: invalid network reclaim policy", ErrRecordInvalid) - } - namespace := requested.Network.Namespace - if namespace == "" { - namespace = request.Claim.Namespace - } - item := fleetnetwork.InterfaceRequest{Name: requested.Name, NetworkName: requested.Network.Name, NetworkNS: namespace, IPFamilies: append([]string(nil), requested.IPFamilies...), ReclaimPolicy: reclaim} - for _, address := range requested.Addresses { - if address.ClassRef.Name == "" { - return nil, fmt.Errorf("%w: address class name is required", ErrRecordInvalid) - } - item.AddressClasses = append(item.AddressClasses, address.ClassRef.Name) - } - if !fleetnetwork.ValidAttachmentLists(item.IPFamilies, item.AddressClasses) { - return nil, fmt.Errorf("%w: network attachment families or address classes violate NSO cardinality or uniqueness", ErrRecordInvalid) - } - result = append(result, item) - } - return result, nil -} - -func validateCapacityRequest(request AllocationRequest) error { - if request.Claim == nil || request.Class == nil || request.Profile == nil || request.Class.Spec.Capacity == nil { - return errors.New("claim, class, profile, and class capacity are required") - } - if request.Claim.UID == "" || request.Class.UID == "" || request.Profile.UID == "" || request.Claim.Namespace == "" || request.Claim.Name == "" || request.NamespaceUID == "" || !request.Admission.valid() { - return errors.New("claim, class, and profile lifetime identities are required") - } - className, profileName := request.LocalClassName, request.LocalProfileName - if className == "" { - className = request.Class.Name - } - if profileName == "" { - profileName = request.Profile.Name - } - if className != request.Claim.Spec.MachineClassRef.Name || profileName != request.Claim.Spec.MachineProfileRef.Name { - return errors.New("resolved class or profile does not match the claim") - } - return nil -} - -func validateAllocationRequest(request AllocationRequest) error { - if err := validateCapacityRequest(request); err != nil { - return err - } - projectAuthority := request.ConsumerProject.Valid() || request.ProviderProject.Valid() || request.Authority.Valid() || request.ExternalHold.Valid() - if projectAuthority && (!request.ConsumerProject.Valid() || !request.ProviderProject.Valid() || !request.Authority.Valid() || !request.ExternalHold.Valid() || localClassUID(request) == "" || localProfileUID(request) == "") { - return errors.New("cross-project allocation requires exact project, source, authority, and hold lifetimes") - } - return nil -} - -func localClassUID(request AllocationRequest) types.UID { - if request.LocalClassUID != "" { - return request.LocalClassUID - } - return request.Class.UID -} - -func localProfileUID(request AllocationRequest) types.UID { - if request.LocalProfileUID != "" { - return request.LocalProfileUID - } - return request.Profile.UID -} - -func allocationAuthorityMatches(custody *ClaimCustodyRecord, request AllocationRequest) bool { - return custody.ConsumerProject == request.ConsumerProject && custody.ProviderProject == request.ProviderProject && custody.Authority == request.Authority && custody.ExternalHold == request.ExternalHold -} - -// CheckCapacity performs the same current hardware selection test as Allocate -// without retaining selection or authorizing effects. Allocate always rechecks. -func (c *Coordinator) CheckCapacity(request AllocationRequest) error { - if err := validateCapacityRequest(request); err != nil { - return err - } - selector, err := metav1.LabelSelectorAsSelector(&request.Class.Spec.Capacity.MachineCapacities.Selector) - if err != nil { - return fmt.Errorf("invalid MachineClass selector: %w", err) - } - for i := range request.MachineCapacities { - machine := &request.MachineCapacities[i] - if machine.Namespace == request.Class.Spec.Capacity.MachineCapacities.Namespace && selector.Matches(labels.Set(machine.Labels)) && machineEligible(machine, request.EvidenceObservedAt[machine.UID], c.now(), c.maxEvidenceAge) && matches(request.Profile.Spec, machine.Status.Hardware) { - return nil - } - } - return ErrInsufficientCapacity -} - -func machineEligible(machine *fleetv1.MachineCapacity, observedAt, now time.Time, maxAge time.Duration) bool { - if machine.UID == "" || machine.Spec.AllocationPolicy != "Enabled" || observedAt.IsZero() || observedAt.After(now) || now.Sub(observedAt) > maxAge { - return false - } - for _, conditionType := range []string{"Prepared", "Healthy", "Available"} { - condition := apiMeta.FindStatusCondition(machine.Status.Conditions, conditionType) - if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != machine.Generation { - return false - } - } - return true -} - -func (c *Coordinator) prepareAsset(ctx context.Context, request AllocationRequest, machine *fleetv1.MachineCapacity) (*AssetRecord, bool, error) { - assetID := machineAssetID(machine, request.ProviderProject) - custody, _, err := c.getCustodyScoped(ctx, allocationClaimScope(request), request.Claim.UID) - if err != nil { - return nil, false, err - } - if custody.State != CustodySelecting || custody.AssetID != assetID || custody.ProposedAsset == nil || !sameRecord(custody.ProposedAsset, newAssetRecord(request, machine, assetID, custody.ProposedAsset.Epoch, custody.ProposedAsset.BindingID, custody.ProposedAsset.FenceToken)) { - return nil, false, nil - } - proposal := custody.ProposedAsset - name := assetRecordName(assetID) - var secret corev1.Secret - err = c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) - if err == nil { - existing, decodeErr := decodeAssetSecret(ctx, &secret) - if decodeErr != nil { - return nil, false, unreadableCandidate(&secret, request.Claim.UID, decodeErr) - } - if existing.State != AssetReleased { - if existing.ClaimUID != request.Claim.UID { - return nil, false, nil - } - if err := validateAssetForRequest(existing, request); err != nil { - return nil, false, err - } - if existing.MachineNamespace != machine.Namespace || existing.MachineName != machine.Name || existing.MachineUID != machine.UID { - return nil, false, ErrRecordInvalid - } - return existing, sameRecord(existing, proposal), nil - } - previousCustody, custodySecret, custodyErr := c.getCustodyForAsset(ctx, existing) - if errors.Is(custodyErr, ErrRecordUnreadable) { - return nil, false, unreadableCandidate(custodySecret, request.Claim.UID, custodyErr) - } - if custodyErr != nil { - return nil, false, custodyErr - } - if previousCustody.State != CustodyReleased || previousCustody.AssetID != existing.AssetID { - return nil, false, nil - } - if proposal.Epoch != existing.Epoch+1 { - return nil, false, ErrRecordInvalid - } - next := proposal - if err := encodeRecord(&secret, next, "asset"); err != nil { - return nil, false, err - } - if err := c.client.Update(ctx, &secret); apierrors.IsConflict(err) { - return c.prepareAsset(ctx, request, machine) - } else if err != nil { - return nil, false, err - } - return next, true, nil - } - if !apierrors.IsNotFound(err) { - return nil, false, err - } - if proposal.Epoch != 1 { - return nil, false, ErrRecordInvalid - } - record := proposal - secret = corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: c.namespace}} - if err := encodeRecord(&secret, record, "asset"); err != nil { - return nil, false, err - } - if err := c.client.Create(ctx, &secret); apierrors.IsAlreadyExists(err) { - return c.prepareAsset(ctx, request, machine) - } else if err != nil { - return nil, false, err - } - return record, true, nil -} - -func sameRecord(a, b *AssetRecord) bool { - left, _ := json.Marshal(a) - right, _ := json.Marshal(b) - return string(left) == string(right) -} - -func (c *Coordinator) proposeAsset(ctx context.Context, request AllocationRequest, machine *fleetv1.MachineCapacity) (*AssetRecord, bool, error) { - assetID := machineAssetID(machine, request.ProviderProject) - epoch := int64(1) - existing, secret, err := c.getAsset(ctx, assetID) - if errors.Is(err, ErrRecordUnreadable) { - return nil, false, unreadableCandidate(secret, request.Claim.UID, err) - } - if err == nil { - if existing.State != AssetReleased { - return nil, false, nil - } - previous, custodySecret, err := c.getCustodyForAsset(ctx, existing) - if errors.Is(err, ErrRecordUnreadable) { - return nil, false, unreadableCandidate(custodySecret, request.Claim.UID, err) - } - if err != nil { - return nil, false, err - } - if previous.State != CustodyReleased || previous.AssetID != assetID { - return nil, false, nil - } - epoch = existing.Epoch + 1 - } else if !apierrors.IsNotFound(err) { - return nil, false, err - } - binding, fence, err := c.authorityIDs() - if err != nil { - return nil, false, err - } - return newAssetRecord(request, machine, assetID, epoch, binding, fence), true, nil -} - -// unreadableCandidate handles a candidate asset whose asset record, or the -// custody record of its previous claim, cannot be decoded. The asset is never -// proposed: without the record there is no proof that it was released or of -// its epoch, so treating it as free could double-bind it or restart its epoch -// fence below a stale operation. Allocation moves on to the next candidate, -// unless the record is attributed to the allocating claim itself, which then -// fails closed. -func unreadableCandidate(secret *corev1.Secret, claimUID types.UID, err error) error { - if secret.Labels[claimUIDLabel] == string(claimUID) { - return err - } - return nil -} - -func newAssetRecord(request AllocationRequest, machine *fleetv1.MachineCapacity, assetID string, epoch int64, bindingID, fenceToken string) *AssetRecord { - record := &AssetRecord{SchemaVersion: recordSchemaVersion, State: AssetPreparing, AssetID: assetID, - MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, - ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, ClaimScope: allocationClaimScope(request), - ClassUID: request.Class.UID, ProfileUID: request.Profile.UID, LocalClassUID: localClassUID(request), LocalProfileUID: localProfileUID(request), - ConsumerProject: request.ConsumerProject, ProviderProject: request.ProviderProject, Authority: request.Authority, ExternalHold: request.ExternalHold, - BindingID: bindingID, Epoch: epoch, - FenceToken: fenceToken, CurrentInstallationName: "None", AcceptedRequirements: request.Profile.Spec, Hardware: machine.Status.Hardware} - if request.networkPlan != nil { - record.Network = &NetworkRecord{Plan: *request.networkPlan} - } - return record -} - -func (c *Coordinator) commitPrepared(ctx context.Context, assetID string, claimUID types.UID) (*AssetRecord, error) { - var committed *AssetRecord - err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - record, secret, err := c.getAsset(ctx, assetID) - if err != nil { - return err - } - if record.ClaimUID != claimUID { - return fmt.Errorf("%w: asset belongs to another claim", ErrRecordInvalid) - } - if record.State == AssetCommitted { - committed = record - return nil - } - if record.State != AssetPreparing { - return fmt.Errorf("%w: cannot commit asset in state %s", ErrRecordInvalid, record.State) - } - record.State = AssetCommitted - if err := encodeRecord(secret, record, "asset"); err != nil { - return err - } - if err := c.client.Update(ctx, secret); err != nil { - return err - } - committed = record - return nil - }) - return committed, err -} - -// ReconcileNetwork materializes and observes NSO claims only after the asset -// binding is committed. It uses the retained plan rather than the public claim. -func (c *Coordinator) ReconcileNetwork(ctx context.Context, claimUID types.UID) (fleetnetwork.Observation, error) { - return c.reconcileNetwork(ctx, ProjectIdentity{}, claimUID) -} - -func (c *Coordinator) ReconcileNetworkScoped(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (fleetnetwork.Observation, error) { - if !consumer.Valid() { - return fleetnetwork.Observation{}, ErrRecordInvalid - } - return c.reconcileNetwork(ctx, consumer, claimUID) -} - -func (c *Coordinator) reconcileNetwork(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (fleetnetwork.Observation, error) { - ctx = withUndecodableReporting(ctx) - if c.networks == nil || claimUID == "" { - return fleetnetwork.Observation{}, fleetnetwork.ErrAuthorizationUnavailable - } - records, err := c.recordsForClaimScoped(ctx, claimUID, consumer) - if err != nil || len(records) != 1 { - if err != nil { - return fleetnetwork.Observation{}, err - } - return fleetnetwork.Observation{}, ErrRecordInvalid - } - asset := records[0] - if asset.State != AssetCommitted || asset.Network == nil { - return fleetnetwork.Observation{}, ErrRecordInvalid - } - previous := asset.Network.Observation - previous.Lifecycle = append([]fleetnetwork.InterfaceLifecycleState(nil), asset.Network.Lifecycle...) - observation, ensureErr := c.networks.Ensure(ctx, fleetnetwork.EnsureRequest{ClaimUID: claimUID, BindingID: asset.BindingID, Plan: asset.Network.Plan, Previous: previous}) - if observation.Revision != "" || len(observation.Lifecycle) != 0 { - err = retry.RetryOnConflict(retry.DefaultRetry, func() error { - current, secret, getErr := c.getAsset(ctx, asset.AssetID) - if getErr != nil { - return getErr - } - if current.ClaimUID != claimUID || current.State != AssetCommitted || current.Network == nil || current.Network.Plan.RequestDigest != asset.Network.Plan.RequestDigest { - return ErrRecordInvalid - } - // An unsuccessful refresh is not evidence that the last verified - // allocation disappeared. Preserve a Programmed observation (and its - // addresses) while retaining any complete lifecycle progress needed - // for an exact retry. - if ensureErr == nil || !current.Network.Observation.Programmed(current.Network.Plan) { - current.Network.Observation = observation - } - if len(observation.Lifecycle) != 0 { - current.Network.Lifecycle = append([]fleetnetwork.InterfaceLifecycleState(nil), observation.Lifecycle...) - } - if err := validateNetworkRecord(current.Network); err != nil { - return err - } - if err := encodeRecord(secret, current, "asset"); err != nil { - return err - } - return c.client.Update(ctx, secret) - }) - if err != nil { - return observation, err - } - } - return observation, ensureErr -} - -func (c *Coordinator) authorityIDs() (string, string, error) { - binding, err := c.newID() - if err != nil { - return "", "", err - } - fence, err := c.newID() - if err != nil { - return "", "", err - } - return binding, fence, nil -} - -type ReleaseResult struct { - State AssetState - SafeToRemoveFinalizer bool - ExternalSettlementRequired bool -} - -func (c *Coordinator) Release(ctx context.Context, claimUID types.UID) (ReleaseResult, error) { - return c.release(ctx, ClaimScope{}, claimUID) -} - -func (c *Coordinator) ReleaseScoped(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (ReleaseResult, error) { - if !consumer.Valid() { - return ReleaseResult{}, ErrRecordInvalid - } - return c.release(ctx, ProjectClaimScope(consumer), claimUID) -} - -func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID types.UID) (ReleaseResult, error) { - ctx = withUndecodableReporting(ctx) - if claimUID == "" { - return ReleaseResult{}, errors.New("claim UID is required") - } - var custody *ClaimCustodyRecord - var err error - if scope.Valid() { - custody, _, err = c.getCustodyScoped(ctx, scope, claimUID) - } else { - custody, _, err = c.getCustody(ctx, claimUID) - } - if err != nil { - return ReleaseResult{}, fmt.Errorf("%w: claim custody is missing or invalid: %v", ErrRecordInvalid, err) - } - // Released custody is the terminal authority for this claim lifetime. The - // asset record may already belong to a later epoch and another claim by the - // time a conflicted finalizer update retries release. - if custody.State == CustodyReleased { - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - records, err := c.recordsForClaimScoped(ctx, claimUID, custody.ConsumerProject) - if err != nil { - return ReleaseResult{}, err - } - if len(records) == 0 { - if custody.State == CustodyReleased && custody.AssetID == "" { - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if custody.State == CustodySelecting && custody.AssetID != "" { - if err := c.materializeSelectionForRelease(ctx, custody); err != nil { - return ReleaseResult{}, err - } - updated, _, err := c.getCustodyScoped(ctx, custody.Scope, claimUID) - if err != nil { - return ReleaseResult{}, err - } - if updated.State == CustodyReleased { - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - return c.release(ctx, custody.Scope, claimUID) - } - if custody.State != CustodyUnbound || custody.AssetID != "" { - return ReleaseResult{}, fmt.Errorf("%w: bound custody has no asset authority", ErrRecordInvalid) - } - if custody.ExternalHold.Valid() { - return ReleaseResult{State: AssetCleanupVerified, ExternalSettlementRequired: true}, nil - } - if err := c.releaseCustody(ctx, claimUID, "", custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if len(records) != 1 { - return ReleaseResult{}, fmt.Errorf("%w: claim has duplicate asset records", ErrRecordInvalid) - } - record := records[0] - if custody.State == CustodyReleased && custody.AssetID == record.AssetID && record.State == AssetReleased { - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if custody.State == CustodySelecting && custody.AssetID == record.AssetID && record.State == AssetPreparing { - // Allocation may have crashed after the exclusive asset create but - // before custody was advanced. Adopt that exact preparation solely to - // release it; Preparing has admitted no provider effect. - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: record.ClaimNamespace, Name: record.ClaimName, UID: record.ClaimUID}} - if err := c.bindCustody(ctx, claim, record.AssetID, custody.Scope); err != nil { - return ReleaseResult{}, err - } - custody.State, custody.AssetID = CustodyBound, record.AssetID - } - if custody.State != CustodyBound || custody.AssetID != record.AssetID { - return ReleaseResult{}, fmt.Errorf("%w: custody and asset authority disagree", ErrRecordInvalid) - } - if record.ActiveOperationID != "" { - if err := c.settleActiveOperation(ctx, record); err != nil { - return ReleaseResult{State: record.State}, err - } - return c.release(ctx, custody.Scope, claimUID) - } - if record.State == AssetReleased { - if err := c.releaseCustody(ctx, claimUID, record.AssetID, custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if record.State == AssetCleanupVerified { - return ReleaseResult{State: AssetCleanupVerified, ExternalSettlementRequired: true}, nil - } - if record.State == AssetPreparing { - if operations, err := c.operationsForBinding(ctx, record.ClaimUID, record.BindingID); err != nil { - return ReleaseResult{}, err - } else if len(operations) != 0 { - return ReleaseResult{}, fmt.Errorf("%w: preparing binding has retained operations", ErrRecordInvalid) - } - target := AssetReleased - if record.ExternalHold.Valid() { - target = AssetCleanupVerified - } - if _, err := c.setAssetState(ctx, record.AssetID, claimUID, AssetPreparing, target); err != nil { - return ReleaseResult{}, err - } - if target == AssetCleanupVerified { - return ReleaseResult{State: target, ExternalSettlementRequired: true}, nil - } - if err := c.releaseCustody(ctx, claimUID, record.AssetID, custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if record.State == AssetCommitted { - record, err = c.setAssetState(ctx, record.AssetID, claimUID, AssetCommitted, AssetReleasing) - if err != nil { - return ReleaseResult{}, err - } - } - if record.State != AssetReleasing { - return ReleaseResult{}, fmt.Errorf("%w: unexpected release state %s", ErrRecordInvalid, record.State) - } - if record.Network != nil && record.Network.ReleaseRevision == "" { - if c.networks == nil { - return ReleaseResult{State: AssetReleasing}, fleetnetwork.ErrAuthorizationUnavailable - } - released, releaseErr := c.networks.Release(ctx, fleetnetwork.ReleaseRequest{ClaimUID: record.ClaimUID, BindingID: record.BindingID, Plan: record.Network.Plan, Observation: record.Network.Observation, Lifecycle: record.Network.Lifecycle}) - if len(released.Lifecycle) != 0 || released.Verified { - if err := c.retainNetworkRelease(ctx, record.AssetID, record.ClaimUID, released); err != nil { - return ReleaseResult{State: AssetReleasing}, err - } - record, _, err = c.getAsset(ctx, record.AssetID) - if err != nil { - return ReleaseResult{State: AssetReleasing}, err - } - } - if releaseErr != nil { - return ReleaseResult{State: AssetReleasing}, releaseErr - } - if !released.Verified { - return ReleaseResult{State: AssetReleasing}, fleetnetwork.ErrPending - } - } - request := simulator.Request{ID: "cleanup-" + record.BindingID, Kind: "cleanup", AssetID: record.AssetID, BindingID: record.BindingID, Epoch: record.Epoch, FenceToken: record.FenceToken} - if _, err := c.executeAndRecover(ctx, request); err != nil { - return ReleaseResult{State: AssetReleasing}, err - } - target := AssetReleased - if record.ExternalHold.Valid() { - target = AssetCleanupVerified - } - if _, err := c.setAssetState(ctx, record.AssetID, claimUID, AssetReleasing, target); err != nil { - return ReleaseResult{}, err - } - if target == AssetCleanupVerified { - return ReleaseResult{State: target, ExternalSettlementRequired: true}, nil - } - if err := c.releaseCustody(ctx, claimUID, record.AssetID, custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil -} - -// CompleteExternalRelease consumes an exact external settlement acknowledgment. -// Object absence is not an acknowledgment and this method never queries the -// external owner; callers must supply the retained authority and hold identities. -func (c *Coordinator) CompleteExternalRelease(ctx context.Context, claimUID types.UID, authority AuthorityRef, hold ExternalHoldRef, project ...ProjectIdentity) (ReleaseResult, error) { - ctx = withUndecodableReporting(ctx) - if claimUID == "" || !authority.Valid() || !hold.Valid() { - return ReleaseResult{}, ErrRecordInvalid - } - var custody *ClaimCustodyRecord - var err error - if len(project) == 1 && project[0].Valid() { - custody, _, err = c.getCustodyScoped(ctx, ProjectClaimScope(project[0]), claimUID) - } else if len(project) == 0 { - custody, _, err = c.getCustody(ctx, claimUID) - } else { - return ReleaseResult{}, ErrRecordInvalid - } - if err != nil || custody.Authority != authority || custody.ExternalHold != hold { - return ReleaseResult{}, ErrRecordInvalid - } - records, err := c.recordsForClaimScoped(ctx, claimUID, custody.ConsumerProject) - if err != nil { - return ReleaseResult{}, err - } - if len(records) == 0 { - if custody.State != CustodyUnbound || custody.AssetID != "" { - return ReleaseResult{}, ErrRecordInvalid - } - if err := c.releaseCustody(ctx, claimUID, "", custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil - } - if len(records) != 1 || records[0].State != AssetCleanupVerified || records[0].Authority != authority || records[0].ExternalHold != hold { - return ReleaseResult{}, ErrRecordInvalid - } - if _, err := c.setAssetState(ctx, records[0].AssetID, claimUID, AssetCleanupVerified, AssetReleased); err != nil { - return ReleaseResult{}, err - } - if err := c.releaseCustody(ctx, claimUID, records[0].AssetID, custody.Scope); err != nil { - return ReleaseResult{}, err - } - return ReleaseResult{State: AssetReleased, SafeToRemoveFinalizer: true}, nil -} - -func (c *Coordinator) retainNetworkRelease(ctx context.Context, assetID string, claimUID types.UID, released fleetnetwork.ReleaseObservation) error { - return retry.RetryOnConflict(retry.DefaultRetry, func() error { - record, secret, err := c.getAsset(ctx, assetID) - if err != nil { - return err - } - if record.ClaimUID != claimUID || record.State != AssetReleasing || record.Network == nil { - return ErrRecordInvalid - } - if len(released.Lifecycle) != 0 { - record.Network.Lifecycle = append([]fleetnetwork.InterfaceLifecycleState(nil), released.Lifecycle...) - } - if released.Verified { - if released.Revision == "" { - return ErrRecordInvalid - } - record.Network.ReleaseRevision = released.Revision - } - if err := validateNetworkRecord(record.Network); err != nil { - return err - } - if err := encodeRecord(secret, record, "asset"); err != nil { - return err - } - return c.client.Update(ctx, secret) - }) -} - -func (c *Coordinator) settleActiveOperation(ctx context.Context, asset *AssetRecord) error { - operations, err := c.operationsForBinding(ctx, asset.ClaimUID, asset.BindingID) - if err != nil { - return err - } - var operation *InstallationRecord - for _, candidate := range operations { - if candidate.OperationID == asset.ActiveOperationID { - if operation != nil { - return ErrRecordInvalid - } - operation = candidate - } - } - if operation == nil { - return ErrOperationActive - } - request := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} - if operation.State == OperationAdmitted { - if _, err := c.executeAndRecover(ctx, request); err != nil { - return err - } - operation, err = c.markOperationSucceeded(ctx, operationRecordName(operation.ClaimScope, operation.ClaimUID, operation.Predecessor), operation) - if err != nil { - return err - } - } - return c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation) -} - -type InstallationRequest struct { - Claim *fleetv1.Machine - Installation *fleetv1.Installation - NamespaceUID types.UID - ClaimScope ClaimScope - ConsumerProject ProjectIdentity - Admission InstallationAdmissionAuthority -} - -func installationClaimScope(request InstallationRequest) (ClaimScope, error) { - want := LocalClaimScope(request.NamespaceUID) - if request.ConsumerProject.Valid() { - want = ProjectClaimScope(request.ConsumerProject) - } - if request.ClaimScope.Valid() && request.ClaimScope != want { - return ClaimScope{}, ErrRecordInvalid - } - return want, nil -} - -type InstallationResult struct { - Revision string - Record InstallationRecord - RequestDigest string -} - -func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) (InstallationResult, error) { - ctx = withUndecodableReporting(ctx) - if request.Claim == nil || request.Installation == nil || request.Claim.UID == "" || request.Installation.UID == "" || request.NamespaceUID == "" || !request.Admission.valid() { - return InstallationResult{}, errors.New("claim, installation, and namespace lifetime identities are required") - } - if request.Installation.Namespace != request.Claim.Namespace || request.Installation.Spec.MachineRef.Name != request.Claim.Name { - return InstallationResult{}, errors.New("installation does not target the supplied claim lifetime") - } - if request.Claim.DeletionTimestamp != nil || !contains(request.Claim.Finalizers, MachineFinalizer) { - return InstallationResult{}, errors.New("claim must be live and carry the Fleet finalizer before installation admission") - } - if request.Installation.Spec.BootstrapConfigRef != nil { - return InstallationResult{}, fmt.Errorf("%w: bootstrap retention and authorization are not implemented", ErrUnsupported) - } - predecessor, err := predecessorValue(request.Installation.Spec.ExpectedPredecessor) - if err != nil { - return InstallationResult{}, err - } - scope, err := installationClaimScope(request) - if err != nil { - return InstallationResult{}, err - } - assets, err := c.recordsForClaimScoped(ctx, request.Claim.UID, request.ConsumerProject) - if err != nil { - return InstallationResult{}, err - } - if len(assets) != 1 { - return InstallationResult{}, fmt.Errorf("%w: claim does not have one retained asset", ErrRecordInvalid) - } - asset := assets[0] - if asset.State != AssetCommitted || asset.ClaimNamespace != request.Claim.Namespace || asset.ClaimName != request.Claim.Name || asset.ClaimUID != request.Claim.UID || asset.ClaimScope != scope || asset.ConsumerProject != request.ConsumerProject { - return InstallationResult{}, ErrPredecessorConflict - } - custody, _, err := c.getCustodyScoped(ctx, scope, request.Claim.UID) - if err != nil || custody.State != CustodyBound || custody.AssetID != asset.AssetID || custody.ClaimNamespace != request.Claim.Namespace || custody.ClaimName != request.Claim.Name || custody.ClaimUID != request.Claim.UID || custody.Scope != scope || custody.NamespaceUID != request.NamespaceUID || custody.Admission.PrincipalUID != request.Admission.PrincipalUID || custody.ConsumerProject != asset.ConsumerProject || custody.ProviderProject != asset.ProviderProject || custody.Authority != asset.Authority || custody.ExternalHold != asset.ExternalHold { - return InstallationResult{}, ErrRecordInvalid - } - operationName := operationRecordName(scope, request.Claim.UID, predecessor) - operation, _, err := c.getOperation(ctx, operationName) - if apierrors.IsNotFound(err) { - if asset.Network != nil && (!asset.Network.Observation.Prepared(asset.Network.Plan) || asset.Network.Observation.ObservedAt.After(c.now()) || c.now().Sub(asset.Network.Observation.ObservedAt) > c.maxEvidenceAge) { - return InstallationResult{}, fleetnetwork.ErrEvidenceStale - } - image, resolveErr := c.images.ResolveImage(ctx, ImageRequest{NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, InstallationUID: request.Installation.UID, ImageName: request.Installation.Spec.ImageRef.Name}) - if resolveErr != nil { - return InstallationResult{}, resolveErr - } - if err := image.Validate(); err != nil { - return InstallationResult{}, err - } - if image.CatalogAuthority != request.Admission.CatalogAuthority || image.CatalogRevision != request.Admission.CatalogRevision || image.ImageDecisionID != request.Admission.ImageDecisionID { - return InstallationResult{}, ErrRecordInvalid - } - operation, _, err = c.getOrCreateOperation(ctx, operationName, request, asset, predecessor, image) - } - if err != nil { - return InstallationResult{}, err - } - if operation.InstallationNamespace != request.Installation.Namespace || operation.InstallationName != request.Installation.Name || operation.InstallationUID != request.Installation.UID || operation.NamespaceUID != request.NamespaceUID || operation.ClaimNamespace != request.Claim.Namespace || operation.ClaimName != request.Claim.Name || operation.ClaimUID != request.Claim.UID || operation.ClaimScope != scope || operation.ConsumerProject != request.ConsumerProject || operation.AssetID != asset.AssetID || operation.BindingID != asset.BindingID || operation.Epoch != asset.Epoch || operation.Predecessor != predecessor || operation.ImageName != request.Installation.Spec.ImageRef.Name || operation.Admission != request.Admission { - return InstallationResult{}, ErrPredecessorConflict - } - execRequest := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} - requestDigest, err := simulator.RequestDigest(execRequest) - if err != nil { - return InstallationResult{}, err - } - if operation.State == OperationSucceeded { - if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { - return InstallationResult{}, err - } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil - } - if asset.CurrentInstallationName != predecessor || (asset.ActiveOperationID != "" && asset.ActiveOperationID != operation.OperationID) { - return InstallationResult{}, ErrPredecessorConflict - } - if err := c.activateOperation(ctx, asset.AssetID, asset.ClaimUID, predecessor, operation.OperationID); err != nil { - return InstallationResult{}, err - } - if _, err := c.executeAndRecover(ctx, execRequest); err != nil { - return InstallationResult{}, err - } - operation, err = c.markOperationSucceeded(ctx, operationName, operation) - if err != nil { - return InstallationResult{}, err - } - if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { - return InstallationResult{}, err - } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil -} - -func predecessorValue(value fleetv1.InstallationPredecessor) (string, error) { - switch value.Type { - case "None": - if value.Name == "" { - return "None", nil - } - case "Installation": - if value.Name != "" { - return value.Name, nil - } - } - return "", errors.New("expectedPredecessor must be None without a name or Installation with a nonempty name") -} - -func sameNetworkInputs(inputs *fleetnetwork.Observation, record *NetworkRecord) bool { - if inputs == nil || record == nil { - return inputs == nil && record == nil - } - left, _ := json.Marshal(inputs) - right, _ := json.Marshal(record.Observation) - return string(left) == string(right) -} - -func installationInputs(operation *InstallationRecord) json.RawMessage { - type interfaceInput struct { - Name string `json:"name"` - MTU int32 `json:"mtu,omitempty"` - Addresses []fleetnetwork.Address `json:"addresses,omitempty"` - } - type networkInput struct { - Revision string `json:"revision"` - Interfaces []interfaceInput `json:"interfaces"` - } - value := struct { - Image string `json:"image"` - Network *networkInput `json:"network,omitempty"` - }{Image: operation.Image.Reference()} - if operation.NetworkInputs != nil { - value.Network = &networkInput{Revision: operation.NetworkInputs.Revision} - for _, iface := range operation.NetworkInputs.Interfaces { - value.Network.Interfaces = append(value.Network.Interfaces, interfaceInput{Name: iface.Name, MTU: iface.MTU, Addresses: append([]fleetnetwork.Address(nil), iface.Addresses...)}) - } - } - b, _ := json.Marshal(value) - return b -} - -func (c *Coordinator) getOrCreateOperation(ctx context.Context, name string, request InstallationRequest, asset *AssetRecord, predecessor string, image ResolvedImage) (*InstallationRecord, *corev1.Secret, error) { - var secret corev1.Secret - err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) - if err == nil { - record, decodeErr := decodeOperationSecret(ctx, &secret) - return record, &secret, decodeErr - } - if !apierrors.IsNotFound(err) { - return nil, nil, err - } - operationID, err := c.newID() - if err != nil { - return nil, nil, err - } - revisionID, err := c.newID() - if err != nil { - return nil, nil, err - } - scope, scopeErr := installationClaimScope(request) - if scopeErr != nil { - return nil, nil, scopeErr - } - record := &InstallationRecord{SchemaVersion: installationRecordSchemaVersion, State: OperationAdmitted, OperationID: "install-" + operationID, InstallationNamespace: request.Installation.Namespace, InstallationName: request.Installation.Name, InstallationUID: request.Installation.UID, NamespaceUID: request.NamespaceUID, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, ClaimScope: scope, ConsumerProject: request.ConsumerProject, AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, Predecessor: predecessor, ResultRevision: "ir-" + revisionID, Image: image, ImageName: request.Installation.Spec.ImageRef.Name, Admission: request.Admission} - if asset.Network != nil { - inputs := asset.Network.Observation - record.NetworkInputs = &inputs - } - secret = corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: c.namespace}} - if err := encodeRecord(&secret, record, "installation"); err != nil { - return nil, nil, err - } - if err := c.client.Create(ctx, &secret); apierrors.IsAlreadyExists(err) { - return c.getOrCreateOperation(ctx, name, request, asset, predecessor, image) - } else if err != nil { - return nil, nil, err - } - return record, &secret, nil -} - -func (c *Coordinator) getOperation(ctx context.Context, name string) (*InstallationRecord, *corev1.Secret, error) { - var secret corev1.Secret - if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret); err != nil { - return nil, nil, err - } - record, err := decodeOperationSecret(ctx, &secret) - return record, &secret, err -} - -func (c *Coordinator) activateOperation(ctx context.Context, assetID string, claimUID types.UID, predecessor, operationID string) error { - record, secret, err := c.getAsset(ctx, assetID) - if err != nil { - return err - } - if record.ClaimUID != claimUID || record.State != AssetCommitted || record.CurrentInstallationName != predecessor { - return ErrPredecessorConflict - } - if record.ActiveOperationID != "" && record.ActiveOperationID != operationID { - return ErrOperationActive - } - record.ActiveOperationID = operationID - if err := encodeRecord(secret, record, "asset"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -func (c *Coordinator) publishInstalledName(ctx context.Context, assetID string, claimUID types.UID, operation *InstallationRecord) error { - record, secret, err := c.getAsset(ctx, assetID) - if err != nil { - return err - } - if record.ClaimUID != claimUID || record.State != AssetCommitted { - return ErrPredecessorConflict - } - if record.CurrentInstallationName == operation.InstallationName && record.ActiveOperationID == "" { - return nil - } - if record.CurrentInstallationName != operation.Predecessor || record.ActiveOperationID != operation.OperationID { - return ErrPredecessorConflict - } - record.CurrentInstallationName = operation.InstallationName - record.ActiveOperationID = "" - if err := encodeRecord(secret, record, "asset"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -func (c *Coordinator) markOperationSucceeded(ctx context.Context, name string, expected *InstallationRecord) (*InstallationRecord, error) { - var secret corev1.Secret - if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret); err != nil { - return nil, err - } - record, err := decodeOperationSecret(ctx, &secret) - if err != nil { - return nil, err - } - if record.OperationID != expected.OperationID || record.InstallationUID != expected.InstallationUID { - return nil, ErrRecordInvalid - } - if record.State == OperationSucceeded { - return record, nil - } - record.State = OperationSucceeded - if err := encodeRecord(&secret, record, "installation"); err != nil { - return nil, err - } - if err := c.client.Update(ctx, &secret); err != nil { - return nil, err - } - return record, nil -} - -func (c *Coordinator) executeAndRecover(ctx context.Context, request simulator.Request) (simulator.OperationResult, error) { - result, err := c.executor.Execute(ctx, request) - if err == nil { - return result, validateTerminalResult(request, result) - } - if !errors.Is(err, executor.ErrOutcomeUnknown) { - return simulator.OperationResult{}, err - } - retained, found, lookupErr := c.executor.Lookup(ctx, request.ID) - if lookupErr != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: lookup failed: %v", executor.ErrOutcomeUnknown, lookupErr) - } - if !found { - return simulator.OperationResult{}, err - } - if validateTerminalResult(request, retained) != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: retained result does not match request", executor.ErrOutcomeUnknown) - } - return retained, nil -} - -func validateTerminalResult(request simulator.Request, result simulator.OperationResult) error { - digest, err := simulator.RequestDigest(request) - if err != nil || result.InputDigest != digest { - return fmt.Errorf("%w: executor evidence does not bind the exact request", executor.ErrOutcomeUnknown) - } - if result.ID != request.ID || result.Kind != request.Kind || result.Phase != "Succeeded" || result.CompletedAt == nil { - return fmt.Errorf("%w: executor result is not the correlated terminal operation", executor.ErrOutcomeUnknown) - } - want := map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind] - if want != "" && result.Result != want { - return fmt.Errorf("%w: %s result lacks %q evidence", executor.ErrOutcomeUnknown, request.Kind, want) - } - return nil -} - -func (c *Coordinator) setAssetState(ctx context.Context, assetID string, claimUID types.UID, from, to AssetState) (*AssetRecord, error) { - record, secret, err := c.getAsset(ctx, assetID) - if err != nil { - return nil, err - } - if record.ClaimUID != claimUID || record.State != from || record.ActiveOperationID != "" { - return nil, fmt.Errorf("%w: asset transition %s to %s rejected", ErrRecordInvalid, record.State, to) - } - record.State = to - if err := encodeRecord(secret, record, "asset"); err != nil { - return nil, err - } - if err := c.client.Update(ctx, secret); err != nil { - return nil, err - } - return record, nil -} - -func (c *Coordinator) getAsset(ctx context.Context, assetID string) (*AssetRecord, *corev1.Secret, error) { - var secret corev1.Secret - if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: assetRecordName(assetID)}, &secret); err != nil { - return nil, nil, err - } - record, err := decodeAssetSecret(ctx, &secret) - return record, &secret, err -} - -func (c *Coordinator) getCustody(ctx context.Context, claimUID types.UID) (*ClaimCustodyRecord, *corev1.Secret, error) { - var list corev1.SecretList - if err := c.client.List(ctx, &list, client.InNamespace(c.namespace), client.MatchingLabels{recordTypeLabel: "custody", claimUIDLabel: string(claimUID)}); err != nil { - return nil, nil, err - } - if len(list.Items) != 1 { - return nil, nil, ErrRecordInvalid - } - record, err := decodeCustodySecret(ctx, &list.Items[0]) - return record, &list.Items[0], err -} - -func (c *Coordinator) getCustodyScoped(ctx context.Context, scope ClaimScope, claimUID types.UID) (*ClaimCustodyRecord, *corev1.Secret, error) { - if !scope.Valid() || claimUID == "" { - return nil, nil, ErrRecordInvalid - } - var secret corev1.Secret - if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: custodyRecordName(scope, claimUID)}, &secret); err != nil { - return nil, nil, err - } - record, err := decodeCustodySecret(ctx, &secret) - return record, &secret, err -} - -// HasClaimCustody reports whether the exact project-scoped claim lifetime has -// any retained custody record. It is used only to distinguish a genuinely -// never-admitted claim from authority-record loss; a present record never -// authorizes cleanup bypass. -func (c *Coordinator) HasClaimCustody(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (bool, error) { - if !consumer.Valid() || claimUID == "" { - return false, ErrRecordInvalid - } - _, _, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) - if apierrors.IsNotFound(err) { - return false, nil - } - if err != nil { - return false, err - } - return true, nil -} - -// ClaimReleased reads terminal custody for the exact project and claim lifetime. -// Callers use this to avoid restoring protection after verified release; public -// status is not authority for this decision. Missing or corrupt custody fails. -func (c *Coordinator) ClaimReleased(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (bool, error) { - if !consumer.Valid() || claimUID == "" { - return false, ErrRecordInvalid - } - record, _, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) - if err != nil { - return false, err - } - return record.State == CustodyReleased, nil -} - -func (c *Coordinator) getCustodyForAsset(ctx context.Context, asset *AssetRecord) (*ClaimCustodyRecord, *corev1.Secret, error) { - return c.getCustodyScoped(ctx, asset.ClaimScope, asset.ClaimUID) -} - -func (c *Coordinator) bindCustody(ctx context.Context, claim *fleetv1.Machine, assetID string, scopes ...ClaimScope) error { - var record *ClaimCustodyRecord - var secret *corev1.Secret - var err error - if len(scopes) == 1 { - record, secret, err = c.getCustodyScoped(ctx, scopes[0], claim.UID) - } else { - record, secret, err = c.getCustody(ctx, claim.UID) - } - if err != nil { - return err - } - if record.ClaimNamespace != claim.Namespace || record.ClaimName != claim.Name { - return ErrRecordInvalid - } - if record.State == CustodyBound && record.AssetID == assetID { - return nil - } - if record.State != CustodySelecting || record.AssetID != assetID { - return ErrRecordInvalid - } - record.State, record.AssetID = CustodyBound, assetID - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -func (c *Coordinator) selectCustody(ctx context.Context, request AllocationRequest, proposal *AssetRecord) error { - claim := request.Claim - if proposal == nil || proposal.ClaimUID != claim.UID || validateAssetRecord(proposal) != nil { - return ErrRecordInvalid - } - record, secret, err := c.getCustodyScoped(ctx, allocationClaimScope(request), claim.UID) - if err != nil { - return err - } - if record.State == CustodySelecting && record.AssetID == proposal.AssetID && sameRecord(record.ProposedAsset, proposal) { - return nil - } - if record.State != CustodyUnbound || record.AssetID != "" { - return ErrRecordInvalid - } - record.State, record.AssetID, record.ProposedAsset = CustodySelecting, proposal.AssetID, proposal - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -// materializeSelectionForRelease settles a claim that is releasing while its -// custody still only proposes an asset. If the proposed asset's record already -// belongs to another claim, this claim never held the asset, so custody is -// released without touching that record. A record that cannot be decoded is -// attributed by its claim-uid label, as in unreadableCandidate: one labeled -// for another claim is that claim's binding, so release proceeds the same way -// and leaves the record, and the epoch it fences, unchanged. One labeled for -// this claim, or with no label, may be this claim's binding at an unknown -// state, so release fails closed and keeps the finalizer. -func (c *Coordinator) materializeSelectionForRelease(ctx context.Context, custody *ClaimCustodyRecord) error { - if custody.ProposedAsset == nil || custody.ProposedAsset.AssetID != custody.AssetID || custody.ProposedAsset.ClaimUID != custody.ClaimUID { - return ErrRecordInvalid - } - proposal := custody.ProposedAsset - var secret corev1.Secret - err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: assetRecordName(proposal.AssetID)}, &secret) - if err == nil { - existing, err := decodeAssetSecret(ctx, &secret) - if err != nil { - if recordMayBelongTo(&secret, custody.ClaimUID) { - return err - } - return c.releaseCustody(ctx, custody.ClaimUID, custody.AssetID, custody.Scope) - } - if existing.ClaimUID != custody.ClaimUID { - return c.releaseCustody(ctx, custody.ClaimUID, custody.AssetID, custody.Scope) - } - if !sameRecord(existing, proposal) { - return ErrRecordInvalid - } - return nil - } - if !apierrors.IsNotFound(err) { - return err - } - secret = corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: assetRecordName(proposal.AssetID), Namespace: c.namespace}} - if err := encodeRecord(&secret, proposal, "asset"); err != nil { - return err - } - if err := c.client.Create(ctx, &secret); apierrors.IsAlreadyExists(err) { - return c.materializeSelectionForRelease(ctx, custody) - } else { - return err - } -} - -func (c *Coordinator) clearSelection(ctx context.Context, claimUID types.UID, assetID string, scopes ...ClaimScope) error { - var record *ClaimCustodyRecord - var secret *corev1.Secret - var err error - if len(scopes) == 1 { - record, secret, err = c.getCustodyScoped(ctx, scopes[0], claimUID) - } else { - record, secret, err = c.getCustody(ctx, claimUID) - } - if err != nil { - return err - } - records, err := c.recordsForClaimScoped(ctx, claimUID, record.ConsumerProject) - if err != nil { - return err - } - if len(records) != 0 { - return fmt.Errorf("%w: cannot clear selection with retained asset authority", ErrRecordInvalid) - } - if record.State != CustodySelecting || record.AssetID != assetID { - return ErrRecordInvalid - } - record.State, record.AssetID = CustodyUnbound, "" - record.ProposedAsset = nil - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -func (c *Coordinator) releaseCustody(ctx context.Context, claimUID types.UID, assetID string, scopes ...ClaimScope) error { - var record *ClaimCustodyRecord - var secret *corev1.Secret - var err error - if len(scopes) == 1 { - record, secret, err = c.getCustodyScoped(ctx, scopes[0], claimUID) - } else { - record, secret, err = c.getCustody(ctx, claimUID) - } - if err != nil { - return err - } - if record.State == CustodyReleased { - if record.AssetID != assetID { - return ErrRecordInvalid - } - return nil - } - if assetID == "" { - if record.State != CustodyUnbound || record.AssetID != "" { - return ErrRecordInvalid - } - } else if (record.State != CustodyBound && record.State != CustodySelecting) || record.AssetID != assetID { - return ErrRecordInvalid - } - record.State = CustodyReleased - if err := encodeRecord(secret, record, "custody"); err != nil { - return err - } - return c.client.Update(ctx, secret) -} - -func (c *Coordinator) recordsForClaim(ctx context.Context, claimUID types.UID) ([]*AssetRecord, error) { - return c.recordsForClaimScoped(ctx, claimUID, ProjectIdentity{}) -} - -// recordsForClaimScoped returns the asset records of one claim. A record that -// cannot be decoded blocks only the claim it is attributed to (see -// recordMayBelongTo); for every other claim it is reported and skipped. A -// skipped record still fences its asset, because allocation reads an asset's -// record by name and never proposes an asset whose record cannot be decoded. -func (c *Coordinator) recordsForClaimScoped(ctx context.Context, claimUID types.UID, consumer ProjectIdentity) ([]*AssetRecord, error) { - var list corev1.SecretList - if err := c.client.List(ctx, &list, client.InNamespace(c.namespace)); err != nil { - return nil, err - } - var records []*AssetRecord - for i := range list.Items { - secret := &list.Items[i] - if !strings.HasPrefix(secret.Name, assetRecordPrefix) { - continue - } - record, err := decodeAssetSecret(ctx, secret) - if err != nil { - if recordMayBelongTo(secret, claimUID) { - return nil, err - } - continue - } - if record.ClaimUID == claimUID && (consumer.Valid() && record.ConsumerProject == consumer || !consumer.Valid() && !record.ConsumerProject.Valid()) { - records = append(records, record) - } - } - return records, nil -} - -// operationsForBinding returns the installation records of one binding. A -// binding belongs to exactly one claim, so an undecodable record attributed to -// another claim cannot be one of its operations and is reported and skipped. -// One attributed to claimUID, or to no claim, fails the scan closed. -func (c *Coordinator) operationsForBinding(ctx context.Context, claimUID types.UID, bindingID string) ([]*InstallationRecord, error) { - var list corev1.SecretList - if err := c.client.List(ctx, &list, client.InNamespace(c.namespace)); err != nil { - return nil, err - } - var records []*InstallationRecord - for i := range list.Items { - secret := &list.Items[i] - if !strings.HasPrefix(secret.Name, operationPrefix) { - continue - } - record, err := decodeOperationSecret(ctx, secret) - if err != nil { - if recordMayBelongTo(secret, claimUID) { - return nil, err - } - continue - } - if record.BindingID == bindingID { - records = append(records, record) - } - } - return records, nil -} - -func encodeRecord(secret *corev1.Secret, value any, recordType string) error { - b, err := json.Marshal(value) - if err != nil { - return err - } - if secret.Labels == nil { - secret.Labels = map[string]string{} - } - secret.Type = corev1.SecretType("fleet.datumapis.com/private-lifecycle") - secret.Labels[recordTypeLabel] = recordType - secret.Data = map[string][]byte{recordDataKey: b} - switch record := value.(type) { - case *AssetRecord: - secret.Labels[claimUIDLabel] = string(record.ClaimUID) - case *InstallationRecord: - secret.Labels[claimUIDLabel] = string(record.ClaimUID) - case *ClaimCustodyRecord: - secret.Labels[claimUIDLabel] = string(record.ClaimUID) - } - return nil -} - -func parseCustodySecret(secret *corev1.Secret) (*ClaimCustodyRecord, error) { - var record ClaimCustodyRecord - if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "custody" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateCustodyRecord(&record) != nil || secret.Name != custodyRecordName(record.Scope, record.ClaimUID) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: custody secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) - } - return &record, nil -} - -func validateCustodyRecord(r *ClaimCustodyRecord) error { - if r.SchemaVersion != recordSchemaVersion || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || r.NamespaceUID == "" || !r.Scope.Valid() || !r.Admission.valid() { - return ErrRecordInvalid - } - projectAuthority := r.ConsumerProject.Valid() || r.ProviderProject.Valid() || r.Authority.Valid() || r.ExternalHold.Valid() - if projectAuthority && (!r.ConsumerProject.Valid() || !r.ProviderProject.Valid() || !r.Authority.Valid()) { - return ErrRecordInvalid - } - if r.ConsumerProject.Valid() && r.Scope != ProjectClaimScope(r.ConsumerProject) { - return ErrRecordInvalid - } - switch r.State { - case CustodyUnbound: - if r.AssetID != "" || r.ProposedAsset != nil { - return ErrRecordInvalid - } - case CustodySelecting, CustodyBound, CustodyReleased: - // Released may have no asset only for a claim proven never bound. - if (r.State == CustodySelecting || r.State == CustodyBound) && r.AssetID == "" { - return ErrRecordInvalid - } - if r.State == CustodySelecting && (r.ProposedAsset == nil || r.ProposedAsset.AssetID != r.AssetID || r.ProposedAsset.ClaimUID != r.ClaimUID || validateAssetRecord(r.ProposedAsset) != nil) { - return ErrRecordInvalid - } - default: - return ErrRecordInvalid - } - return nil -} - -func parseAssetSecret(secret *corev1.Secret) (*AssetRecord, error) { - var record AssetRecord - if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "asset" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateAssetRecord(&record) != nil || secret.Name != assetRecordName(record.AssetID) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: asset secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) - } - return &record, nil -} - -func parseOperationSecret(secret *corev1.Secret) (*InstallationRecord, error) { - var record InstallationRecord - if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "installation" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateInstallationRecord(&record) != nil || secret.Name != operationRecordName(record.ClaimScope, record.ClaimUID, record.Predecessor) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: installation secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) - } - return &record, nil -} - -// PrivateRecordRoute is the minimal routing identity exposed by the lifecycle -// record owner after the complete persisted record and deterministic Secret -// identity have been validated. -type PrivateRecordRoute struct { - RecordType string - ClaimNamespace string - ClaimName string - ClaimUID types.UID - InstallationNamespace string - InstallationName string - InstallationUID types.UID - ConsumerProject ProjectIdentity - NamespaceUIDs []types.UID - MachineUIDs []types.UID - NetworkUIDs []types.UID - NICClaimUIDs []types.UID - InterfaceUIDs []types.UID - AuthorityRecordIDs []string - QuotaUIDs []types.UID - EntitlementUIDs []types.UID - PendingEntitlement bool -} - -func DecodePrivateLifecycleRoute(secret *corev1.Secret) (PrivateRecordRoute, error) { - if secret == nil || secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") { - return PrivateRecordRoute{}, ErrRecordInvalid - } - switch secret.Labels[recordTypeLabel] { - case "custody": - record, err := parseCustodySecret(secret) - if err != nil { - return PrivateRecordRoute{}, err - } - route := PrivateRecordRoute{RecordType: "custody", ClaimNamespace: record.ClaimNamespace, ClaimName: record.ClaimName, ClaimUID: record.ClaimUID, ConsumerProject: record.ConsumerProject, NamespaceUIDs: []types.UID{record.NamespaceUID}} - appendAuthorityIndexes(&route, record.Authority, record.ExternalHold) - if record.ProposedAsset != nil { - appendAssetIndexes(&route, record.ProposedAsset) - } - return route, nil - case "asset": - record, err := parseAssetSecret(secret) - if err != nil { - return PrivateRecordRoute{}, err - } - route := PrivateRecordRoute{RecordType: "asset", ClaimNamespace: record.ClaimNamespace, ClaimName: record.ClaimName, ClaimUID: record.ClaimUID, ConsumerProject: record.ConsumerProject} - appendAssetIndexes(&route, record) - return route, nil - case "installation": - record, err := parseOperationSecret(secret) - if err != nil { - return PrivateRecordRoute{}, err - } - route := PrivateRecordRoute{RecordType: "installation", ClaimNamespace: record.ClaimNamespace, ClaimName: record.ClaimName, ClaimUID: record.ClaimUID, InstallationNamespace: record.InstallationNamespace, InstallationName: record.InstallationName, InstallationUID: record.InstallationUID, ConsumerProject: record.ConsumerProject, NamespaceUIDs: []types.UID{record.NamespaceUID}} - if record.NetworkInputs != nil { - appendObservationIndexes(&route, *record.NetworkInputs) - } - return route, nil - default: - return PrivateRecordRoute{}, ErrRecordInvalid - } -} - -func appendAuthorityIndexes(route *PrivateRecordRoute, authority AuthorityRef, hold ExternalHoldRef) { - if authority.Valid() { - route.AuthorityRecordIDs = append(route.AuthorityRecordIDs, authority.RecordID) - } - if hold.Valid() { - route.QuotaUIDs = append(route.QuotaUIDs, hold.UID) - } -} - -func appendAssetIndexes(route *PrivateRecordRoute, record *AssetRecord) { - route.MachineUIDs = append(route.MachineUIDs, record.MachineUID) - appendAuthorityIndexes(route, record.Authority, record.ExternalHold) - if record.Network == nil { - return - } - for _, iface := range record.Network.Plan.Interfaces { - route.NetworkUIDs = append(route.NetworkUIDs, iface.NetworkUID) - } - appendObservationIndexes(route, record.Network.Observation) - for _, state := range record.Network.Lifecycle { - if state.CreatedUID != "" { - route.NICClaimUIDs = append(route.NICClaimUIDs, state.CreatedUID) - } - if state.RetainedInterfaceUID != "" { - route.InterfaceUIDs = append(route.InterfaceUIDs, state.RetainedInterfaceUID) - } - } -} - -func appendObservationIndexes(route *PrivateRecordRoute, observation fleetnetwork.Observation) { - for _, iface := range observation.Interfaces { - if iface.ClaimUID != "" { - route.NICClaimUIDs = append(route.NICClaimUIDs, iface.ClaimUID) - } - if iface.NetworkInterfaceUID != "" { - route.InterfaceUIDs = append(route.InterfaceUIDs, iface.NetworkInterfaceUID) - } - } -} - -func validateAssetRecord(r *AssetRecord) error { - if r.SchemaVersion != recordSchemaVersion || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { - return ErrRecordInvalid - } - projectAuthority := r.ConsumerProject.Valid() || r.ProviderProject.Valid() || r.Authority.Valid() || r.ExternalHold.Valid() - if projectAuthority && (!r.ConsumerProject.Valid() || !r.ProviderProject.Valid() || !r.Authority.Valid() || !r.ExternalHold.Valid()) { - return ErrRecordInvalid - } - if r.ConsumerProject.Valid() && r.ClaimScope != ProjectClaimScope(r.ConsumerProject) { - return ErrRecordInvalid - } - switch r.State { - case AssetPreparing, AssetCommitted, AssetReleasing, AssetCleanupVerified, AssetReleased: - default: - return ErrRecordInvalid - } - if (r.State == AssetPreparing || r.State == AssetReleasing || r.State == AssetCleanupVerified || r.State == AssetReleased) && r.ActiveOperationID != "" { - return ErrRecordInvalid - } - if validateNetworkRecord(r.Network) != nil { - return ErrRecordInvalid - } - if r.Network != nil && r.State == AssetReleased && r.Network.ReleaseRevision == "" && (r.Network.Observation.Revision != "" || len(r.Network.Lifecycle) != 0) { - return ErrRecordInvalid - } - return nil -} - -func validateInstallationRecord(r *InstallationRecord) error { - if r.SchemaVersion != installationRecordSchemaVersion || !strings.HasPrefix(r.OperationID, "install-") || r.InstallationNamespace == "" || r.InstallationName == "" || r.InstallationUID == "" || r.NamespaceUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.AssetID == "" || r.BindingID == "" || r.Epoch < 1 || r.Predecessor == "" || !strings.HasPrefix(r.ResultRevision, "ir-") || r.ImageName == "" || !r.Admission.valid() || r.Image.Validate() != nil || r.Image.CatalogAuthority != r.Admission.CatalogAuthority || r.Image.CatalogRevision != r.Admission.CatalogRevision || r.Image.ImageDecisionID != r.Admission.ImageDecisionID { - return ErrRecordInvalid - } - if r.InstallationNamespace != r.ClaimNamespace { - return ErrRecordInvalid - } - if r.ConsumerProject.Valid() && r.ClaimScope != ProjectClaimScope(r.ConsumerProject) || !r.ConsumerProject.Valid() && r.ClaimScope != LocalClaimScope(r.NamespaceUID) { - return ErrRecordInvalid - } - if r.State != OperationAdmitted && r.State != OperationSucceeded { - return ErrRecordInvalid - } - if r.NetworkInputs != nil && (r.NetworkInputs.Revision == "" || r.NetworkInputs.ObservedAt.IsZero()) { - return ErrRecordInvalid - } - return nil -} - -func assetRecordName(assetID string) string { return assetRecordPrefix + shortHash(assetID) } -func custodyRecordName(scope ClaimScope, claimUID types.UID) string { - return custodyRecordPrefix + shortHash(scope.AuthorityID+"/"+string(scope.ProjectUID)+"/"+string(claimUID)) -} -func operationRecordName(scope ClaimScope, claimUID types.UID, predecessor string) string { - return operationPrefix + shortHash(scope.AuthorityID+"/"+string(scope.ProjectUID)+"/"+string(claimUID)+"/"+predecessor) -} -func shortHash(value string) string { - sum := sha256.Sum256([]byte(value)) - return hex.EncodeToString(sum[:])[:24] -} - -func randomID() (string, error) { - var b [16]byte - if _, err := rand.Read(b[:]); err != nil { - return "", err - } - return hex.EncodeToString(b[:]), nil -} -func validSHA256(value string) bool { - if len(value) != len("sha256:")+64 || !strings.HasPrefix(value, "sha256:") { - return false - } - _, err := hex.DecodeString(strings.TrimPrefix(value, "sha256:")) - return err == nil && strings.ToLower(value) == value -} - -func matches(profile fleetv1.MachineProfileSpec, hardware fleetv1.Hardware) bool { - // CPU and memory are exact requests. An inexact profile fails closed, and - // capacity matches only when its observed cores and installed memory equal - // the request; larger machines are not silently substituted. - if ValidateExactHardware(profile) != nil || profile.CPU.Architecture != hardware.CPU.Architecture || profile.CPU.Cores != hardware.CPU.Cores || !sameMemory(profile.Memory.Capacity, hardware.Memory.Capacity) { - return false - } - var gpuCount int64 - for _, gpu := range hardware.GPUs { - if profile.GPUs != nil && (profile.GPUs.Vendor == "" || profile.GPUs.Vendor == gpu.Vendor) && (len(profile.GPUs.Models) == 0 || contains(profile.GPUs.Models, gpu.Model)) && matchesQuantity(profile.GPUs.MemoryPerDevice, gpu.Memory) { - gpuCount++ - } - } - if profile.GPUs != nil && !matchesCount(profile.GPUs.Count, gpuCount) { - return false - } - used := make([]bool, len(hardware.Disks)) - for _, group := range profile.Disks { - var candidates []int - for i, disk := range hardware.Disks { - if !used[i] && (group.Media == "" || group.Media == disk.Media) && (group.Interface == "" || group.Interface == disk.Interface) && matchesQuantity(group.Capacity, disk.Capacity) { - candidates = append(candidates, i) - } - } - if !matchesCount(group.Count, int64(len(candidates))) { - return false - } - count := requiredCount(group.Count) - // A disk group always requires at least one distinct device when no - // explicit minimum or exact count is supplied. Fail closed on malformed - // negative counts and on groups with too few candidates before slicing. - if count < 0 || int64(len(candidates)) < count { - return false - } - for _, index := range candidates[:count] { - used[index] = true - } - } - usedInterfaces := make([]bool, len(hardware.Interfaces)) - for _, requirement := range profile.Interfaces { - found := false - for i, iface := range hardware.Interfaces { - if !usedInterfaces[i] && (requirement.Type == "" || requirement.Type == iface.Type) && matchesQuantity(requirement.Speed, iface.Speed) { - usedInterfaces[i] = true - found = true - break - } - } - if !found { - return false - } - } - return true -} - -func requiredCount(c fleetv1.Constraint) int64 { - if c.Exact != nil { - return *c.Exact - } - if c.Min != nil { - return *c.Min - } - return 1 -} -func matchesCount(c fleetv1.Constraint, value int64) bool { - if c.Exact != nil { - return value == *c.Exact - } - return (c.Min == nil || value >= *c.Min) && (c.Max == nil || value <= *c.Max) -} -func matchesQuantity(c fleetv1.QuantityConstraint, value string) bool { - if c.Min == "" && c.Max == "" && c.Exact == "" { - return true - } - v, err := resource.ParseQuantity(value) - if err != nil { - return false - } - if c.Exact != "" { - q, err := resource.ParseQuantity(c.Exact) - return err == nil && v.Cmp(q) == 0 - } - if c.Min != "" { - q, err := resource.ParseQuantity(c.Min) - if err != nil || v.Cmp(q) < 0 { - return false - } - } - if c.Max != "" { - q, err := resource.ParseQuantity(c.Max) - if err != nil || v.Cmp(q) > 0 { - return false - } - } - return true -} -func contains(values []string, value string) bool { - for _, item := range values { - if item == value { - return true - } - } - return false -} diff --git a/internal/controller/lifecycle_test.go b/internal/controller/lifecycle_test.go deleted file mode 100644 index 5b3fc6bb..00000000 --- a/internal/controller/lifecycle_test.go +++ /dev/null @@ -1,1019 +0,0 @@ -package controller - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "sync" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - 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" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/executor" - fleetnetwork "go.datum.net/fleet/internal/network" - "go.datum.net/fleet/internal/simulator" -) - -type memoryExecutor struct { - requests []simulator.Request - results map[string]simulator.OperationResult - unknown bool - malform bool -} - -type failingResolver struct{} - -func (failingResolver) ResolveImage(context.Context, ImageRequest) (ResolvedImage, error) { - return ResolvedImage{}, errors.New("resolver unavailable") -} - -type countingResolver struct { - calls int -} - -func (r *countingResolver) ResolveImage(ctx context.Context, request ImageRequest) (ResolvedImage, error) { - r.calls++ - return (LocalDigestImageResolver{}).ResolveImage(ctx, request) -} - -type fakeNetworkLifecycle struct { - preflights int - ensures int - releases int - plan fleetnetwork.Plan - observation fleetnetwork.Observation - partialEnsure bool - partialRelease bool -} - -func (f *fakeNetworkLifecycle) Preflight(_ context.Context, request fleetnetwork.PreflightRequest) (fleetnetwork.Plan, error) { - f.preflights++ - digest, _ := fleetnetwork.DigestRequests(request.Interfaces) - f.plan = fleetnetwork.Plan{RequestDigest: digest, Location: request.Location} - for _, iface := range request.Interfaces { - f.plan.Interfaces = append(f.plan.Interfaces, fleetnetwork.InterfacePlan{Name: iface.Name, NetworkNamespace: request.ClaimNamespace, NetworkName: iface.NetworkName, NetworkUID: types.UID("network-" + iface.Name), NetworkGeneration: 1, IPFamilies: append([]string(nil), iface.IPFamilies...), ReclaimPolicy: iface.ReclaimPolicy, ClaimName: "guarded-" + iface.Name, Decision: fleetnetwork.Decision{ID: "network-decision-" + iface.Name, Revision: "policy-r1"}}) - } - return f.plan, nil -} - -func (f *fakeNetworkLifecycle) Ensure(_ context.Context, request fleetnetwork.EnsureRequest) (fleetnetwork.Observation, error) { - f.ensures++ - if request.Plan.RequestDigest != f.plan.RequestDigest { - return fleetnetwork.Observation{}, fleetnetwork.ErrObjectConflict - } - if f.partialEnsure { - return fleetnetwork.Observation{Lifecycle: []fleetnetwork.InterfaceLifecycleState{{Name: request.Plan.Interfaces[0].Name, GuardToken: "partial", CreateAdmitted: true}}}, fleetnetwork.ErrPending - } - return f.observation, nil -} - -func (f *fakeNetworkLifecycle) Release(_ context.Context, request fleetnetwork.ReleaseRequest) (fleetnetwork.ReleaseObservation, error) { - f.releases++ - if f.partialRelease { - return fleetnetwork.ReleaseObservation{Lifecycle: []fleetnetwork.InterfaceLifecycleState{{Name: request.Plan.Interfaces[0].Name, GuardToken: "partial", CreateAdmitted: true, DeleteAdmitted: true}}}, fleetnetwork.ErrPending - } - states := append([]fleetnetwork.InterfaceLifecycleState(nil), request.Lifecycle...) - if len(states) == 0 { - for _, planned := range request.Plan.Interfaces { - states = append(states, fleetnetwork.InterfaceLifecycleState{Name: planned.Name, GuardToken: "guard-" + planned.Name, CreateAdmitted: true, DeleteAdmitted: true}) - } - return fleetnetwork.ReleaseObservation{Lifecycle: states}, fleetnetwork.ErrPending - } - for i := range states { - if !states[i].DeleteAdmitted { - return fleetnetwork.ReleaseObservation{}, fleetnetwork.ErrObjectConflict - } - states[i].DeleteCompleted = true - } - return fleetnetwork.ReleaseObservation{Verified: true, Lifecycle: states, Revision: "release-r1"}, nil -} - -func (e *memoryExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - e.requests = append(e.requests, request) - now := time.Now() - evidence := map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind] - digest, err := simulator.RequestDigest(request) - if err != nil { - return simulator.OperationResult{}, err - } - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: evidence, InputDigest: digest, CompletedAt: &now} - if e.malform { - result.CompletedAt = nil - } - e.results[request.ID] = result - if e.unknown { - e.unknown = false - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - return result, nil -} -func (e *memoryExecutor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { - result, ok := e.results[id] - return result, ok, nil -} - -type fixture struct { - coordinator *Coordinator - executor *memoryExecutor - now time.Time - ids int - mu sync.Mutex -} - -func newFixture(t *testing.T) *fixture { - t.Helper() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - kube := fake.NewClientBuilder().WithScheme(scheme).Build() - exec := &memoryExecutor{results: map[string]simulator.OperationResult{}} - coordinator, err := NewCoordinator(kube, "private", exec, LocalDigestImageResolver{}, nil, time.Minute) - if err != nil { - t.Fatal(err) - } - f := &fixture{coordinator: coordinator, executor: exec, now: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)} - coordinator.now = func() time.Time { return f.now } - coordinator.newID = func() (string, error) { - f.mu.Lock() - defer f.mu.Unlock() - f.ids++ - return fmt.Sprintf("id-%d", f.ids), nil - } - return f -} - -func (f *fixture) request(claimUID types.UID) AllocationRequest { - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "project", Name: "claim-" + string(claimUID), UID: claimUID, Finalizers: []string{MachineFinalizer}}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "class"}, MachineProfileRef: fleetv1.LocalReference{Name: "profile"}}} - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "provider"}}}} - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile", UID: "profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - conditions := []metav1.Condition{} - for _, typ := range []string{"Prepared", "Healthy", "Available"} { - conditions = append(conditions, metav1.Condition{Type: typ, Status: metav1.ConditionTrue, ObservedGeneration: 2, LastTransitionTime: metav1.Now()}) - } - machine := fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "provider", Name: "machine-1", UID: "machine-uid", Generation: 2}, Spec: fleetv1.MachineCapacitySpec{AllocationPolicy: "Enabled", DeviceRef: fleetv1.LocalReference{Name: "host-1"}}, Status: fleetv1.MachineCapacityStatus{Hardware: fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}}, Conditions: conditions}} - return AllocationRequest{Claim: claim, Class: class, Profile: profile, MachineCapacities: []fleetv1.MachineCapacity{machine}, EvidenceObservedAt: map[types.UID]time.Time{machine.UID: f.now}, NamespaceUID: "namespace-uid", Admission: AdmissionAuthority{PrincipalUID: "user-uid", DecisionID: "decision-1"}} -} - -func TestAllocationReleaseAndEpochReuse(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - first, second := f.request("one"), f.request("two") - if err := f.coordinator.EnsureClaimCustody(ctx, first.Claim, first.NamespaceUID, first.Admission); err != nil { - t.Fatal(err) - } - if err := f.coordinator.EnsureClaimCustody(ctx, second.Claim, second.NamespaceUID, second.Admission); err != nil { - t.Fatal(err) - } - record, err := f.coordinator.Allocate(ctx, first) - if err != nil || record.State != AssetCommitted || record.Epoch != 1 { - t.Fatalf("Allocate = %#v, %v", record, err) - } - if _, err := f.coordinator.Allocate(ctx, second); !errors.Is(err, ErrInsufficientCapacity) { - t.Fatalf("second allocation error = %v", err) - } - released, err := f.coordinator.Release(ctx, first.Claim.UID) - if err != nil || !released.SafeToRemoveFinalizer || len(f.executor.requests) != 1 || f.executor.requests[0].Kind != "cleanup" { - t.Fatalf("Release = %#v, %v, requests=%#v", released, err, f.executor.requests) - } - if again, err := f.coordinator.Release(ctx, first.Claim.UID); err != nil || !again.SafeToRemoveFinalizer { - t.Fatalf("idempotent Release = %#v, %v", again, err) - } - record, err = f.coordinator.Allocate(ctx, second) - if err != nil || record.Epoch != 2 || record.ClaimUID != second.Claim.UID { - t.Fatalf("reallocate = %#v, %v", record, err) - } - if again, err := f.coordinator.Release(ctx, first.Claim.UID); err != nil || !again.SafeToRemoveFinalizer || again.State != AssetReleased { - t.Fatalf("release retry after reallocation = %#v, %v", again, err) - } -} - -func TestConcurrentDifferingCandidatesSelectOnlyOneAsset(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - left, right := f.request("claim"), f.request("claim") - right.MachineCapacities[0].Name, right.MachineCapacities[0].UID, right.MachineCapacities[0].Spec.DeviceRef.Name = "machine-2", "machine-2-uid", "host-2" - right.EvidenceObservedAt = map[types.UID]time.Time{right.MachineCapacities[0].UID: f.now} - if err := f.coordinator.EnsureClaimCustody(ctx, left.Claim, left.NamespaceUID, left.Admission); err != nil { - t.Fatal(err) - } - errorsCh := make(chan error, 2) - go func() { _, err := f.coordinator.Allocate(ctx, left); errorsCh <- err }() - go func() { _, err := f.coordinator.Allocate(ctx, right); errorsCh <- err }() - <-errorsCh - <-errorsCh - var secrets corev1.SecretList - if err := f.coordinator.client.List(ctx, &secrets); err != nil { - t.Fatal(err) - } - assets := 0 - for i := range secrets.Items { - if len(secrets.Items[i].Name) >= len(assetRecordPrefix) && secrets.Items[i].Name[:len(assetRecordPrefix)] == assetRecordPrefix { - assets++ - } - } - if assets != 1 { - t.Fatalf("asset records = %d, want 1", assets) - } -} - -func TestOccupiedSelectedCandidateClearsOnlyUnmaterializedSelection(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - owner, waiter := f.request("owner"), f.request("waiter") - for _, r := range []*AllocationRequest{&owner, &waiter} { - if err := f.coordinator.EnsureClaimCustody(ctx, r.Claim, r.NamespaceUID, r.Admission); err != nil { - t.Fatal(err) - } - } - if _, err := f.coordinator.Allocate(ctx, owner); err != nil { - t.Fatal(err) - } - second := waiter.MachineCapacities[0] - second.Name, second.UID, second.Spec.DeviceRef.Name = "machine-2", "machine-2-uid", "host-2" - waiter.MachineCapacities = []fleetv1.MachineCapacity{waiter.MachineCapacities[0], second} - waiter.EvidenceObservedAt[second.UID] = f.now - record, err := f.coordinator.Allocate(ctx, waiter) - if err != nil || record.MachineUID != second.UID { - t.Fatalf("Allocate = %#v, %v", record, err) - } -} - -func TestReleasedAssetCannotBeReusedBeforeCustodyRecordsCompletion(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - first, second := f.request("one"), f.request("two") - for _, claim := range []*fleetv1.Machine{first.Claim, second.Claim} { - if err := f.coordinator.EnsureClaimCustody(ctx, claim, "namespace-uid", AdmissionAuthority{PrincipalUID: "user-uid", DecisionID: "decision-1"}); err != nil { - t.Fatal(err) - } - } - asset, err := f.coordinator.Allocate(ctx, first) - if err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.setAssetState(ctx, asset.AssetID, first.Claim.UID, AssetCommitted, AssetReleased); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, second); !errors.Is(err, ErrInsufficientCapacity) { - t.Fatalf("reuse before custody completion error = %v", err) - } - if result, err := f.coordinator.Release(ctx, first.Claim.UID); err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("finish release = %#v, %v", result, err) - } - if asset, err := f.coordinator.Allocate(ctx, second); err != nil || asset.Epoch != 2 { - t.Fatalf("reuse after custody completion = %#v, %v", asset, err) - } -} - -func TestCustodyProvesUnboundAndMissingBoundAuthorityFailsClosed(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("missing custody error = %v", err) - } - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 0 { - t.Fatalf("unbound Release = %#v, %v", result, err) - } - - f = newFixture(t) - request = f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - record, secret, err := f.coordinator.getCustody(ctx, request.Claim.UID) - if err != nil { - t.Fatal(err) - } - record.State, record.AssetID = CustodyBound, "missing" - if err := encodeRecord(secret, record, "custody"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Update(ctx, secret); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("missing authority error = %v", err) - } -} - -func TestCustodyAloneCannotAllocateWithoutLiveFleetFinalizer(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - request.Claim.Finalizers = nil - if _, err := f.coordinator.Allocate(ctx, request); err == nil { - t.Fatal("allocation without finalizer succeeded") - } - now := metav1.Now() - request.Claim.Finalizers = []string{MachineFinalizer} - request.Claim.DeletionTimestamp = &now - if _, err := f.coordinator.Allocate(ctx, request); err == nil { - t.Fatal("deleting claim allocated") - } -} - -func TestReleaseRecoversPreparationBeforeCustodyAdvanceWithoutCleanup(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - proposal, _, err := f.coordinator.proposeAsset(ctx, request, &request.MachineCapacities[0]) - if err != nil { - t.Fatal(err) - } - if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { - t.Fatal(err) - } - if _, won, err := f.coordinator.prepareAsset(ctx, request, &request.MachineCapacities[0]); err != nil || !won { - t.Fatalf("prepare won=%v error=%v", won, err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 0 { - t.Fatalf("Release = %#v, %v, requests=%#v", result, err, f.executor.requests) - } -} - -func TestReleaseBetweenSelectionAndCreateTombstonesProposalAgainstStaleAllocator(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - proposal, reusable, err := f.coordinator.proposeAsset(ctx, request, &request.MachineCapacities[0]) - if err != nil || !reusable { - t.Fatalf("proposal=%#v reusable=%v err=%v", proposal, reusable, err) - } - if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { - t.Fatal(err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("Release=%#v err=%v", result, err) - } - if _, won, err := f.coordinator.prepareAsset(ctx, request, &request.MachineCapacities[0]); err != nil || won { - t.Fatalf("stale prepare won=%v err=%v", won, err) - } - record, _, err := f.coordinator.getAsset(ctx, proposal.AssetID) - if err != nil || record.State != AssetReleased || record.Epoch != proposal.Epoch { - t.Fatalf("asset=%#v err=%v", record, err) - } -} - -func TestPreparingRetryRevalidatesInputsAndDuplicateRecordsBlock(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - proposal, _, err := f.coordinator.proposeAsset(ctx, request, &request.MachineCapacities[0]) - if err != nil { - t.Fatal(err) - } - if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { - t.Fatal(err) - } - prepared, won, err := f.coordinator.prepareAsset(ctx, request, &request.MachineCapacities[0]) - if err != nil || !won { - t.Fatalf("prepare = %#v, %v, %v", prepared, won, err) - } - request.Profile.UID = "different-profile-lifetime" - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("retry error = %v", err) - } - - request.Profile.UID = "profile-uid" - if err := f.coordinator.bindCustody(ctx, request.Claim, prepared.AssetID); err != nil { - t.Fatal(err) - } - duplicate := *prepared - duplicate.AssetID, duplicate.MachineUID, duplicate.MachineName = "provider/test/Host/host-2", "machine-2", "machine-2" - secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: assetRecordName(duplicate.AssetID)}} - if err := encodeRecord(secret, &duplicate, "asset"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Create(ctx, secret); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("duplicate error = %v", err) - } -} - -func TestInstallUsesPrivatePredecessorAndRecoversUnknownOutcome(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - request.Claim.Status.CurrentInstallationRef = &fleetv1.LocalReference{Name: "forged-public-value"} - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "installation-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "registry/image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - f.executor.unknown = true - result, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: "namespace-uid", Admission: installAdmission()}) - if err != nil || result.Revision == "" { - t.Fatalf("Install = %#v, %v", result, err) - } - if result.Record.InstallationNamespace != installation.Namespace || result.Record.InstallationName != installation.Name || result.Record.InstallationUID != installation.UID || result.Record.ClaimNamespace != request.Claim.Namespace || result.Record.ClaimName != request.Claim.Name || result.Record.ClaimUID != request.Claim.UID { - t.Fatalf("operation omitted recovery routing identity: %#v", result.Record) - } - invalid := result.Record - invalid.InstallationName = "" - if !errors.Is(validateInstallationRecord(&invalid), ErrRecordInvalid) { - t.Fatal("operation without retained installation name validated") - } - if len(f.executor.requests) != 1 || f.executor.requests[0].AssetID != asset.AssetID { - t.Fatalf("requests = %#v", f.executor.requests) - } - f.coordinator.images = failingResolver{} - again, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: "namespace-uid", Admission: installAdmission()}) - if err != nil || again.Revision != result.Revision || len(f.executor.requests) != 1 { - t.Fatalf("idempotent retry = %#v, %v", again, err) - } - changed := installAdmission() - changed.DecisionID = "different-install-decision" - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: "namespace-uid", Admission: changed}); !errors.Is(err, ErrPredecessorConflict) { - t.Fatalf("changed admission error = %v", err) - } - f.coordinator.images = LocalDigestImageResolver{} - successor := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install-2", UID: "installation-uid-2"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: installation.Name}, ImageRef: fleetv1.LocalReference{Name: "registry/image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: successor, NamespaceUID: "namespace-uid", Admission: installAdmission()}); err != nil { - t.Fatalf("named predecessor install: %v", err) - } - retained, _, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil || retained.CurrentInstallationName != successor.Name { - t.Fatalf("current installation = %q, %v", retained.CurrentInstallationName, err) - } - stale := successor.DeepCopyObject().(*fleetv1.Installation) - stale.Name, stale.UID = "install-stale", "installation-uid-stale" - stale.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "None"} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: stale, NamespaceUID: "namespace-uid", Admission: installAdmission()}); !errors.Is(err, ErrPredecessorConflict) { - t.Fatalf("stale predecessor error = %v", err) - } -} - -func TestInstallReplayRejectsRetainedRoutingIdentitySubstitution(t *testing.T) { - ctx := context.Background() - for name, mutate := range map[string]func(*InstallationRecord){ - "installation namespace": func(record *InstallationRecord) { - record.InstallationNamespace, record.ClaimNamespace = "other", "other" - }, - "installation name": func(record *InstallationRecord) { record.InstallationName = "other" }, - "claim namespace": func(record *InstallationRecord) { - record.ClaimNamespace, record.InstallationNamespace = "other", "other" - }, - "claim name": func(record *InstallationRecord) { record.ClaimName = "other" }, - } { - t.Run(name, func(t *testing.T) { - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "install-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - installRequest := InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} - image, _ := f.coordinator.images.ResolveImage(ctx, ImageRequest{NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, InstallationUID: installation.UID, ImageName: installation.Spec.ImageRef.Name}) - scope := LocalClaimScope(request.NamespaceUID) - operationName := operationRecordName(scope, request.Claim.UID, "None") - record, secret, err := f.coordinator.getOrCreateOperation(ctx, operationName, installRequest, asset, "None", image) - if err != nil { - t.Fatal(err) - } - mutate(record) - if err := encodeRecord(secret, record, "installation"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Update(ctx, secret); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Install(ctx, installRequest); !errors.Is(err, ErrPredecessorConflict) { - t.Fatalf("error=%v", err) - } - if len(f.executor.requests) != 0 { - t.Fatalf("substituted routing identity reached executor: %#v", f.executor.requests) - } - }) - } -} - -func TestInstallRejectsOperationRecordFromOlderSchema(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "install-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - installRequest := InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} - image, _ := f.coordinator.images.ResolveImage(ctx, ImageRequest{NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, InstallationUID: installation.UID, ImageName: installation.Spec.ImageRef.Name}) - scope := LocalClaimScope(request.NamespaceUID) - // A schema-version-1 operation record lacks the retained routing names. It - // is invalid like any other malformed record and is never rewritten. - older := &InstallationRecord{SchemaVersion: 1, State: OperationAdmitted, OperationID: "install-older", InstallationUID: installation.UID, NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, ClaimScope: scope, AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, Predecessor: "None", ResultRevision: "ir-older", Image: image, ImageName: installation.Spec.ImageRef.Name, Admission: installAdmission()} - secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: operationRecordName(scope, request.Claim.UID, "None")}} - if err := encodeRecord(secret, older, "installation"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Create(ctx, secret); err != nil { - t.Fatal(err) - } - before := append([]byte(nil), secret.Data[recordDataKey]...) - if _, err := f.coordinator.Install(ctx, installRequest); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("error=%v, want ErrRecordInvalid", err) - } - if len(f.executor.requests) != 0 { - t.Fatalf("older operation record reached executor: %#v", f.executor.requests) - } - var stored corev1.Secret - if err := f.coordinator.client.Get(ctx, client.ObjectKeyFromObject(secret), &stored); err != nil { - t.Fatal(err) - } - if !bytes.Equal(stored.Data[recordDataKey], before) { - t.Fatalf("older operation record was rewritten: %s", stored.Data[recordDataKey]) - } -} - -func TestAssetRecordWithPreExactRequirementsIsInvalid(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - var secret corev1.Secret - if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: "private", Name: assetRecordName(asset.AssetID)}, &secret); err != nil { - t.Fatal(err) - } - var fields map[string]json.RawMessage - if err := json.Unmarshal(secret.Data[recordDataKey], &fields); err != nil { - t.Fatal(err) - } - fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) - data, err := json.Marshal(fields) - if err != nil { - t.Fatal(err) - } - secret.Data[recordDataKey] = data - if err := f.coordinator.client.Update(ctx, &secret); err != nil { - t.Fatal(err) - } - if _, err := parseAssetSecret(&secret); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("decode error=%v, want ErrRecordInvalid", err) - } - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("allocate error=%v, want ErrRecordInvalid", err) - } -} - -func TestReleaseRecoversRetainedActiveInstallationBeforeCleanup(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "install-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - image, _ := f.coordinator.images.ResolveImage(ctx, ImageRequest{NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, InstallationUID: installation.UID, ImageName: installation.Spec.ImageRef.Name}) - op, _, err := f.coordinator.getOrCreateOperation(ctx, operationRecordName(LocalClaimScope(request.NamespaceUID), request.Claim.UID, "None"), InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()}, asset, "None", image) - if err != nil { - t.Fatal(err) - } - if err := f.coordinator.activateOperation(ctx, asset.AssetID, asset.ClaimUID, "None", op.OperationID); err != nil { - t.Fatal(err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 2 || f.executor.requests[0].Kind != "install" || f.executor.requests[1].Kind != "cleanup" { - t.Fatalf("Release = %#v, %v, requests=%#v", result, err, f.executor.requests) - } -} - -func TestInstallRejectsDeletingOrUnprotectedClaim(t *testing.T) { - ctx := context.Background() - for _, deleting := range []bool{false, true} { - t.Run(fmt.Sprintf("deleting-%t", deleting), func(t *testing.T) { - f := newFixture(t) - request := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); err != nil { - t.Fatal(err) - } - if deleting { - now := metav1.NewTime(f.now) - request.Claim.DeletionTimestamp = &now - } else { - request.Claim.Finalizers = nil - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "install-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()}); err == nil { - t.Fatal("installation admission remained open") - } - if len(f.executor.requests) != 0 { - t.Fatalf("executor requests = %#v", f.executor.requests) - } - }) - } -} - -func TestCoordinatorRejectsMalformedGenericExecutorEvidence(t *testing.T) { - ctx := context.Background() - request := simulator.Request{ID: "cleanup-binding", Kind: "cleanup"} - for _, recover := range []bool{false, true} { - t.Run(fmt.Sprintf("recover-%t", recover), func(t *testing.T) { - f := newFixture(t) - f.executor.malform = true - f.executor.unknown = recover - if _, err := f.coordinator.executeAndRecover(ctx, request); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("error = %v, want unknown outcome", err) - } - }) - } -} - -func TestFailClosedInputsAndDiskCount(t *testing.T) { - ctx := context.Background() - for name, test := range map[string]struct { - mutate func(*AllocationRequest) - want error - }{ - "source": {mutate: func(r *AllocationRequest) { - r.Class.Spec.Source = &fleetv1.SourceReference{Project: "other", Name: "class"} - }, want: ErrUnsupported}, - "network": {mutate: func(r *AllocationRequest) { - r.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management"}} - }, want: fleetnetwork.ErrAuthorizationUnavailable}, - } { - t.Run(name, func(t *testing.T) { - f := newFixture(t) - r := f.request("claim") - if err := f.coordinator.EnsureClaimCustody(ctx, r.Claim, r.NamespaceUID, r.Admission); err != nil { - t.Fatal(err) - } - test.mutate(&r) - if _, err := f.coordinator.Allocate(ctx, r); !errors.Is(err, test.want) { - t.Fatalf("error = %v", err) - } - }) - } - exactCPU, exactMemory := fleetv1.CPURequirement{Architecture: "amd64", Cores: 8}, fleetv1.MemoryRequirement{Capacity: "32Gi"} - observedCPU, observedMemory := fleetv1.HardwareCPU{Architecture: "amd64", Cores: 8}, fleetv1.HardwareMemory{Capacity: "32Gi"} - profile := fleetv1.MachineProfileSpec{CPU: exactCPU, Memory: exactMemory, Disks: []fleetv1.DiskRequirement{{Count: fleetv1.Constraint{Exact: int64ptr(1)}, Media: "ssd"}}} - hardware := fleetv1.Hardware{CPU: observedCPU, Memory: observedMemory, Disks: []fleetv1.HardwareDisk{{Media: "ssd"}, {Media: "ssd"}}} - if matches(profile, hardware) { - t.Fatal("exactly one matching disk accepted two") - } - for name, count := range map[string]fleetv1.Constraint{ - "max-only": {Max: int64ptr(2)}, - "empty": {}, - } { - t.Run("missing-disk-"+name, func(t *testing.T) { - profile := fleetv1.MachineProfileSpec{CPU: exactCPU, Memory: exactMemory, Disks: []fleetv1.DiskRequirement{{Count: count, Media: "ssd"}}} - hardware := fleetv1.Hardware{CPU: observedCPU, Memory: observedMemory} - if matches(profile, hardware) { - t.Fatal("disk group with no matching device was accepted") - } - }) - } - - f := newFixture(t) - r := f.request("install-claim") - if err := f.coordinator.EnsureClaimCustody(ctx, r.Claim, r.NamespaceUID, r.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, r); err != nil { - t.Fatal(err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: r.Claim.Namespace, Name: "install", UID: "install"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: r.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:ABC"}}} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: r.Claim, Installation: installation, NamespaceUID: "namespace", Admission: installAdmission()}); err == nil { - t.Fatal("non-canonical digest accepted") - } - installation.Spec.BootstrapConfigRef = &fleetv1.LocalReference{Name: "secret"} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: r.Claim, Installation: installation, NamespaceUID: "namespace", Admission: installAdmission()}); !errors.Is(err, ErrUnsupported) { - t.Fatalf("bootstrap error = %v", err) - } -} - -func TestNetworkLifecycleRetainsInputsAndGatesProviderCleanup(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - f.coordinator.networks = networks - request := f.request("networked") - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}} - request.MachineCapacities[0].Status.Hardware.Interfaces = []fleetv1.HardwareInterface{{Name: "eno1"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}, IPFamilies: []string{"IPv4"}}} - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil || networks.preflights != 1 || asset.Network == nil || asset.Network.Plan.Interfaces[0].NetworkUID != "network-management" { - t.Fatalf("Allocate = %#v, %v, preflights=%d", asset, err, networks.preflights) - } - networks.observation = fleetnetwork.Observation{Revision: "network-r1", ObservedAt: f.now, Interfaces: []fleetnetwork.InterfaceObservation{{Name: "management", ClaimUID: "network-claim-uid", ClaimGeneration: 4, NetworkInterfaceUID: "private-interface-uid", NetworkInterfaceName: "private-interface-name", MTU: 1440, Addresses: []fleetnetwork.Address{{Address: "10.20.30.42/24", Family: "IPv4", Primary: true}}, Conditions: []fleetnetwork.Condition{{Type: "Allocated", Status: metav1.ConditionTrue, Reason: "internal-detail", ObservedGeneration: 4}, {Type: "Prepared", Status: metav1.ConditionTrue, Reason: "internal-detail", ObservedGeneration: 4}, {Type: "Programmed", Status: metav1.ConditionTrue, Reason: "internal-detail", ObservedGeneration: 4}}}}} - if observation, err := f.coordinator.ReconcileNetwork(ctx, request.Claim.UID); err != nil || !observation.Programmed(asset.Network.Plan) { - t.Fatalf("ReconcileNetwork = %#v, %v", observation, err) - } - retained, _, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil || retained.Network.Observation.Interfaces[0].ClaimUID != "network-claim-uid" { - t.Fatalf("retained network = %#v, %v", retained.Network, err) - } - status, ready := ProjectNetworkStatus(retained.Network, f.now, time.Minute) - if ready.Status != metav1.ConditionTrue || status.Interfaces[0].Conditions[0].Reason != "Verified" || status.Interfaces[0].Addresses[0].Address != "10.20.30.42/24" { - t.Fatalf("projection = %#v, condition %#v", status, ready) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "installation-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "registry/image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - installed, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()}) - if err != nil || installed.Record.NetworkInputs == nil || installed.Record.NetworkInputs.Revision != "network-r1" { - t.Fatalf("Install = %#v, %v", installed, err) - } - if inputs := string(f.executor.requests[0].Inputs); strings.Contains(inputs, "network-claim-uid") || strings.Contains(inputs, "private-interface-uid") || !strings.Contains(inputs, "network-r1") { - t.Fatalf("provider network inputs were not sanitized: %s", inputs) - } - current, secret, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil { - t.Fatal(err) - } - current.Network.Observation.ObservedAt = f.now.Add(-2 * time.Minute) - if err := encodeRecord(secret, current, "asset"); err != nil { - t.Fatal(err) - } - if err := f.coordinator.client.Update(ctx, secret); err != nil { - t.Fatal(err) - } - if _, ready := ProjectNetworkStatus(current.Network, f.now, time.Minute); ready.Status != metav1.ConditionUnknown { - t.Fatalf("stale network evidence projected ready: %#v", ready) - } - f.coordinator.images = failingResolver{} - if recovered, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()}); err != nil || recovered.Revision != installed.Revision || len(f.executor.requests) != 1 { - t.Fatalf("retained install recovery = %#v, %v, provider=%#v", recovered, err, f.executor.requests) - } - f.executor.requests = nil - first, err := f.coordinator.Release(ctx, request.Claim.UID) - if !errors.Is(err, fleetnetwork.ErrPending) || first.State != AssetReleasing || len(f.executor.requests) != 0 { - t.Fatalf("first Release = %#v, %v, provider=%#v", first, err, f.executor.requests) - } - second, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !second.SafeToRemoveFinalizer || len(f.executor.requests) != 1 || f.executor.requests[0].Kind != "cleanup" { - t.Fatalf("second Release = %#v, %v, provider=%#v", second, err, f.executor.requests) - } -} - -func TestNetworkRefreshErrorKeepsLastProgrammedObservation(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - f.coordinator.networks = networks - request := f.request("network-refresh-error") - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}} - request.MachineCapacities[0].Status.Hardware.Interfaces = []fleetv1.HardwareInterface{{Name: "eno1"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}, IPFamilies: []string{"IPv4"}}} - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - networks.observation = fleetnetwork.Observation{Revision: "network-r1", ObservedAt: f.now, Interfaces: []fleetnetwork.InterfaceObservation{{Name: "management", ClaimUID: "network-claim-uid", ClaimGeneration: 4, Addresses: []fleetnetwork.Address{{Address: "10.20.30.42/24", Family: "IPv4", Primary: true}}, Conditions: []fleetnetwork.Condition{{Type: "Allocated", Status: metav1.ConditionTrue, ObservedGeneration: 4}, {Type: "Prepared", Status: metav1.ConditionTrue, ObservedGeneration: 4}, {Type: "Programmed", Status: metav1.ConditionTrue, ObservedGeneration: 4}}}}} - if _, err := f.coordinator.ReconcileNetwork(ctx, request.Claim.UID); err != nil { - t.Fatal(err) - } - - networks.partialEnsure = true - if observation, err := f.coordinator.ReconcileNetwork(ctx, request.Claim.UID); !errors.Is(err, fleetnetwork.ErrPending) || len(observation.Interfaces) != 0 { - t.Fatalf("failed refresh = %#v, %v", observation, err) - } - retained, _, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil || !retained.Network.Observation.Programmed(retained.Network.Plan) || retained.Network.Observation.Interfaces[0].Addresses[0].Address != "10.20.30.42/24" || retained.Network.Lifecycle[0].GuardToken != "partial" { - t.Fatalf("failed refresh discarded last good observation: %#v, %v", retained.Network, err) - } -} - -func TestNetworkPreflightRunsBeforeHardwareSelection(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - f.coordinator.networks = networks - request := f.request("networked") - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}}} - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - request.MachineCapacities = nil - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrInsufficientCapacity) || networks.preflights != 1 { - t.Fatalf("Allocate error = %v, preflights=%d", err, networks.preflights) - } -} - -func TestNetworkRequestShapeIsRejectedBeforePreflight(t *testing.T) { - for name, mutate := range map[string]func(*fleetv1.NetworkInterfaceRequest){ - "duplicate families": func(request *fleetv1.NetworkInterfaceRequest) { - request.IPFamilies = []string{"IPv4", "IPv4"} - }, - "too many families": func(request *fleetv1.NetworkInterfaceRequest) { - request.IPFamilies = []string{"IPv4", "IPv6", "IPv4"} - }, - "unknown family": func(request *fleetv1.NetworkInterfaceRequest) { - request.IPFamilies = []string{"IPX"} - }, - "duplicate address classes": func(request *fleetv1.NetworkInterfaceRequest) { - request.Addresses = []fleetv1.AddressRequest{{ClassRef: fleetv1.LocalReference{Name: "public"}}, {ClassRef: fleetv1.LocalReference{Name: "public"}}} - }, - "too many address classes": func(request *fleetv1.NetworkInterfaceRequest) { - for i := 0; i < 5; i++ { - request.Addresses = append(request.Addresses, fleetv1.AddressRequest{ClassRef: fleetv1.LocalReference{Name: fmt.Sprintf("class-%d", i)}}) - } - }, - } { - t.Run(name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - f.coordinator.networks = networks - request := f.request(types.UID(strings.ReplaceAll(name, " ", "-"))) - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}}} - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - mutate(&request.Claim.Spec.NetworkInterfaces[0]) - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("Allocate error = %v, want ErrRecordInvalid", err) - } - if networks.preflights != 0 { - t.Fatalf("invalid request reached network preflight %d times", networks.preflights) - } - }) - } -} - -func TestNetworkReleaseBeforeEnsurePersistsDeleteIntent(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - f.coordinator.networks = networks - request := f.request("network-delete-before-ensure") - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}} - request.MachineCapacities[0].Status.Hardware.Interfaces = []fleetv1.HardwareInterface{{Name: "eno1"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}}} - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, fleetnetwork.ErrPending) { - t.Fatalf("first Release error = %v", err) - } - retained, _, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil || len(retained.Network.Lifecycle) != 1 || !retained.Network.Lifecycle[0].DeleteAdmitted { - t.Fatalf("retained lifecycle = %#v, err=%v", retained.Network, err) - } - if result, err := f.coordinator.Release(ctx, request.Claim.UID); err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("second Release = %#v, %v", result, err) - } -} - -func TestCoordinatorRejectsPartialNetworkLifecycleWithoutCorruptingRecord(t *testing.T) { - for _, test := range []struct { - name string - partial func(*fakeNetworkLifecycle) - run func(context.Context, *Coordinator, types.UID) error - state AssetState - }{ - { - name: "ensure", - partial: func(lifecycle *fakeNetworkLifecycle) { lifecycle.partialEnsure = true }, - run: func(ctx context.Context, coordinator *Coordinator, claimUID types.UID) error { - _, err := coordinator.ReconcileNetwork(ctx, claimUID) - return err - }, - state: AssetCommitted, - }, - { - name: "release", - partial: func(lifecycle *fakeNetworkLifecycle) { lifecycle.partialRelease = true }, - run: func(ctx context.Context, coordinator *Coordinator, claimUID types.UID) error { - _, err := coordinator.Release(ctx, claimUID) - return err - }, - state: AssetReleasing, - }, - } { - t.Run(test.name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - networks := &fakeNetworkLifecycle{} - test.partial(networks) - f.coordinator.networks = networks - request := twoInterfaceNetworkRequest(f, types.UID("partial-"+test.name)) - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - asset, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - if err := test.run(ctx, f.coordinator, request.Claim.UID); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("operation error = %v, want ErrRecordInvalid", err) - } - retained, _, err := f.coordinator.getAsset(ctx, asset.AssetID) - if err != nil { - t.Fatalf("retained asset became undecodable: %v", err) - } - if retained.State != test.state || len(retained.Network.Lifecycle) != 0 { - t.Fatalf("retained asset = %#v, want state %s with no lifecycle", retained, test.state) - } - }) - } -} - -func twoInterfaceNetworkRequest(f *fixture, claimUID types.UID) AllocationRequest { - request := f.request(claimUID) - request.Profile.Spec.Interfaces = []fleetv1.InterfaceRequirement{{Name: "management"}, {Name: "data"}} - request.MachineCapacities[0].Status.Hardware.Interfaces = []fleetv1.HardwareInterface{{Name: "eno1"}, {Name: "eno2"}} - request.Claim.Spec.LocationRef = fleetv1.LocalReference{Name: "us-central-1"} - request.Claim.Spec.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{ - {Name: "management", Network: fleetv1.NamespacedReference{Name: "management"}}, - {Name: "data", Network: fleetv1.NamespacedReference{Name: "workload"}}, - } - request.Location = fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - return request -} - -func int64ptr(value int64) *int64 { return &value } - -func installAdmission() InstallationAdmissionAuthority { - return InstallationAdmissionAuthority{PrincipalUID: "user-uid", DecisionID: "install-decision-1", CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} -} - -// The physical group participates in durable asset identity. Changing this -// encoding can make occupied capacity appear new and requires a migration. -func TestMachineAssetIdentityUsesPhysicalFleetGroup(t *testing.T) { - machine := &fleetv1.MachineCapacity{ - ObjectMeta: metav1.ObjectMeta{Namespace: "provider", Name: "capacity"}, - Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "host-1"}}, - } - if got := machineAssetID(machine, ProjectIdentity{}); got != "provider/fleet.datumapis.com/Device/host-1" { - t.Fatalf("standalone asset identity changed: %s", got) - } - provider := ProjectIdentity{AuthorityID: "milo", RouteName: "provider-project", UID: "provider-uid"} - if got := machineAssetID(machine, provider); got != "milo/provider-uid/provider/fleet.datumapis.com/Device/host-1" { - t.Fatalf("project asset identity changed: %s", got) - } -} diff --git a/internal/controller/network_records.go b/internal/controller/network_records.go deleted file mode 100644 index 8e448f49..00000000 --- a/internal/controller/network_records.go +++ /dev/null @@ -1,109 +0,0 @@ -package controller - -import ( - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - fleetnetwork "go.datum.net/fleet/internal/network" -) - -type NetworkRecord struct { - Plan fleetnetwork.Plan `json:"plan"` - Observation fleetnetwork.Observation `json:"observation,omitempty"` - Lifecycle []fleetnetwork.InterfaceLifecycleState `json:"lifecycle,omitempty"` - ReleaseRevision string `json:"releaseRevision,omitempty"` -} - -func validateNetworkRecord(record *NetworkRecord) error { - if record == nil { - return nil - } - if !record.Plan.Valid() { - return ErrRecordInvalid - } - if len(record.Lifecycle) != 0 && len(record.Lifecycle) != len(record.Plan.Interfaces) { - return ErrRecordInvalid - } - planned := map[string]bool{} - for _, iface := range record.Plan.Interfaces { - planned[iface.Name] = true - } - seenObservations := map[string]bool{} - for _, observation := range record.Observation.Interfaces { - if !planned[observation.Name] || seenObservations[observation.Name] { - return ErrRecordInvalid - } - seenObservations[observation.Name] = true - } - seen := map[string]bool{} - for _, state := range record.Lifecycle { - if !planned[state.Name] || seen[state.Name] || !state.CreateAdmitted || state.GuardToken == "" || state.DeleteCompleted && !state.DeleteAdmitted || (state.RetainedInterfaceName == "") != (state.RetainedInterfaceUID == "") || state.NoBindingVerified && state.RetainedInterfaceUID != "" { - return ErrRecordInvalid - } - seen[state.Name] = true - } - if record.ReleaseRevision != "" { - if len(record.Lifecycle) != len(record.Plan.Interfaces) { - return ErrRecordInvalid - } - for _, state := range record.Lifecycle { - if !state.DeleteCompleted { - return ErrRecordInvalid - } - } - } - return nil -} - -// ProjectNetworkStatus publishes only consumer-safe NSO facts. Retained UIDs, -// claim names, binding metadata, and raw provider messages remain private. -func ProjectNetworkStatus(record *NetworkRecord, now time.Time, maxEvidenceAge time.Duration) (*fleetv1.NetworkStatus, metav1.Condition) { - if record == nil { - return nil, metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionTrue, Reason: "NoAttachmentsRequired", Message: "The claim requests no network attachments."} - } - status := &fleetv1.NetworkStatus{Revision: record.Observation.Revision} - observed := map[string]fleetnetwork.InterfaceObservation{} - for _, iface := range record.Observation.Interfaces { - observed[iface.Name] = iface - } - for _, planned := range record.Plan.Interfaces { - projected := fleetv1.NetworkInterfaceStatus{Name: planned.Name, Network: fleetv1.NetworkReference{APIGroup: "networking.datumapis.com", Kind: "Network", Namespace: planned.NetworkNamespace, Name: planned.NetworkName}} - if iface, ok := observed[planned.Name]; ok { - projected.MTU = iface.MTU - for _, address := range iface.Addresses { - if address.Class == "" { - projected.Addresses = append(projected.Addresses, fleetv1.AddressAssignment{Address: address.Address, Family: address.Family, Gateway: address.Gateway, Primary: address.Primary}) - } else { - projected.ExternalAddresses = append(projected.ExternalAddresses, fleetv1.ExternalAddressAssignment{Address: address.Address, Family: address.Family, ClassRef: fleetv1.LocalReference{Name: address.Class}}) - } - } - for _, condition := range iface.Conditions { - message := "Networking has not verified this requirement." - if condition.Status == metav1.ConditionTrue { - message = "Networking verified this requirement." - } - projected.Conditions = append(projected.Conditions, metav1.Condition{Type: condition.Type, Status: condition.Status, Reason: normalizedNetworkReason(condition), Message: message, ObservedGeneration: condition.ObservedGeneration}) - } - } - status.Interfaces = append(status.Interfaces, projected) - } - current := maxEvidenceAge > 0 && !record.Observation.ObservedAt.IsZero() && !record.Observation.ObservedAt.After(now) && now.Sub(record.Observation.ObservedAt) <= maxEvidenceAge - if current && record.Observation.Programmed(record.Plan) { - return status, metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionTrue, Reason: "AttachmentsVerified", Message: "Networking verified every requested interface."} - } - return status, metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionUnknown, Reason: "NetworkPending", Message: "Waiting for current network allocation, preparation, and programming evidence."} -} - -func normalizedNetworkReason(condition fleetnetwork.Condition) string { - if condition.Status == metav1.ConditionTrue { - return "Verified" - } - switch condition.Reason { - case "NetworkNotAvailableInLocation", "AddressFamilyNotCarried", "AddressFamiliesUnknown", "NetworkContextTerminating", "SubnetTerminating": - return condition.Reason - default: - return "NetworkPending" - } -} diff --git a/internal/controller/requested_hardware_test.go b/internal/controller/requested_hardware_test.go index 2a4ecead..ddc9a8da 100644 --- a/internal/controller/requested_hardware_test.go +++ b/internal/controller/requested_hardware_test.go @@ -63,26 +63,6 @@ func TestValidateExactHardwareRejectsAbsentOrInexactValues(t *testing.T) { } } -func TestAllocatorMatchesOnlyExactCPUAndMemory(t *testing.T) { - observed := fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} - if !matches(exactProfile("p", 1, 24, "128Gi").Spec, observed) { - t.Fatal("exact request did not match equal capacity") - } - if !matches(exactProfile("p", 1, 24, "131072Mi").Spec, observed) { - t.Fatal("equal memory in another unit did not match") - } - for name, spec := range map[string]fleetv1.MachineProfileSpec{ - "fewer cores": exactProfile("p", 1, 8, "128Gi").Spec, - "more cores": exactProfile("p", 1, 32, "128Gi").Spec, - "less memory": exactProfile("p", 1, 24, "64Gi").Spec, - "inexact zero": exactProfile("p", 1, 0, "128Gi").Spec, - } { - if matches(spec, observed) { - t.Errorf("%s matched 24-core 128Gi capacity", name) - } - } -} - func TestSameRequestedHardwareComparesPinnedValues(t *testing.T) { pinned := &fleetv1.RequestedHardwareStatus{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 8}, Memory: fleetv1.MemoryRequirement{Capacity: "32Gi"}} if !SameRequestedHardware(pinned, exactProfile("p", 1, 8, "32768Mi").Spec) { diff --git a/internal/controller/unreadable_records.go b/internal/controller/unreadable_records.go deleted file mode 100644 index 3c837cd4..00000000 --- a/internal/controller/unreadable_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package controller - -import ( - "context" - "fmt" - "sync" - - "github.com/prometheus/client_golang/prometheus" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/metrics" -) - -// ReasonUnreadablePrivateRecord is the Machine condition reason used when a -// private lifecycle record attributed to the Machine cannot be decoded. The -// Machine is not allocated, installed, or released through that record until -// an operator removes it. -const ReasonUnreadablePrivateRecord = "UnreadablePrivateRecord" - -// ErrRecordUnreadable identifies a private lifecycle record that does not -// decode into the current record shape. It wraps ErrRecordInvalid, so every -// caller that fails closed on an invalid record keeps doing so. -var ErrRecordUnreadable = fmt.Errorf("%w: private lifecycle record cannot be decoded and must be removed", ErrRecordInvalid) - -var undecodablePrivateRecords = prometheus.NewCounterVec(prometheus.CounterOpts{ - Name: "fleet_private_lifecycle_record_undecodable_total", - Help: "Private lifecycle records that failed to decode, counted once per record per lifecycle call. Labeled by record type only.", -}, []string{"record_type"}) - -func init() { - metrics.Registry.MustRegister(undecodablePrivateRecords) -} - -// recordMayBelongTo attributes a private record that failed to decode without -// trusting its body. encodeRecord writes the owning claim UID to the -// claim-uid label of every asset, installation, and custody record, so the -// label is the attribution. A record without that label cannot be attributed -// and may belong to any claim, so it is treated as belonging to the caller: -// the caller fails closed rather than proceeding as if the claim had no -// record, which could re-allocate its capacity or double-bind it. -func recordMayBelongTo(secret *corev1.Secret, claimUID types.UID) bool { - owner := secret.Labels[claimUIDLabel] - return owner == "" || types.UID(owner) == claimUID -} - -type undecodableSeenKey struct{} - -type undecodableSeen struct { - mu sync.Mutex - names map[string]struct{} -} - -// withUndecodableReporting scopes reporting to one lifecycle call, so a record -// seen by several scans in that call is logged and counted once. Nested calls -// share the outer scope. -func withUndecodableReporting(ctx context.Context) context.Context { - if _, ok := ctx.Value(undecodableSeenKey{}).(*undecodableSeen); ok { - return ctx - } - return context.WithValue(ctx, undecodableSeenKey{}, &undecodableSeen{names: map[string]struct{}{}}) -} - -// ReportUndecodableRecord logs and counts one private record that failed to -// decode. The log carries the Secret identity and attributed claim UID, never -// record contents. recordType must be a fixed record kind, not a value read -// from the Secret. -func ReportUndecodableRecord(ctx context.Context, recordType string, secret *corev1.Secret, err error) { - if seen, ok := ctx.Value(undecodableSeenKey{}).(*undecodableSeen); ok { - seen.mu.Lock() - _, dup := seen.names[secret.Name] - seen.names[secret.Name] = struct{}{} - seen.mu.Unlock() - if dup { - return - } - } - undecodablePrivateRecords.WithLabelValues(recordType).Inc() - log.FromContext(ctx).Error(err, "private lifecycle record cannot be decoded; remove it to unblock its claim", "recordType", recordType, "secret", secret.Namespace+"/"+secret.Name, "claimUID", secret.Labels[claimUIDLabel]) -} - -// decodeCustodySecret, decodeAssetSecret, and decodeOperationSecret are the -// only decoders lifecycle code calls. Each reports a record that fails to -// decode, so no read path can skip the log and counter. Route decoding for -// event mapping uses the parse functions directly: it runs on every Secret -// event outside any lifecycle call, and the lifecycle call it wakes reports -// the record. -func decodeCustodySecret(ctx context.Context, secret *corev1.Secret) (*ClaimCustodyRecord, error) { - return reportedDecode(ctx, "custody", secret, parseCustodySecret) -} - -func decodeAssetSecret(ctx context.Context, secret *corev1.Secret) (*AssetRecord, error) { - return reportedDecode(ctx, "asset", secret, parseAssetSecret) -} - -func decodeOperationSecret(ctx context.Context, secret *corev1.Secret) (*InstallationRecord, error) { - return reportedDecode(ctx, "installation", secret, parseOperationSecret) -} - -func reportedDecode[T any](ctx context.Context, recordType string, secret *corev1.Secret, parse func(*corev1.Secret) (*T, error)) (*T, error) { - record, err := parse(secret) - if err != nil { - ReportUndecodableRecord(ctx, recordType, secret, err) - } - return record, err -} diff --git a/internal/controller/unreadable_records_test.go b/internal/controller/unreadable_records_test.go deleted file mode 100644 index 9f65e3a6..00000000 --- a/internal/controller/unreadable_records_test.go +++ /dev/null @@ -1,440 +0,0 @@ -package controller - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "testing" - - dto "github.com/prometheus/client_model/go" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" -) - -// withSecondMachine adds machine-2 after the fixture's machine-1, so an -// allocation that cannot use machine-1 has somewhere else to go. -func (f *fixture) withSecondMachine(request AllocationRequest) AllocationRequest { - second := request.MachineCapacities[0] - second.Name, second.UID, second.Spec.DeviceRef.Name = "machine-2", "machine-2-uid", "host-2" - request.MachineCapacities = append(request.MachineCapacities, second) - request.EvidenceObservedAt[second.UID] = f.now - return request -} - -func (f *fixture) allocate(t *testing.T, request AllocationRequest) *AssetRecord { - t.Helper() - ctx := context.Background() - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - record, err := f.coordinator.Allocate(ctx, request) - if err != nil { - t.Fatal(err) - } - return record -} - -// writeOlderAssetShape rewrites an asset record's accepted requirements into -// the pre-exact minimum and maximum CPU and memory shape, which no longer -// decodes. It returns the stored bytes so callers can prove nothing rewrote -// them. -func (f *fixture) writeOlderAssetShape(t *testing.T, assetID string, mutateLabels func(map[string]string)) []byte { - t.Helper() - ctx := context.Background() - var secret corev1.Secret - if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: "private", Name: assetRecordName(assetID)}, &secret); err != nil { - t.Fatal(err) - } - var fields map[string]json.RawMessage - if err := json.Unmarshal(secret.Data[recordDataKey], &fields); err != nil { - t.Fatal(err) - } - fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) - data, err := json.Marshal(fields) - if err != nil { - t.Fatal(err) - } - secret.Data[recordDataKey] = data - if mutateLabels != nil { - mutateLabels(secret.Labels) - } - if err := f.coordinator.client.Update(ctx, &secret); err != nil { - t.Fatal(err) - } - return data -} - -func (f *fixture) storedAsset(t *testing.T, assetID string) []byte { - t.Helper() - var secret corev1.Secret - if err := f.coordinator.client.Get(context.Background(), client.ObjectKey{Namespace: "private", Name: assetRecordName(assetID)}, &secret); err != nil { - t.Fatal(err) - } - return secret.Data[recordDataKey] -} - -func installRequestFor(request AllocationRequest, name string) InstallationRequest { - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: name, UID: types.UID(name + "-uid")}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - return InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} -} - -func undecodableCount(t *testing.T, recordType string) float64 { - t.Helper() - var metric dto.Metric - if err := undecodablePrivateRecords.WithLabelValues(recordType).Write(&metric); err != nil { - t.Fatal(err) - } - return metric.GetCounter().GetValue() -} - -// An older-shape asset record must not stop the coordinator from serving -// other claims, and must keep its own claim blocked without being rewritten. -func TestUndecodableAssetRecordBlocksOnlyItsOwnClaim(t *testing.T) { - cases := []struct { - name string - run func(t *testing.T, f *fixture, other AllocationRequest) - }{ - {name: "allocate", run: func(t *testing.T, f *fixture, other AllocationRequest) { - record := f.allocate(t, other) - if record.MachineName != "machine-2" || record.State != AssetCommitted || record.Epoch != 1 { - t.Fatalf("other claim allocation = %#v", record) - } - }}, - {name: "install", run: func(t *testing.T, f *fixture, other AllocationRequest) { - f.allocate(t, other) - result, err := f.coordinator.Install(context.Background(), installRequestFor(other, "other-install")) - if err != nil || result.Revision == "" { - t.Fatalf("other claim install = %#v, %v", result, err) - } - }}, - {name: "release", run: func(t *testing.T, f *fixture, other AllocationRequest) { - f.allocate(t, other) - released, err := f.coordinator.Release(context.Background(), other.Claim.UID) - if err != nil || !released.SafeToRemoveFinalizer || released.State != AssetReleased { - t.Fatalf("other claim release = %#v, %v", released, err) - } - }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - stale, other := f.withSecondMachine(f.request("stale")), f.withSecondMachine(f.request("other")) - asset := f.allocate(t, stale) - if asset.MachineName != "machine-1" { - t.Fatalf("stale claim allocated %s, want machine-1", asset.MachineName) - } - stored := f.writeOlderAssetShape(t, asset.AssetID, nil) - - tc.run(t, f, other) - - if _, err := f.coordinator.Allocate(ctx, stale); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("stale allocate error = %v, want ErrRecordUnreadable", err) - } - if _, err := f.coordinator.Install(ctx, installRequestFor(stale, "stale-install")); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("stale install error = %v, want ErrRecordUnreadable", err) - } - if released, err := f.coordinator.Release(ctx, stale.Claim.UID); !errors.Is(err, ErrRecordUnreadable) || released.SafeToRemoveFinalizer { - t.Fatalf("stale release = %#v, %v, want ErrRecordUnreadable", released, err) - } - if got := f.storedAsset(t, asset.AssetID); !bytes.Equal(got, stored) { - t.Fatalf("undecodable asset record was rewritten: %s", got) - } - for _, request := range f.executor.requests { - if request.AssetID == asset.AssetID { - t.Fatalf("executor received work for the undecodable asset: %#v", request) - } - } - }) - } -} - -// The claim-uid label attributes an undecodable record. Without it the record -// may belong to any claim, so every claim-scoped scan fails closed. -func TestUndecodableRecordAttribution(t *testing.T) { - cases := []struct { - name string - labels func(map[string]string) - otherBlocks bool - }{ - {name: "labeled for its claim", otherBlocks: false}, - {name: "label names a different claim", labels: func(l map[string]string) { l[claimUIDLabel] = "someone-else" }, otherBlocks: false}, - {name: "label missing", labels: func(l map[string]string) { delete(l, claimUIDLabel) }, otherBlocks: true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - stale := f.request("stale") - asset := f.allocate(t, stale) - f.writeOlderAssetShape(t, asset.AssetID, tc.labels) - _, err := f.coordinator.recordsForClaimScoped(ctx, "other", ProjectIdentity{}) - if blocked := errors.Is(err, ErrRecordUnreadable); blocked != tc.otherBlocks { - t.Fatalf("asset scan for another claim error = %v, want blocked=%v", err, tc.otherBlocks) - } - if tc.labels == nil { - if _, err := f.coordinator.recordsForClaimScoped(ctx, stale.Claim.UID, ProjectIdentity{}); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("asset scan for its own claim error = %v, want ErrRecordUnreadable", err) - } - } - - // The same rule applies to installation records scanned by binding. - operation := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: operationPrefix + "older", Labels: map[string]string{recordTypeLabel: "installation", claimUIDLabel: string(stale.Claim.UID)}}, Type: corev1.SecretType("fleet.datumapis.com/private-lifecycle"), Data: map[string][]byte{recordDataKey: []byte(`{"schemaVersion":1}`)}} - if tc.labels != nil { - tc.labels(operation.Labels) - } - if err := f.coordinator.client.Create(ctx, operation); err != nil { - t.Fatal(err) - } - _, err = f.coordinator.operationsForBinding(ctx, "other", "other-binding") - if blocked := errors.Is(err, ErrRecordUnreadable); blocked != tc.otherBlocks { - t.Fatalf("operation scan for another claim error = %v, want blocked=%v", err, tc.otherBlocks) - } - if tc.labels == nil { - if _, err := f.coordinator.operationsForBinding(ctx, stale.Claim.UID, asset.BindingID); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("operation scan for its own claim error = %v, want ErrRecordUnreadable", err) - } - } - }) - } -} - -// A Released asset record is retained so the next binding advances the -// executor epoch. If it cannot be decoded, its epoch is unknown, so the asset -// is never proposed again: a new binding at an earlier epoch could otherwise -// sit below a stale operation's fence. -func TestUndecodableReleasedRecordKeepsTheEpochFence(t *testing.T) { - cases := []struct { - name string - secondMachine bool - wantErr error - }{ - {name: "only the fenced asset", wantErr: ErrInsufficientCapacity}, - {name: "another asset available", secondMachine: true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - first, next := f.request("first"), f.request("next") - if tc.secondMachine { - first, next = f.withSecondMachine(first), f.withSecondMachine(next) - } - asset := f.allocate(t, first) - if released, err := f.coordinator.Release(ctx, first.Claim.UID); err != nil || !released.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", released, err) - } - stored := f.writeOlderAssetShape(t, asset.AssetID, nil) - executed := len(f.executor.requests) - - if err := f.coordinator.EnsureClaimCustody(ctx, next.Claim, next.NamespaceUID, next.Admission); err != nil { - t.Fatal(err) - } - record, err := f.coordinator.Allocate(ctx, next) - if tc.wantErr != nil { - if !errors.Is(err, tc.wantErr) { - t.Fatalf("allocate error = %v, want %v", err, tc.wantErr) - } - } else if err != nil || record.AssetID == asset.AssetID || record.Epoch != 1 { - t.Fatalf("allocate = %#v, %v, want the other asset at epoch 1", record, err) - } - custody, _, err := f.coordinator.getCustody(ctx, next.Claim.UID) - if err != nil || custody.AssetID == asset.AssetID || custody.ProposedAsset != nil && custody.ProposedAsset.AssetID == asset.AssetID { - t.Fatalf("custody selected the fenced asset: %#v, %v", custody, err) - } - // The released claim's retained operations cannot run again. - if _, err := f.coordinator.Install(ctx, installRequestFor(first, "stale-install")); !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("stale install error = %v, want ErrRecordInvalid", err) - } - if got := f.storedAsset(t, asset.AssetID); !bytes.Equal(got, stored) { - t.Fatalf("undecodable Released record was rewritten: %s", got) - } - for _, request := range f.executor.requests[executed:] { - if request.AssetID == asset.AssetID { - t.Fatalf("executor received work for the fenced asset: %#v", request) - } - } - }) - } -} - -func TestUndecodableRecordsAreCountedOncePerCall(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - stale, other := f.withSecondMachine(f.request("stale")), f.withSecondMachine(f.request("other")) - asset := f.allocate(t, stale) - f.writeOlderAssetShape(t, asset.AssetID, nil) - if err := f.coordinator.EnsureClaimCustody(ctx, other.Claim, other.NamespaceUID, other.Admission); err != nil { - t.Fatal(err) - } - - before := undecodableCount(t, "asset") - // The record is seen by the claim scan and again as candidate machine-1. - if _, err := f.coordinator.Allocate(ctx, other); err != nil { - t.Fatal(err) - } - if got := undecodableCount(t, "asset") - before; got != 1 { - t.Fatalf("asset counter advanced by %v in one call, want 1", got) - } - if _, err := f.coordinator.Allocate(ctx, stale); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("stale allocate error = %v", err) - } - if got := undecodableCount(t, "asset") - before; got != 2 { - t.Fatalf("asset counter advanced by %v after two calls, want 2", got) - } -} - -// selectingOn leaves request's claim in Selecting custody with a proposal for -// the asset another claim already holds, as when two claims race for the -// same free asset and the other claim's exclusive create wins. -func (f *fixture) selectingOn(t *testing.T, request AllocationRequest, held *AssetRecord) { - t.Helper() - ctx := context.Background() - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - binding, fence, err := f.coordinator.authorityIDs() - if err != nil { - t.Fatal(err) - } - proposal := newAssetRecord(request, &request.MachineCapacities[0], held.AssetID, held.Epoch, binding, fence) - if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { - t.Fatal(err) - } -} - -// A claim releasing from Selecting reads its proposed asset's record by name. -// An undecodable record labeled for another claim is that claim's binding, so -// the releasing claim never held the asset: it releases without touching the -// record. A record labeled for the releasing claim, or with no label, might be -// its binding, so release fails closed and keeps the finalizer. -func TestReleaseFromSelectionAttributesAnUndecodableProposedAsset(t *testing.T) { - cases := []struct { - name string - labels func(releasing types.UID) func(map[string]string) - released bool - }{ - {name: "labeled for another claim", released: true}, - {name: "labeled for the releasing claim", labels: func(releasing types.UID) func(map[string]string) { - return func(l map[string]string) { l[claimUIDLabel] = string(releasing) } - }}, - {name: "label missing", labels: func(types.UID) func(map[string]string) { - return func(l map[string]string) { delete(l, claimUIDLabel) } - }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - holder, releasing := f.request("holder"), f.request("releasing") - held := f.allocate(t, holder) - f.selectingOn(t, releasing, held) - var labels func(map[string]string) - if tc.labels != nil { - labels = tc.labels(releasing.Claim.UID) - } - stored := f.writeOlderAssetShape(t, held.AssetID, labels) - executed := len(f.executor.requests) - - result, err := f.coordinator.Release(ctx, releasing.Claim.UID) - custody, _, custodyErr := f.coordinator.getCustody(ctx, releasing.Claim.UID) - if custodyErr != nil { - t.Fatal(custodyErr) - } - if tc.released { - if err != nil || !result.SafeToRemoveFinalizer || custody.State != CustodyReleased { - t.Fatalf("release = %#v, %v, custody %s; want released", result, err, custody.State) - } - } else if !errors.Is(err, ErrRecordUnreadable) || result.SafeToRemoveFinalizer || custody.State != CustodySelecting { - t.Fatalf("release = %#v, %v, custody %s; want ErrRecordUnreadable with custody kept", result, err, custody.State) - } - if !tc.released { - // The claim's own asset scan stops Release first, so check the - // selection path directly as well. - if err := f.coordinator.materializeSelectionForRelease(ctx, custody); !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("materialize selection error = %v, want ErrRecordUnreadable", err) - } - } - if got := f.storedAsset(t, held.AssetID); !bytes.Equal(got, stored) { - t.Fatalf("undecodable proposed asset record was rewritten: %s", got) - } - if len(f.executor.requests) != executed { - t.Fatalf("release sent executor work: %#v", f.executor.requests[executed:]) - } - // The holder's binding is still fenced by its undecodable record. - if tc.released { - if released, err := f.coordinator.Release(ctx, holder.Claim.UID); !errors.Is(err, ErrRecordUnreadable) || released.SafeToRemoveFinalizer { - t.Fatalf("holder release = %#v, %v, want ErrRecordUnreadable", released, err) - } - } - }) - } -} - -// Every lifecycle read that decodes a private record by name reports a record -// that cannot be decoded, not only the scans across claims. -func TestUndecodableRecordsAreReportedOnEveryDecodePath(t *testing.T) { - undecodable := func(name, recordType string, claimUID types.UID) *corev1.Secret { - return &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: name, Labels: map[string]string{recordTypeLabel: recordType, claimUIDLabel: string(claimUID)}}, Type: corev1.SecretType("fleet.datumapis.com/private-lifecycle"), Data: map[string][]byte{recordDataKey: []byte(`{"schemaVersion":1}`)}} - } - cases := []struct { - name string - recordType string - run func(t *testing.T, f *fixture) error - // released is set where the record belongs to another claim, so the - // call succeeds after reporting it. - released bool - }{ - {name: "EnsureClaimCustody", recordType: "custody", run: func(t *testing.T, f *fixture) error { - request := f.request("claim") - name := custodyRecordName(LocalClaimScope(request.NamespaceUID), request.Claim.UID) - if err := f.coordinator.client.Create(context.Background(), undecodable(name, "custody", request.Claim.UID)); err != nil { - t.Fatal(err) - } - return f.coordinator.EnsureClaimCustody(context.Background(), request.Claim, request.NamespaceUID, request.Admission) - }}, - {name: "getOrCreateOperation", recordType: "installation", run: func(t *testing.T, f *fixture) error { - if err := f.coordinator.client.Create(context.Background(), undecodable(operationPrefix+"existing", "installation", "claim")); err != nil { - t.Fatal(err) - } - _, _, err := f.coordinator.getOrCreateOperation(context.Background(), operationPrefix+"existing", InstallationRequest{}, &AssetRecord{}, "None", ResolvedImage{}) - return err - }}, - {name: "markOperationSucceeded", recordType: "installation", run: func(t *testing.T, f *fixture) error { - if err := f.coordinator.client.Create(context.Background(), undecodable(operationPrefix+"running", "installation", "claim")); err != nil { - t.Fatal(err) - } - _, err := f.coordinator.markOperationSucceeded(context.Background(), operationPrefix+"running", &InstallationRecord{}) - return err - }}, - {name: "materializeSelectionForRelease", recordType: "asset", released: true, run: func(t *testing.T, f *fixture) error { - holder, releasing := f.request("holder"), f.request("releasing") - held := f.allocate(t, holder) - f.selectingOn(t, releasing, held) - f.writeOlderAssetShape(t, held.AssetID, nil) - custody, _, err := f.coordinator.getCustody(context.Background(), releasing.Claim.UID) - if err != nil { - t.Fatal(err) - } - return f.coordinator.materializeSelectionForRelease(context.Background(), custody) - }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - f := newFixture(t) - before := undecodableCount(t, tc.recordType) - err := tc.run(t, f) - if tc.released && err != nil || !tc.released && !errors.Is(err, ErrRecordUnreadable) { - t.Fatalf("error = %v, want released=%v", err, tc.released) - } - if got := undecodableCount(t, tc.recordType) - before; got != 1 { - t.Fatalf("%s counter advanced by %v, want 1", tc.recordType, got) - } - }) - } -} diff --git a/internal/coordination/cell.go b/internal/coordination/cell.go new file mode 100644 index 00000000..9044c3de --- /dev/null +++ b/internal/coordination/cell.go @@ -0,0 +1,148 @@ +package coordination + +import ( + "context" + "encoding/json" + "errors" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/client-go/dynamic" + + "go.datum.net/fleet/internal/site" +) + +// ErrNotDelivered means the handoff is not an assignment delivered to this +// cell under its own name, or it is being deleted. The worker sends nothing. +var ErrNotDelivered = errors.New("coordination: the handoff is not an assignment for this cell") + +// Cell is one cell's view of its delivered handoffs. Execution is split by +// least privilege: a per-operation worker Job runs one assignment and can +// read only its own handoff; the observer is the only writer of handoff +// status, and reports only what the site store holds. +type Cell struct { + API dynamic.Interface + Namespace string + Name string + Now func() time.Time +} + +func (c *Cell) now() time.Time { + if c.Now != nil { + return c.Now().UTC() + } + return time.Now().UTC() +} + +func (c *Cell) api() dynamic.ResourceInterface { + return c.API.Resource(Resource).Namespace(c.Namespace) +} + +// assignment validates one delivered assignment handoff. +func (c *Cell) assignment(object *unstructured.Unstructured) (site.Assignment, Spec, error) { + spec, err := decode(object, nil) + if err != nil || spec.Cell != c.Name || object.GetLabels()[CellLabel] != c.Name || object.GetLabels()[RoleLabel] != RoleAssignment || object.GetDeletionTimestamp() != nil { + return site.Assignment{}, spec, ErrNotDelivered + } + var assignment site.Assignment + if err := json.Unmarshal([]byte(spec.AssignmentJSON), &assignment); err != nil || assignment.Device != spec.Device || object.GetName() != AssignmentName(assignment) { + return site.Assignment{}, spec, ErrNotDelivered + } + return assignment, spec, nil +} + +// Work runs the named handoff's assignment through the site runner. A +// DeviceRecovery only raises the fence and confirms the older worker +// stopped. Work never writes status. +func (c *Cell) Work(ctx context.Context, name string, runner *site.Runner) error { + object, err := c.api().Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return err + } + assignment, _, err := c.assignment(object) + if err != nil { + return err + } + if assignment.Operation.Kind == "DeviceRecovery" { + return runner.Fence(ctx, assignment) + } + _, err = runner.Run(ctx, assignment) + return err +} + +// Publish writes the observation of one handoff: the Device's stored fences +// and, for an assignment, its stored result. It deletes the site's copy of a +// result the coordinator answered. +func (c *Cell) Publish(ctx context.Context, object *unstructured.Unstructured, store *site.Store, results *site.Results) error { + observation := Observation{Cell: c.Name, ObservedAt: c.now()} + var device string + switch object.GetLabels()[RoleLabel] { + case RoleAssignment: + assignment, spec, err := c.assignment(object) + if err != nil { + return err + } + device, observation.AssignmentDigest = assignment.Device, Digest(spec.AssignmentJSON) + result, found, err := results.Get(assignment.Device, assignment.Operation, assignment.Fence) + if err != nil { + return err + } + if found && object.GetLabels()[AnsweredLabel] == "true" { + if err := results.Forget(assignment.Device, result); err != nil { + return err + } + } else if found { + observation.Result = &result + } + case RoleReport: + spec, err := decode(object, nil) + if err != nil || spec.Cell != c.Name || object.GetLabels()[CellLabel] != c.Name || spec.AssignmentJSON != "" || object.GetName() != ReportName(spec.Device) { + return ErrNotDelivered + } + device = spec.Device + default: + return ErrNotDelivered + } + seen, stopped, err := store.Peek(device) + if err != nil { + return err + } + observation.Fence = FenceReport{Seen: seen, Stopped: stopped} + data, err := json.Marshal(CellStatus{Observation: &observation}) + if err != nil { + return err + } + var status map[string]any + if err := json.Unmarshal(data, &status); err != nil { + return err + } + object.Object["status"] = status + _, err = c.api().UpdateStatus(ctx, object, metav1.UpdateOptions{}) + return err +} + +// Observe republishes every handoff of this cell on a fixed interval, so the +// coordinator can check that fence reports are fresh. onError must not log +// handoff contents. +func (c *Cell) Observe(ctx context.Context, interval time.Duration, store *site.Store, results *site.Results, onError func(string, error)) error { + for { + list, err := c.api().List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + c.Name}) + if err != nil { + onError("", err) + } else { + for index := range list.Items { + if err := c.Publish(ctx, &list.Items[index], store, results); err != nil { + onError(list.Items[index].GetName(), err) + } + } + } + timer := time.NewTimer(interval) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} diff --git a/internal/coordination/mapping.go b/internal/coordination/mapping.go deleted file mode 100644 index 55cefb39..00000000 --- a/internal/coordination/mapping.go +++ /dev/null @@ -1,71 +0,0 @@ -package coordination - -import ( - "context" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/dynamic" -) - -// LocalAssetMapping is an explicit local-test binding of one project-scoped -// Device to the disposable provider's fixed physical ID. No alias or suffix -// matching is allowed. The exact original request remains durable in the local -// handoff and the backend retains its exact translated request before effects. -// This is a synthetic hardware enrollment seam, not production authority. -type LocalAssetMapping struct { - API dynamic.Interface - Namespace, Cell, ScopedAsset, PhysicalAsset string - Backend executor.Client -} - -func (m *LocalAssetMapping) request(ctx context.Context, id string) (Intent, simulator.Request, error) { - obj, err := m.API.Resource(Resource).Namespace(m.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) - if err != nil { - return Intent{}, simulator.Request{}, err - } - i, _, err := decode(obj) - if err != nil { - return i, simulator.Request{}, err - } - if i.Cell != m.Cell || i.Request.ID != id || m.ScopedAsset == "" || m.PhysicalAsset == "" || i.Request.AssetID != m.ScopedAsset { - return i, simulator.Request{}, executor.ErrFenced - } - translated := i.Request - translated.AssetID = m.PhysicalAsset - return i, translated, nil -} -func (m *LocalAssetMapping) translate(i Intent, translated simulator.Request, r simulator.OperationResult) (simulator.OperationResult, error) { - if err := ValidateResult(Intent{Cell: i.Cell, Request: translated}, r); err != nil { - return simulator.OperationResult{}, err - } - r.InputDigest, _ = simulator.RequestDigest(i.Request) - return r, nil -} -func (m *LocalAssetMapping) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { - i, t, err := m.request(ctx, r.ID) - if err != nil { - return simulator.OperationResult{}, err - } - if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { - return simulator.OperationResult{}, executor.ErrConflict - } - result, err := m.Backend.Execute(ctx, t) - if err != nil { - return simulator.OperationResult{}, err - } - return m.translate(i, t, result) -} -func (m *LocalAssetMapping) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { - i, t, err := m.request(ctx, id) - if err != nil { - return simulator.OperationResult{}, false, err - } - r, found, err := m.Backend.Lookup(ctx, id) - if err != nil || !found { - return r, found, err - } - result, err := m.translate(i, t, r) - return result, true, err -} diff --git a/internal/coordination/mapping_test.go b/internal/coordination/mapping_test.go deleted file mode 100644 index d1fbfd4e..00000000 --- a/internal/coordination/mapping_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package coordination - -import ( - "context" - "errors" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/dynamic/fake" - "testing" -) - -func TestLocalMappingRequiresExactAssetAndRecoversDigest(t *testing.T) { - i, s, _ := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - translated := i.Request - translated.AssetID = "local-physical-device" - digest, _ := simulator.RequestDigest(translated) - result := s.Reflected[0].Observation.Result - result.InputDigest = digest - backend := &effect{result: result} - mapping := LocalAssetMapping{API: api, Namespace: "private", Cell: i.Cell, ScopedAsset: i.Request.AssetID, PhysicalAsset: translated.AssetID, Backend: backend} - original, err := mapping.Execute(context.Background(), i.Request) - if err != nil { - t.Fatal(err) - } - if original.InputDigest != s.Reflected[0].Observation.Result.InputDigest { - t.Fatal("lost original digest") - } - recovered, found, err := mapping.Lookup(context.Background(), i.Request.ID) - if err != nil || !found || recovered.InputDigest != original.InputDigest { - t.Fatal("restart lost exact mapping", err) - } - mapping.ScopedAsset = "another-project/same-device" - if _, err := mapping.Execute(context.Background(), i.Request); !errors.Is(err, executor.ErrFenced) { - t.Fatal("accepted alias", err) - } - if backend.calls != 1 { - t.Fatal("duplicate execution") - } -} diff --git a/internal/coordination/recovery_adversarial_test.go b/internal/coordination/recovery_adversarial_test.go deleted file mode 100644 index a23e92e8..00000000 --- a/internal/coordination/recovery_adversarial_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package coordination - -import ( - "context" - "errors" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/dynamic/fake" -) - -// journaled models a provider that retains each operation before effects: -// Lookup of an unfinished operation is Unknown, and Execute of a retained ID -// resumes it (digest-checked) rather than starting another effect. -type journaled struct { - retained map[string]simulator.Request - done map[string]simulator.OperationResult - lookupErr error - starts int - resumes []simulator.Request - finish simulator.OperationResult - complete bool -} - -func (j *journaled) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { - if j.lookupErr != nil { - return simulator.OperationResult{}, false, j.lookupErr - } - if r, ok := j.done[id]; ok { - return r, true, nil - } - if _, ok := j.retained[id]; ok { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown - } - return simulator.OperationResult{}, false, nil -} -func (j *journaled) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { - if old, ok := j.retained[r.ID]; ok { - a, _ := simulator.RequestDigest(old) - b, _ := simulator.RequestDigest(r) - if a != b { - return simulator.OperationResult{}, executor.ErrConflict - } - j.resumes = append(j.resumes, r) - } else { - j.retained[r.ID] = r - j.starts++ - } - if !j.complete { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - j.done[r.ID] = j.finish - return j.finish, nil -} - -func observed(t *testing.T, obj *unstructured.Unstructured) bool { - t.Helper() - _, found, err := unstructured.NestedMap(obj.Object, "status", "observation") - if err != nil { - t.Fatal(err) - } - return found -} - -func TestAdversarialCellRestartResumesUnfinishedOperationOnce(t *testing.T) { - ctx := context.Background() - i, s, now := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result} - name := Name(i.Request.ID) - newCell := func() *Cell { - return &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} - } - // First delivery starts the operation; its outcome is lost. - if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost outcome must stay unknown: %v", err) - } - // A restarted cell sees Lookup Unknown and resumes; still unfinished. - if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("unfinished operation must stay unknown: %v", err) - } - obj, err := api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) - if err != nil { - t.Fatal(err) - } - if observed(t, obj) { - t.Fatal("unknown outcome was published as an observation") - } - provider.complete = true - if err := reconcile(newCell(), ctx, name); err != nil { - t.Fatalf("restart did not recover the retained operation: %v", err) - } - if err := reconcile(newCell(), ctx, name); err != nil { - t.Fatal(err) - } - if provider.starts != 1 || len(provider.resumes) != 2 { - t.Fatalf("want one start and two exact resumes, got %d starts %d resumes", provider.starts, len(provider.resumes)) - } - for _, r := range provider.resumes { - if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { - t.Fatal("resume did not re-deliver the exact retained request") - } - } - obj, err = api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) - if err != nil { - t.Fatal(err) - } - if !observed(t, obj) { - t.Fatal("terminal observation missing after recovery") - } -} - -func TestAdversarialCellLookupFailuresNeverExecute(t *testing.T) { - for name, lookupErr := range map[string]error{ - "conflict": executor.ErrConflict, - "fenced": executor.ErrFenced, - "transport": errors.New("journal unreadable"), - } { - t.Run(name, func(t *testing.T) { - i, s, now := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result, complete: true, lookupErr: lookupErr} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} - if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, lookupErr) { - t.Fatalf("lookup failure not reported: %v", err) - } - if provider.starts != 0 || len(provider.resumes) != 0 { - t.Fatal("lookup failure led to an effect") - } - }) - } -} - -// foundUnknown reports a retained but unverifiable terminal record. Resuming -// would only replay the same bytes, so the cell must report it, not execute. -type foundUnknown struct{ calls int } - -func (f *foundUnknown) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return simulator.OperationResult{}, true, executor.ErrOutcomeUnknown -} -func (f *foundUnknown) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { - f.calls++ - return simulator.OperationResult{}, nil -} - -func TestAdversarialCellFoundUnknownIsNotSuccess(t *testing.T) { - i, _, now := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - e := &foundUnknown{} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} - if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) || e.calls != 0 { - t.Fatalf("found-unknown result: %v, executes %d", err, e.calls) - } -} diff --git a/internal/coordination/run.go b/internal/coordination/run.go deleted file mode 100644 index c32ea32b..00000000 --- a/internal/coordination/run.go +++ /dev/null @@ -1,40 +0,0 @@ -package coordination - -import ( - "context" - "errors" - "time" - - "go.datum.net/fleet/internal/executor" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// CellLabel selects the handoffs delivered for one cell. -const CellLabel = "coordination.fleet.datumapis.com/cell" - -// Observe refreshes journal-derived observations for this cell's delivered -// handoffs on a fixed interval. Execution, retry and replacement belong to the -// Kubernetes Job controller and KRO; this loop only republishes terminal -// results so management can check freshness. A pending or invalid handoff is -// reported to onError, which must not log handoff contents. -func (c *Cell) Observe(ctx context.Context, interval time.Duration, onError func(string, error)) error { - for { - list, err := c.API.Resource(Resource).Namespace(c.Namespace).List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + c.Name}) - if err != nil { - onError("", err) - } else { - for _, obj := range list.Items { - if err := c.Publish(ctx, obj.GetName()); err != nil && !errors.Is(err, executor.ErrOutcomeUnknown) { - onError(obj.GetName(), err) - } - } - } - t := time.NewTimer(interval) - select { - case <-ctx.Done(): - t.Stop() - return ctx.Err() - case <-t.C: - } - } -} diff --git a/internal/coordination/site_test.go b/internal/coordination/site_test.go deleted file mode 100644 index 6019a468..00000000 --- a/internal/coordination/site_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package coordination - -import ( - "context" - "errors" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/dynamic/fake" -) - -// reconcile composes the two site roles: the worker Job executes, then the -// observer publishes from the provider journal. -func reconcile(c *Cell, ctx context.Context, name string) error { - if err := c.Execute(ctx, name); err != nil { - return err - } - return c.Publish(ctx, name) -} - -func TestWorkerExecuteNeverWritesStatus(t *testing.T) { - i, s, now := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - e := &effect{result: s.Reflected[0].Observation.Result} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} - if err := c.Execute(context.Background(), Name(i.Request.ID)); err != nil || e.calls != 1 { - t.Fatalf("execute: %v calls %d", err, e.calls) - } - for _, a := range api.Actions() { - if a.GetVerb() != "get" { - t.Fatalf("worker used %s on %s", a.GetVerb(), a.GetSubresource()) - } - } -} - -func TestObserverPublishNeverExecutes(t *testing.T) { - ctx := context.Background() - i, s, now := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - provider := &journaled{retained: map[string]simulator.Request{i.Request.ID: i.Request}, done: map[string]simulator.OperationResult{}} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} - if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("unfinished journal must stay unknown: %v", err) - } - empty := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}} - c.Executor = empty - if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("absent journal record must stay unknown: %v", err) - } - if provider.starts+len(provider.resumes)+empty.starts+len(empty.resumes) != 0 { - t.Fatal("observer executed an effect") - } - obj, _ := api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) - if observed(t, obj) { - t.Fatal("unknown outcome published") - } - // A terminal but mismatched journal result is not published either. - wrong := s.Reflected[0].Observation.Result - wrong.InputDigest = "0" - c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: wrong}} - if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("mismatched terminal result accepted: %v", err) - } - c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result}} - if err := c.Publish(ctx, Name(i.Request.ID)); err != nil { - t.Fatal(err) - } - obj, _ = api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) - if !observed(t, obj) { - t.Fatal("terminal journal result was not published") - } -} - -// A re-delivered copy under another name, a wrong-cell intent, or an invalid -// intent never reaches the executor. -func TestDeliveryFaultsFenceBeforeEffects(t *testing.T) { - i, s, now := fixture() - duplicate := object("private", i) - duplicate.SetName("copy-of-" + Name(i.Request.ID)) - wrongCell := i - wrongCell.Cell = "other-cell" - wrongObj := object("private", wrongCell) - wrongObj.SetLabels(map[string]string{CellLabel: i.Cell}) - invalid := object("private", i) - invalid.SetName("op-invalid") - _ = unstructured.SetNestedField(invalid.Object, "{", "spec", "requestJSON") - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), duplicate, invalid) - _, _ = api.Resource(Resource).Namespace("private").Create(context.Background(), wrongObj, metav1.CreateOptions{}) - for name, want := range map[string]error{duplicate.GetName(): executor.ErrFenced, Name(i.Request.ID): executor.ErrFenced, "op-invalid": executor.ErrInvalid} { - e := &effect{result: s.Reflected[0].Observation.Result} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} - if err := c.Execute(context.Background(), name); !errors.Is(err, want) || e.calls != 0 { - t.Fatalf("%s: %v calls %d", name, err, e.calls) - } - if err := c.Publish(context.Background(), name); !errors.Is(err, want) { - t.Fatalf("%s publish: %v", name, err) - } - } -} - -func TestObserveListsOnlyThisCell(t *testing.T) { - i, s, now := fixture() - other := i - other.Cell = "other-cell" - other.Request.ID = "other-op" - api := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}, object("private", i), object("private", other)) - done := map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result} - c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: &journaled{retained: map[string]simulator.Request{}, done: done}, Now: func() time.Time { return now }} - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - var errs []error - _ = c.Observe(ctx, time.Hour, func(_ string, err error) { errs = append(errs, err) }) - if len(errs) != 0 { - t.Fatalf("unexpected observer errors: %v", errs) - } - mine, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(i.Request.ID), metav1.GetOptions{}) - theirs, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(other.Request.ID), metav1.GetOptions{}) - if !observed(t, mine) || observed(t, theirs) { - t.Fatal("observer published outside its cell selector") - } -} diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index f3b836b5..42ff7d63 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -1,5 +1,9 @@ -// Package coordination implements the experimental management -> Karmada -> -// cell executor transport. It is not a production admission authority. +// Package coordination is the federation layer between the custody +// coordinator and a cell: the coordinator writes handoffs on the Karmada API, +// Karmada delivers each to its cell, and the cell's status comes back through +// Karmada's status reflection. A handoff carries either one admitted +// operation's assignment or a request for a Device's fence report. It is a +// local acceptance transport, not a production admission authority. package coordination import ( @@ -8,163 +12,147 @@ import ( "encoding/hex" "encoding/json" "errors" - "fmt" - "time" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" + + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" ) var Resource = schema.GroupVersionResource{Group: "coordination.fleet.datumapis.com", Version: "v1alpha1", Resource: "machineallocationhandoffs"} -const Kind = "MachineAllocationHandoff" +const ( + Kind = "MachineAllocationHandoff" + // CellLabel selects the handoffs delivered to one cell. + CellLabel = "coordination.fleet.datumapis.com/cell" + // RoleLabel is RoleAssignment or RoleReport. Only assignments start a + // worker. + RoleLabel = "coordination.fleet.datumapis.com/role" + RoleAssignment = "assignment" + RoleReport = "report" + // AnsweredLabel marks an assignment whose result the coordinator + // answered. The cell then deletes its copy of the result. + AnsweredLabel = "coordination.fleet.datumapis.com/answered" +) -// Intent is immutable. Request retains the allocator's exact operation, asset, -// allocation, epoch, fence and inputs before federation may deliver any effect. -type Intent struct { - Cell string `json:"cell"` - Request simulator.Request `json:"-"` -} +var ( + // ErrConflict means a handoff exists with other contents. + ErrConflict = errors.New("coordination: the handoff exists with other contents") + // ErrInvalid means a handoff or its reflected status is malformed, from + // another cell, or stale. + ErrInvalid = errors.New("coordination: invalid handoff or reflection") +) -// Encode exact request bytes as a string so an API server cannot reorder opaque -// input object fields and silently change the executor's retained digest. -func (i Intent) MarshalJSON() ([]byte, error) { - b, err := json.Marshal(i.Request) - if err != nil { - return nil, err - } - return json.Marshal(struct { - Cell string `json:"cell"` - RequestJSON string `json:"requestJSON"` - }{i.Cell, string(b)}) +// Spec is a handoff's immutable contents. +type Spec struct { + Cell string `json:"cell"` + // Device is "/". + Device string `json:"device"` + // AssignmentJSON is the exact assignment, as a string so an API server + // cannot reorder it. A report handoff has none. + AssignmentJSON string `json:"assignmentJSON,omitempty"` } -func (i *Intent) UnmarshalJSON(b []byte) error { - var wire struct { - Cell string `json:"cell"` - RequestJSON string `json:"requestJSON"` - } - if err := json.Unmarshal(b, &wire); err != nil { - return err - } - i.Cell = wire.Cell - return json.Unmarshal([]byte(wire.RequestJSON), &i.Request) + +// FenceReport is the cell's stored fences for the Device. +type FenceReport struct { + Seen int64 `json:"seen"` + Stopped int64 `json:"stopped"` } +// Observation is what the cell's observer reports for one handoff. type Observation struct { - Cell string `json:"cell"` - IntentDigest string `json:"intentDigest"` - ObservedAt time.Time `json:"observedAt"` - Result simulator.OperationResult `json:"result"` + Cell string `json:"cell"` + // AssignmentDigest is the digest of the assignment observed, empty for a + // report. + AssignmentDigest string `json:"assignmentDigest,omitempty"` + ObservedAt time.Time `json:"observedAt"` + Fence FenceReport `json:"fence"` + Result *custody.SiteResult `json:"result,omitempty"` } + +// CellStatus is the status the cell writes. +type CellStatus struct { + Observation *Observation `json:"observation,omitempty"` +} + +// Reflected is one cell's status as Karmada aggregates it on the hub. type Reflected struct { ClusterName string `json:"clusterName"` Observation Observation `json:"observation"` } -type Status struct { - Observation *Observation `json:"observation,omitempty"` - Reflected []Reflected `json:"reflected,omitempty"` + +// HubStatus is the status Karmada writes on the hub. +type HubStatus struct { + Reflected []Reflected `json:"reflected,omitempty"` } -func Name(id string) string { - sum := sha256.Sum256([]byte(id)) - return "op-" + hex.EncodeToString(sum[:])[:40] +// AssignmentName is the only name an assignment's handoff may have. +func AssignmentName(assignment site.Assignment) string { + return "op-" + digest(assignment.Device + "/" + assignment.Key())[:40] } -func Digest(i Intent) string { - b, _ := json.Marshal(i) - sum := sha256.Sum256(b) + +// ReportName is the only name a Device's report handoff may have. +func ReportName(device string) string { return "fence-" + digest(device)[:40] } + +func digest(value string) string { + sum := sha256.Sum256([]byte(value)) return hex.EncodeToString(sum[:]) } -func (i Intent) Validate() error { - r := i.Request - if i.Cell == "" || r.ID == "" || r.AssetID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" { - return errors.New("incomplete retained execution authority") - } - switch r.Kind { - case "install", "cleanup", "power": - default: - return errors.New("unsupported operation kind") - } - _, err := simulator.RequestDigest(r) - return err -} -func decode(obj *unstructured.Unstructured) (Intent, Status, error) { - var i Intent - var s Status - b, err := json.Marshal(obj.Object["spec"]) - if err != nil { - return i, s, err - } - if err = json.Unmarshal(b, &i); err != nil { - return i, s, err + +// Digest is the digest of an assignment's exact JSON. +func Digest(assignmentJSON string) string { return digest(assignmentJSON) } + +func decode(object *unstructured.Unstructured, status any) (Spec, error) { + var parsed struct { + Spec Spec `json:"spec"` + Status json.RawMessage `json:"status"` } - b, err = json.Marshal(obj.Object["status"]) + data, err := object.MarshalJSON() if err != nil { - return i, s, err - } - if err = json.Unmarshal(b, &s); err != nil { - return i, s, err + return Spec{}, err } - return i, s, i.Validate() -} -func object(ns string, i Intent) *unstructured.Unstructured { - b, _ := json.Marshal(i) - var spec map[string]interface{} - _ = json.Unmarshal(b, &spec) - return &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": Resource.GroupVersion().String(), "kind": Kind, "metadata": map[string]interface{}{"name": Name(i.Request.ID), "namespace": ns, "labels": map[string]interface{}{CellLabel: i.Cell}}, "spec": spec}} -} - -// ValidateResult never interprets an incomplete/uncertain result as success. -func ValidateResult(i Intent, r simulator.OperationResult) error { - d, err := simulator.RequestDigest(i.Request) - if err != nil || r.ID != i.Request.ID || r.Kind != i.Request.Kind || r.InputDigest != d || r.Phase != "Succeeded" || r.CompletedAt == nil || r.CreatedAt.IsZero() || r.CompletedAt.Before(r.CreatedAt) { - return executor.ErrOutcomeUnknown + if err := json.Unmarshal(data, &parsed); err != nil { + return Spec{}, err } - switch r.Kind { - case "install": - if r.Result != "installed" { - return executor.ErrOutcomeUnknown - } - case "cleanup": - if r.Result != "clean" { - return executor.ErrOutcomeUnknown + if status != nil && len(parsed.Status) != 0 { + if err := json.Unmarshal(parsed.Status, status); err != nil { + return Spec{}, err } } - return nil + return parsed.Spec, nil } -func ValidateReflection(i Intent, s Status, now time.Time, maxAge time.Duration) (simulator.OperationResult, error) { - // ClusterName is supplied by Karmada's status aggregator, independently of - // the cell-reported identity. Never take the first of conflicting replicas. - if i.Validate() != nil || maxAge <= 0 || len(s.Reflected) != 1 { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - r := s.Reflected[0] - o := r.Observation - if r.ClusterName != i.Cell || o.Cell != i.Cell || o.IntentDigest != Digest(i) || o.ObservedAt.IsZero() || o.ObservedAt.After(now) || now.Sub(o.ObservedAt) > maxAge { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - if err := ValidateResult(i, o.Result); err != nil { - return simulator.OperationResult{}, err - } - if o.Result.CompletedAt.After(o.ObservedAt) { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - return o.Result, nil + +func newObject(namespace, name, role string, spec Spec) *unstructured.Unstructured { + object := &unstructured.Unstructured{} + object.SetAPIVersion(Resource.GroupVersion().String()) + object.SetKind(Kind) + object.SetNamespace(namespace) + object.SetName(name) + object.SetLabels(map[string]string{CellLabel: spec.Cell, RoleLabel: role}) + data, _ := json.Marshal(spec) + var fields map[string]any + _ = json.Unmarshal(data, &fields) + object.Object["spec"] = fields + return object } -// Hub implements executor.Client. Only management holds this client. It writes -// immutable intent, reads federation-owned status, and never writes hub status. -// The caller must have retained lifecycle authority before Execute. +// Hub is the coordinator's view of one cell through Karmada. It implements +// delivery.Site. It writes handoffs and their answered label; it never +// writes status. type Hub struct { - API dynamic.Interface - Namespace, Cell string - MaxAge time.Duration - Now func() time.Time + API dynamic.Interface + Namespace string + Cell string + // MaxAge is how old a fence report may be. A result is a durable fact + // and has no age limit. + MaxAge time.Duration + Now func() time.Time } func (h *Hub) now() time.Time { @@ -173,129 +161,105 @@ func (h *Hub) now() time.Time { } return time.Now().UTC() } -func (h *Hub) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { - if h.API == nil || h.Namespace == "" { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - i := Intent{Cell: h.Cell, Request: r} - if err := i.Validate(); err != nil { - return simulator.OperationResult{}, err - } - api := h.API.Resource(Resource).Namespace(h.Namespace) - obj, err := api.Create(ctx, object(h.Namespace, i), metav1.CreateOptions{}) + +func (h *Hub) api() dynamic.ResourceInterface { return h.API.Resource(Resource).Namespace(h.Namespace) } + +// ensure creates the handoff or requires the existing one to be identical. +func (h *Hub) ensure(ctx context.Context, name, role string, spec Spec) (*unstructured.Unstructured, error) { + object, err := h.api().Create(ctx, newObject(h.Namespace, name, role, spec), metav1.CreateOptions{}) if apierrors.IsAlreadyExists(err) { - obj, err = api.Get(ctx, Name(r.ID), metav1.GetOptions{}) + object, err = h.api().Get(ctx, name, metav1.GetOptions{}) } if err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: handoff persistence unavailable", executor.ErrOutcomeUnknown) + return nil, err } - retained, status, err := decode(obj) - if err != nil || Digest(retained) != Digest(i) { - return simulator.OperationResult{}, executor.ErrConflict + retained, err := decode(object, nil) + if err != nil || retained != spec || object.GetLabels()[RoleLabel] != role || object.GetLabels()[CellLabel] != h.Cell { + return nil, ErrConflict } - return ValidateReflection(retained, status, h.now(), h.MaxAge) + return object, nil } -func (h *Hub) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { - if h.API == nil || h.Namespace == "" || id == "" { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown - } - obj, err := h.API.Resource(Resource).Namespace(h.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - return simulator.OperationResult{}, false, nil - } + +func (h *Hub) Deliver(ctx context.Context, assignment site.Assignment) error { + data, err := json.Marshal(assignment) if err != nil { - return simulator.OperationResult{}, false, err - } - i, s, err := decode(obj) - if err != nil || i.Request.ID != id || i.Cell != h.Cell { - return simulator.OperationResult{}, true, executor.ErrConflict + return err } - r, err := ValidateReflection(i, s, h.now(), h.MaxAge) - return r, true, err + _, err = h.ensure(ctx, AssignmentName(assignment), RoleAssignment, Spec{Cell: h.Cell, Device: assignment.Device, AssignmentJSON: string(data)}) + return err } -// Cell is the selected location's view of delivered intent. Site execution is -// split by least privilege: a per-operation worker Job calls Execute and holds -// only read access to its one handoff; the site observer calls Publish and is -// the only writer of handoff status. Publish derives every observation from -// the provider journal, never from Job, Pod or KRO status. -type Cell struct { - API dynamic.Interface - Namespace, Name string - Executor executor.Client - Now func() time.Time +// reflected returns the one valid observation of this cell. +func (h *Hub) reflected(object *unstructured.Unstructured) (Spec, Observation, error) { + var status HubStatus + spec, err := decode(object, &status) + if err != nil || spec.Cell != h.Cell || len(status.Reflected) != 1 { + return spec, Observation{}, ErrInvalid + } + reflected := status.Reflected[0] + observation := reflected.Observation + if reflected.ClusterName != h.Cell || observation.Cell != h.Cell || observation.ObservedAt.IsZero() || observation.ObservedAt.After(h.now()) { + return spec, Observation{}, ErrInvalid + } + return spec, observation, nil } -// intent reads and validates one delivered handoff for this cell. -func (c *Cell) intent(ctx context.Context, name string) (*unstructured.Unstructured, Intent, error) { - if c.API == nil || c.Executor == nil || c.Namespace == "" || c.Name == "" { - return nil, Intent{}, executor.ErrOutcomeUnknown - } - obj, err := c.API.Resource(Resource).Namespace(c.Namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return nil, Intent{}, err - } - i, _, err := decode(obj) +// Fence reads the Device's fence report, creating its report handoff on +// first use. A missing, stale or foreign report is not a report. +func (h *Hub) Fence(ctx context.Context, device string) (custody.SiteFence, bool, error) { + object, err := h.ensure(ctx, ReportName(device), RoleReport, Spec{Cell: h.Cell, Device: device}) if err != nil { - return nil, Intent{}, fmt.Errorf("%w: invalid delivered intent", executor.ErrInvalid) + return custody.SiteFence{}, false, err } - if i.Cell != c.Name || name != Name(i.Request.ID) || obj.GetDeletionTimestamp() != nil { - return nil, Intent{}, executor.ErrFenced + spec, observation, err := h.reflected(object) + if err != nil || spec.Device != device || observation.AssignmentDigest != "" || h.now().Sub(observation.ObservedAt) > h.MaxAge { + return custody.SiteFence{}, false, nil } - return obj, i, nil + return custody.SiteFence{Seen: observation.Fence.Seen, Stopped: observation.Fence.Stopped}, true, nil } -// Execute runs or resumes exactly the delivered operation and returns nil only -// for a validated terminal provider result. It never writes status. -// -// Lookup Unknown means the provider retained this exact operation but has not -// reached a terminal result. Resuming re-delivers the identical retained -// request under the same operation ID, which the executor contract replays -// against its own journal (digest-checked, never a new operation). Conflict, -// fencing and transport errors stop before any effect. -func (c *Cell) Execute(ctx context.Context, name string) error { - _, i, err := c.intent(ctx, name) +// Results returns each unanswered assignment's reflected result. A result +// counts only when it is for exactly the assignment the handoff carries. +func (h *Hub) Results(ctx context.Context) ([]site.Stored, error) { + list, err := h.api().List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + h.Cell + "," + RoleLabel + "=" + RoleAssignment + "," + AnsweredLabel + "!=true"}) if err != nil { - return err - } - r, found, err := c.Executor.Lookup(ctx, i.Request.ID) - if err != nil && (found || !errors.Is(err, executor.ErrOutcomeUnknown)) { - return err + return nil, err } - if !found { - if r, err = c.Executor.Execute(ctx, i.Request); err != nil { - return err + var out []site.Stored + for index := range list.Items { + spec, observation, err := h.reflected(&list.Items[index]) + if err != nil || observation.Result == nil || observation.AssignmentDigest != Digest(spec.AssignmentJSON) { + continue + } + var assignment site.Assignment + if err := json.Unmarshal([]byte(spec.AssignmentJSON), &assignment); err != nil || assignment.Device != spec.Device || list.Items[index].GetName() != AssignmentName(assignment) { + continue + } + result := *observation.Result + if result.Operation != assignment.Operation || result.Fence != assignment.Fence || spec.Device != namespaceOf(spec.Device)+"/"+result.Device { + continue } + out = append(out, site.Stored{Device: spec.Device, Result: result}) } - return ValidateResult(i, r) + return out, nil } -// Publish writes a fresh observation only for a validated terminal journal -// result. It never executes; absent or unfinished results stay Unknown. -func (c *Cell) Publish(ctx context.Context, name string) error { - obj, i, err := c.intent(ctx, name) - if err != nil { - return err - } - r, found, err := c.Executor.Lookup(ctx, i.Request.ID) - if err != nil { - return err - } - if !found { - return executor.ErrOutcomeUnknown - } - if err = ValidateResult(i, r); err != nil { - return err +func namespaceOf(device string) string { + for index := range device { + if device[index] == '/' { + return device[:index] + } } - now := time.Now().UTC() - if c.Now != nil { - now = c.Now().UTC() + return "" +} + +// Forget marks the assignment answered, so the cell deletes its copy. +func (h *Hub) Forget(ctx context.Context, stored site.Stored) error { + name := AssignmentName(site.Assignment{Device: stored.Device, Operation: stored.Result.Operation, Fence: stored.Result.Fence}) + patch := []byte(`{"metadata":{"labels":{"` + AnsweredLabel + `":"true"}}}`) + _, err := h.api().Patch(ctx, name, types.MergePatchType, patch, metav1.PatchOptions{}) + if apierrors.IsNotFound(err) { + return nil } - o := Observation{Cell: c.Name, IntentDigest: Digest(i), ObservedAt: now, Result: r} - b, _ := json.Marshal(Status{Observation: &o}) - var status map[string]interface{} - _ = json.Unmarshal(b, &status) - obj.Object["status"] = status - _, err = c.API.Resource(Resource).Namespace(c.Namespace).UpdateStatus(ctx, obj, metav1.UpdateOptions{}) return err } diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index c9be4716..dd091632 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -2,114 +2,294 @@ package coordination import ( "context" - "errors" + "encoding/json" + "fmt" + "os" "testing" "time" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" + k8sschema "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" "k8s.io/client-go/dynamic/fake" + + 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" + "go.datum.net/fleet/internal/site/simwork" +) + +const ( + namespace = "fleet-coordination" + cellName = "cell-example-a" + device = "fleet-provider/server-example-001" + keyDigest = "1111111111111111111111111111111111111111111111111111111111111111" ) -func fixture() (Intent, Status, time.Time) { - now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) - i := Intent{Cell: "cell-a", Request: simulator.Request{ID: "op", Kind: "cleanup", AssetID: "device", BindingID: "allocation", Epoch: 2, FenceToken: "synthetic-test-fence"}} - digest, _ := simulator.RequestDigest(i.Request) - r := simulator.OperationResult{ID: "op", Kind: "cleanup", InputDigest: digest, Phase: "Succeeded", Result: "clean", CreatedAt: now.Add(-time.Second), CompletedAt: &now} - return i, Status{Reflected: []Reflected{{ClusterName: i.Cell, Observation: Observation{Cell: i.Cell, IntentDigest: Digest(i), ObservedAt: now, Result: r}}}}, now +func client() dynamic.Interface { + return fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[k8sschema.GroupVersionResource]string{Resource: Kind + "List"}) } -func TestReflectionRejectsUncertainAndConflictingResults(t *testing.T) { - cases := map[string]func(*Intent, *Status, time.Time){ - "wrong federation cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].ClusterName = "cell-b" }, - "wrong reported cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Cell = "cell-b" }, - "stale": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(-time.Hour) }, - "future": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(time.Second) }, - "wrong epoch": func(i *Intent, _ *Status, _ time.Time) { i.Request.Epoch++ }, - "wrong allocation": func(i *Intent, _ *Status, _ time.Time) { i.Request.BindingID = "other" }, - "wrong fence": func(i *Intent, _ *Status, _ time.Time) { i.Request.FenceToken = "other" }, - "wrong inputs": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.InputDigest = "other" }, - "wrong operation": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.ID = "other" }, - "unknown": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Phase = "Unknown" }, - "unclean": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Result = "unknown" }, - "duplicate": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = append(s.Reflected, s.Reflected[0]) }, - "missing": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = nil }, - } - for name, change := range cases { - t.Run(name, func(t *testing.T) { - i, s, n := fixture() - change(&i, &s, n) - if _, err := ValidateReflection(i, s, n, time.Minute); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("accepted invalid reflection: %v", err) + +// federation copies hub handoffs to the cell and aggregates cell status +// back, as Karmada's propagation and status interpreter do. +type federation struct { + t *testing.T + hub, cell dynamic.Interface + clusterFor string +} + +func (f federation) sync() { + f.t.Helper() + ctx := context.Background() + hub, cell := f.hub.Resource(Resource).Namespace(namespace), f.cell.Resource(Resource).Namespace(namespace) + list, err := hub.List(ctx, metav1.ListOptions{}) + if err != nil { + f.t.Fatal(err) + } + for index := range list.Items { + object := list.Items[index] + copied := &unstructured.Unstructured{Object: map[string]any{"apiVersion": object.GetAPIVersion(), "kind": Kind, "metadata": map[string]any{"name": object.GetName(), "namespace": namespace, "labels": toAny(object.GetLabels())}, "spec": object.Object["spec"]}} + existing, err := cell.Get(ctx, object.GetName(), metav1.GetOptions{}) + if err != nil { + if _, err := cell.Create(ctx, copied, metav1.CreateOptions{}); err != nil { + f.t.Fatal(err) } - }) + continue + } + existing.SetLabels(object.GetLabels()) + if _, err := cell.Update(ctx, existing, metav1.UpdateOptions{}); err != nil { + f.t.Fatal(err) + } + if observation, ok := existing.Object["status"].(map[string]any); ok && observation["observation"] != nil { + object.Object["status"] = map[string]any{"reflected": []any{map[string]any{"clusterName": f.clusterFor, "observation": observation["observation"]}}} + if _, err := hub.UpdateStatus(ctx, &object, metav1.UpdateOptions{}); err != nil { + f.t.Fatal(err) + } + } } - i, s, n := fixture() - if _, err := ValidateReflection(i, s, n, time.Minute); err != nil { - t.Fatal(err) +} + +func toAny(labels map[string]string) map[string]any { + out := map[string]any{} + for key, value := range labels { + out[key] = value } + return out +} + +type rig struct { + t *testing.T + ctx context.Context + hub *Hub + cell *Cell + fed federation + store *site.Store + results *site.Results + runner *site.Runner + snapshot ops.DeviceSnapshot } -type effect struct { - result simulator.OperationResult - calls int - fail bool +func newFixture(t *testing.T) *rig { + hubAPI, cellAPI := client(), client() + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + snapshot := ops.DeviceSnapshot{BMCEndpoint: "https://[2001:db8::1]", SystemUUID: "00000000-0000-4000-8000-000000000001", BootMACAddress: "02:00:00:00:00:01", BMCPublicKeySHA256: keyDigest} + enrollment := fixture.Enrollment{device: {BMCEndpoint: snapshot.BMCEndpoint, SystemUUID: snapshot.SystemUUID, BootMACAddress: snapshot.BootMACAddress, BMCPublicKeySHA256: keyDigest, Disks: []string{"disk-0"}}} + results := site.NewResults(store) + return &rig{ + t: t, ctx: context.Background(), store: store, results: results, snapshot: snapshot, + hub: &Hub{API: hubAPI, Namespace: namespace, Cell: cellName, MaxAge: time.Minute}, + cell: &Cell{API: cellAPI, Namespace: namespace, Name: cellName}, + fed: federation{t: t, hub: hubAPI, cell: cellAPI, clusterFor: cellName}, + runner: &site.Runner{Site: cellName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, Kinds: map[string]site.Kind{"DeviceWipe": simwork.Wipe{}}, Poll: 10 * time.Millisecond}, + } } -func (e *effect) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return e.result, e.calls > 0, nil +func (f *rig) wipe(fence int64, uid string) site.Assignment { + spec := ops.DeviceWipeSpec{OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: "release", UID: "u"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}}, + Step: 1, CleaningPolicyDigest: "sha256:" + keyDigest, TargetDisks: []string{"disk-0"}} + inputs, _ := json.Marshal(spec) + digest, _ := custody.SpecDigest(spec) + now := time.Now().UTC() + return site.Assignment{Device: device, Operation: ops.OperationReference{Kind: "DeviceWipe", Name: "alloc-example-wipe-1-" + uid}, Fence: fence, AdmittedAt: now, Deadline: now.Add(time.Minute), Snapshot: f.snapshot, InputDigest: digest, Inputs: inputs} } -func (e *effect) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { - e.calls++ - if e.fail { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown + +func (f *rig) observe() { + f.t.Helper() + list, err := f.cell.api().List(f.ctx, metav1.ListOptions{}) + if err != nil { + f.t.Fatal(err) + } + for index := range list.Items { + if err := f.cell.Publish(f.ctx, &list.Items[index], f.store, f.results); err != nil { + f.t.Fatal(err) + } } - return e.result, nil + f.fed.sync() } -func TestHubCellRestartAndNoFakeFederation(t *testing.T) { - ctx := context.Background() - i, s, now := fixture() - hubAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) - cellAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) - h := &Hub{API: hubAPI, Namespace: "private", Cell: i.Cell, MaxAge: time.Minute, Now: func() time.Time { return now }} - if _, err := h.Execute(ctx, i.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + +// TestAssignmentRoundTrip delivers an assignment through the federation, +// runs it at the cell, reports its result back, and answers it. +func TestAssignmentRoundTrip(t *testing.T) { + f := newFixture(t) + if _, reported, err := f.hub.Fence(f.ctx, device); err != nil || reported { + t.Fatalf("an unobserved report counts: %v %v", reported, err) + } + f.fed.sync() + f.observe() + if report, reported, err := f.hub.Fence(f.ctx, device); err != nil || !reported || report != (custody.SiteFence{}) { + t.Fatalf("report = %+v %v %v", report, reported, err) + } + assignment := f.wipe(3, "00000000-0000-4000-8000-000000000101") + if err := f.hub.Deliver(f.ctx, assignment); err != nil { t.Fatal(err) } - obj, err := hubAPI.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) - if err != nil { + // Delivery is idempotent; other contents under the same name conflict. + if err := f.hub.Deliver(f.ctx, assignment); err != nil { t.Fatal(err) } - if _, err = cellAPI.Resource(Resource).Namespace("private").Create(ctx, obj, metav1.CreateOptions{}); err != nil { + changed := assignment + changed.Deadline = changed.Deadline.Add(time.Second) + if err := f.hub.Deliver(f.ctx, changed); err != ErrConflict { + t.Fatalf("changed delivery err = %v", err) + } + f.fed.sync() + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); err != nil { t.Fatal(err) } - e := &effect{result: s.Reflected[0].Observation.Result} - for range 2 { - c := &Cell{API: cellAPI, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} - if err = reconcile(c, ctx, obj.GetName()); err != nil { - t.Fatal(err) - } + f.observe() + held, err := f.hub.Results(f.ctx) + if err != nil || len(held) != 1 || held[0].Result.Phase != ops.PhaseSucceeded || held[0].Result.Fence != 3 || held[0].Device != device { + t.Fatalf("results = %+v, %v", held, err) + } + if report, _, _ := f.hub.Fence(f.ctx, device); report.Seen != 3 || report.Stopped != 3 { + t.Fatalf("fence after the wipe = %+v", report) + } + if err := f.hub.Forget(f.ctx, held[0]); err != nil { + t.Fatal(err) + } + f.fed.sync() + f.observe() + if _, found, _ := f.results.Get(device, assignment.Operation, 3); found { + t.Fatal("the cell kept a result the coordinator answered") + } + if held, _ := f.hub.Results(f.ctx); len(held) != 0 { + t.Fatalf("answered results are offered again: %+v", held) + } +} + +// TestReflectionIsRejectedUnlessItIsThisCellsObservation covers each way a +// reflected status can be stale, foreign or for other inputs. +func TestReflectionIsRejectedUnlessItIsThisCellsObservation(t *testing.T) { + cases := map[string]func(*HubStatus, *Spec){ + "another cluster": func(s *HubStatus, _ *Spec) { s.Reflected[0].ClusterName = "cell-example-b" }, + "another cell": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.Cell = "cell-example-b" }, + "two cells": func(s *HubStatus, _ *Spec) { s.Reflected = append(s.Reflected, s.Reflected[0]) }, + "none": func(s *HubStatus, _ *Spec) { s.Reflected = nil }, + "future": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.ObservedAt = time.Now().Add(time.Hour) }, + "other inputs": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.AssignmentDigest = keyDigest }, + "another fence": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.Result.Fence++ }, + "another op": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.Result.Operation.Name = "other" }, + "another device": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.Result.Device = "server-example-002" }, + "spec of another": func(_ *HubStatus, spec *Spec) { spec.Cell = "cell-example-b" }, + "no observed time": func(s *HubStatus, _ *Spec) { s.Reflected[0].Observation.ObservedAt = time.Time{} }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + f := newFixture(t) + assignment := f.wipe(2, "00000000-0000-4000-8000-000000000102") + data, _ := json.Marshal(assignment) + spec := Spec{Cell: cellName, Device: device, AssignmentJSON: string(data)} + result := custody.SiteResult{Site: cellName, Device: "server-example-001", Operation: assignment.Operation, Fence: 2, Phase: ops.PhaseSucceeded} + status := HubStatus{Reflected: []Reflected{{ClusterName: cellName, Observation: Observation{Cell: cellName, AssignmentDigest: Digest(spec.AssignmentJSON), ObservedAt: time.Now().Add(-time.Second), Result: &result}}}} + // The unchanged reflection is accepted, so each case fails only + // for its one change. + if got := f.reflect(t, assignment, spec, status); len(got) != 1 { + t.Fatalf("a valid reflection was rejected: %+v", got) + } + mutate(&status, &spec) + if got := f.reflect(t, assignment, spec, status); len(got) != 0 { + t.Fatalf("accepted %+v", got) + } + }) + } +} + +func (f *rig) reflect(t *testing.T, assignment site.Assignment, spec Spec, status HubStatus) []site.Stored { + t.Helper() + api := f.hub.api() + _ = api.Delete(f.ctx, AssignmentName(assignment), metav1.DeleteOptions{}) + object := newObject(namespace, AssignmentName(assignment), RoleAssignment, Spec{Cell: cellName, Device: spec.Device, AssignmentJSON: spec.AssignmentJSON}) + data, _ := json.Marshal(spec) + var fields map[string]any + _ = json.Unmarshal(data, &fields) + object.Object["spec"] = fields + created, err := api.Create(f.ctx, object, metav1.CreateOptions{}) + if err != nil { + t.Fatal(err) } - if e.calls != 1 { - t.Fatalf("duplicate effects: %d", e.calls) + data, _ = json.Marshal(status) + var raw map[string]any + _ = json.Unmarshal(data, &raw) + created.Object["status"] = raw + if _, err := api.UpdateStatus(f.ctx, created, metav1.UpdateOptions{}); err != nil { + t.Fatal(err) } - // This unit test deliberately does not simulate federation or claim its success. - if _, _, err = h.Lookup(ctx, i.Request.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("cell-local success leaked to hub: %v", err) + held, err := f.hub.Results(f.ctx) + if err != nil { + t.Fatal(err) } - changed := i.Request - changed.Epoch++ - if _, err = h.Execute(ctx, changed); !errors.Is(err, executor.ErrConflict) { - t.Fatalf("accepted changed authority: %v", err) + return held +} + +// TestAStaleFenceReportIsNoReport keeps admission from deciding on an old +// fence. +func TestAStaleFenceReportIsNoReport(t *testing.T) { + f := newFixture(t) + if _, _, err := f.hub.Fence(f.ctx, device); err != nil { + t.Fatal(err) + } + f.fed.sync() + f.observe() + f.hub.Now = func() time.Time { return time.Now().Add(2 * time.Minute) } + if _, reported, err := f.hub.Fence(f.ctx, device); err != nil || reported { + t.Fatalf("a stale report counts: %v %v", reported, err) } } -func TestCellRejectsWrongCellBeforeEffects(t *testing.T) { - i, s, n := fixture() - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) - e := &effect{result: s.Reflected[0].Observation.Result} - c := Cell{API: api, Namespace: "private", Name: "wrong", Executor: e, Now: func() time.Time { return n }} - if err := reconcile(&c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrFenced) || e.calls != 0 { - t.Fatalf("wrong-cell effect: %v, calls %d", err, e.calls) + +// TestTheCellRunsOnlyItsOwnAssignments refuses a handoff for another cell +// or under another name, before anything is sent. +func TestTheCellRunsOnlyItsOwnAssignments(t *testing.T) { + f := newFixture(t) + assignment := f.wipe(4, "00000000-0000-4000-8000-000000000104") + data, _ := json.Marshal(assignment) + for name, object := range map[string]*unstructured.Unstructured{ + "another cell": newObject(namespace, AssignmentName(assignment), RoleAssignment, Spec{Cell: "cell-example-b", Device: device, AssignmentJSON: string(data)}), + // The handoff names another Device than its assignment. + "another device": newObject(namespace, AssignmentName(assignment), RoleAssignment, Spec{Cell: cellName, Device: "fleet-provider/server-example-002", AssignmentJSON: string(data)}), + "another name": newObject(namespace, "op-"+fmt.Sprintf("%040d", 1), RoleAssignment, Spec{Cell: cellName, Device: device, AssignmentJSON: string(data)}), + "a report": newObject(namespace, ReportName(device)+"x", RoleReport, Spec{Cell: cellName, Device: device, AssignmentJSON: string(data)}), + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t) + if _, err := f.cell.api().Create(f.ctx, object, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + if err := f.cell.Work(f.ctx, object.GetName(), f.runner); err != ErrNotDelivered { + t.Fatalf("err = %v", err) + } + if journal, _ := f.store.Journal(device); len(journal) != 0 { + t.Fatalf("journal = %+v", journal) + } + }) } } diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 39a07c59..827721dc 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -95,7 +95,7 @@ func TestAdmissionPreconditions(t *testing.T) { t.Run("2: a staff operation on an allocated or releasing server is refused", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-held"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-held"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence @@ -114,7 +114,7 @@ func TestAdmissionPreconditions(t *testing.T) { t.Run("3: an allocationRef must name the holder's allocation", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-mine"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-mine"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence @@ -136,7 +136,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.requirePhase(second, ops.PhaseFailed, ReasonHolderMismatch) queued := fresh() - if err := e.coord.Claim(e.ctx, queued.Name, "alloc-queue"); err != nil { + if err := e.coord.Claim(e.ctx, queued.Name, queued.UID, "alloc-queue"); err != nil { t.Fatal(err) } running := e.providerOp(queued, "alloc-queue", "a") @@ -153,12 +153,12 @@ func TestAdmissionPreconditions(t *testing.T) { e.requirePhase(waiting, ops.PhaseAdmitted, "") }) - t.Run("5: the Device UID must match deviceRef.uid", func(t *testing.T) { + t.Run("5: the Device UID must match the operation's device-uid label", func(t *testing.T) { e := e.sub(t) device := fresh() fence := e.custody(device.Name).Spec.Fence operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "stale-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("old record")), Input: "a"}} - operation.Spec.DeviceRef.UID = "00000000-0000-4000-8000-ffffffffffff" + labelDevice(operation, "00000000-0000-4000-8000-ffffffffffff") e.create(operation) e.settle(device.Name) e.requirePhase(operation, ops.PhaseFailed, ReasonDeviceIdentityMismatch) @@ -218,7 +218,7 @@ func TestAdmissionPreconditions(t *testing.T) { t.Run("names: deterministic kinds must use their rule, staff kinds a generated name", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-name"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-name"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence @@ -248,18 +248,18 @@ func TestAdmissionPreconditions(t *testing.T) { t.Run("bootstrap stays refused", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-boot"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-boot"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-1"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), RequestUID: "request-1", - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-1"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, }} e.create(operation) - missing := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-2"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), RequestUID: "request-2", - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, + missing := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-2"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-2"}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, }} e.create(missing) e.settle(device.Name) diff --git a/internal/custody/concurrency_test.go b/internal/custody/concurrency_test.go index 2869e3df..17dd7e5b 100644 --- a/internal/custody/concurrency_test.go +++ b/internal/custody/concurrency_test.go @@ -56,7 +56,7 @@ func TestConcurrency(t *testing.T) { group.Add(1) go func() { defer group.Done() - err := allocator.Claim(e.ctx, device.Name, fmt.Sprintf("alloc-race-%d", index)) + err := allocator.Claim(e.ctx, device.Name, device.UID, fmt.Sprintf("alloc-race-%d", index)) switch { case err == nil: wins.Add(1) @@ -82,7 +82,10 @@ func TestConcurrency(t *testing.T) { var group sync.WaitGroup group.Add(2) go func() { defer group.Done(); reconcileErr = settleQuiet(e.ctx, coordinator, device.Name) }() - go func() { defer group.Done(); claimErr = allocator.Claim(e.ctx, device.Name, "alloc-staff-race") }() + go func() { + defer group.Done() + claimErr = allocator.Claim(e.ctx, device.Name, device.UID, "alloc-staff-race") + }() group.Wait() if reconcileErr != nil { t.Fatal(reconcileErr) @@ -145,7 +148,7 @@ func TestConcurrency(t *testing.T) { for range 5 { device := fresh() allocation := "alloc-hc-" + device.Name - if err := e.coord.Claim(e.ctx, device.Name, allocation); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { t.Fatal(err) } before := e.custody(device.Name).Spec.Fence @@ -170,7 +173,7 @@ func TestConcurrency(t *testing.T) { switch status.Phase { case ops.PhaseAdmitted: // Admitted under Allocation, then released while running. - if custody.Spec.ActiveOperation == nil || custody.Spec.ActiveOperation.UID != string(operation.UID) || custody.Spec.Fence != before+1 { + if custody.Spec.ActiveOperation == nil || custody.Spec.ActiveOperation.Name != operation.Name || custody.Spec.Fence != before+1 { t.Fatalf("admitted but custody %+v", custody.Spec) } case ops.PhaseFailed, ops.PhaseCancelled: @@ -208,10 +211,10 @@ func TestConcurrency(t *testing.T) { device, other := fresh(), fresh() lossy := &faultClient{Client: e.client(), failAt: 1, lost: true} allocator := e.coordinator(lossy) - if err := allocator.Claim(e.ctx, device.Name, "alloc-lost"); err == nil { + if err := allocator.Claim(e.ctx, device.Name, device.UID, "alloc-lost"); err == nil { t.Fatal("the lost response was not reported") } - if err := allocator.Claim(e.ctx, device.Name, "alloc-lost"); err != nil { + if err := allocator.Claim(e.ctx, device.Name, device.UID, "alloc-lost"); err != nil { t.Fatalf("retry: %v", err) } if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != "alloc-lost" { diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 6be3aed9..35d2f548 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -162,7 +162,7 @@ func (c *Coordinator) Reconcile(ctx context.Context, name string) (Outcome, erro if changed, err := c.copyStatus(ctx, custody); err != nil || changed { return Outcome{Changed: changed}, err } - if custody.Spec.DeviceRef.UID != string(device.UID) && !slices.Contains(custody.Spec.Conflicts, ConflictDeviceUID) { + if custody.Labels[ops.LabelDeviceUID] != string(device.UID) && !slices.Contains(custody.Spec.Conflicts, ConflictDeviceUID) { return c.markUnverified(ctx, custody, ConflictDeviceUID) } var requeue time.Duration @@ -253,9 +253,13 @@ func (c *Coordinator) settleHolder(ctx context.Context, custody *ops.DeviceCusto return Outcome{}, nil } -// get reads one operation. It returns nil if it does not exist or is a -// different incarnation. -func (c *Coordinator) get(ctx context.Context, reference ops.OperationReference) (ops.Operation, *Kind, error) { +// get reads the operation custody admitted at fence. It returns nil if the +// operation does not exist or is a different incarnation. No spec holds an +// object UID, so the incarnation is the admission record the coordinator +// wrote to the operation's status before custody named it: a same-name +// operation created later has none, and never inherits the admission, its +// result or its hold. +func (c *Coordinator) get(ctx context.Context, reference ops.OperationReference, fence int64) (ops.Operation, *Kind, error) { kind := c.Registry.Kind(reference.Kind) if kind == nil { return nil, nil, fmt.Errorf("custody names unregistered kind %s", reference.Kind) @@ -266,18 +270,33 @@ func (c *Coordinator) get(ctx context.Context, reference ops.OperationReference) } else if err != nil { return nil, kind, err } - if reference.UID != "" && string(operation.GetUID()) != reference.UID { + if !admittedAt(operation, fence) { return nil, kind, nil } return operation, kind, nil } +// admittedAt reports whether operation is the incarnation custody admitted +// at fence: its status carries that admission. +func admittedAt(operation ops.Operation, fence int64) bool { + admission := operation.OperationStatus().Admission + return admission != nil && admission.Fence == fence +} + +// admissionFence is the fence an operation records it was admitted at, or 0. +func admissionFence(operation ops.Operation) int64 { + if admission := operation.OperationStatus().Admission; admission != nil { + return admission.Fence + } + return 0 +} + // copyStatus copies the active operation and the last result from custody to // operation status. Custody is written first, so after a crash this copies // again. A missing operation is skipped. func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody) (bool, error) { if result := custody.Spec.LastResult; result != nil { - operation, _, err := c.get(ctx, result.OperationReference) + operation, _, err := c.get(ctx, result.OperationReference, result.Fence) if err != nil { return false, err } @@ -293,7 +312,7 @@ func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody // A held operation has ended, even if a rebuild found it unfinished. It // is never admitted again. if hold := custody.Spec.RecoveryHold; hold != nil { - operation, _, err := c.get(ctx, hold.OperationReference) + operation, _, err := c.get(ctx, hold.OperationReference, hold.Fence) if err != nil { return false, err } @@ -310,7 +329,7 @@ func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody if active == nil { return false, nil } - operation, _, err := c.get(ctx, active.OperationReference) + operation, _, err := c.get(ctx, active.OperationReference, active.Fence) if err != nil { return false, err } @@ -332,14 +351,14 @@ func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody func activeStatus(active ops.ActiveOperation) ops.OperationStatus { snapshot := active.Snapshot admitted, deadline := active.AdmittedAt, active.Deadline - return ops.OperationStatus{Phase: active.Phase, Fence: active.Fence, AdmittedAt: &admitted, Deadline: &deadline, InputDigest: active.InputDigest, Snapshot: &snapshot} + return ops.OperationStatus{Admission: &ops.OperationAdmission{Fence: active.Fence}, Phase: active.Phase, Fence: active.Fence, AdmittedAt: &admitted, Deadline: &deadline, InputDigest: active.InputDigest, Snapshot: &snapshot} } func resultStatus(result ops.OperationResult, current *ops.OperationStatus) ops.OperationStatus { finished := result.FinishedAt status := ops.OperationStatus{Phase: result.Phase, Reason: result.Reason, Message: result.Message, Fence: result.Fence, FinishedAt: &finished, Evidence: result.Evidence} // Keep what admission recorded. - status.AdmittedAt, status.Deadline, status.InputDigest, status.Snapshot = current.AdmittedAt, current.Deadline, current.InputDigest, current.Snapshot + status.Admission, status.AdmittedAt, status.Deadline, status.InputDigest, status.Snapshot = current.Admission, current.AdmittedAt, current.Deadline, current.InputDigest, current.Snapshot return status } @@ -402,7 +421,7 @@ func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCus if err != nil || !ok { return Outcome{RequeueAfter: min(due.Sub(now), 5*time.Second)}, err } - operation, _, err := c.get(ctx, active.OperationReference) + operation, _, err := c.get(ctx, active.OperationReference, active.Fence) if err != nil { return Outcome{}, err } @@ -422,6 +441,10 @@ func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCus } spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded, FinishedAt: metav1.NewTime(now), Evidence: evidence} custody.Spec = *spec + // Resolve adopts the current Device incarnation. + if ops.RecoveryDecision(variantOf(kind, operation)) == ops.DecisionResolve { + setDeviceUID(custody, device) + } return c.writeCustody(ctx, custody) } @@ -495,7 +518,7 @@ func (c *Coordinator) holdUnknown(custody *ops.DeviceCustody, active ops.ActiveO next := &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason, Deadline: &deadline, Snapshot: &snapshot} // A retry that itself ends unknown keeps the original operation's name // and Retry count, so the next retry is named on from it. - if previous := spec.RecoveryHold; previous != nil && active.Settles != nil && *active.Settles == previous.OperationReference && previous.Retries > 0 && active.Name == RetryName(*previous, previous.Retries) { + if previous := spec.RecoveryHold; previous != nil && active.Settles != nil && *active.Settles == heldReference(*previous) && previous.Retries > 0 && active.Name == RetryName(*previous, previous.Retries) { next.RetryName, next.Retries = previous.RetryName, previous.Retries if next.RetryName == "" { next.RetryName = previous.Name @@ -531,10 +554,10 @@ func (c *Coordinator) candidates(ctx context.Context, custody *ops.DeviceCustody if operation.Envelope().DeviceRef.Name != custody.Name || operation.OperationStatus().Phase.Ended() || !operation.GetDeletionTimestamp().IsZero() { continue } - if active := custody.Spec.ActiveOperation; active != nil && active.Kind == kind.GVK.Kind && active.UID == string(operation.GetUID()) { + if active := custody.Spec.ActiveOperation; active != nil && active.Kind == kind.GVK.Kind && active.Name == operation.GetName() && admittedAt(operation, active.Fence) { continue } - if hold := custody.Spec.RecoveryHold; hold != nil && hold.Kind == kind.GVK.Kind && hold.UID == string(operation.GetUID()) { + if hold := custody.Spec.RecoveryHold; hold != nil && hold.Kind == kind.GVK.Kind && hold.Name == operation.GetName() && admittedAt(operation, hold.Fence) { continue } out = append(out, candidate{operation: operation, kind: kind}) @@ -568,7 +591,7 @@ type decision struct { reason string message string row Rule - settles *ops.OperationReference + settles *ops.HeldOperationReference extra map[string]string } @@ -705,8 +728,8 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper if len(rows) == 0 { return fail(ReasonCreatorNotPermitted, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) } - if envelope.DeviceRef.UID != string(device.UID) { - return fail(ReasonDeviceIdentityMismatch, "deviceRef.uid does not match the Device") + if operation.GetLabels()[ops.LabelDeviceUID] != string(device.UID) { + return fail(ReasonDeviceIdentityMismatch, "the "+ops.LabelDeviceUID+" label does not match the Device") } // Precondition 1: custody state. rows = slices.DeleteFunc(rows, func(rule Rule) bool { return rule.custodyState() != custody.Spec.State }) @@ -742,7 +765,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } } // Recovery holds. - var settles *ops.OperationReference + var settles *ops.HeldOperationReference switch hold := custody.Spec.RecoveryHold; { case row.Hold == HoldIgnored: case row.Hold == HoldRequired && hold == nil: @@ -759,7 +782,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonRecoveryHold, "%s %s is held; only its settling operations are admitted", hold.Kind, hold.Name) } - reference := hold.OperationReference + reference := heldReference(*hold) settles = &reference } // Precondition 4: one active operation. @@ -919,7 +942,7 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, } spec.Fence = max(spec.Fence, seen) + 1 active := &ops.ActiveOperation{ - OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName(), UID: string(operation.GetUID())}, + OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}, Fence: spec.Fence, Phase: ops.PhaseAdmitted, AdmittedAt: metav1.NewTime(now), @@ -930,6 +953,17 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, Settles: d.settles, } spec.ActiveOperation = active + // The operation records the admission before custody names it, so + // custody never names an object that cannot prove it is the one + // admitted. A conflict here admits nothing; the next pass decides again. + if !admittedAt(operation, spec.Fence) { + operation.OperationStatus().Admission = &ops.OperationAdmission{Fence: spec.Fence} + if err := c.Client.Status().Update(ctx, operation); apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + return Outcome{Changed: true}, nil + } else if err != nil { + return Outcome{}, err + } + } if d.row.Creator == CreatorStaff && spec.Holder.Type == ops.HolderNone { spec.Holder = ops.Holder{Type: ops.HolderService} } @@ -984,3 +1018,19 @@ func validExtra(extra map[string]string) error { } return nil } + +// heldReference names a hold by its operation and fence. +func heldReference(hold ops.RecoveryHold) ops.HeldOperationReference { + return ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence} +} + +// setDeviceUID records the Device incarnation custody is for. Only the +// coordinator writes custody, so its label is written with custody's spec. +func setDeviceUID(custody *ops.DeviceCustody, device *inventory.Device) { + labels := custody.GetLabels() + if labels == nil { + labels = map[string]string{} + } + labels[ops.LabelDeviceUID] = string(device.UID) + custody.SetLabels(labels) +} diff --git a/internal/custody/creatorwebhook/envtest_test.go b/internal/custody/creatorwebhook/envtest_test.go index 4dac53a5..6bcc6aa7 100644 --- a/internal/custody/creatorwebhook/envtest_test.go +++ b/internal/custody/creatorwebhook/envtest_test.go @@ -70,18 +70,19 @@ func TestCreatorAgainstAPIServer(t *testing.T) { if err := admin.Create(context.Background(), webhooks); err != nil { t.Fatal(err) } - actor := func(name, project string) client.Client { + actorWithUID := func(name, uid, project string) client.Client { cfg := rest.CopyConfig(config) - cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}}} + cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: uid, Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}}} api, err := client.New(cfg, client.Options{Scheme: scheme}) if err != nil { t.Fatal(err) } return api } + actor := func(name, project string) client.Client { return actorWithUID(name, name+"-uid", project) } recovery := func(creator ops.Creator) *ops.DeviceRecovery { return &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "recovery-", Namespace: "default"}, Spec: ops.DeviceRecoverySpec{ - OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: "server-example-001", UID: "00000000-0000-4000-8000-000000000001"}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "settle"}}}, + OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "settle"}}}, Decision: ops.DecisionSettle, Hold: &ops.HeldOperationReference{Kind: "DeviceWipe", Name: "alloc-example-wipe-1", Fence: 3}, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(time.Now()), Summary: "observed"}, }} @@ -131,6 +132,25 @@ func TestCreatorAgainstAPIServer(t *testing.T) { t.Fatalf("impersonated creator: %v", err) } }) + t.Run("a caller without a UID is identified by username", func(t *testing.T) { + service := actorWithUID("service-example", "", "provider-example") + created := recovery(ops.Creator{Username: "service-example"}) + if err := service.Create(ctx, created); err != nil { + t.Fatal(err) + } + stored := &ops.DeviceRecovery{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(created), stored); err != nil { + t.Fatal(err) + } + if stored.Spec.Creator != (ops.Creator{Username: "service-example"}) { + t.Fatalf("creator = %+v", stored.Spec.Creator) + } + for _, creator := range []ops.Creator{{Username: "service-example", UID: "forged"}, {Username: "staff-example"}} { + if err := service.Create(ctx, recovery(creator)); !apierrors.IsForbidden(err) { + t.Fatalf("creator %+v: %v", creator, err) + } + } + }) t.Run("a caller outside the provider projects is refused", func(t *testing.T) { if err := actor("staff-example", "consumer-example").Create(ctx, recovery(ops.Creator{Username: "staff-example", UID: "staff-example-uid"})); !apierrors.IsForbidden(err) { t.Fatalf("consumer project: %v", err) diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go index 495887dd..21f2bcbf 100644 --- a/internal/custody/creatorwebhook/handler.go +++ b/internal/custody/creatorwebhook/handler.go @@ -26,6 +26,9 @@ import ( // Path is where the handler is served. const Path = "/validate-operation-creator" +// Resources are the operation plurals whose creator the webhook governs. +var Resources = []string{"deviceinstallations", "devicewipes", "devicerecoveries"} + // Handler admits creates whose creator is the caller and updates that leave // the creator unchanged. type Handler struct { @@ -66,7 +69,7 @@ func project(actor authenticationv1.UserInfo) (string, error) { } } values := actor.Extra[iam.ParentNameExtraKey] - if len(values) != 1 || values[0] == "" || actor.Username == "" || actor.UID == "" { + if len(values) != 1 || values[0] == "" || actor.Username == "" { return "", errors.New("an authenticated caller and project are required") } return values[0], nil @@ -89,8 +92,9 @@ func (h *Handler) Handle(_ context.Context, request admission.Request) admission if err != nil { return admission.Denied("the operation could not be decoded") } + // A caller without a UID must leave spec.creator.uid unset. if creator == nil || creator.Username != request.UserInfo.Username || creator.UID != request.UserInfo.UID { - return admission.Denied("spec.creator must be the authenticated caller's username and UID") + return admission.Denied("spec.creator must be the authenticated caller's username, and UID when it has one") } return admission.Allowed("the creator is the caller") case admissionv1.Update: diff --git a/internal/custody/creatorwebhook/handler_test.go b/internal/custody/creatorwebhook/handler_test.go index b61ef060..8e326c04 100644 --- a/internal/custody/creatorwebhook/handler_test.go +++ b/internal/custody/creatorwebhook/handler_test.go @@ -52,19 +52,25 @@ func TestHandler(t *testing.T) { handler := &Handler{Projects: []string{"provider-example"}, Resources: resources} staff := caller("staff-example", "provider-example") self := &ops.Creator{Username: "staff-example", UID: "staff-example-uid"} + // Some credentials, such as client certificates, carry no UID. + service := caller("service-example", "provider-example") + service.UID = "" cases := map[string]struct { request admission.Request allowed bool }{ - "a create naming the caller": {request(admissionv1.Create, staff, object(t, self), runtime.RawExtension{}), true}, - "a create naming someone else": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "other", UID: "other-uid"}), runtime.RawExtension{}), false}, - "a create with the caller's name only": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "staff-example", UID: "forged"}), runtime.RawExtension{}), false}, - "a create without a creator": {request(admissionv1.Create, staff, object(t, nil), runtime.RawExtension{}), false}, - "a caller outside a project": {request(admissionv1.Create, authenticationv1.UserInfo{Username: "staff-example", UID: "staff-example-uid"}, object(t, self), runtime.RawExtension{}), false}, - "a caller in another project": {request(admissionv1.Create, caller("staff-example", "consumer-example"), object(t, self), runtime.RawExtension{}), false}, - "an update keeping the creator": {request(admissionv1.Update, caller("coordinator", "provider-example"), object(t, self), object(t, self)), true}, - "an update changing the creator": {request(admissionv1.Update, staff, object(t, &ops.Creator{Username: "x", UID: "y"}), object(t, self)), false}, - "a delete": {request(admissionv1.Delete, staff, runtime.RawExtension{}, object(t, self)), false}, + "a create naming the caller": {request(admissionv1.Create, staff, object(t, self), runtime.RawExtension{}), true}, + "a create naming someone else": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "other", UID: "other-uid"}), runtime.RawExtension{}), false}, + "a create with the caller's name only": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "staff-example", UID: "forged"}), runtime.RawExtension{}), false}, + "a create without a creator": {request(admissionv1.Create, staff, object(t, nil), runtime.RawExtension{}), false}, + "a caller outside a project": {request(admissionv1.Create, authenticationv1.UserInfo{Username: "staff-example", UID: "staff-example-uid"}, object(t, self), runtime.RawExtension{}), false}, + "a caller in another project": {request(admissionv1.Create, caller("staff-example", "consumer-example"), object(t, self), runtime.RawExtension{}), false}, + "an update keeping the creator": {request(admissionv1.Update, caller("coordinator", "provider-example"), object(t, self), object(t, self)), true}, + "an update changing the creator": {request(admissionv1.Update, staff, object(t, &ops.Creator{Username: "x", UID: "y"}), object(t, self)), false}, + "a delete": {request(admissionv1.Delete, staff, runtime.RawExtension{}, object(t, self)), false}, + "a caller without a UID naming itself": {request(admissionv1.Create, service, object(t, &ops.Creator{Username: "service-example"}), runtime.RawExtension{}), true}, + "a caller without a UID adding one": {request(admissionv1.Create, service, object(t, &ops.Creator{Username: "service-example", UID: "forged"}), runtime.RawExtension{}), false}, + "a caller without a UID naming another": {request(admissionv1.Create, service, object(t, &ops.Creator{Username: "staff-example"}), runtime.RawExtension{}), false}, } for name, test := range cases { t.Run(name, func(t *testing.T) { diff --git a/internal/custody/creatorwebhook/policy_envtest_test.go b/internal/custody/creatorwebhook/policy_envtest_test.go new file mode 100644 index 00000000..487c798b --- /dev/null +++ b/internal/custody/creatorwebhook/policy_envtest_test.go @@ -0,0 +1,129 @@ +package creatorwebhook + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/go-logr/logr" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/yaml" +) + +// TestStandaloneCreatorPolicyAgainstAPIServer applies the packaged standalone +// creator policy, which enforces the webhook's rule on a plain cluster. +func TestStandaloneCreatorPolicyAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(root, "config", "components", "device-operations", "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{ops.AddToScheme, admissionregistrationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(root, "config", "standalone", "site.yaml")) + if err != nil { + t.Fatal(err) + } + applied := 0 + for _, document := range bytes.Split(data, []byte("\n---\n")) { + var meta metav1.TypeMeta + if err := yaml.Unmarshal(document, &meta); err != nil { + t.Fatal(err) + } + var object client.Object + switch meta.Kind { + case "ValidatingAdmissionPolicy": + object = &admissionregistrationv1.ValidatingAdmissionPolicy{} + case "ValidatingAdmissionPolicyBinding": + object = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} + default: + continue + } + if err := yaml.UnmarshalStrict(document, object); err != nil { + t.Fatal(err) + } + if err := admin.Create(context.Background(), object); err != nil { + t.Fatal(err) + } + applied++ + } + if applied != 2 { + t.Fatalf("the standalone site must package the creator policy and its binding, found %d objects", applied) + } + actor := func(name, uid string) client.Client { + cfg := rest.CopyConfig(config) + cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: uid, Groups: []string{"system:masters"}} + api, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return api + } + recovery := func(creator ops.Creator) *ops.DeviceRecovery { + return &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "recovery-", Namespace: "default"}, Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "settle"}}}, + Decision: ops.DecisionSettle, Hold: &ops.HeldOperationReference{Kind: "DeviceWipe", Name: "alloc-example-wipe-1", Fence: 3}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(time.Now()), Summary: "observed"}, + }} + } + staff := actor("staff-example", "staff-example-uid") + // Some credentials, such as client certificates, carry no UID. + service := actor("service-example", "") + ctx := context.Background() + // The policy may take a moment to engage. + deadline := time.Now().Add(15 * time.Second) + for !apierrors.IsInvalid(staff.Create(ctx, recovery(ops.Creator{Username: "probe", UID: "probe"}), client.DryRunAll)) { + if time.Now().After(deadline) { + t.Fatal("creator policy did not engage") + } + time.Sleep(50 * time.Millisecond) + } + cases := map[string]struct { + caller client.Client + creator ops.Creator + allowed bool + }{ + "a caller with a UID naming itself": {staff, ops.Creator{Username: "staff-example", UID: "staff-example-uid"}, true}, + "a caller with a UID forging it": {staff, ops.Creator{Username: "staff-example", UID: "forged"}, false}, + "a caller with a UID omitting it": {staff, ops.Creator{Username: "staff-example"}, false}, + "a caller without a UID naming itself": {service, ops.Creator{Username: "service-example"}, true}, + "a caller without a UID adding one": {service, ops.Creator{Username: "service-example", UID: "forged"}, false}, + "a caller without a UID naming another": {service, ops.Creator{Username: "staff-example"}, false}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + err := test.caller.Create(ctx, recovery(test.creator), client.DryRunAll) + if test.allowed && err != nil { + t.Fatalf("refused: %v", err) + } + if !test.allowed && !apierrors.IsInvalid(err) { + t.Fatalf("not refused by the policy: %v", err) + } + }) + } +} diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index 526cb12b..bae82818 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -60,7 +60,7 @@ func TestExtensionSeams(t *testing.T) { // future provider kind would. e.coord.Registry.Kind("DeviceInstallation").Supersedes = true device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-scope"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-scope"); err != nil { t.Fatal(err) } running := e.installation(device, "alloc-scope", "request-running") @@ -130,7 +130,7 @@ func TestExtensionSeams(t *testing.T) { settling := e.staffOp(device, "ok") e.settle(device.Name) e.requirePhase(settling, ops.PhaseAdmitted, "") - if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || active.Settles.UID != hold.UID { + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || *active.Settles != heldReference(hold) { t.Fatalf("active = %+v", active) } if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { @@ -154,7 +154,7 @@ func TestExtensionSeams(t *testing.T) { other := fresh() custody := e.custody(other.Name) custody.Spec.Holder = ops.Holder{Type: ops.HolderService} - custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: testProviderKind, Name: "alloc-x-test-a", UID: "00000000-0000-4000-8000-00000000abcd"}, Fence: custody.Spec.Fence, Since: metav1.NewTime(e.clock.Now()), Reason: "Test"} + custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: testProviderKind, Name: "alloc-x-test-a"}, Fence: custody.Spec.Fence, Since: metav1.NewTime(e.clock.Now()), Reason: "Test"} if err := e.admin.Update(e.ctx, custody); err != nil { t.Fatal(err) } @@ -185,7 +185,7 @@ func TestExtensionSeams(t *testing.T) { // unless it declares itself Retryable. e.coord.Registry.Kind("DeviceWipe").Retryable = false wiped := fresh() - if err := e.coord.Claim(e.ctx, wiped.Name, "alloc-nr"); err != nil { + if err := e.coord.Claim(e.ctx, wiped.Name, wiped.UID, "alloc-nr"); err != nil { t.Fatal(err) } if err := e.coord.BeginRelease(e.ctx, wiped.Name, "alloc-nr"); err != nil { diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index be0a7e81..8b01531a 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -19,6 +19,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" @@ -270,7 +271,7 @@ func (e *env) verified(name, uuid, key string) *inventory.Device { } func envelope(device *inventory.Device, user string, authority ops.Authority) ops.OperationEnvelope { - return ops.OperationEnvelope{Creator: ops.Creator{Username: user, UID: user + "-uid"}, DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, Authority: authority} + return ops.OperationEnvelope{Creator: ops.Creator{Username: user, UID: user + "-uid"}, DeviceRef: ops.DeviceReference{Name: device.Name}, Authority: authority} } func service(reason string) ops.Authority { @@ -281,13 +282,46 @@ func allocated(name string) ops.Authority { return ops.Authority{AllocationRef: &ops.LocalReference{Name: name}} } +// create creates an object. An operation without a device-uid label gets +// its Device's UID, as the operation's creator records it; a test that +// needs another value sets the label itself. func (e *env) create(object client.Object) { e.t.Helper() + if operation, ok := object.(ops.Operation); ok && operation.GetLabels()[ops.LabelDeviceUID] == "" { + device := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: operation.Envelope().DeviceRef.Name}, device); err == nil { + labelDevice(operation, string(device.UID)) + } + } if err := e.admin.Create(e.ctx, object); err != nil { e.t.Fatal(err) } } +// admitted is the admission record the coordinator writes to an operation +// before custody names it. +func admitted(fence int64) *ops.OperationAdmission { return &ops.OperationAdmission{Fence: fence} } + +// markAdmitted gives an operation the admission record the coordinator +// would have written, as one admitted before custody was lost. +func (e *env) markAdmitted(operation ops.Operation, fence int64) { + e.t.Helper() + operation.OperationStatus().Admission = admitted(fence) + if err := e.admin.Status().Update(e.ctx, operation); err != nil { + e.t.Fatal(err) + } +} + +// labelDevice sets an object's device-uid label. +func labelDevice(object client.Object, uid string) { + labels := object.GetLabels() + if labels == nil { + labels = map[string]string{} + } + labels[ops.LabelDeviceUID] = uid + object.SetLabels(labels) +} + func (e *env) staffOp(device *inventory.Device, input string) *DeviceTestStaffOperation { e.t.Helper() operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-staff-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("qualification")), Input: input}} @@ -304,9 +338,9 @@ func (e *env) providerOp(device *inventory.Device, allocation, input string) *De func (e *env) installation(device *inventory.Device, allocation, request string) *ops.DeviceInstallation { e.t.Helper() - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: request, - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, }} e.create(operation) return operation @@ -361,7 +395,7 @@ func (e *env) requirePhase(operation ops.Operation, phase ops.Phase, reason stri } func reference(kind string, operation ops.Operation) ops.OperationReference { - return ops.OperationReference{Kind: kind, Name: operation.GetName(), UID: string(operation.GetUID())} + return ops.OperationReference{Kind: kind, Name: operation.GetName()} } // result reports a site result for the active operation. @@ -387,8 +421,18 @@ func (e *env) allocation(device *inventory.Device, name, phase string) *metal.Ma if err := e.admin.Create(e.ctx, capacity); err != nil && !apierrors.IsAlreadyExists(err) { e.t.Fatal(err) } - allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: metal.MachineAllocationSpec{ - MachineRef: metal.ProjectNamespacedReference{Project: "consumer-example", Namespace: "default", Name: "machine-" + name}, MachineCapacityRef: metal.NamespacedReference{Namespace: "default", Name: capacityName}, + allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: map[string]string{ + metal.LabelMachineUID: uid(901), metal.LabelConsumerUID: uid(900), metal.LabelDeviceUID: string(device.UID)}}, Spec: metal.MachineAllocationSpec{ + ConsumerRef: metal.TypedReference{APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: "consumer-example"}, + MachineRef: metal.AllocatedMachineReference{Namespace: "default", Name: "machine-" + name}, + MachineCapacityRef: metal.NamespacedReference{Namespace: "default", Name: capacityName}, + DeviceRef: metal.AllocatedDeviceReference{Name: device.Name}, + Accepted: metal.AcceptedContract{MachineClassRef: metal.ContentReference{Name: "class-example", Generation: 1, Digest: policyDigest}, MachineProfileRef: metal.ContentReference{Name: "profile-example", Generation: 1, Digest: policyDigest}, + CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, + Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture-" + name}, + CleaningPolicyDigest: policyDigest, + BootInterface: "primary", + TargetDisks: []string{"disk-0"}, }} e.create(allocation) if phase != "" { @@ -401,3 +445,14 @@ func (e *env) allocation(device *inventory.Device, name, phase string) *metal.Ma } func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } + +// deviceUID is the live Device's incarnation, as an allocation's +// device-uid label records it. +func (e *env) deviceUID(name string) types.UID { + e.t.Helper() + device := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: name}, device); err != nil { + e.t.Fatal(err) + } + return device.UID +} diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go index 4dd2757a..de49a4d0 100644 --- a/internal/custody/holds_test.go +++ b/internal/custody/holds_test.go @@ -61,10 +61,10 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { fence := e.custody(device.Name).Spec.Fence e.dropCustody(device.Name) custody := verify(e, device, fence) - if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(install.UID) || custody.Spec.ActiveOperation != nil { + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.Name != install.Name || custody.Spec.ActiveOperation != nil { t.Fatalf("rebuilt = %+v", custody.Spec) } - if err := e.coord.Claim(e.ctx, device.Name, "alloc-other"); err == nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-other"); err == nil { t.Fatal("a held server was claimed") } }) @@ -77,14 +77,14 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { // It may have run before custody was lost: its status says Admitted. deadline := metav1.NewTime(e.clock.Now().Add(InstallationDeadline)) recorded := ops.DeviceSnapshot{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: device.Spec.Identity.SystemUUID, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), Extra: map[string]string{"resetTypes": "On"}} - install.Status = ops.OperationStatus{Phase: ops.PhaseAdmitted, Fence: 4, Deadline: &deadline, Snapshot: &recorded} + install.Status = ops.OperationStatus{Admission: admitted(4), Phase: ops.PhaseAdmitted, Fence: 4, Deadline: &deadline, Snapshot: &recorded} if err := e.admin.Status().Update(e.ctx, install); err != nil { t.Fatal(err) } custody := verify(e, device, 4) e.settle(device.Name) custody = e.custody(device.Name) - if hold := custody.Spec.RecoveryHold; hold == nil || hold.UID != string(install.UID) || custody.Spec.ActiveOperation != nil || custody.Spec.Fence <= 4 { + if hold := custody.Spec.RecoveryHold; hold == nil || hold.Name != install.Name || custody.Spec.ActiveOperation != nil || custody.Spec.Fence <= 4 { t.Fatalf("rebuilt = %+v", custody.Spec) } // The rebuilt hold keeps the deadline and snapshot the status recorded. @@ -99,12 +99,14 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { device := next() e.allocation(device, "alloc-r-"+device.Name, "Releasing") wipe := e.wipe(device, "alloc-r-"+device.Name, 1) - wipe.Status = ops.OperationStatus{Phase: ops.PhasePending, Reason: ReasonOperationInProgress} + // Its admission was recorded, then custody was lost before the rest + // of its status was copied. + wipe.Status = ops.OperationStatus{Admission: admitted(1), Phase: ops.PhasePending, Reason: ReasonOperationInProgress} if err := e.admin.Status().Update(e.ctx, wipe); err != nil { t.Fatal(err) } custody := verify(e, device, 0) - if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(wipe.UID) || custody.Spec.ActiveOperation != nil { + if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.Name != wipe.Name || custody.Spec.ActiveOperation != nil { t.Fatalf("rebuilt = %+v", custody.Spec) } // A Pending status recorded no deadline or snapshot, so the hold has @@ -122,12 +124,12 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { e.allocation(device, allocation, "Releasing") verify(e, device, 0) install := e.installation(device, allocation, "request-1") - install.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + install.Status = ops.OperationStatus{Admission: admitted(1), Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} if err := e.admin.Status().Update(e.ctx, install); err != nil { t.Fatal(err) } wipe := e.wipe(device, allocation, 1) - wipe.Status = ops.OperationStatus{Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: ptrTime(e.clock.Now())} + wipe.Status = ops.OperationStatus{Admission: admitted(2), Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: ptrTime(e.clock.Now())} if err := e.admin.Status().Update(e.ctx, wipe); err != nil { t.Fatal(err) } @@ -144,18 +146,18 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { allocation := "alloc-l-" + device.Name e.allocation(device, allocation, "Releasing") original := e.wipe(device, allocation, 1) - original.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + original.Status = ops.OperationStatus{Admission: admitted(1), Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} if err := e.admin.Status().Update(e.ctx, original); err != nil { t.Fatal(err) } retried := e.namedWipe(device, allocation, original.Name+"-retry-2", 1) - retried.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 3, FinishedAt: ptrTime(e.clock.Now())} + retried.Status = ops.OperationStatus{Admission: admitted(3), Phase: ops.PhaseOutcomeUnknown, Fence: 3, FinishedAt: ptrTime(e.clock.Now())} if err := e.admin.Status().Update(e.ctx, retried); err != nil { t.Fatal(err) } custody := verify(e, device, 3) hold := custody.Spec.RecoveryHold - if hold == nil || hold.UID != string(retried.UID) || hold.RetryName != original.Name || hold.Retries != 2 || RetryName(*hold, 3) != original.Name+"-retry-3" || len(custody.Spec.Conflicts) != 0 { + if hold == nil || hold.Name != retried.Name || hold.RetryName != original.Name || hold.Retries != 2 || RetryName(*hold, 3) != original.Name+"-retry-3" || len(custody.Spec.Conflicts) != 0 { t.Fatalf("rebuilt hold = %+v", hold) } }) @@ -168,14 +170,14 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { var newest *ops.DeviceInstallation for index, fence := range []int64{2, 5} { install := e.installation(device, allocation, fmt.Sprintf("request-%d", index)) - install.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: fence, FinishedAt: ptrTime(e.clock.Now())} + install.Status = ops.OperationStatus{Admission: admitted(fence), Phase: ops.PhaseOutcomeUnknown, Fence: fence, FinishedAt: ptrTime(e.clock.Now())} if err := e.admin.Status().Update(e.ctx, install); err != nil { t.Fatal(err) } newest = install } custody := verify(e, device, 5) - if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, ConflictMultipleUnfinished) || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(newest.UID) { + if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, ConflictMultipleUnfinished) || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.Name != newest.Name { t.Fatalf("rebuilt = %+v", custody.Spec) } // Resolve must agree with the live allocation, and keeps the hold. @@ -198,7 +200,7 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { e.settle(device.Name) e.requirePhase(resolve, ops.PhaseSucceeded, "") custody = e.custody(device.Name) - if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(newest.UID) { + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.Name != newest.Name { t.Fatalf("after Resolve: %+v", custody.Spec) } }) @@ -259,7 +261,7 @@ func TestARefusalNeverUsesCustodyReadBeforeAHolderChange(t *testing.T) { device := e.verified("server-example-800", uid(800), fmt.Sprintf("%064x", 800)) var install *ops.DeviceInstallation racing := &claimingClient{Client: e.client(), before: func() { - if err := e.coord.Claim(e.ctx, device.Name, "alloc-late"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-late"); err != nil { t.Error(err) } install = e.installation(device, "alloc-late", "request-1") @@ -302,12 +304,13 @@ func TestFencesFollowTheSiteReport(t *testing.T) { func TestAHeldOperationIsNeverACandidate(t *testing.T) { e := startEnv(t) device := e.verified("server-example-820", uid(820), fmt.Sprintf("%064x", 820)) - if err := e.coord.Claim(e.ctx, device.Name, "alloc-held"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-held"); err != nil { t.Fatal(err) } install := e.installation(device, "alloc-held", "request-1") custody := e.custody(device.Name) - custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: reference("DeviceInstallation", install), Fence: 0, Since: metav1.NewTime(e.clock.Now()), Reason: ReasonRebuilt} + e.markAdmitted(install, custody.Spec.Fence+1) + custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: reference("DeviceInstallation", install), Fence: custody.Spec.Fence + 1, Since: metav1.NewTime(e.clock.Now()), Reason: ReasonRebuilt} candidates, err := e.coord.candidates(e.ctx, custody) if err != nil { t.Fatal(err) diff --git a/internal/custody/incarnation_test.go b/internal/custody/incarnation_test.go new file mode 100644 index 00000000..c07dc0f5 --- /dev/null +++ b/internal/custody/incarnation_test.go @@ -0,0 +1,286 @@ +package custody + +import ( + "errors" + "fmt" + "testing" + + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// No spec holds an object UID, so custody names an operation by kind and +// name with the fence it admitted it at. These tests pin the guards that +// keep a same-name recreation from inheriting anything. + +// recreate deletes an operation and creates another with the same name and +// spec, as a client that lost the first might. The new object has no +// admission record. +func (e *env) recreate(operation ops.Operation) { + e.t.Helper() + if err := e.admin.Delete(e.ctx, operation); err != nil { + e.t.Fatal(err) + } + fresh := operation.DeepCopyObject().(ops.Operation) + fresh.SetResourceVersion("") + fresh.SetUID("") + *fresh.OperationStatus() = ops.OperationStatus{} + e.create(fresh) +} + +// statusOf reads an operation's current status by name. +func (e *env) statusOf(operation ops.Operation) ops.OperationStatus { + e.t.Helper() + current := operation.DeepCopyObject().(ops.Operation) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), current); err != nil { + e.t.Fatal(err) + } + return *current.OperationStatus() +} + +// TestARecreatedActiveOperationNeverGetsItsResult recreates the active +// operation after admission, and the coordinator passes over it before the +// site's result arrives. The recreated object never takes the admission, so +// the result for it is never applied to that object. +func TestARecreatedActiveOperationNeverGetsItsResult(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-842", uid(842), fmt.Sprintf("%064x", 842)) + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-a"); err != nil { + t.Fatal(err) + } + first := e.providerOp(device, "alloc-a", "again") + e.settle(device.Name) + active := *e.custody(device.Name).Spec.ActiveOperation + e.recreate(first) + e.settle(device.Name) + _ = e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded}) + e.settle(device.Name) + if status := e.statusOf(first); status.Fence == active.Fence || status.Phase == ops.PhaseSucceeded || admittedAtStatus(status, active.Fence) { + t.Fatalf("the recreated operation got the admission's result: %+v", status) + } +} + +// TestARecreatedOperationNeverInheritsItsLastResult recreates an operation +// after it ended. Custody's last result names the first at its fence, and is +// never copied to the second. +func TestARecreatedOperationNeverInheritsItsLastResult(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-840", uid(840), fmt.Sprintf("%064x", 840)) + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-r"); err != nil { + t.Fatal(err) + } + first := e.providerOp(device, "alloc-r", "again") + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + ended := e.requirePhase(first, ops.PhaseSucceeded, "") + e.recreate(first) + e.settle(device.Name) + if last := e.custody(device.Name).Spec.LastResult; last == nil || last.Name != first.Name || last.Fence != ended.Fence { + t.Fatalf("custody's last result = %+v", last) + } + if status := e.statusOf(first); status.Fence == ended.Fence || status.Phase == ops.PhaseSucceeded { + t.Fatalf("the recreated operation inherited the result: %+v", status) + } +} + +// TestARecreatedHeldOperationNeverTakesTheHold recreates an operation whose +// outcome custody holds. The hold stays on the first, and the second is +// neither held nor admitted as the held operation. +func TestARecreatedHeldOperationNeverTakesTheHold(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-843", uid(843), fmt.Sprintf("%064x", 843)) + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-h"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-h"); err != nil { + t.Fatal(err) + } + wipe := e.wipe(device, "alloc-h", 1) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + e.recreate(wipe) + e.settle(device.Name) + if after := e.custody(device.Name).Spec.RecoveryHold; after == nil || heldReference(*after) != heldReference(hold) { + t.Fatalf("hold after the recreation = %+v", after) + } + if status := e.statusOf(wipe); status.Phase == ops.PhaseOutcomeUnknown || status.Admission != nil { + t.Fatalf("the recreated operation took the hold: %+v", status) + } +} + +// TestARecreatedRetryIsNeverCountedAsTheRetry recreates the operation a +// Retry admitted to settle a hold. The recreated object is not the Retry's +// operation: it is not admitted in its place, and a result for the Retry's +// admission never settles the hold through it. +func TestARecreatedRetryIsNeverCountedAsTheRetry(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-844", uid(844), fmt.Sprintf("%064x", 844)) + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-t"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-t"); err != nil { + t.Fatal(err) + } + e.wipe(device, "alloc-t", 1) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseSucceeded, "") + retried := e.namedWipe(device, "alloc-t", RetryName(hold, 1), 1) + e.settle(device.Name) + e.requirePhase(retried, ops.PhaseAdmitted, "") + active := *e.custody(device.Name).Spec.ActiveOperation + e.recreate(retried) + e.settle(device.Name) + _ = e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded}) + e.settle(device.Name) + if status := e.statusOf(retried); admittedAtStatus(status, active.Fence) || status.Phase == ops.PhaseSucceeded { + t.Fatalf("the recreated operation was counted as the Retry's: %+v", status) + } + if after := e.custody(device.Name).Spec.RecoveryHold; after == nil || heldReference(*after) != heldReference(hold) || after.Retries != 1 { + t.Fatalf("hold after the recreated retry = %+v", after) + } +} + +func admittedAtStatus(status ops.OperationStatus, fence int64) bool { + return status.Admission != nil && status.Admission.Fence == fence +} + +// TestARecreatedDeviceLeavesCustodyUnverified recreates a Device under the +// same name. Custody's device-uid label names the first Device, so custody +// stays Unverified until a Resolve. +func TestARecreatedDeviceLeavesCustodyUnverified(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-841", uid(841), fmt.Sprintf("%064x", 841)) + before := e.custody(device.Name) + if before.Labels[ops.LabelDeviceUID] != string(device.UID) { + t.Fatalf("custody label = %q, want the Device UID", before.Labels[ops.LabelDeviceUID]) + } + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + recreated := e.device(device.Name, uid(841), fmt.Sprintf("%064x", 841)) + e.settle(device.Name) + after := e.custody(device.Name) + if after.Spec.State != ops.CustodyUnverified || after.Labels[ops.LabelDeviceUID] == string(recreated.UID) { + t.Fatalf("custody for a recreated Device = %s, label %q", after.Spec.State, after.Labels[ops.LabelDeviceUID]) + } +} + +// TestARecreatedRetryNeverSupersedesARebuiltHold rebuilds custody for a +// held wipe whose retry was deleted and recreated before it was admitted +// again. A later retry carries the lineage only if it was admitted, so the +// recreated one never takes the hold away from the wipe it was named for. +func TestARecreatedRetryNeverSupersedesARebuiltHold(t *testing.T) { + e := startEnv(t) + device := e.device("server-example-845", uid(845), fmt.Sprintf("%064x", 845)) + allocation := "alloc-n-" + device.Name + e.allocation(device, allocation, "Releasing") + original := e.wipe(device, allocation, 1) + original.Status = ops.OperationStatus{Admission: admitted(1), Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, original); err != nil { + t.Fatal(err) + } + // The retry, deleted and recreated: it carries no admission record. + e.namedWipe(device, allocation, original.Name+"-retry-1", 1) + e.sites.report(device.Name, 1) + e.settle(device.Name) + custody := e.custody(device.Name) + if hold := custody.Spec.RecoveryHold; hold == nil || hold.Name != original.Name || hold.Fence != 1 { + t.Fatalf("rebuilt hold = %+v", custody.Spec.RecoveryHold) + } +} + +// TestCustodyForAnotherDeviceIncarnationIsNeverClaimed covers custody still +// recorded for an earlier Device under the same name, before rebuild has +// marked it Unverified: no allocation claims it for the new Device. +func TestCustodyForAnotherDeviceIncarnationIsNeverClaimed(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-846", uid(846), fmt.Sprintf("%064x", 846)) + custody := e.custody(device.Name) + custody.Labels[ops.LabelDeviceUID] = uid(847) + if err := e.admin.Update(e.ctx, custody); err != nil { + t.Fatal(err) + } + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-earlier-incarnation"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("claim of custody for another Device incarnation = %v", err) + } + if after := e.custody(device.Name); after.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("holder = %+v", after.Spec.Holder) + } +} + +// TestRebuildIgnoresAnEarlierDeviceIncarnation rebuilds custody for a +// Device recreated under the same name. An allocation and an admitted +// operation recorded for the earlier Device name it only by name, and +// rebuild takes neither as the new Device's holder or hold. +func TestRebuildIgnoresAnEarlierDeviceIncarnation(t *testing.T) { + e := startEnv(t) + device := e.device("server-example-848", uid(848), fmt.Sprintf("%064x", 848)) + allocation := "alloc-old-" + device.Name + e.allocation(device, allocation, "Releasing") + wipe := e.wipe(device, allocation, 1) + wipe.Status = ops.OperationStatus{Admission: admitted(1), Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, wipe); err != nil { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + recreated := e.device(device.Name, uid(848), fmt.Sprintf("%064x", 848)) + if recreated.UID == device.UID { + t.Fatal("the Device was not recreated") + } + // Custody does not exist yet, so the first reconcile rebuilds it. + e.sites.report(device.Name, 0) + e.settle(device.Name) + rebuilt := e.custody(device.Name) + if rebuilt.Spec.RecoveryHold != nil || rebuilt.Spec.ActiveOperation != nil { + t.Fatalf("rebuild took the earlier Device's operation: hold %+v, active %+v", rebuilt.Spec.RecoveryHold, rebuilt.Spec.ActiveOperation) + } + if rebuilt.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("rebuild took the earlier Device's allocation as the holder: %+v", rebuilt.Spec.Holder) + } +} + +// TestARecreatedDeviceIsNeverClaimedUnderItsStaleLabel covers custody still +// labelled for the earlier Device, recreated under the same name before +// rebuild relabels custody. The allocation names that earlier incarnation, +// so custody's label matches it, and only the live Device shows the claim is +// stale. +func TestARecreatedDeviceIsNeverClaimedUnderItsStaleLabel(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-849", uid(849), fmt.Sprintf("%064x", 849)) + old := device.UID + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + recreated := e.device(device.Name, uid(849), fmt.Sprintf("%064x", 849)) + if recreated.UID == old { + t.Fatal("the Device was not recreated") + } + if label := e.custody(device.Name).Labels[ops.LabelDeviceUID]; label != string(old) { + t.Fatalf("custody label = %q, want the earlier Device's", label) + } + if err := e.coord.Claim(e.ctx, device.Name, old, "alloc-stale-label"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("claim for the earlier Device incarnation = %v", err) + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("holder = %+v", holder) + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 2f179eed..19ab1a19 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -36,15 +36,15 @@ const ( ReasonRetryAuthorized = "RetryAlreadyAuthorized" ReasonDisposalRequired = "DisposalRequired" ReasonInvalidResolve = "InvalidResolve" - // Reasons the Redfish install and wipe workers raise. + // Reasons every site's install and wipe workers raise. ReasonTargetUnsupported = "TargetUnsupported" ReasonTargetDisks = "TargetDisksUnknown" ReasonInputsUnreadable = "InputsUnreadable" ) -// redfishWorkerReasons are the reasons the site's install and wipe workers +// workerReasons are the reasons every site's install and wipe workers // raise before sending anything. -var redfishWorkerReasons = []Reason{{Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonTargetDisks, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}} +var workerReasons = []Reason{{Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonTargetDisks, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}} const evidenceLimit = 4096 @@ -95,7 +95,7 @@ func DeviceInstallationKind() Kind { }, Naming: DeterministicName, Name: func(operation ops.Operation) string { - return InstallationName(allocationName(operation), operation.(*ops.DeviceInstallation).Spec.RequestUID) + return InstallationName(allocationName(operation), operation.GetLabels()[ops.LabelInstallationUID]) }, Deadline: InstallationDeadline, Effectful: true, @@ -114,7 +114,7 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, redfishWorkerReasons...), + Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), @@ -143,7 +143,7 @@ func DeviceWipeKind() Kind { // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, - Reasons: redfishWorkerReasons, + Reasons: workerReasons, Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") @@ -292,7 +292,8 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody return nil, refusal } spec := custody.Spec - reference := ops.OperationReference{Kind: "DeviceRecovery", Name: recovery.Name, UID: string(recovery.UID)} + // The recovery is applied while it is the active operation, at its fence. + reference := ops.HeldOperationReference{Kind: "DeviceRecovery", Name: recovery.Name, Fence: custody.Spec.ActiveOperation.Fence} switch recovery.Spec.Decision { case ops.DecisionSettle: spec.RecoveryHold = nil @@ -311,7 +312,6 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody resolve := recovery.Spec.Resolve spec.State = ops.CustodyVerified spec.Conflicts = nil - spec.DeviceRef.UID = string(apply.Device.UID) spec.Fence = max(spec.Fence, apply.HighestFence) spec.Holder = ops.Holder{Type: resolve.Holder} if resolve.AllocationRef != nil { diff --git a/internal/custody/lifecycle_test.go b/internal/custody/lifecycle_test.go index 0bc4f300..2146fc63 100644 --- a/internal/custody/lifecycle_test.go +++ b/internal/custody/lifecycle_test.go @@ -19,13 +19,13 @@ func TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing(t *testing.T) { device := e.device("server-example-001", uid(1), testKeyA) e.settle(device.Name) custody := e.custody(device.Name) - if custody.Spec.State != ops.CustodyUnverified || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.ActiveOperation != nil || custody.Spec.DeviceRef.UID != string(device.UID) { + if custody.Spec.State != ops.CustodyUnverified || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.ActiveOperation != nil || custody.Labels[ops.LabelDeviceUID] != string(device.UID) { t.Fatalf("new custody = %+v", custody.Spec) } if len(custody.Finalizers) != 1 || custody.Finalizers[0] != ops.CustodyFinalizer { t.Fatalf("finalizers = %v", custody.Finalizers) } - if err := e.coord.Claim(e.ctx, device.Name, "alloc-example"); !errors.Is(err, ErrUnavailable) { + 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}) @@ -62,10 +62,10 @@ func TestLifecycle(t *testing.T) { t.Run("holder transitions None Allocation Release None", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-a"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-a"); err != nil { t.Fatal(err) } - if err := e.coord.Claim(e.ctx, device.Name, "alloc-b"); !errors.Is(err, ErrUnavailable) { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-b"); !errors.Is(err, ErrUnavailable) { t.Fatalf("a second allocation claimed the server: %v", err) } if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-b"); !errors.Is(err, ErrUnavailable) { @@ -179,7 +179,7 @@ func TestLifecycle(t *testing.T) { t.Run("pending operations are admitted oldest first", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-q"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-q"); err != nil { t.Fatal(err) } e.providerOp(device, "alloc-q", "first") @@ -203,7 +203,7 @@ func TestLifecycle(t *testing.T) { t.Run("a newer pending operation supersedes an older one for the same authority", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-s"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-s"); err != nil { t.Fatal(err) } running := e.installation(device, "alloc-s", "request-running") @@ -220,7 +220,7 @@ func TestLifecycle(t *testing.T) { t.Run("a holder change cancels pending operations that no longer match", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-c"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-c"); err != nil { t.Fatal(err) } running := e.installation(device, "alloc-c", "request-a") @@ -258,9 +258,9 @@ func TestLifecycle(t *testing.T) { } other := stale other.Fence = active.Fence - other.Operation.UID = "00000000-0000-4000-8000-000000000999" + other.Operation.Name = "another-operation" if err := e.coord.AcceptResult(e.ctx, other); !errors.Is(err, ErrStaleFence) { - t.Fatalf("result for another incarnation: %v", err) + t.Fatalf("result for another operation: %v", err) } after := e.custody(device.Name) if after.Spec.ActiveOperation == nil || after.Spec.Holder.Type != custody.Spec.Holder.Type || after.Spec.RejectedResults == nil || after.Spec.RejectedResults.Count != 2 || after.Spec.RejectedResults.Last.Fence != active.Fence || after.Spec.RejectedResults.Last.Site != testSite { diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go index 3bdd2bc0..4cb27864 100644 --- a/internal/custody/rebuild.go +++ b/internal/custody/rebuild.go @@ -50,6 +50,7 @@ func (c *Coordinator) rebuild(ctx context.Context, device *inventory.Device) (Ou return Outcome{}, err } custody := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: device.Namespace, Finalizers: []string{ops.CustodyFinalizer}}, Spec: spec} + setDeviceUID(custody, device) if err := c.Client.Create(ctx, custody); err != nil && !apierrors.IsAlreadyExists(err) { return Outcome{}, err } @@ -57,7 +58,7 @@ func (c *Coordinator) rebuild(ctx context.Context, device *inventory.Device) (Ou } func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) (ops.DeviceCustodySpec, error) { - spec := ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}} + spec := ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}} holders := map[ops.HolderType]bool{} if inventory.LifecycleOf(device) == inventory.DeviceRetired { holders[ops.HolderRetired] = true @@ -90,11 +91,11 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) } for _, operation := range kind.Items(list) { envelope := operation.Envelope() - if envelope.DeviceRef.Name != device.Name || envelope.DeviceRef.UID != string(device.UID) { + if envelope.DeviceRef.Name != device.Name || operation.GetLabels()[ops.LabelDeviceUID] != string(device.UID) { continue } status := operation.OperationStatus() - spec.Fence = max(spec.Fence, status.Fence) + spec.Fence = max(spec.Fence, status.Fence, admissionFence(operation)) if kind.Retires != nil && status.Phase == ops.PhaseSucceeded && kind.Retires(operation) { holders[ops.HolderRetired] = true } @@ -105,10 +106,10 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) // an operation whose kind settles the held kind, or a recovery that // cleared that exact hold. settled := func(held found) bool { - fence := held.operation.OperationStatus().Fence + fence := admissionFence(held.operation) for _, other := range all { // A later retry of the same operation continues its hold. - if other.kind == held.kind && retryBase(other.operation.GetName()) == retryBase(held.operation.GetName()) && other.operation.GetName() != held.operation.GetName() && other.operation.OperationStatus().Fence > fence { + if other.kind == held.kind && retryBase(other.operation.GetName()) == retryBase(held.operation.GetName()) && other.operation.GetName() != held.operation.GetName() && admissionFence(other.operation) > fence { return true } status := other.operation.OperationStatus() @@ -120,19 +121,21 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) return true } } - if status.Fence > fence && slices.ContainsFunc(other.kind.Settles, func(rule SettleRule) bool { return rule.Held == held.kind.GVK.Kind }) { + if admissionFence(other.operation) > fence && slices.ContainsFunc(other.kind.Settles, func(rule SettleRule) bool { return rule.Held == held.kind.GVK.Kind }) { return true } } return false } - // Every operation that has not ended may already have been admitted and - // executed, even if its status says Pending, because custody is written - // before status. An unknown outcome nothing later settled is held too. + // An operation records its admission before custody names it, so one + // without an admission record was never admitted. Every admitted + // operation that has not ended may already have executed, even if its + // status says Pending, because custody is written before the rest of its + // status. An unknown outcome nothing later settled is held too. var held []found for _, candidate := range all { phase := candidate.operation.OperationStatus().Phase - if phase.Ended() && (phase != ops.PhaseOutcomeUnknown || settled(candidate)) { + if candidate.operation.OperationStatus().Admission == nil || phase.Ended() && (phase != ops.PhaseOutcomeUnknown || settled(candidate)) { continue } held = append(held, candidate) @@ -150,11 +153,11 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) // With several, the newest is held and a Resolve must decide, so the // hold is never dropped. slices.SortStableFunc(held, func(a, b found) int { - return cmp.Compare(b.operation.OperationStatus().Fence, a.operation.OperationStatus().Fence) + return cmp.Compare(admissionFence(b.operation), admissionFence(a.operation)) }) newest := held[0] status := newest.operation.OperationStatus() - spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName(), UID: string(newest.operation.GetUID())}, Fence: status.Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt, Deadline: status.Deadline, Snapshot: status.Snapshot} + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName()}, Fence: admissionFence(newest.operation), Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt, Deadline: status.Deadline, Snapshot: status.Snapshot} // A held retry keeps its lineage: its name is the original // operation's name, "-retry-" and the Retry count. if match := retrySuffix.FindStringSubmatch(newest.operation.GetName()); match != nil && slices.ContainsFunc(all, func(other found) bool { @@ -187,26 +190,17 @@ func appendOnce(list []string, value string) []string { return append(list, value) } -// LiveAllocations returns the MachineAllocations that are not Released and -// whose MachineCapacity is backed by the Device. +// LiveAllocations returns the MachineAllocations in the Device's namespace +// that are not Released and name this Device incarnation. func LiveAllocations(ctx context.Context, reader client.Reader, device *inventory.Device) ([]metal.MachineAllocation, error) { var allocations metal.MachineAllocationList - if err := reader.List(ctx, &allocations); err != nil { + if err := reader.List(ctx, &allocations, client.InNamespace(device.Namespace)); err != nil { return nil, err } var out []metal.MachineAllocation for _, allocation := range allocations.Items { - if allocation.Status.Phase == "Released" { - continue - } - capacity := &metal.MachineCapacity{} - reference := allocation.Spec.MachineCapacityRef - if err := reader.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, capacity); apierrors.IsNotFound(err) { - continue - } else if err != nil { - return nil, err - } - if capacity.Namespace == device.Namespace && capacity.Spec.DeviceRef.Name == device.Name { + reference := allocation.Spec.DeviceRef + if allocation.Status.Phase != metal.AllocationReleased && reference.Name == device.Name && allocation.Labels[metal.LabelDeviceUID] == string(device.UID) { out = append(out, allocation) } } diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index dbac7d14..9f9b590b 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -148,7 +148,7 @@ func TestRecovery(t *testing.T) { e.clock.Advance(RecoveryDeadline + DefaultSkewMargin) e.settle(device.Name) e.requirePhase(settle, ops.PhaseFailed, ReasonSiteNotConfirmed) - if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.UID != hold.UID { + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.Name != hold.Name || got.Fence != hold.Fence { t.Fatalf("hold = %+v", got) } }) @@ -156,7 +156,7 @@ func TestRecovery(t *testing.T) { t.Run("a wipe after release settles an installation hold", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-i"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-i"); err != nil { t.Fatal(err) } install := e.installation(device, "alloc-i", "request-1") @@ -181,7 +181,7 @@ func TestRecovery(t *testing.T) { wipe := e.wipe(device, "alloc-i", 1) e.settle(device.Name) e.requirePhase(wipe, ops.PhaseAdmitted, "") - if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || active.Settles.UID != string(install.UID) { + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || active.Settles.Name != install.Name { t.Fatalf("wipe does not record what it settles: %+v", active) } if err := e.result(device.Name, ops.PhaseSucceeded, `{"wipedDisks":["disk-0"],"policyDigest":"`+policyDigest+`"}`); err != nil { @@ -206,7 +206,7 @@ func TestRecovery(t *testing.T) { t.Run("a held wipe settles only with a wipe named for the Retry, and retries count on", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-w"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-w"); err != nil { t.Fatal(err) } if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-w"); err != nil { @@ -243,7 +243,7 @@ func TestRecovery(t *testing.T) { e.requirePhase(retried, ops.PhaseAdmitted, "") e.requirePhase(later, ops.PhasePending, ReasonRecoveryHold) custody := e.custody(device.Name) - if got := custody.Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil || got.Retries != 1 || custody.Spec.ActiveOperation.Settles == nil || custody.Spec.ActiveOperation.Settles.UID != hold.UID { + if got := custody.Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil || got.Retries != 1 || custody.Spec.ActiveOperation.Settles == nil || *custody.Spec.ActiveOperation.Settles != heldReference(hold) { t.Fatalf("the retry was not used by the retried wipe: %+v", custody.Spec) } // The retried wipe ends unknown too: the next retry keeps the @@ -253,7 +253,7 @@ func TestRecovery(t *testing.T) { } e.settle(device.Name) second := *e.custody(device.Name).Spec.RecoveryHold - if second.UID != string(retried.UID) || second.RetryName != hold.Name || second.Retries != 1 { + if second.Name != retried.Name || second.RetryName != hold.Name || second.Retries != 1 { t.Fatalf("second hold = %+v", second) } again := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(second)}) @@ -281,7 +281,7 @@ func TestRecovery(t *testing.T) { t.Run("pending replacement never cancels an operation that settles a hold", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-ps"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-ps"); err != nil { t.Fatal(err) } e.providerOp(device, "alloc-ps", "held") @@ -303,7 +303,7 @@ func TestRecovery(t *testing.T) { t.Run("a second Retry for the same hold is refused", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-rr"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-rr"); err != nil { t.Fatal(err) } if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-rr"); err != nil { @@ -321,7 +321,7 @@ func TestRecovery(t *testing.T) { e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) e.settle(device.Name) e.requirePhase(retry, ops.PhaseSucceeded, "") - if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) || got.Retries != 1 { + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.Name != retry.Name || got.Retries != 1 { t.Fatalf("retry not recorded: %+v", got) } second := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) @@ -332,7 +332,7 @@ func TestRecovery(t *testing.T) { t.Run("retiring from Release records disk disposal", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-r"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-r"); err != nil { t.Fatal(err) } if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-r"); err != nil { @@ -358,7 +358,7 @@ func TestRecovery(t *testing.T) { } // An allocated server cannot be retired. allocated := fresh() - if err := e.coord.Claim(e.ctx, allocated.Name, "alloc-live"); err != nil { + if err := e.coord.Claim(e.ctx, allocated.Name, allocated.UID, "alloc-live"); err != nil { t.Fatal(err) } e.providerOp(allocated, "alloc-live", "a") @@ -439,7 +439,7 @@ func TestRebuild(t *testing.T) { if rebuilt.Spec.State != ops.CustodyUnverified { t.Fatalf("rebuilt = %+v", rebuilt.Spec) } - if err := e.coord.Claim(e.ctx, name, "alloc-new"); err == nil { + if err := e.coord.Claim(e.ctx, name, e.deviceUID(name), "alloc-new"); err == nil { t.Fatal("rebuilt custody was allocatable before verification") } e.sites.report(name, used) @@ -448,7 +448,7 @@ func TestRebuild(t *testing.T) { if rebuilt.Spec.State != ops.CustodyVerified || rebuilt.Spec.Fence <= used { t.Fatalf("verified fence %d, site stored %d", rebuilt.Spec.Fence, used) } - if err := e.coord.Claim(e.ctx, name, "alloc-new"); err != nil { + if err := e.coord.Claim(e.ctx, name, e.deviceUID(name), "alloc-new"); err != nil { t.Fatal(err) } }) @@ -507,18 +507,18 @@ func TestRebuild(t *testing.T) { } }) - t.Run("from operations: an unfinished operation, even Pending, is held", func(t *testing.T) { + t.Run("from operations: an admitted unfinished operation, even Pending, is held", func(t *testing.T) { e := e.sub(t) name, id, key := next() device := e.device(name, id, key) operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("restore")), Input: "a"}} e.create(operation) - operation.Status = ops.OperationStatus{Phase: ops.PhasePending, Fence: 9} + operation.Status = ops.OperationStatus{Admission: admitted(9), Phase: ops.PhasePending, Fence: 9} if err := e.admin.Status().Update(e.ctx, operation); err != nil { t.Fatal(err) } custody := rebuildFrom(e, name, 4) - if hold := custody.Spec.RecoveryHold; hold == nil || hold.UID != string(operation.UID) || hold.Reason != ReasonRebuilt || custody.Spec.Holder.Type != ops.HolderService || custody.Spec.Fence != 10 { + if hold := custody.Spec.RecoveryHold; hold == nil || hold.Name != operation.Name || hold.Reason != ReasonRebuilt || custody.Spec.Holder.Type != ops.HolderService || custody.Spec.Fence != 10 { t.Fatalf("rebuilt = %+v", custody.Spec) } }) @@ -530,7 +530,7 @@ func TestRebuild(t *testing.T) { recovery := &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: ops.DeviceRecoverySpec{OperationEnvelope: envelope(device, staffUser, service("retired")), Decision: ops.DecisionRetire, Hold: &ops.HeldOperationReference{Kind: testStaffKind, Name: "x", Fence: 1}, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "s"}}} e.create(recovery) finished := metav1.NewTime(e.clock.Now()) - recovery.Status = ops.OperationStatus{Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: &finished} + recovery.Status = ops.OperationStatus{Admission: admitted(2), Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: &finished} if err := e.admin.Status().Update(e.ctx, recovery); err != nil { t.Fatal(err) } @@ -545,7 +545,7 @@ func TestRebuild(t *testing.T) { if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, want) { t.Fatalf("rebuilt = %+v, want conflict %s", custody.Spec, want) } - if err := e.coord.Claim(e.ctx, name, "alloc-any"); err == nil { + if err := e.coord.Claim(e.ctx, name, e.deviceUID(name), "alloc-any"); err == nil { t.Fatal("conflicted custody was claimed") } } @@ -564,7 +564,9 @@ func TestRebuild(t *testing.T) { name, id, key := next() device := e.device(name, id, key) e.allocation(device, "alloc-"+name, "Active") - e.create(&DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}}) + staff := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}} + e.create(staff) + e.markAdmitted(staff, 1) conflict(t, e, name, ConflictHolderSources) }) @@ -572,8 +574,10 @@ func TestRebuild(t *testing.T) { e := e.sub(t) name, id, key := next() device := e.device(name, id, key) - for range 2 { - e.create(&DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}}) + for fence := range int64(2) { + staff := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}} + e.create(staff) + e.markAdmitted(staff, fence+1) } conflict(t, e, name, ConflictMultipleUnfinished) }) @@ -602,7 +606,7 @@ func TestRebuild(t *testing.T) { e.settle(name) e.requirePhase(resolve, ops.PhaseSucceeded, "") custody = e.custody(name) - if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.DeviceRef.UID != string(replacement.UID) || len(custody.Spec.Conflicts) != 0 { + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderNone || custody.Labels[ops.LabelDeviceUID] != string(replacement.UID) || len(custody.Spec.Conflicts) != 0 { t.Fatalf("after Resolve: %+v", custody.Spec) } }) diff --git a/internal/custody/results.go b/internal/custody/results.go index 8a69b9ff..d5062bb9 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -2,15 +2,21 @@ package custody import ( "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" "errors" "fmt" "slices" + "strconv" + "strings" "time" 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" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -33,15 +39,16 @@ var ( // SiteResult is what a site reports for one operation. It always carries the // operation's fence. type SiteResult struct { - Site string - Device string - Operation ops.OperationReference - Fence int64 + Site string `json:"site"` + Device string `json:"device"` + Operation ops.OperationReference `json:"operation"` + Fence int64 `json:"fence"` // Phase is Dispatched, Verifying, Succeeded, Failed or OutcomeUnknown. - Phase ops.Phase - Reason string - Message string - Evidence []byte + Phase ops.Phase `json:"phase"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + // Evidence is the kind's typed evidence as JSON. + Evidence json.RawMessage `json:"evidence,omitempty"` } // update reads custody, applies change and writes it with the @@ -75,6 +82,22 @@ func ignoreNoChange(err error) error { return err } +// OperationKey is the site's name for one admission of an operation: its +// lowercased kind, name and fence. A same-name operation admitted later has +// a higher fence and so another key. It is a valid site record and file +// name: a name too long for that is replaced by its digest. +func OperationKey(reference ops.OperationReference, fence int64) string { + kind, suffix := strings.ToLower(reference.Kind), "."+strconv.FormatInt(fence, 10) + if key := kind + "." + reference.Name + suffix; len(key) <= maxOperationKey { + return key + } + sum := sha256.Sum256([]byte(reference.Name)) + return kind + "." + hex.EncodeToString(sum[:])[:32] + suffix +} + +// maxOperationKey is the site store's limit on a record name. +const maxOperationKey = 128 + // AcceptResult records a site result in custody. A result whose fence or // operation does not match the active operation is rejected and recorded as // a rejected fence; ErrStaleFence is returned either way, so the site @@ -85,7 +108,7 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error // unregistered kind is rejected as stale below. var operation ops.Operation if kind := c.Registry.Kind(result.Operation.Kind); kind != nil && len(result.Evidence) != 0 { - found, _, err := c.get(ctx, result.Operation) + found, _, err := c.get(ctx, result.Operation, result.Fence) if err != nil { return err } @@ -161,7 +184,7 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error case ops.PhaseFailed: c.finishActive(custody, *active, ops.PhaseFailed, result.Reason, result.Message, evidence) case ops.PhaseSucceeded: - if hold := spec.RecoveryHold; hold != nil && active.Settles != nil && *active.Settles == hold.OperationReference { + if hold := spec.RecoveryHold; hold != nil && active.Settles != nil && *active.Settles == heldReference(*hold) { spec.RecoveryHold = nil } c.finishActive(custody, *active, ops.PhaseSucceeded, result.Reason, result.Message, evidence) @@ -185,22 +208,34 @@ func progressRank(phase ops.Phase) int { // The allocator decides with this update, never with the advisory Available // condition. A claim that already names the allocation succeeds, so a retry // after a lost response does not claim a second server. -func (c *Coordinator) Claim(ctx context.Context, deviceName, allocation string) error { - device, err := c.device(ctx, deviceName) - if err != nil { - return err - } - if device == nil || inventory.LifecycleOf(device) != inventory.DeviceActive { - return fmt.Errorf("%w: the Device is not Active", ErrUnavailable) +// +// deviceUID is the Device incarnation the allocation was made against, from +// its device-uid label. Each attempt of the conditional update reads the +// Device again and requires both it and custody's label to name that +// incarnation, so a Device recreated after selection is never claimed for an +// allocation made against the earlier one. +func (c *Coordinator) Claim(ctx context.Context, deviceName string, deviceUID types.UID, allocation string) error { + if deviceUID == "" { + return fmt.Errorf("%w: the allocation names no Device incarnation", ErrUnavailable) } return ignoreNoChange(c.update(ctx, deviceName, func(custody *ops.DeviceCustody) error { + device, err := c.device(ctx, deviceName) + if err != nil { + return err + } + switch { + case device == nil, device.UID != deviceUID: + return fmt.Errorf("%w: the Device is not the incarnation the allocation names", ErrUnavailable) + case !custody.DeletionTimestamp.IsZero(), custody.Labels[ops.LabelDeviceUID] != string(deviceUID): + return fmt.Errorf("%w: custody is for another Device incarnation", ErrUnavailable) + } spec := &custody.Spec if spec.Holder.Type == ops.HolderAllocation && spec.Holder.AllocationRef != nil && spec.Holder.AllocationRef.Name == allocation { return errNoChange } switch { - case !custody.DeletionTimestamp.IsZero(), spec.DeviceRef.UID != string(device.UID): - return fmt.Errorf("%w: custody is for another Device incarnation", ErrUnavailable) + case inventory.LifecycleOf(device) != inventory.DeviceActive: + return fmt.Errorf("%w: the Device is not Active", ErrUnavailable) case spec.State != ops.CustodyVerified: return fmt.Errorf("%w: custody is Unverified", ErrUnavailable) case spec.Holder.Type != ops.HolderNone: diff --git a/internal/custody/retention.go b/internal/custody/retention.go index 805a7c72..0300132b 100644 --- a/internal/custody/retention.go +++ b/internal/custody/retention.go @@ -6,7 +6,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" - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -18,17 +17,19 @@ import ( func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { cfg := c.config() cutoff := c.now().Add(-cfg.Retention) - referenced := map[types.UID]bool{} + // Custody names operations by kind and name, with the fence they were + // admitted at. + referenced := map[ops.OperationReference]bool{} var custodies ops.DeviceCustodyList if err := c.Client.List(ctx, &custodies, client.InNamespace(cfg.Namespace)); err != nil { return 0, err } for _, custody := range custodies.Items { if active := custody.Spec.ActiveOperation; active != nil { - referenced[types.UID(active.UID)] = true + referenced[active.OperationReference] = true } if hold := custody.Spec.RecoveryHold; hold != nil { - referenced[types.UID(hold.UID)] = true + referenced[hold.OperationReference] = true } } deleted := 0 @@ -39,7 +40,7 @@ func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { } for _, operation := range kind.Items(list) { status := operation.OperationStatus() - if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[operation.GetUID()] { + if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}] { continue } // A succeeded retirement is the only record of it until diff --git a/internal/custody/rows_test.go b/internal/custody/rows_test.go index 00dba5a3..dcc4582f 100644 --- a/internal/custody/rows_test.go +++ b/internal/custody/rows_test.go @@ -23,7 +23,7 @@ func TestRowsAndReplacement(t *testing.T) { t.Run("a request refused its permission check replaces nothing", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-cust"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-cust"); err != nil { t.Fatal(err) } e.installation(device, "alloc-cust", "request-running") @@ -65,7 +65,7 @@ func TestRowsAndReplacement(t *testing.T) { t.Fatal(err) } device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-row"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-row"); err != nil { t.Fatal(err) } named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-row-staff-a", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, providerUser, allocated("alloc-row")), Input: "a"}} @@ -157,7 +157,7 @@ func TestRowsAndReplacement(t *testing.T) { e.staffOp(device, "ok") e.settle(device.Name) active := e.custody(device.Name).Spec.ActiveOperation - err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: ops.OperationReference{Kind: "DeviceInvented", Name: active.Name, UID: active.UID}, Fence: active.Fence, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}) + err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: ops.OperationReference{Kind: "DeviceInvented", Name: active.Name}, Fence: active.Fence, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}) if !errors.Is(err, ErrStaleFence) { t.Fatalf("result for an unregistered kind: %v", err) } diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index adcde936..c637f8f7 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -99,6 +99,24 @@ func TestPrincipals(t *testing.T) { t.Fatalf("%+v classified %s, want %s", creator, got, want) } } + // Credentials that carry no UID are identified by username alone. + byName := Principals{CreatorMetalProvider: {{Username: "svc-a"}}, CreatorReleaseController: {{Username: "svc-b"}}} + if err := byName.Validate(); err != nil { + t.Fatal(err) + } + for creator, want := range map[ops.Creator]CreatorClass{ + {Username: "svc-a"}: CreatorMetalProvider, + {Username: "svc-b"}: CreatorReleaseController, + {Username: "svc-c"}: CreatorStaff, + } { + if got := byName.Classify(creator); got != want { + t.Fatalf("%+v classified %s, want %s", creator, got, want) + } + } + // A configured UID is checked: a creator without it is staff. + if got := principals.Classify(ops.Creator{Username: "svc-a"}); got != CreatorStaff { + t.Fatalf("a creator without the configured UID classified %s", got) + } for _, bad := range []Principals{{CreatorStaff: {{Username: "x"}}}, {CreatorMetalProvider: {{}}}, {CreatorMetalProvider: {{Username: "x"}}, CreatorReleaseController: {{Username: "x"}}}} { if bad.Validate() == nil { t.Fatalf("%v validated", bad) @@ -263,7 +281,7 @@ func TestCRDRules(t *testing.T) { custody = e.custody(device.Name) custody.Spec.DeviceRef.Name = "another" requireInvalid(t, e.admin.Update(ctx, custody)) - requireInvalid(t, e.admin.Create(ctx, &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: "mismatch", Namespace: "default"}, Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: "other", UID: "u"}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}}})) + requireInvalid(t, e.admin.Create(ctx, &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: "mismatch", Namespace: "default"}, Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: "other"}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}}})) custody = e.custody(device.Name) custody.Spec.Holder = ops.Holder{Type: ops.HolderAllocation} requireInvalid(t, e.admin.Update(ctx, custody)) diff --git a/internal/custody/testdata/crds/test-kinds.yaml b/internal/custody/testdata/crds/test-kinds.yaml index ca93d2a8..e629f79e 100644 --- a/internal/custody/testdata/crds/test-kinds.yaml +++ b/internal/custody/testdata/crds/test-kinds.yaml @@ -59,7 +59,6 @@ spec: maxLength: 512 required: - username - - uid deviceRef: type: object properties: @@ -67,13 +66,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid authority: type: object properties: @@ -113,6 +107,15 @@ spec: status: type: object properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence phase: type: string enum: @@ -241,7 +244,6 @@ spec: maxLength: 512 required: - username - - uid deviceRef: type: object properties: @@ -249,13 +251,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid authority: type: object properties: @@ -295,6 +292,15 @@ spec: status: type: object properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence phase: type: string enum: diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go new file mode 100644 index 00000000..7b72dfa8 --- /dev/null +++ b/internal/delivery/delivery.go @@ -0,0 +1,276 @@ +// Package delivery carries admitted operations from custody to the sites +// that serve each Device, and carries their results back. It is the +// coordinator's side of the federation layer. Delivery is replayed from +// custody after any crash, so a site sees each assignment at least once and +// ignores a fence it has already passed. +package delivery + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// Site is the coordinator's view of one remote site. +type Site interface { + // Deliver hands the site one assignment. It is idempotent. + Deliver(ctx context.Context, assignment site.Assignment) error + // Fence returns the site's fence report for a "/" + // Device, and false if the site has not reported one. + Fence(ctx context.Context, device string) (custody.SiteFence, bool, error) + // Results returns the results the site holds. + Results(ctx context.Context) ([]site.Stored, error) + // Forget tells the site the coordinator answered a result. + Forget(ctx context.Context, stored site.Stored) error +} + +// Sites is the coordinator's explicit site configuration: which sites serve +// which Device. Inventory does not yet record a Device's sites, so this is +// configuration, never inferred from placement. +type Sites struct { + Sites map[string]Site + // Devices maps a Device name to the names of the sites serving it. + Devices map[string][]string +} + +var _ custody.Sites = (*Sites)(nil) + +func (s *Sites) Serving(device *inventory.Device) []string { + var out []string + for _, name := range s.Devices[device.Name] { + if _, ok := s.Sites[name]; ok { + out = append(out, name) + } + } + return out +} + +func (s *Sites) Fence(ctx context.Context, name string, device *inventory.Device) (custody.SiteFence, bool, error) { + remote, ok := s.Sites[name] + if !ok { + return custody.SiteFence{}, false, nil + } + return remote.Fence(ctx, device.Namespace+"/"+device.Name) +} + +// Assignment builds the assignment for the active operation from custody +// and the operation's spec, exactly as admitted. +func Assignment(state *ops.DeviceCustody, operation ops.Operation) (site.Assignment, error) { + active := state.Spec.ActiveOperation + // The operation records the fence custody admitted it at, so a same-name + // operation created later is never delivered as this one. + if admission := operation.OperationStatus().Admission; active == nil || operation.GetName() != active.Name || admission == nil || admission.Fence != active.Fence { + return site.Assignment{}, errors.New("delivery: the operation is not custody's active operation") + } + var object struct { + Spec json.RawMessage `json:"spec"` + } + data, err := json.Marshal(operation) + if err != nil { + return site.Assignment{}, err + } + if err := json.Unmarshal(data, &object); err != nil { + return site.Assignment{}, err + } + return site.Assignment{ + Device: state.Namespace + "/" + state.Name, + Operation: active.OperationReference, + Fence: active.Fence, + AdmittedAt: active.AdmittedAt.Time, + Deadline: active.Deadline.Time, + Snapshot: active.Snapshot, + InputDigest: active.InputDigest, + Inputs: object.Spec, + }, nil +} + +// Courier delivers each Device's active operation to its sites and reports +// their results to the coordinator. +type Courier struct { + // Client reads custody and operations. It must read through to the API + // server. + Client client.Reader + Registry *custody.Registry + Coordinator *custody.Coordinator + Sites *Sites + Namespace string +} + +// Deliver sends a Device's active operation to every site serving it, once +// its admission is copied to the operation's status. +func (c *Courier) Deliver(ctx context.Context, name string) error { + state := &ops.DeviceCustody{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, state); apierrors.IsNotFound(err) { + return nil + } else if err != nil { + return err + } + active := state.Spec.ActiveOperation + if active == nil { + return nil + } + kind := c.Registry.Kind(active.Kind) + if kind == nil { + return fmt.Errorf("delivery: custody names unregistered kind %s", active.Kind) + } + operation := kind.New() + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: active.Name}, operation); apierrors.IsNotFound(err) { + return nil + } else if err != nil { + return err + } + status := operation.OperationStatus() + if status.Fence != active.Fence || status.Phase == ops.PhasePending || status.Phase.Ended() { + return nil + } + assignment, err := Assignment(state, operation) + if err != nil { + return err + } + device := &inventory.Device{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, device); err != nil { + return err + } + var failed error + for _, serving := range c.Sites.Serving(device) { + if err := c.Sites.Sites[serving].Deliver(ctx, assignment); err != nil { + failed = errors.Join(failed, fmt.Errorf("deliver to %s: %w", serving, err)) + } + } + return failed +} + +// Collect reports every site's held results to the coordinator, and tells +// the site to forget each one the coordinator accepted or rejected as stale. +func (c *Courier) Collect(ctx context.Context) error { + var failed error + names := make([]string, 0, len(c.Sites.Sites)) + for name := range c.Sites.Sites { + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + remote := c.Sites.Sites[name] + held, err := remote.Results(ctx) + if err != nil { + failed = errors.Join(failed, fmt.Errorf("results from %s: %w", name, err)) + continue + } + for _, stored := range held { + // The site names itself; the coordinator records the site it + // asked. + stored.Result.Site = name + if err := c.Coordinator.AcceptResult(ctx, stored.Result); err != nil && !errors.Is(err, custody.ErrStaleFence) { + failed = errors.Join(failed, err) + continue + } + if err := remote.Forget(ctx, stored); err != nil { + failed = errors.Join(failed, err) + } + } + } + return failed +} + +// Loop is the coordinator process: it reconciles every Device's custody, +// delivers active operations, collects results and sweeps retention. +type Loop struct { + Client client.Reader + Coordinator *custody.Coordinator + Courier *Courier + Namespace string + // Interval is the time between passes. It defaults to one second. + Interval time.Duration + // OnError reports a pass's errors. The loop keeps running. + OnError func(error) + // lastSweep is when retention last ran. + lastSweep time.Time +} + +// maxSteps bounds the reconciles of one Device in one pass. +const maxSteps = 32 + +// Pass reconciles each Device until it settles, delivers, and collects. +func (l *Loop) Pass(ctx context.Context) error { + names := map[string]bool{} + var devices inventory.DeviceList + if err := l.Client.List(ctx, &devices, client.InNamespace(l.Namespace)); err != nil { + return err + } + for _, device := range devices.Items { + names[device.Name] = true + } + var custodies ops.DeviceCustodyList + if err := l.Client.List(ctx, &custodies, client.InNamespace(l.Namespace)); err != nil { + return err + } + for _, state := range custodies.Items { + names[state.Name] = true + } + sorted := make([]string, 0, len(names)) + for name := range names { + sorted = append(sorted, name) + } + slices.Sort(sorted) + var failed error + for _, name := range sorted { + if err := l.Settle(ctx, name); err != nil { + failed = errors.Join(failed, fmt.Errorf("%s: %w", name, err)) + continue + } + if err := l.Courier.Deliver(ctx, name); err != nil { + failed = errors.Join(failed, fmt.Errorf("%s: %w", name, err)) + } + } + if err := l.Courier.Collect(ctx); err != nil { + failed = errors.Join(failed, err) + } + if time.Since(l.lastSweep) > time.Hour { + if _, err := l.Coordinator.SweepRetention(ctx); err != nil { + failed = errors.Join(failed, err) + } else { + l.lastSweep = time.Now() + } + } + return failed +} + +// Settle reconciles one Device until a reconcile changes nothing. +func (l *Loop) Settle(ctx context.Context, name string) error { + for range maxSteps { + outcome, err := l.Coordinator.Reconcile(ctx, name) + if err != nil || !outcome.Changed { + return err + } + } + return nil +} + +// Run makes passes until the context ends. +func (l *Loop) Run(ctx context.Context) error { + interval := l.Interval + if interval <= 0 { + interval = time.Second + } + for { + if err := l.Pass(ctx); err != nil && ctx.Err() == nil && l.OnError != nil { + l.OnError(err) + } + select { + case <-ctx.Done(): + return nil + case <-time.After(interval): + } + } +} diff --git a/internal/delivery/delivery_test.go b/internal/delivery/delivery_test.go new file mode 100644 index 00000000..ead64345 --- /dev/null +++ b/internal/delivery/delivery_test.go @@ -0,0 +1,35 @@ +package delivery + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// TestOnlyTheAdmittedOperationIsDelivered never builds an assignment from +// an operation that does not carry the fence custody admitted it at, so a +// same-name operation created later is never delivered as the admitted one. +func TestOnlyTheAdmittedOperationIsDelivered(t *testing.T) { + state := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001", Namespace: "default"}, Spec: ops.DeviceCustodySpec{ + ActiveOperation: &ops.ActiveOperation{OperationReference: ops.OperationReference{Kind: "DeviceWipe", Name: "wipe-example"}, Fence: 2}}} + for _, tt := range []struct { + name string + admission *ops.OperationAdmission + delivered bool + }{ + {"recreated, with no admission record", nil, false}, + {"admitted at another fence", &ops.OperationAdmission{Fence: 1}, false}, + {"admitted at the active fence", &ops.OperationAdmission{Fence: 2}, true}, + } { + operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: "wipe-example", Namespace: "default"}, Status: ops.OperationStatus{Admission: tt.admission}} + assignment, err := Assignment(state, operation) + if delivered := err == nil; delivered != tt.delivered { + t.Fatalf("%s: delivered = %v, %v", tt.name, delivered, err) + } + if tt.delivered && assignment.Fence != 2 { + t.Fatalf("%s: fence = %d", tt.name, assignment.Fence) + } + } +} diff --git a/internal/executor/client.go b/internal/executor/client.go deleted file mode 100644 index 67120813..00000000 --- a/internal/executor/client.go +++ /dev/null @@ -1,235 +0,0 @@ -package executor - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "path" - "strings" - "time" - - "go.datum.net/fleet/internal/simulator" -) - -const ( - maxResponseBytes = 64 << 10 - maxTokenBytes = 4 << 10 -) - -var ( - ErrConflict = errors.New("executor operation conflicts with retained input") - ErrFenced = errors.New("executor operation is fenced") - ErrInvalid = errors.New("executor rejected the operation") - ErrOutcomeUnknown = errors.New("executor operation outcome is unknown") -) - -// Client is the exact provider-executor contract used by the standalone -// lifecycle library. Implementations must preserve the operation ID and return -// only a verified terminal result. Execute must accept exact-request replay under -// the same operation ID without duplicating effects. Lookup returning false and -// ErrOutcomeUnknown means a retained unfinished operation may be resumed by -// replaying its exact request. Transport failures must use a different error; -// true with any error never authorizes recovery or establishes success. -type Client interface { - Execute(context.Context, simulator.Request) (simulator.OperationResult, error) - Lookup(context.Context, string) (simulator.OperationResult, bool, error) -} - -type HTTPClient struct { - base *url.URL - tokenSource func() (string, error) - http *http.Client -} - -func NewHTTPClient(baseURL, bearerToken string, client *http.Client) (*HTTPClient, error) { - if err := validateBearerToken(bearerToken); err != nil { - return nil, err - } - return newHTTPClient(baseURL, func() (string, error) { return bearerToken, nil }, client) -} - -// NewHTTPClientFromTokenFile creates a client that reloads the projected token -// before every request. Kubernetes rotates service-account tokens by replacing -// the projected file, so retaining its startup value can permanently split the -// manager and provider after only one container restarts. -func NewHTTPClientFromTokenFile(baseURL, tokenFile string, client *http.Client) (*HTTPClient, error) { - if strings.TrimSpace(tokenFile) == "" { - return nil, errors.New("executor bearer token file is required") - } - tokenSource := func() (string, error) { - token, err := os.ReadFile(tokenFile) - if err != nil { - return "", fmt.Errorf("read executor bearer token: %w", err) - } - if len(token) > maxTokenBytes { - return "", errors.New("executor bearer token exceeds size limit") - } - value := strings.TrimSpace(string(token)) - if err := validateBearerToken(value); err != nil { - return "", err - } - return value, nil - } - if _, err := tokenSource(); err != nil { - return nil, err - } - return newHTTPClient(baseURL, tokenSource, client) -} - -func newHTTPClient(baseURL string, tokenSource func() (string, error), client *http.Client) (*HTTPClient, error) { - parsed, err := url.Parse(baseURL) - if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.RawQuery != "" || parsed.Fragment != "" { - return nil, errors.New("executor base URL must be an absolute HTTP URL without query or fragment") - } - if parsed.Scheme != "http" && parsed.Scheme != "https" { - return nil, errors.New("executor base URL must use http or https") - } - if client == nil { - client = &http.Client{Timeout: 30 * time.Second} - } else if client.Timeout <= 0 { - return nil, errors.New("executor HTTP client must have a positive timeout") - } - return &HTTPClient{base: parsed, tokenSource: tokenSource, http: client}, nil -} - -func validateBearerToken(token string) error { - if strings.TrimSpace(token) == "" || strings.ContainsAny(token, "\r\n") { - return errors.New("executor bearer token must be nonempty and single-line") - } - return nil -} - -func (c *HTTPClient) Execute(ctx context.Context, request simulator.Request) (simulator.OperationResult, error) { - body, err := json.Marshal(request) - if err != nil { - return simulator.OperationResult{}, fmt.Errorf("encode executor request: %w", err) - } - response, err := c.do(ctx, http.MethodPost, "v1/operations", bytes.NewReader(body)) - if err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: submit request: %v", ErrOutcomeUnknown, err) - } - defer response.Body.Close() - if response.StatusCode == http.StatusOK { - result, err := decodeResult(response.Body) - if err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: decode submit result: %v", ErrOutcomeUnknown, err) - } - if err := validateResult(result, request.ID, request.Kind); err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: %v", ErrOutcomeUnknown, err) - } - return result, nil - } - code, message := decodeError(response.Body) - switch response.StatusCode { - case http.StatusBadRequest: - return simulator.OperationResult{}, fmt.Errorf("%w: %s", ErrInvalid, message) - case http.StatusConflict: - if code == "operation_fenced" { - return simulator.OperationResult{}, fmt.Errorf("%w: %s", ErrFenced, message) - } - return simulator.OperationResult{}, fmt.Errorf("%w: %s", ErrConflict, message) - case http.StatusServiceUnavailable: - return simulator.OperationResult{}, fmt.Errorf("%w: %s", ErrOutcomeUnknown, message) - default: - return simulator.OperationResult{}, fmt.Errorf("%w: executor returned HTTP %d", ErrOutcomeUnknown, response.StatusCode) - } -} - -func (c *HTTPClient) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { - if operationID == "" || operationID == "." || operationID == ".." || strings.Contains(operationID, "/") { - return simulator.OperationResult{}, false, errors.New("operation ID is empty, a dot segment, or contains a path separator") - } - response, err := c.do(ctx, http.MethodGet, path.Join("v1/operations", url.PathEscape(operationID)), nil) - if err != nil { - return simulator.OperationResult{}, false, err - } - defer response.Body.Close() - if response.StatusCode == http.StatusNotFound { - _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxResponseBytes)) - return simulator.OperationResult{}, false, nil - } - if response.StatusCode != http.StatusOK { - _, message := decodeError(response.Body) - return simulator.OperationResult{}, false, fmt.Errorf("lookup executor operation: HTTP %d: %s", response.StatusCode, message) - } - result, err := decodeResult(response.Body) - if err != nil { - return simulator.OperationResult{}, false, err - } - if err := validateResult(result, operationID, result.Kind); err != nil { - return simulator.OperationResult{}, false, err - } - return result, true, nil -} - -func (c *HTTPClient) do(ctx context.Context, method, relative string, body io.Reader) (*http.Response, error) { - token, err := c.tokenSource() - if err != nil { - return nil, err - } - target := *c.base - target.Path = path.Join(c.base.Path, relative) - request, err := http.NewRequestWithContext(ctx, method, target.String(), body) - if err != nil { - return nil, err - } - request.Header.Set("Authorization", "Bearer "+token) - if body != nil { - request.Header.Set("Content-Type", "application/json") - } - return c.http.Do(request) -} - -func decodeResult(reader io.Reader) (simulator.OperationResult, error) { - body, err := io.ReadAll(io.LimitReader(reader, maxResponseBytes+1)) - if err != nil { - return simulator.OperationResult{}, err - } - if len(body) > maxResponseBytes { - return simulator.OperationResult{}, errors.New("executor response exceeds size limit") - } - var result simulator.OperationResult - decoder := json.NewDecoder(bytes.NewReader(body)) - decoder.DisallowUnknownFields() - if err := decoder.Decode(&result); err != nil { - return simulator.OperationResult{}, err - } - if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { - return simulator.OperationResult{}, errors.New("executor returned multiple JSON values") - } - return result, nil -} - -func validateResult(result simulator.OperationResult, id, kind string) error { - if result.ID != id || result.Kind == "" || (kind != "" && result.Kind != kind) || result.Phase != "Succeeded" || result.CompletedAt == nil { - return errors.New("executor result does not match the requested terminal operation") - } - switch result.Kind { - case "cleanup": - if result.Result != "clean" { - return errors.New("cleanup result lacks clean evidence") - } - case "install": - if result.Result != "installed" { - return errors.New("install result lacks installed evidence") - } - } - return nil -} - -func decodeError(reader io.Reader) (string, string) { - var response struct { - Code string `json:"code"` - Message string `json:"message"` - } - if err := json.NewDecoder(io.LimitReader(reader, maxResponseBytes)).Decode(&response); err != nil { - return "", "executor returned an unreadable error" - } - return response.Code, response.Message -} diff --git a/internal/executor/client_test.go b/internal/executor/client_test.go deleted file mode 100644 index 0740f46a..00000000 --- a/internal/executor/client_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package executor - -import ( - "context" - "errors" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "testing" - "time" - - "go.datum.net/fleet/internal/simulator" -) - -type handlerTransport struct{ handler http.Handler } - -func (t handlerTransport) RoundTrip(request *http.Request) (*http.Response, error) { - recorder := httptest.NewRecorder() - t.handler.ServeHTTP(recorder, request) - return recorder.Result(), nil -} - -func clientForHandler(t *testing.T, handler http.Handler, token string) *HTTPClient { - t.Helper() - client, err := NewHTTPClient("http://executor", token, &http.Client{Transport: handlerTransport{handler: handler}, Timeout: time.Second}) - if err != nil { - t.Fatal(err) - } - return client -} - -func TestHTTPClientAuthenticatesAndRecoversLostResponse(t *testing.T) { - store, err := simulator.Open(filepath.Join(t.TempDir(), "state.json")) - if err != nil { - t.Fatal(err) - } - if err := store.SetFault("lost-response", true); err != nil { - t.Fatal(err) - } - client := clientForHandler(t, simulator.RuntimeHandler(store, "secret", slog.New(slog.NewTextHandler(os.Stderr, nil))), "secret") - request := simulator.Request{ID: "op-1", Kind: "cleanup", AssetID: "asset", BindingID: "binding", Epoch: 1, FenceToken: "fence"} - if _, err := client.Execute(context.Background(), request); !errors.Is(err, ErrOutcomeUnknown) { - t.Fatalf("Execute error = %v", err) - } - result, found, err := client.Lookup(context.Background(), request.ID) - if err != nil || !found || result.ID != request.ID || result.Phase != "Succeeded" { - t.Fatalf("Lookup = %#v, %v, %v", result, found, err) - } -} - -func TestHTTPClientRejectsWrongAuthenticationAndMalformedTerminalResult(t *testing.T) { - t.Run("authentication", func(t *testing.T) { - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer right" { - http.Error(w, "no", http.StatusUnauthorized) - return - } - w.WriteHeader(http.StatusNotFound) - }) - client := clientForHandler(t, handler, "wrong") - if _, _, err := client.Lookup(context.Background(), "op"); err == nil { - t.Fatal("expected authentication failure") - } - }) - t.Run("terminal result", func(t *testing.T) { - handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = io.WriteString(w, `{"id":"wrong","kind":"cleanup","phase":"Succeeded","completedAt":"2026-01-01T00:00:00Z"}`) - }) - client := clientForHandler(t, handler, "token") - _, err := client.Execute(context.Background(), simulator.Request{ID: "wanted", Kind: "cleanup"}) - if !errors.Is(err, ErrOutcomeUnknown) { - t.Fatalf("error = %v", err) - } - }) -} - -func TestHTTPClientRejectsOperationSpecificFalseEvidence(t *testing.T) { - completed := `"2026-01-01T00:00:00Z"` - for _, method := range []string{http.MethodPost, http.MethodGet} { - t.Run(method, func(t *testing.T) { - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - id := "op" - if method == http.MethodPost { - id = "op" - } - _, _ = io.WriteString(w, `{"id":"`+id+`","kind":"cleanup","phase":"Succeeded","result":"installed","completedAt":`+completed+`}`) - }) - client := clientForHandler(t, handler, "token") - if method == http.MethodPost { - if _, err := client.Execute(context.Background(), simulator.Request{ID: "op", Kind: "cleanup"}); !errors.Is(err, ErrOutcomeUnknown) { - t.Fatalf("Execute error = %v", err) - } - } else if _, _, err := client.Lookup(context.Background(), "op"); err == nil { - t.Fatal("Lookup accepted false cleanup evidence") - } - }) - } -} - -func TestHTTPClientRequiresBoundedTimeout(t *testing.T) { - if _, err := NewHTTPClient("http://executor", "token", &http.Client{}); err == nil { - t.Fatal("accepted unbounded custom client") - } - client, err := NewHTTPClient("http://executor", "token", nil) - if err != nil || client.http.Timeout <= 0 { - t.Fatalf("default client timeout = %v, error=%v", client.http.Timeout, err) - } -} - -func TestHTTPClientReloadsRotatedTokenForEveryRequest(t *testing.T) { - tokenFile := filepath.Join(t.TempDir(), "token") - if err := os.WriteFile(tokenFile, []byte("first\n"), 0o600); err != nil { - t.Fatal(err) - } - want := "first" - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got := r.Header.Get("Authorization"); got != "Bearer "+want { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - w.WriteHeader(http.StatusNotFound) - }) - client, err := NewHTTPClientFromTokenFile("http://executor", tokenFile, &http.Client{Transport: handlerTransport{handler: handler}, Timeout: time.Second}) - if err != nil { - t.Fatal(err) - } - if _, _, err := client.Lookup(context.Background(), "before-rotation"); err != nil { - t.Fatalf("Lookup before rotation: %v", err) - } - - // Model kubelet replacing the projected file while only the provider side - // restarts and begins requiring the new token. - want = "second" - rotated := tokenFile + ".rotated" - if err := os.WriteFile(rotated, []byte("second\n"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.Rename(rotated, tokenFile); err != nil { - t.Fatal(err) - } - if _, _, err := client.Lookup(context.Background(), "after-provider-restart"); err != nil { - t.Fatalf("Lookup after rotation: %v", err) - } -} - -func TestHTTPClientFailsClosedWhenRotatedTokenIsUnavailable(t *testing.T) { - tokenFile := filepath.Join(t.TempDir(), "token") - if err := os.WriteFile(tokenFile, []byte("initial\n"), 0o600); err != nil { - t.Fatal(err) - } - called := false - handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }) - client, err := NewHTTPClientFromTokenFile("http://executor", tokenFile, &http.Client{Transport: handlerTransport{handler: handler}, Timeout: time.Second}) - if err != nil { - t.Fatal(err) - } - if err := os.Remove(tokenFile); err != nil { - t.Fatal(err) - } - if _, _, err := client.Lookup(context.Background(), "op"); err == nil { - t.Fatal("Lookup accepted an unavailable token") - } - if called { - t.Fatal("request was sent without a current token") - } -} diff --git a/internal/executor/path_adversarial_test.go b/internal/executor/path_adversarial_test.go deleted file mode 100644 index fbb19dcb..00000000 --- a/internal/executor/path_adversarial_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package executor - -import ( - "context" - "net/http" - "testing" -) - -func TestAdversarialLookupRejectsDotSegmentsBeforeTransport(t *testing.T) { - for _, id := range []string{".", ".."} { - t.Run(id, func(t *testing.T) { - called := false - client := clientForHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - t.Logf("unexpected lookup path: %s", r.URL.Path) - w.WriteHeader(http.StatusNotFound) - }), "synthetic-token") - if _, _, err := client.Lookup(context.Background(), id); err == nil || called { - t.Fatalf("dot-segment ID reached transport or was accepted: called=%v err=%v", called, err) - } - }) - } -} diff --git a/internal/localvm/boot.go b/internal/localvm/boot.go deleted file mode 100644 index 4f6ab8af..00000000 --- a/internal/localvm/boot.go +++ /dev/null @@ -1,258 +0,0 @@ -package localvm - -import ( - "context" - "crypto/sha256" - "crypto/subtle" - "encoding/hex" - "fmt" - "io" - "net/http" - "os" - "strconv" - "strings" - "time" -) - -// defaultBootOrigin is the provisioning-bridge address used when the boot -// service shares the hypervisor network namespace (single-container mode). -const defaultBootOrigin = "http://192.168.77.1:8080" - -func (p *Provider) origin() string { - if p.bootOrigin == "" { - return defaultBootOrigin - } - return p.bootOrigin -} - -// prepareNetwork is the sole local network writer. DHCP stays on a bridge in the -// runtime namespace. NAT forwarding lets firmware reach a boot Service outside -// that namespace; the runtime restricts forwarded traffic to that origin. -func (p *Provider) prepareNetwork(ctx context.Context, r *record) error { - names, err := p.virsh(ctx, "net-list", "--name") - if err != nil { - return err - } - for _, n := range strings.Fields(names) { - if n == "fleet-pxe" { - if _, err = p.virsh(ctx, "net-destroy", n); err != nil { - return err - } - } - } - xml := fmt.Sprintf(`fleet-pxe%s`, p.forward(), p.origin(), key(r.Request.ID)[:16], r.BootToken) - path := p.stateRoot() + "/network-private.xml" - if err = os.WriteFile(path, []byte(xml), 0600); err != nil { - return err - } - _, err = p.virsh(ctx, "net-create", path) - return err -} - -// forward is empty when the boot service is on the bridge itself. -func (p *Provider) forward() string { - if p.origin() == defaultBootOrigin { - return "" - } - return "" -} - -// BootHandler never uses a file server or caller-selected filesystem path. -// Atomic journal replacement allows reads while the executor holds its flock. -func (p *Provider) BootHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { - w.Header().Set("Cache-Control", "no-store") - deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } - parts := strings.Split(q.URL.Path, "/") - if q.Method != "GET" || q.URL.RawQuery != "" || len(parts) != 4 { - deny() - return - } - j, err := p.read() - if err != nil || p.checkMode(j) != nil || j.BootMode != "pxe" || j.Image != p.image || j.Closed { - deny() - return - } - var r *record - for _, candidate := range j.Operations { - if key(candidate.Request.ID)[:16] == parts[1] { - r = candidate - break - } - } - if r == nil || r.Request.Kind != "install" || r.Stage != "installer-started" || r.BootClosed || !time.Now().Before(r.BootExpires) || len(r.BootToken) != 64 || subtle.ConstantTimeCompare([]byte(parts[2]), []byte(r.BootToken)) != 1 || r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence || p.validate(r.Request) != nil { - deny() - return - } - name := parts[3] - var data []byte - var artifact *os.File - var size int64 - switch name { - case "boot.ipxe": - base := p.origin() + "/" + parts[1] + "/" + r.BootToken - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, base)) - size = int64(len(data)) - case "kernel", "installer.gz": - // Stream: hash the pinned artifact, then serve the same open file. - artifact, err = os.Open(artifacts + "/" + name) - if err != nil { - deny() - return - } - defer artifact.Close() - manifest, e := os.ReadFile(artifacts + "/SHA256SUMS") - sum := sha256.Sum256(manifest) - h := sha256.New() - size, err = io.Copy(h, artifact) - if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { - deny() - return - } - if _, err = artifact.Seek(0, io.SeekStart); err != nil { - deny() - return - } - default: - deny() - return - } - // No URLs, headers, credentials or bootstrap script in evidence. - if err := os.MkdirAll(p.bootDirectory(r), 0700); err != nil { - deny() - return - } - f, err := os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) - if err != nil { - deny() - return - } - _, err = fmt.Fprintf(f, "%s admitted %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, size) - if err == nil { - err = f.Sync() - } - f.Close() - if err != nil { - deny() - return - } - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) - var n int64 - var writeErr error - if artifact != nil { - n, writeErr = io.Copy(w, artifact) - } else { - var written int - written, writeErr = w.Write(data) - n = int64(written) - } - if writeErr != nil || n != size { - return - } - // A completed server write is not proof of client receipt or guest boot. - f, err = os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_APPEND|os.O_WRONLY, 0600) - if err != nil { - return - } - _, err = fmt.Fprintf(f, "%s write-complete %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, n) - if err == nil { - err = f.Sync() - } - closeErr := f.Close() - if err == nil && closeErr == nil { - _ = p.syncDir(p.bootDirectory(r)) - } - }) -} - -func (p *Provider) ServeBoot() error { - // The write bound matches the boot admission window: through the site's - // NAT path an emulated firmware takes several minutes for the installer. - s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} - return s.ListenAndServe() -} - -func (p *Provider) verifyNetworkBoot(ctx context.Context, r *record) error { - b, err := os.ReadFile(p.bootDirectory(r) + "/boot-delivery.log") - if err != nil { - return err - } - completed := map[string]bool{} - for _, line := range strings.Split(string(b), "\n") { - fields := strings.Fields(line) - if len(fields) != 4 || fields[1] != "write-complete" || !strings.HasPrefix(fields[3], "bytes=") { - continue - } - n, err := strconv.Atoi(strings.TrimPrefix(fields[3], "bytes=")) - if err == nil && n > 0 { - completed[fields[2]] = true - } - } - for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { - if !completed[name] { - return fmt.Errorf("missing network delivery: %s", name) - } - } - leases, err := p.virsh(ctx, "net-dhcp-leases", "fleet-pxe") - if err != nil { - return err - } - if !strings.Contains(leases, "52:54:00:77:00:02") || !strings.Contains(leases, "192.168.77.2") { - return fmt.Errorf("missing firmware DHCP lease") - } - return os.WriteFile(p.directory(r)+"/dhcp-leases.txt", []byte(leases), 0600) -} - -func (p *Provider) stopNetwork(ctx context.Context) error { - names, err := p.virsh(ctx, "net-list", "--name") - if err != nil { - return err - } - for _, n := range strings.Fields(names) { - if n == "fleet-pxe" { - _, err = p.virsh(ctx, "net-destroy", n) - return err - } - } - return nil -} - -// CheckClosedBoot probes a live boot listener without printing capability URLs. -// origin is the listener under test, e.g. the boot Service seen by the runtime. -func (p *Provider) CheckClosedBoot(origin string) (string, error) { - origin, err := parseBootOrigin(origin) - if err != nil { - return "", err - } - j, err := p.read() - if err != nil { - return "", err - } - client := &http.Client{Timeout: 10 * time.Second} - count := 0 - for _, r := range j.Operations { - if r.Request.Kind != "install" { - continue - } - if !r.BootClosed { - return "", fmt.Errorf("boot admission not closed") - } - base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken - for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { - resp, e := client.Get(url) - if e != nil { - return "", fmt.Errorf("boot denial probe unavailable") - } - resp.Body.Close() - if resp.StatusCode != http.StatusForbidden { - return "", fmt.Errorf("closed/unknown boot access allowed") - } - count++ - } - } - if count == 0 { - return "", fmt.Errorf("no retained admission to probe") - } - return fmt.Sprintf("PASS %d live HTTP denials: closed predecessor scripts/artifacts, unsupported artifact, unguarded artifact, unknown identity", count), nil -} diff --git a/internal/localvm/boot_test.go b/internal/localvm/boot_test.go deleted file mode 100644 index 7376d142..00000000 --- a/internal/localvm/boot_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package localvm - -import ( - "go.datum.net/fleet/internal/simulator" - "net/http/httptest" - "os" - "strings" - "testing" - "time" -) - -func TestBootAdmission(t *testing.T) { - f := newVMFixture(t) - p := f.p - p.bootMode = "pxe" - q := vmRequest("admitted-installation") - digest, _ := simulator.RequestDigest(q) - base := record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} - os.Mkdir(p.directory(&base), 0700) - for _, tc := range []struct { - name string - change func(*record, *journal) - path string - allowed bool - }{ - {name: "admitted", allowed: true}, - {name: "unknown identity", path: "/unknown/" + base.BootToken + "/boot.ipxe"}, - {name: "wrong operation credential", path: "/" + key(q.ID)[:16] + "/" + strings.Repeat("c", 64) + "/boot.ipxe"}, - {name: "expired", change: func(r *record, j *journal) { r.BootExpires = time.Now().Add(-time.Second) }}, - {name: "revoked", change: func(r *record, j *journal) { r.BootClosed = true }}, - {name: "not started", change: func(r *record, j *journal) { r.Stage = "admitted" }}, - {name: "stale epoch", change: func(r *record, j *journal) { j.Epoch++ }}, - {name: "wrong fence", change: func(r *record, j *journal) { j.Fence = "other" }}, - {name: "closed predecessor", change: func(r *record, j *journal) { r.Stage = "installer-verified"; r.BootClosed = true }}, - {name: "closed allocation", change: func(r *record, j *journal) { j.Closed = true }}, - {name: "unsupported artifact", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/disk.raw"}, - {name: "unguarded artifact", path: "/kernel"}, - {name: "traversal", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/../journal.json"}, - } { - t.Run(tc.name, func(t *testing.T) { - r := base - j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: &r}} - if tc.change != nil { - tc.change(&r, &j) - } - if err := p.save(j); err != nil { - t.Fatal(err) - } - path := tc.path - if path == "" { - path = "/" + key(q.ID)[:16] + "/" + base.BootToken + "/boot.ipxe" - } - w := httptest.NewRecorder() - p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) - want := 403 - if tc.allowed { - want = 200 - } - if w.Code != want { - t.Fatalf("status %d want %d", w.Code, want) - } - }) - } -} -func TestFirmwarePXEAndModeBinding(t *testing.T) { - p := &Provider{bootMode: "pxe"} - r := &record{} - x := p.domainXML(r, "installer") - if strings.Contains(x, "") || strings.Contains(x, "") || strings.Contains(x, "boot dev='hd'") || !strings.Contains(x, "boot dev='network'") || !strings.Contains(x, "") { - t.Fatal(x) - } -} - -func TestCrossOperationCapabilityOverHTTP(t *testing.T) { - f := newVMFixture(t) - p := f.p - p.bootMode = "pxe" - j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: 1, Binding: "allocation", Fence: "fence", Operations: map[string]*record{}} - for i, id := range []string{"predecessor", "successor"} { - q := vmRequest(id) - d, _ := simulator.RequestDigest(q) - r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: d, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat(string(rune('b'+i)), 64), BootExpires: time.Now().Add(time.Minute)} - j.Operations[id] = r - if err := os.Mkdir(p.directory(r), 0700); err != nil { - t.Fatal(err) - } - } - server := httptest.NewServer(p.BootHandler()) - defer server.Close() - check := func(op, token string, want int) { - t.Helper() - resp, err := server.Client().Get(server.URL + "/" + key(op)[:16] + "/" + token + "/boot.ipxe") - if err != nil { - t.Fatal("HTTP request failed") - } - resp.Body.Close() - if resp.StatusCode != want { - t.Fatalf("status %d want %d", resp.StatusCode, want) - } - } - save := func() { - t.Helper() - if err := p.save(j); err != nil { - t.Fatal(err) - } - } - save() - check("successor", j.Operations["predecessor"].BootToken, 403) - check("successor", j.Operations["successor"].BootToken, 200) - j.Operations["successor"].BootExpires = time.Now().Add(-time.Second) - save() - check("successor", j.Operations["successor"].BootToken, 403) - j.Operations["predecessor"].BootClosed = true - save() - check("predecessor", j.Operations["predecessor"].BootToken, 403) -} diff --git a/internal/localvm/lifecycle_test.go b/internal/localvm/lifecycle_test.go deleted file mode 100644 index 5f1b5767..00000000 --- a/internal/localvm/lifecycle_test.go +++ /dev/null @@ -1,294 +0,0 @@ -package localvm - -import ( - "context" - "encoding/json" - "errors" - "os" - "path/filepath" - "strings" - "testing" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -type vmFixture struct { - p *Provider - creates []string - failStart bool - present string -} - -func newVMFixture(t *testing.T) *vmFixture { - t.Helper() - f := &vmFixture{p: &Provider{root: t.TempDir(), image: "local@sha256:approved"}} - f.p.command = func(_ context.Context, name string, args ...string) (string, error) { - if name != "virsh" || len(args) < 3 || args[0] != "--connect" || args[1] != "qemu:///system" { - t.Fatalf("unexpected command %s %v", name, args) - } - switch args[2] { - case "list": - return f.present, nil - case "create": - f.creates = append(f.creates, args[3]) - if f.failStart { - return "", errors.New("lost start response") - } - j, err := f.p.read() - if err != nil { - return "", err - } - for _, r := range j.Operations { - stage := strings.TrimSuffix(filepath.Base(args[3]), ".xml") - if args[3] != filepath.Join(f.p.directory(r), stage+".xml") { - continue - } - if r.Stage != stage+"-started" { - t.Fatalf("command preceded durable uncertainty: %s", r.Stage) - } - marker := "FLEET-INSTALLED:" - if stage == "disk" { - marker = "FLEET-DISK-BOOT:" - } - return "", os.WriteFile(filepath.Join(f.p.directory(r), stage+".log"), []byte(marker+r.Receipt+"\n"), 0600) - } - return "", errors.New("command not bound to journal") - default: - t.Fatalf("unexpected virsh operation %v", args) - } - return "", nil - } - return f -} -func vmRequest(id string) simulator.Request { - return simulator.Request{ID: id, Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"local@sha256:approved"}`)} -} -func TestLocalReplayAndAuthorityTransitions(t *testing.T) { - f := newVMFixture(t) - ctx := context.Background() - q := vmRequest("install") - result, err := f.p.Execute(ctx, q) - if err != nil { - t.Fatal(err) - } - if result.Result != "installed" || len(f.creates) != 2 { - t.Fatalf("unexpected install: %+v %v", result, f.creates) - } - // Reopen state through a fresh provider without changing the command fixture. - f.p = &Provider{root: f.p.root, image: f.p.image, command: f.p.command} - replay, err := f.p.Execute(ctx, q) - if err != nil || replay.InputDigest != result.InputDigest || len(f.creates) != 2 { - t.Fatalf("replay caused effects: %v", err) - } - for _, change := range []func(*simulator.Request){ - func(r *simulator.Request) { r.AssetID = "another" }, func(r *simulator.Request) { r.BindingID = "another" }, - func(r *simulator.Request) { r.Epoch++ }, func(r *simulator.Request) { r.FenceToken = "another" }, - func(r *simulator.Request) { r.Inputs = json.RawMessage(`{"image":"another"}`) }, - } { - altered := q - change(&altered) - if _, err = f.p.Execute(ctx, altered); err == nil { - t.Fatal("accepted substituted retained request") - } - } - next := vmRequest("next") - next.Epoch = 2 - next.BindingID = "next" - next.FenceToken = "next" - if _, err = f.p.Execute(ctx, next); !errors.Is(err, executor.ErrFenced) { - t.Fatalf("advanced before cleanup: %v", err) - } - cleanup := q - cleanup.ID = "cleanup" - cleanup.Kind = "cleanup" - cleanup.Inputs = nil - f.present = domain(&record{Request: q}) - if _, err = f.p.Execute(ctx, cleanup); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("cleaned live domain: %v", err) - } - if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); err != nil { - t.Fatal("deleted live disk", err) - } - f.present = "decoy-domain" - decoy := filepath.Join(f.p.root, "decoy.raw") - if err = os.WriteFile(decoy, []byte("retain"), 0600); err != nil { - t.Fatal(err) - } - if _, err = f.p.Execute(ctx, cleanup); err != nil { - t.Fatal(err) - } - if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); !os.IsNotExist(err) { - t.Fatalf("disk survived cleanup: %v", err) - } - if b, err := os.ReadFile(decoy); err != nil || string(b) != "retain" { - t.Fatal("decoy changed") - } - stale := vmRequest("stale") - if _, err = f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { - t.Fatalf("stale authority accepted: %v", err) - } - if _, err = f.p.Execute(ctx, next); err != nil { - t.Fatal(err) - } - count := len(f.creates) - if _, err = f.p.Execute(ctx, cleanup); err != nil || len(f.creates) != count { - t.Fatal("old cleanup replay changed current allocation") - } - if _, err = os.Stat(f.p.directory(&record{Request: next}) + "/disk.raw"); err != nil { - t.Fatal("old cleanup deleted new disk", err) - } -} -func TestLocalDiskDirectorySyncPrecedesPrepared(t *testing.T) { - f := newVMFixture(t) - ctx := context.Background() - q := vmRequest("sync-failure") - injected := errors.New("directory sync failed") - f.p.syncDirectory = func(path string) error { - j, err := f.p.read() - if err != nil { - t.Fatal(err) - } - if j.Operations[q.ID].Stage != "admitted" { - t.Fatal("journal advanced before sync") - } - info, err := os.Stat(filepath.Join(path, "disk.raw")) - if err != nil || info.Size() != 2<<30 { - t.Fatal("disk not prepared before sync", err) - } - return injected - } - if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("sync failure ignored: %v", err) - } - j, err := f.p.read() - if err != nil { - t.Fatal(err) - } - if j.Operations[q.ID].Stage != "admitted" || len(f.creates) != 0 { - t.Fatal("sync failure permitted boot") - } - path := f.p.directory(j.Operations[q.ID]) + "/disk.raw" - file, err := os.OpenFile(path, os.O_WRONLY, 0) - if err != nil { - t.Fatal(err) - } - if _, err = file.Write([]byte("do-not-overwrite")); err != nil { - t.Fatal(err) - } - file.Close() - f.p.syncDirectory = nil - if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("overwrote uncertain preparation: %v", err) - } - file, err = os.Open(path) - if err != nil { - t.Fatal(err) - } - defer file.Close() - b := make([]byte, len("do-not-overwrite")) - if _, err = file.Read(b); err != nil { - t.Fatal(err) - } - if string(b) != "do-not-overwrite" { - t.Fatalf("disk overwritten: %q", b) - } -} -func TestLocalUncertainStartRecoversReceiptWithoutReinstall(t *testing.T) { - for _, bad := range []string{"missing", "wrong-receipt", "wrong-stage"} { - t.Run(bad, func(t *testing.T) { - f := newVMFixture(t) - ctx := context.Background() - q := vmRequest("interrupted") - f.failStart = true - if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatal(err) - } - j, err := f.p.read() - if err != nil { - t.Fatal(err) - } - r := j.Operations[q.ID] - if r.Stage != "installer-started" { - t.Fatal(r.Stage) - } - if _, _, err = f.p.Lookup(ctx, q.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatal("lookup inferred completion") - } - log := f.p.directory(r) + "/installer.log" - content := "FLEET-INSTALLED:stale\n" - if bad == "wrong-stage" { - content = "FLEET-DISK-BOOT:" + r.Receipt + "\n" - } - if bad != "missing" { - if err = os.WriteFile(log, []byte(content), 0600); err != nil { - t.Fatal(err) - } - } - f.failStart = false - if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.creates) != 1 { - t.Fatalf("uncertain start retried or bad receipt accepted: %v", err) - } - if err = os.WriteFile(log, []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { - t.Fatal(err) - } - if _, err = f.p.Execute(ctx, q); err != nil { - t.Fatal(err) - } - if len(f.creates) != 2 || !strings.HasSuffix(f.creates[1], "/disk.xml") { - t.Fatalf("installer repeated: %v", f.creates) - } - }) - } -} - -func TestExplicitAccelerationAndJournalBinding(t *testing.T) { - for _, value := range []string{"auto", "qemu", "TCG", " kvm"} { - if _, err := parseAccelerator(value); err == nil { - t.Fatalf("accepted unknown accelerator %q", value) - } - } - for _, mode := range []string{"kvm", "tcg"} { - t.Run(mode, func(t *testing.T) { - f := newVMFixture(t) - f.p.accelerator = mode - q := vmRequest("mode-bound") - expected := "kvm" - if mode == "tcg" { - expected = "qemu" - } - if !strings.Contains(f.p.domainXML(&record{Request: q}, "disk"), "") { - t.Fatal("incorrect domain accelerator") - } - if _, err := f.p.Execute(context.Background(), q); err != nil { - t.Fatal(err) - } - j, err := f.p.read() - if err != nil { - t.Fatal(err) - } - if j.Accelerator != mode { - t.Fatal("accelerator not retained") - } - other := "tcg" - if mode == "tcg" { - other = "kvm" - } - f.p.accelerator = other - if _, err = f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrConflict) { - t.Fatalf("mode changed on replay: %v", err) - } - if _, _, err = f.p.Lookup(context.Background(), q.ID); !errors.Is(err, executor.ErrConflict) { - t.Fatalf("lookup ignored mode: %v", err) - } - }) - } - if mode, err := parseAccelerator(""); err != nil || mode != "kvm" { - t.Fatal("default changed") - } - f := newVMFixture(t) - f.p.accelerator = "tcg" - if err := f.p.checkMode(journal{Image: f.p.image}); !errors.Is(err, executor.ErrConflict) { - t.Fatal("legacy journal was not bound to KVM") - } -} diff --git a/internal/localvm/multiplane_recovery_adversarial_test.go b/internal/localvm/multiplane_recovery_adversarial_test.go deleted file mode 100644 index 751bfd3f..00000000 --- a/internal/localvm/multiplane_recovery_adversarial_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package localvm - -import ( - "context" - "encoding/json" - "errors" - "os" - "testing" - "time" - - "go.datum.net/fleet/internal/coordination" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/dynamic/fake" -) - -func TestAdversarialCellResumesRetainedInstallerWithoutSecondStart(t *testing.T) { - ctx := context.Background() - fixture := newVMFixture(t) - fixture.failStart = true - request := vmRequest("cell-recovery") - intent := coordination.Intent{Cell: "cell-a", Request: request} - name := coordination.Name(request.ID) - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, intent)) - mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} - cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} - if err := reconcile(&cell, ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost installer response must remain unknown: %v", err) - } - journal, err := fixture.p.read() - if err != nil { - t.Fatal(err) - } - retained := journal.Operations[request.ID] - if retained.Stage != "installer-started" || len(fixture.creates) != 1 { - t.Fatal("did not retain exactly one uncertain installer start") - } - if err := os.WriteFile(fixture.p.directory(retained)+"/installer.log", []byte("FLEET-INSTALLED:"+retained.Receipt+"\n"), 0600); err != nil { - t.Fatal(err) - } - fixture.failStart = false - restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} - if err := reconcile(&restarted, ctx, name); err != nil { - t.Fatalf("cell cannot resume exact retained request after installer completion: %v", err) - } - if len(fixture.creates) != 2 { - t.Fatalf("want one installer and one disk boot, got %d starts", len(fixture.creates)) - } - updated, err := api.Resource(coordination.Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) - if err != nil { - t.Fatal(err) - } - phase, _, _ := unstructured.NestedString(updated.Object, "status", "observation", "result", "phase") - if phase != "Succeeded" { - t.Fatalf("recovered terminal observation missing: %q", phase) - } -} - -func handoff(t *testing.T, intent coordination.Intent) *unstructured.Unstructured { - t.Helper() - encoded, err := json.Marshal(intent) - if err != nil { - t.Fatal(err) - } - var spec map[string]interface{} - if err := json.Unmarshal(encoded, &spec); err != nil { - t.Fatal(err) - } - return &unstructured.Unstructured{Object: map[string]interface{}{ - "apiVersion": coordination.Resource.GroupVersion().String(), - "kind": coordination.Kind, - "metadata": map[string]interface{}{"name": coordination.Name(intent.Request.ID), "namespace": "private"}, - "spec": spec, - }} -} - -// A cell restarted while the retained installer guest is still running must -// observe it, never boot a second installer, and never publish an observation. -// A different handoff for the same device must not act while it is unfinished. -func TestAdversarialCellRestartDuringRunningInstallerAndCompetingHandoff(t *testing.T) { - fixture := newVMFixture(t) - fixture.failStart = true - request := vmRequest("running-install") - cleanup := simulator.Request{ID: "competing-cleanup", Kind: "cleanup", AssetID: request.AssetID, BindingID: request.BindingID, Epoch: request.Epoch, FenceToken: request.FenceToken} - api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, coordination.Intent{Cell: "cell-a", Request: request}), handoff(t, coordination.Intent{Cell: "cell-a", Request: cleanup})) - mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} - name := coordination.Name(request.ID) - cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} - if err := reconcile(&cell, context.Background(), name); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost start must be unknown: %v", err) - } - journal, err := fixture.p.read() - if err != nil { - t.Fatal(err) - } - fixture.present = domain(journal.Operations[request.ID]) - for range 2 { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} - err := reconcile(&restarted, ctx, name) - cancel() - if !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("running installer must remain unknown: %v", err) - } - } - if err := reconcile(&cell, context.Background(), coordination.Name(cleanup.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("competing handoff acted during unfinished install: %v", err) - } - if len(fixture.creates) != 1 { - t.Fatalf("restart started another guest: %v", fixture.creates) - } - journal, err = fixture.p.read() - if err != nil { - t.Fatal(err) - } - if journal.Operations[cleanup.ID] != nil || journal.Operations[request.ID].Stage != "installer-started" { - t.Fatal("unfinished install was superseded") - } - for _, id := range []string{request.ID, cleanup.ID} { - obj, err := api.Resource(coordination.Resource).Namespace("private").Get(context.Background(), coordination.Name(id), metav1.GetOptions{}) - if err != nil { - t.Fatal(err) - } - if _, found, _ := unstructured.NestedMap(obj.Object, "status"); found { - t.Fatalf("unknown outcome published for %s", id) - } - } -} - -// reconcile composes the site worker (Execute) and observer (Publish) roles. -func reconcile(c *coordination.Cell, ctx context.Context, name string) error { - if err := c.Execute(ctx, name); err != nil { - return err - } - return c.Publish(ctx, name) -} diff --git a/internal/localvm/provider.go b/internal/localvm/provider.go deleted file mode 100644 index ef35cbb0..00000000 --- a/internal/localvm/provider.go +++ /dev/null @@ -1,715 +0,0 @@ -// Package localvm implements a deliberately bounded local VM executor. -// It is not a remotely accessible provider or a production authorization boundary. -package localvm - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/url" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - "golang.org/x/sys/unix" -) - -const Root = "/var/lib/fleet-local" -const artifacts = "/opt/fleet-local/artifacts" - -// bootWindow bounds one-time network boot admission after an install is retained. -const bootWindow = 10 * time.Minute - -const AssetID = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" - -type Provider struct { - bootMode string - image string - accelerator string - root string - // bootRoot holds boot-service delivery evidence. In the Kubernetes site it - // is a separate volume path so the boot service never writes the journal. - bootRoot string - // bootOrigin is the boot Service URL written into the DHCP boot filename. - bootOrigin string - // uri selects the libvirt daemon; the site shares only its socket. - uri string - // readOnly providers (boot service, observer) never take the journal lock, - // create inventory, or execute effects. - readOnly bool - command func(context.Context, string, ...string) (string, error) - syncDirectory func(string) error -} - -func parseAccelerator(value string) (string, error) { - switch value { - case "", "kvm": - return "kvm", nil - case "tcg": - return "tcg", nil - default: - return "", errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") - } -} -func (p *Provider) mode() string { - if p.accelerator == "" { - return "kvm" - } - return p.accelerator -} -func (p *Provider) checkMode(j journal) error { - mode, err := parseAccelerator(j.Accelerator) - if err != nil { - return err - } - if j.Image != "" && (mode != p.mode() || j.BootMode != p.bootMode) { - return executor.ErrConflict - } - return nil -} -func (p *Provider) stateRoot() string { - if p.root != "" { - return p.root - } - return Root -} -func syncDir(path string) error { - f, err := os.Open(path) - if err != nil { - return err - } - defer f.Close() - return f.Sync() -} -func (p *Provider) syncDir(path string) error { - if p.syncDirectory != nil { - return p.syncDirectory(path) - } - return syncDir(path) -} - -type record struct { - Request simulator.Request `json:"request"` - Result simulator.OperationResult `json:"result"` - Receipt string `json:"receipt"` - Stage string `json:"stage"` - BootToken string `json:"bootToken,omitempty"` - BootExpires time.Time `json:"bootExpires"` - BootClosed bool `json:"bootClosed"` -} -type journal struct { - BootMode string `json:"bootMode"` - Accelerator string `json:"accelerator"` - Image string `json:"image"` - Epoch int64 `json:"epoch"` - Binding string `json:"binding"` - Fence string `json:"fence"` - Closed bool `json:"closed"` - Operations map[string]*record `json:"operations"` -} - -// Open returns the effectful provider used only by per-operation workers. -func Open() (*Provider, error) { - p, err := open() - if err != nil { - return nil, err - } - if err := os.MkdirAll(Root, 0700); err != nil { - return nil, err - } - inventory := []byte(`{"kind":"Device","name":"synthetic-device-central-01","assetID":"` + AssetID + `","management":"LocalOwned","architecture":"amd64","vcpus":2,"memoryMiB":2048,"diskBytes":2147483648,"networkInterfaces":1}`) - guard, e := p.lock() - if e != nil { - return nil, e - } - defer guard.Close() - current, e := os.ReadFile(Root + "/device.json") - if os.IsNotExist(e) { - f, e := os.OpenFile(Root+"/device.json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) - if e != nil { - return nil, e - } - _, e = f.Write(inventory) - if e == nil { - e = f.Sync() - } - f.Close() - if e != nil { - return nil, e - } - } else if e != nil { - return nil, e - } else if string(current) != string(inventory) { - return nil, errors.New("local device inventory differs; adoption is not authorized") - } - return p, nil -} - -// OpenReadOnly verifies the same artifacts and configuration but cannot -// execute, lock, or create state. The boot service and observer use it with -// a read-only journal mount. -func OpenReadOnly() (*Provider, error) { - p, err := open() - if err != nil { - return nil, err - } - p.readOnly = true - return p, nil -} - -func open() (*Provider, error) { - if os.Getenv("FLEET_LOCAL_VM") != "disposable-container" { - return nil, errors.New("local VM provider requires its disposable container") - } - accelerator, err := parseAccelerator(os.Getenv("FLEET_LOCAL_VM_ACCEL")) - if err != nil { - return nil, err - } - if accelerator == "kvm" { - if _, err := os.Stat("/dev/kvm"); err != nil { - return nil, err - } - } - origin, err := parseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) - if err != nil { - return nil, err - } - uri, err := parseLibvirtURI(os.Getenv("FLEET_LIBVIRT_URI")) - if err != nil { - return nil, err - } - bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") - if bootRoot != "" && (!filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot) { - return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") - } - b, err := os.ReadFile(artifacts + "/SHA256SUMS") - if err != nil { - return nil, err - } - lines := strings.Split(strings.TrimSpace(string(b)), "\n") - if len(lines) != 2 { - return nil, errors.New("artifact manifest requires exactly two artifacts") - } - seen := map[string]bool{} - for _, line := range lines { - fields := strings.Fields(line) - if len(fields) != 2 || (fields[1] != "kernel" && fields[1] != "installer.gz") { - return nil, errors.New("invalid artifact manifest") - } - if seen[fields[1]] { - return nil, errors.New("duplicate artifact") - } - seen[fields[1]] = true - f, e := os.Open(artifacts + "/" + fields[1]) - if e != nil { - return nil, e - } - h := sha256.New() - _, e = io.Copy(h, f) - f.Close() - if e != nil { - return nil, e - } - if hex.EncodeToString(h.Sum(nil)) != fields[0] { - return nil, errors.New("artifact digest mismatch") - } - } - sum := sha256.Sum256(b) - p := &Provider{accelerator: accelerator, bootMode: "pxe", bootOrigin: origin, bootRoot: bootRoot, uri: uri} - p.image = "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]) - return p, nil -} - -// parseBootOrigin accepts only a literal http://IPv4:port origin. The site -// derives it from the boot Service ClusterIP; no hostname is resolved. -func parseBootOrigin(value string) (string, error) { - if value == "" { - return defaultBootOrigin, nil - } - u, err := url.Parse(value) - if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { - return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") - } - ip := net.ParseIP(u.Hostname()) - port, err := strconv.Atoi(u.Port()) - if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { - return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") - } - return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil -} - -// parseLibvirtURI allows only the system daemon, optionally through an -// explicit absolute socket path shared from the runtime Pod. -func parseLibvirtURI(value string) (string, error) { - if value == "" || value == "qemu:///system" { - return "qemu:///system", nil - } - const prefix = "qemu:///system?socket=" - socket := strings.TrimPrefix(value, prefix) - if !strings.HasPrefix(value, prefix) || !filepath.IsAbs(socket) || filepath.Clean(socket) != socket || strings.ContainsAny(socket, "&?#") { - return "", errors.New("FLEET_LIBVIRT_URI must be qemu:///system or qemu:///system?socket=/absolute/path") - } - return value, nil -} - -func (p *Provider) lock() (*os.File, error) { - f, e := os.OpenFile(p.stateRoot()+"/lock", os.O_CREATE|os.O_RDWR, 0600) - if e != nil { - return nil, e - } - if e = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); e != nil { - f.Close() - return nil, e - } - return f, nil -} -func (p *Provider) read() (journal, error) { - var j journal - b, e := os.ReadFile(p.stateRoot() + "/journal.json") - if os.IsNotExist(e) { - j.Operations = map[string]*record{} - return j, nil - } - if e != nil { - return j, e - } - e = json.Unmarshal(b, &j) - if e == nil { - for id, r := range j.Operations { - if r == nil { - return j, errors.New("invalid retained operation") - } - if _, err := hex.DecodeString(r.Receipt); err != nil { - return j, errors.New("invalid receipt") - } - switch r.Stage { - case "admitted", "prepared", "installer-started", "installer-verified", "disk-started", "disk-verified": - if r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { - return j, errors.New("invalid pending result") - } - case "done": - if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { - return j, errors.New("invalid terminal result") - } - default: - return j, errors.New("unknown journal stage") - } - d, de := simulator.RequestDigest(r.Request) - if de != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Request.AssetID != AssetID || len(r.Receipt) != 64 { - return j, errors.New("invalid retained request") - } - } - } - if e == nil && j.Operations == nil { - e = errors.New("invalid journal") - } - return j, e -} -func (p *Provider) save(j journal) error { - b, e := json.MarshalIndent(j, "", " ") - if e != nil { - return e - } - f, e := os.OpenFile(p.stateRoot()+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) - if e != nil { - return e - } - _, e = f.Write(b) - if e == nil { - e = f.Sync() - } - ce := f.Close() - if e != nil { - return e - } - if ce != nil { - return ce - } - if e = os.Rename(p.stateRoot()+"/journal.tmp", p.stateRoot()+"/journal.json"); e != nil { - return e - } - d, e := os.Open(p.stateRoot()) - if e != nil { - return e - } - defer d.Close() - return d.Sync() -} -func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } -func run(ctx context.Context, name string, args ...string) (string, error) { - c := exec.CommandContext(ctx, name, args...) - b, e := c.CombinedOutput() - if e != nil { - return "", fmt.Errorf("%s failed: %w: %s", name, e, b) - } - return strings.TrimSpace(string(b)), nil -} -func (p *Provider) virsh(ctx context.Context, args ...string) (string, error) { - command := p.command - if command == nil { - command = run - } - uri := p.uri - if uri == "" { - uri = "qemu:///system" - } - return command(ctx, "virsh", append([]string{"--connect", uri}, args...)...) -} - -// Lookup reports only terminal retained results. A read-only provider reads -// without the lock: atomic journal replacement makes each read consistent. -func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { - if !p.readOnly { - f, e := p.lock() - if e != nil { - return simulator.OperationResult{}, false, e - } - defer f.Close() - } - j, e := p.read() - if e != nil { - return simulator.OperationResult{}, false, e - } - if e = p.checkMode(j); e != nil { - return simulator.OperationResult{}, false, e - } - r := j.Operations[id] - if r == nil { - return simulator.OperationResult{}, false, nil - } - if r.Stage != "done" { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown - } - return r.Result, true, nil -} -func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { - if p.readOnly { - return simulator.OperationResult{}, executor.ErrInvalid - } - ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) - defer cancel() - f, e := p.lock() - if e != nil { - return simulator.OperationResult{}, e - } - defer f.Close() - if e = p.validate(q); e != nil { - return simulator.OperationResult{}, e - } - digest, e := simulator.RequestDigest(q) - if e != nil { - return simulator.OperationResult{}, e - } - j, e := p.read() - if e != nil { - return simulator.OperationResult{}, e - } - if e = p.checkMode(j); e != nil { - return simulator.OperationResult{}, e - } - j.Accelerator = p.mode() - j.BootMode = p.bootMode - if j.Image != "" && j.Image != p.image { - return simulator.OperationResult{}, executor.ErrConflict - } - j.Image = p.image - r := j.Operations[q.ID] - if r != nil { - if r.Result.InputDigest != digest { - return simulator.OperationResult{}, executor.ErrConflict - } - if r.Stage == "done" { - return r.Result, nil - } - } else { - for _, old := range j.Operations { - if old.Stage != "done" { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - } - if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { - return simulator.OperationResult{}, executor.ErrFenced - } - j.Epoch = q.Epoch - j.Binding = q.BindingID - j.Fence = q.FenceToken - j.Closed = false - nonce := make([]byte, 32) - if _, e = rand.Read(nonce); e != nil { - return simulator.OperationResult{}, e - } - r = &record{Request: q, Receipt: hex.EncodeToString(nonce), Stage: "admitted", Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now().UTC()}} - if p.bootMode == "pxe" && q.Kind == "install" { - token := make([]byte, 32) - if _, e = rand.Read(token); e != nil { - return simulator.OperationResult{}, e - } - r.BootToken = hex.EncodeToString(token) - r.BootExpires = time.Now().UTC().Add(bootWindow) - } - j.Operations[q.ID] = r - if e = p.save(j); e != nil { - return simulator.OperationResult{}, e - } - } - if q.Kind == "install" { - e = p.install(ctx, &j, r) - } else { - e = p.cleanup(ctx, &j, r) - } - if e != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) - } - now := time.Now().UTC() - r.Stage = "done" - r.Result.Phase = "Succeeded" - r.Result.CompletedAt = &now - r.Result.Result = "installed" - if q.Kind == "cleanup" { - r.Result.Result = "clean" - j.Closed = true - } - if e = p.save(j); e != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) - } - return r.Result, nil -} -func (p *Provider) directory(r *record) string { - return filepath.Join(p.stateRoot(), key(r.Request.ID)) -} - -// bootDirectory holds boot-service delivery evidence for one operation. -func (p *Provider) bootDirectory(r *record) string { - if p.bootRoot == "" { - return p.directory(r) - } - return filepath.Join(p.bootRoot, key(r.Request.ID)) -} -func domain(r *record) string { return "fleet-local-" + key(r.Request.ID)[:24] } -func (p *Provider) install(ctx context.Context, j *journal, r *record) error { - dir := p.directory(r) - if r.Stage == "admitted" { - if e := os.Mkdir(dir, 0700); e != nil && !os.IsExist(e) { - return e - } - // Exclusive creation prevents an interrupted preparation from overwriting a disk. - f, e := os.OpenFile(dir+"/disk.raw", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) - if e != nil { - return e - } - e = f.Truncate(2 << 30) - if e == nil { - e = f.Sync() - } - closeErr := f.Close() - if e != nil { - return e - } - if closeErr != nil { - return closeErr - } - if e = p.syncDir(dir); e != nil { - return e - } - r.Stage = "prepared" - if e = p.save(*j); e != nil { - return e - } - } - for _, stage := range []string{"installer", "disk"} { - before := "prepared" - if stage == "disk" { - before = "installer-verified" - } - if r.Stage == before { - if stage == "disk" && p.bootMode == "pxe" { - if !r.BootClosed { - return errors.New("boot admission still open") - } - if e := p.stopNetwork(ctx); e != nil { - return e - } - } - if stage == "installer" && p.bootMode == "pxe" { - if !time.Now().Before(r.BootExpires) || r.BootClosed { - return errors.New("boot admission expired or closed") - } - if e := p.prepareNetwork(ctx, r); e != nil { - return e - } - } - xml := p.domainXML(r, stage) - if e := os.WriteFile(dir+"/"+stage+".xml", []byte(xml), 0600); e != nil { - return e - } - // Retain start uncertainty before invoking libvirt. Recovery observes it; - // it never repeats a possibly executed installer boot. - r.Stage = stage + "-started" - if e := p.save(*j); e != nil { - return e - } - if _, e := p.virsh(ctx, "create", dir+"/"+stage+".xml"); e != nil { - return e - } - } - if r.Stage == stage+"-started" { - if e := p.waitReceipt(ctx, r, stage); e != nil { - return e - } - if stage == "installer" && p.bootMode == "pxe" { - if e := p.verifyNetworkBoot(ctx, r); e != nil { - return e - } - r.BootClosed = true - } - r.Stage = stage + "-verified" - if e := p.save(*j); e != nil { - return e - } - } - } - if r.Stage != "disk-verified" { - return errors.New("unexpected installation stage") - } - return nil -} -func (p *Provider) domainXML(r *record, stage string) string { - dir := p.directory(r) - boot := "" - nic := "" - if stage == "installer" { - boot = fmt.Sprintf("%s/kernel%s/installer.gzconsole=ttyS0 rdinit=/init fleet.receipt=%s", artifacts, artifacts, r.Receipt) - } - if stage == "installer" && p.bootMode == "pxe" { - boot = "" - nic = "" - } - domainType := "kvm" - if p.mode() == "tcg" { - domainType = "qemu" - } - return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(r), boot, nic, dir, dir, stage) -} -func (p *Provider) waitReceipt(ctx context.Context, r *record, stage string) error { - marker := "FLEET-INSTALLED:" - if stage == "disk" { - marker = "FLEET-DISK-BOOT:" - } - for { - names, e := p.virsh(ctx, "list", "--all", "--name") - if e != nil { - return e - } - present := false - for _, name := range strings.Fields(names) { - if name == domain(r) { - present = true - } - } - if !present { - b, e := os.ReadFile(p.directory(r) + "/" + stage + ".log") - if e != nil { - return e - } - for _, line := range strings.Split(string(b), "\n") { - if strings.TrimSpace(line) == marker+r.Receipt { - evidence, err := os.OpenFile(p.directory(r)+"/"+stage+".log", os.O_RDWR, 0) - if err != nil { - return err - } - err = evidence.Sync() - closeErr := evidence.Close() - if err != nil { - return err - } - if closeErr != nil { - return closeErr - } - return p.syncDir(p.directory(r)) - } - } - return errors.New("guest stopped without exact boot receipt") - } - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(time.Second): - } - } -} -func (p *Provider) cleanup(ctx context.Context, j *journal, r *record) error { - // Only retained operations in this allocation identify cleanup targets. - names, e := p.virsh(ctx, "list", "--all", "--name") - if e != nil { - return e - } - for _, old := range j.Operations { - if old.Request.Kind != "install" || old.Request.BindingID != r.Request.BindingID { - continue - } - for _, n := range strings.Fields(names) { - if n == domain(old) { - return errors.New("domain still exists; cleanup remains unknown") - } - } - path := p.directory(old) + "/disk.raw" - if e = os.Remove(path); e != nil && !os.IsNotExist(e) { - return e - } - dir, err := os.Open(p.directory(old)) - if err != nil { - return err - } - err = dir.Sync() - dir.Close() - if err != nil { - return err - } - if _, e = os.Lstat(path); !os.IsNotExist(e) { - return errors.New("disk deletion unverified") - } - } - d, e := os.Open(p.stateRoot()) - if e != nil { - return e - } - defer d.Close() - return d.Sync() -} - -func (p *Provider) validate(q simulator.Request) error { - if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { - return executor.ErrInvalid - } - if q.AssetID != AssetID || (q.Kind != "install" && q.Kind != "cleanup") { - return executor.ErrInvalid - } - if q.Kind == "install" { - var in struct { - Image string `json:"image"` - } - d := json.NewDecoder(strings.NewReader(string(q.Inputs))) - d.DisallowUnknownFields() - if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { - return executor.ErrInvalid - } - } - if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { - return executor.ErrInvalid - } - return nil -} - -// ImageReference is the locally verified artifact manifest identity. -func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/localvm/provider_test.go b/internal/localvm/provider_test.go deleted file mode 100644 index b35f2c24..00000000 --- a/internal/localvm/provider_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package localvm - -import ( - "encoding/json" - "go.datum.net/fleet/internal/simulator" - "strings" - "testing" -) - -func TestBoundedInputs(t *testing.T) { - p := &Provider{image: "approved@sha256:abc"} - base := simulator.Request{ID: "installation", Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"approved@sha256:abc"}`)} - if e := p.validate(base); e != nil { - t.Fatal(e) - } - for _, mutate := range []func(*simulator.Request){func(q *simulator.Request) { q.AssetID = "other" }, func(q *simulator.Request) { q.Epoch = 0 }, func(q *simulator.Request) { q.FenceToken = "" }, func(q *simulator.Request) { q.Inputs = json.RawMessage(`{"image":"unapproved"}`) }, func(q *simulator.Request) { - q.Inputs = json.RawMessage(`{"image":"approved@sha256:abc","path":"/host"}`) - }, func(q *simulator.Request) { q.Kind = "cleanup"; q.Inputs = json.RawMessage(`{"target":"/host"}`) }, func(q *simulator.Request) { q.Kind = "power" }} { - q := base - mutate(&q) - if p.validate(q) == nil { - t.Fatalf("accepted unsupported request: %#v", q) - } - } -} -func TestDiskBootHasNoInstallerAndNamesAreOpaque(t *testing.T) { - r := &record{Request: simulator.Request{ID: "../../host' "}, Receipt: strings.Repeat("a", 64)} - xml := (&Provider{}).domainXML(r, "disk") - if strings.Contains(xml, "") || strings.Contains(xml, "") || strings.Contains(xml, "") { - t.Fatal("missing disk boot") - } -} diff --git a/internal/localvm/pxe_review_adversarial_test.go b/internal/localvm/pxe_review_adversarial_test.go deleted file mode 100644 index 276f5af7..00000000 --- a/internal/localvm/pxe_review_adversarial_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package localvm - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -func reviewBootRecord(t *testing.T) (*Provider, journal, *record) { - t.Helper() - p := newVMFixture(t).p - p.bootMode = "pxe" - q := vmRequest("independent-review") - digest, err := simulator.RequestDigest(q) - if err != nil { - t.Fatal(err) - } - r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} - j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: r}} - if err := os.Mkdir(p.directory(r), 0700); err != nil { - t.Fatal(err) - } - if err := p.save(j); err != nil { - t.Fatal(err) - } - return p, j, r -} - -type reviewFailedResponse struct { - header http.Header - writes int - short bool -} - -func (w *reviewFailedResponse) Header() http.Header { return w.header } -func (w *reviewFailedResponse) WriteHeader(int) {} -func (w *reviewFailedResponse) Write(data []byte) (int, error) { - w.writes++ - if w.short { - return len(data) - 1, nil - } - return 0, errors.New("client disconnected before body") -} - -func TestReviewIncompleteHTTPWriteCannotRecordCompletion(t *testing.T) { - for _, short := range []bool{false, true} { - p, _, r := reviewBootRecord(t) - w := &reviewFailedResponse{header: make(http.Header), short: short} - p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) - if w.writes != 1 { - t.Fatal("did not exercise body write") - } - b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(b), "admitted boot.ipxe bytes=") || strings.Contains(string(b), "write-complete") { - t.Fatal("incomplete write counted as completion") - } - if err := p.verifyNetworkBoot(context.Background(), r); err == nil { - t.Fatal("attempt counted as network boot evidence") - } - } -} -func TestReviewCompleteHTTPWriteRecordsCompletion(t *testing.T) { - p, _, r := reviewBootRecord(t) - w := httptest.NewRecorder() - p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) - b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") - if err != nil { - t.Fatal(err) - } - if w.Code != http.StatusOK || !strings.Contains(string(b), "write-complete boot.ipxe bytes=") { - t.Fatal("successful write not recorded") - } -} - -func TestReviewCorruptDigestAndHTTPPathVariantsDenied(t *testing.T) { - p, j, r := reviewBootRecord(t) - base := "/" + key(r.Request.ID)[:16] + "/" + r.BootToken - for _, path := range []string{base + "/kernel/extra", base + "/%2e%2e", base + "/boot.ipxe?token=x", base + "/%2fkernel"} { - w := httptest.NewRecorder() - p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) - if w.Code != http.StatusForbidden { - t.Fatalf("path variant allowed: status %d", w.Code) - } - } - r.Result.InputDigest = "substituted" - if err := p.save(j); err != nil { - t.Fatal(err) - } - w := httptest.NewRecorder() - p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", base+"/boot.ipxe", nil)) - if w.Code != http.StatusForbidden { - t.Fatal("corrupt request digest admitted") - } -} - -func TestReviewClosedAdmissionDoesNotSettleLiveInstaller(t *testing.T) { - p, j, r := reviewBootRecord(t) - r.BootClosed = true - r.BootExpires = time.Now().Add(-time.Minute) - if err := p.save(j); err != nil { - t.Fatal(err) - } - // Even an exact receipt cannot settle a domain still present. - if err := os.WriteFile(p.directory(r)+"/installer.log", []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { - t.Fatal(err) - } - p.command = func(_ context.Context, _ string, args ...string) (string, error) { - if args[2] != "list" { - t.Fatalf("unexpected effect %s", args[2]) - } - return domain(r), nil - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := p.Execute(ctx, r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("live expired installer settled: %v", err) - } - got, err := p.read() - if err != nil { - t.Fatal(err) - } - if got.Operations[r.Request.ID].Stage != "installer-started" { - t.Fatal("advanced live installer") - } -} - -func TestReviewNetworkTeardownFailureBlocksDiskBootAndRecovers(t *testing.T) { - p, j, r := reviewBootRecord(t) - r.Stage = "installer-verified" - r.BootClosed = true - if err := p.save(j); err != nil { - t.Fatal(err) - } - fail := true - creates := 0 - p.command = func(_ context.Context, _ string, args ...string) (string, error) { - switch args[2] { - case "net-list": - return "fleet-pxe", nil - case "net-destroy": - if fail { - return "", errors.New("uncertain teardown") - } - return "", nil - case "create": - creates++ - if !strings.HasSuffix(args[3], "/disk.xml") { - t.Fatal("installer replay") - } - return "", os.WriteFile(p.directory(r)+"/disk.log", []byte("FLEET-DISK-BOOT:"+r.Receipt+"\n"), 0600) - case "list": - return "", nil - default: - t.Fatalf("unexpected command %s", args[2]) - return "", nil - } - } - if _, err := p.Execute(context.Background(), r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("teardown failure not unknown: %v", err) - } - if creates != 0 { - t.Fatal("booted despite uncertain teardown") - } - got, err := p.read() - if err != nil { - t.Fatal(err) - } - if got.Operations[r.Request.ID].Stage != "installer-verified" { - t.Fatal("advanced after failure") - } - fail = false - if _, err := p.Execute(context.Background(), r.Request); err != nil { - t.Fatal(err) - } - if creates != 1 { - t.Fatal("unexpected disk boot count") - } -} diff --git a/internal/localvm/site_test.go b/internal/localvm/site_test.go deleted file mode 100644 index 1abcf9b0..00000000 --- a/internal/localvm/site_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package localvm - -import ( - "context" - "errors" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -func TestSiteBootOriginAndLibvirtURIValidation(t *testing.T) { - for value, want := range map[string]string{"": defaultBootOrigin, "http://10.96.12.7:8080": "http://10.96.12.7:8080"} { - if got, err := parseBootOrigin(value); err != nil || got != want { - t.Fatalf("%q: %q %v", value, got, err) - } - } - for _, bad := range []string{"https://10.0.0.1:8080", "http://boot.local:8080", "http://10.0.0.1", "http://10.0.0.1:8080/x", "http://u@10.0.0.1:8080", "http://[::1]:8080", "http://10.0.0.1:0"} { - if _, err := parseBootOrigin(bad); err == nil { - t.Fatalf("accepted boot origin %q", bad) - } - } - for _, good := range []string{"", "qemu:///system", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} { - if _, err := parseLibvirtURI(good); err != nil { - t.Fatalf("%q: %v", good, err) - } - } - for _, bad := range []string{"qemu+tcp://runtime/system", "qemu:///session", "qemu:///system?socket=relative", "qemu:///system?socket=/run/x&no_verify=1", "qemu:///system?socket=/run/../etc"} { - if _, err := parseLibvirtURI(bad); err == nil { - t.Fatalf("accepted libvirt URI %q", bad) - } - } -} - -// The site network forwards only when the boot Service is outside the -// hypervisor namespace, and the DHCP boot file names that exact origin. -func TestSiteNetworkUsesBootServiceOrigin(t *testing.T) { - var defined string - p := &Provider{root: t.TempDir(), bootMode: "pxe", bootOrigin: "http://10.96.0.40:8080", uri: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} - p.command = func(_ context.Context, name string, args ...string) (string, error) { - if args[1] != p.uri { - t.Fatalf("libvirt URI not used: %v", args) - } - if args[2] == "net-create" { - b, err := os.ReadFile(args[3]) - defined = string(b) - return "", err - } - return "", nil - } - r := &record{Request: vmRequest("site-net"), BootToken: strings.Repeat("b", 64)} - if err := p.prepareNetwork(context.Background(), r); err != nil { - t.Fatal(err) - } - if !strings.Contains(defined, "") || !strings.Contains(defined, "file='http://10.96.0.40:8080/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe'") { - t.Fatal(defined) - } - single := &Provider{root: t.TempDir(), bootMode: "pxe"} - single.command = func(_ context.Context, name string, args ...string) (string, error) { - if args[2] == "net-create" { - b, _ := os.ReadFile(args[3]) - defined = string(b) - } - return "", nil - } - if err := single.prepareNetwork(context.Background(), r); err != nil { - t.Fatal(err) - } - if strings.Contains(defined, " 1 { t.Fatalf("%s/%s lifecycle effect without a provider: finalizers=%v status=%#v", project, name, m.Finalizers, m.Status) } - var secrets corev1.SecretList - must(rootClient.List(ctx, &secrets, client.InNamespace(testPrivateNamespace))) - if len(secrets.Items) != 0 { - t.Fatalf("custody written without a provider: %d records", len(secrets.Items)) - } } slow("east pinned through the consumer provider", pinned("east", "m", 8)) diff --git a/internal/manager/multicluster_harness_test.go b/internal/manager/multicluster_harness_test.go index 292b05ce..2299fc16 100644 --- a/internal/manager/multicluster_harness_test.go +++ b/internal/manager/multicluster_harness_test.go @@ -32,10 +32,7 @@ import ( servicesv1alpha1 "go.miloapis.com/service-catalog/api/v1alpha1" ) -const ( - testAuthority = "milo-synthetic" - testPrivateNamespace = "fleet-system-private" -) +const testAuthority = "milo-synthetic" func fleetScheme(t *testing.T) *runtime.Scheme { t.Helper() @@ -70,18 +67,6 @@ func newConsumer(t *testing.T, name string, objects ...client.Object) *multiclus }) } -// newPrivate is the management cluster's private record namespace. -func newPrivate(t *testing.T, objects ...client.Object) *multiclustertest.Project { - t.Helper() - return multiclustertest.NewProject(t, "host", multiclustertest.ProjectOptions{ - Scheme: fleetScheme(t), - Objects: objects, - Indexes: collect(t, func(ctx context.Context, indexer client.FieldIndexer) error { - return RegisterPrivateIndexes(ctx, indexer, testPrivateNamespace) - }), - }) -} - // milo is the root Milo API: Project identities by name. type rootMilo struct { client.Client @@ -126,7 +111,6 @@ func (m *rootMilo) verifierFor(expected controller.ProjectIdentity) ProjectVerif } type fleet struct { - private *multiclustertest.Cluster manager mcmanager.Manager projects *Projects tracker *projectdiscovery.EngageTracker @@ -136,7 +120,7 @@ type fleet struct { // startFleet runs the production wiring (projectdiscovery.NewManager, // NewProjects, Setup) over provider. The host config is never contacted. -func startFleet(t *testing.T, provider multicluster.Provider, root *rootMilo, private *multiclustertest.Project, options SetupOptions) *fleet { +func startFleet(t *testing.T, provider multicluster.Provider, root *rootMilo, options SetupOptions) *fleet { t.Helper() ctx, cancel := context.WithCancel(context.Background()) projects := NewProjects(root.resolver(), root.verifierFor) @@ -151,9 +135,6 @@ func startFleet(t *testing.T, provider multicluster.Provider, root *rootMilo, pr cancel() t.Fatal(err) } - options.PrivateNamespace = testPrivateNamespace - privateCluster := private.NewCluster() - options.PrivateCluster = privateCluster if options.HandlersFor == nil { options.HandlersFor = DefaultHandlers } @@ -161,17 +142,12 @@ func startFleet(t *testing.T, provider multicluster.Provider, root *rootMilo, pr cancel() t.Fatal(err) } - f := &fleet{private: privateCluster, manager: mgr, projects: projects, tracker: tracker, cancel: cancel, done: make(chan error, 1)} + f := &fleet{manager: mgr, projects: projects, tracker: tracker, cancel: cancel, done: make(chan error, 1)} go func() { f.done <- mgr.Start(ctx) }() t.Cleanup(f.stop) return f } -func (f *fleet) privateInformer(t *testing.T) (*multiclustertest.Informer, error) { - t.Helper() - return f.private.FakeCache.InformerFor(corev1.SchemeGroupVersion.WithKind("Secret")) -} - func (f *fleet) stop() { if f.cancel == nil { return diff --git a/internal/manager/multicluster_test.go b/internal/manager/multicluster_test.go index 9d175a96..baebab93 100644 --- a/internal/manager/multicluster_test.go +++ b/internal/manager/multicluster_test.go @@ -5,19 +5,15 @@ import ( "errors" "reflect" "testing" - "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/types" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/multiclustertest" - "go.datum.net/fleet/internal/simulator" ) var ( @@ -25,56 +21,6 @@ var ( consistently = multiclustertest.Consistently ) -// noProvider fails the test if any lifecycle path reaches a provider. -type noProvider struct{ t *testing.T } - -func (p noProvider) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { - p.t.Error("a provider operation was requested") - return simulator.OperationResult{}, errors.New("no provider") -} - -func (p noProvider) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - p.t.Error("a provider operation was looked up") - return simulator.OperationResult{}, false, errors.New("no provider") -} - -func coordinatorFor(t *testing.T, private *multiclustertest.Project) *controller.Coordinator { - t.Helper() - coordinator, err := controller.NewCoordinator(private.Client, testPrivateNamespace, noProvider{t}, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { - t.Fatal(err) - } - return coordinator -} - -// retainCustody writes the real custody record a lifecycle handler writes -// before any effect: project-scoped custody linked to its authority. -func retainCustody(t *testing.T, coordinator *controller.Coordinator, consumer, provider controller.ProjectIdentity, machine *fleetv1.Machine, namespaceUID types.UID) { - t.Helper() - ctx := context.Background() - admission := controller.AdmissionAuthority{PrincipalUID: "test:" + string(consumer.UID), DecisionID: "test:" + string(machine.UID)} - if err := coordinator.EnsureClaimCustody(ctx, machine, namespaceUID, admission, consumer); err != nil { - t.Fatal(err) - } - authority := controller.AuthorityRef{Provider: "test", RecordName: "authority-" + string(consumer.UID), RecordID: "id-" + string(consumer.UID), ContractDigest: "digest-" + string(consumer.UID)} - if err := coordinator.RetainClaimAuthority(ctx, machine.UID, consumer, provider, authority); err != nil { - t.Fatal(err) - } -} - -func privateSecrets(t *testing.T, private *multiclustertest.Project) map[string]string { - t.Helper() - var list corev1.SecretList - if err := private.Client.List(context.Background(), &list, client.InNamespace(testPrivateNamespace)); err != nil { - t.Fatal(err) - } - out := map[string]string{} - for _, secret := range list.Items { - out[secret.Name] = secret.ResourceVersion - } - return out -} - // The default configuration (no provider, no synthetic integration) resolves // requested hardware in every engaged project and performs no lifecycle // effect anywhere. Both projects use identical Machine names and UIDs. @@ -85,9 +31,8 @@ func TestNoProviderResolvesRequestedHardwareWithoutLifecycleEffects(t *testing.T east := newConsumer(t, "east", mcNamespace("east-ns"), mcMachine("m", "shared-uid", "general"), mcProfile("general", 2, 8, "32Gi"), installation()) west := newConsumer(t, "west", mcNamespace("west-ns"), mcMachine("m", "shared-uid", "general"), mcProfile("general", 5, 16, "64Gi"), installation()) root := newMilo(t, map[string]types.UID{"east": "east-project", "west": "west-project"}) - private := newPrivate(t) provider := multiclustertest.NewProvider() - startFleet(t, provider, root, private, SetupOptions{}) + startFleet(t, provider, root, SetupOptions{}) provider.Engage(t, context.Background(), east) provider.Engage(t, context.Background(), west) @@ -100,9 +45,6 @@ func TestNoProviderResolvesRequestedHardwareWithoutLifecycleEffects(t *testing.T } } consistently(t, "no lifecycle effect in any project", func() bool { - if private.Writes() != 0 || len(privateSecrets(t, private)) != 0 { - return false - } for _, p := range []*multiclustertest.Project{east, west} { m := getMachine(t, p, "m") if len(m.Finalizers) != 0 || len(m.Status.Conditions) != 1 || m.Status.Phase != "" || m.Status.AllocatedHardware != nil { @@ -121,110 +63,14 @@ func TestNoProviderResolvesRequestedHardwareWithoutLifecycleEffects(t *testing.T }) } -// Private records live in one host namespace for every project, but each is -// routed only to the project whose exact lifetime it records, never to a -// project with an identically named Machine. -func TestPrivateCustodyRoutesOnlyToItsOwnProject(t *testing.T) { - east := newConsumer(t, "east", mcNamespace("east-ns"), mcMachine("m", "shared-uid", "general"), mcProfile("general", 1, 8, "32Gi")) - west := newConsumer(t, "west", mcNamespace("west-ns"), mcMachine("m", "shared-uid", "general"), mcProfile("general", 1, 8, "32Gi")) - root := newMilo(t, map[string]types.UID{"east": "east-project", "west": "west-project", "provider": "provider-project"}) - private := newPrivate(t) - recorder := newRecordingHandlers() - provider := multiclustertest.NewProvider() - f := startFleet(t, provider, root, private, SetupOptions{HandlersFor: recorder.factory}) - provider.Engage(t, context.Background(), east) - provider.Engage(t, context.Background(), west) - eventually(t, "both projects reconciled their Machine", func() bool { return recorder.count("east") > 0 && recorder.count("west") > 0 }) - eventually(t, "both pinned", func() bool { return pinnedWith(t, east, "m", 8)() && pinnedWith(t, west, "m", 8)() }) - // Engagement replays each project's objects through several controllers - // (the Machine itself, then dependency routes such as its MachineProfile), - // so a project's request count keeps rising briefly after its Machine is - // pinned. Take the baseline only once both projects' initial work has - // settled; otherwise a late replay reconcile looks like a cross-project - // wake-up. - eastBefore, westBefore := settledCounts(t, recorder, "east", "west") - - eastIdentity, westIdentity := root.identity(t, "east"), root.identity(t, "west") - coordinator := coordinatorFor(t, private) - retainCustody(t, coordinator, eastIdentity, root.identity(t, "provider"), getMachine(t, east, "m"), "east-ns") - - // Deterministic routing check, independent of event timing: the actual - // custody record, mapped through the live registry exactly as the - // private-record watch maps it, reaches east only. - var custody corev1.SecretList - if err := private.Client.List(context.Background(), &custody, client.InNamespace(testPrivateNamespace)); err != nil || len(custody.Items) != 1 { - t.Fatalf("custody records = %d, %v", len(custody.Items), err) - } - routed := privateHandler(f.projects, testPrivateNamespace, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { return m.RequestForPrivate })(context.Background(), &custody.Items[0]) - if len(routed) != 1 || routed[0].ClusterName != "east" || !routed[0].SameProject(eastIdentity.AuthorityID, eastIdentity.UID) || routed[0].UID != "shared-uid" { - t.Fatalf("east's custody routed to %#v, want only east's Machine", routed) - } - - eventually(t, "east woken by its custody record", func() bool { return recorder.count("east") > eastBefore }) - consistently(t, "west never woken by east's custody", func() bool { return recorder.count("west") == westBefore }) - for name, identity := range map[multicluster.ClusterName]controller.ProjectIdentity{"east": eastIdentity, "west": westIdentity} { - for _, request := range recorder.all(name) { - if request.ClusterName != name || !request.SameProject(identity.AuthorityID, identity.UID) { - t.Fatalf("%s handled a request for another project: %#v", name, request) - } - } - } - // Custody reads are scoped by project lifetime. - if ok, err := coordinator.HasClaimCustody(context.Background(), eastIdentity, "shared-uid"); err != nil || !ok { - t.Fatalf("east custody = %v, %v", ok, err) - } - if ok, err := coordinator.HasClaimCustody(context.Background(), westIdentity, "shared-uid"); err != nil || ok { - t.Fatalf("west read east's custody: %v, %v", ok, err) - } - // Identically named and identically UID'd claims get distinct records. - retainCustody(t, coordinator, westIdentity, root.identity(t, "provider"), getMachine(t, west, "m"), "west-ns") - if secrets := privateSecrets(t, private); len(secrets) != 2 { - t.Fatalf("private records = %v, want one per project", secrets) - } - if _, err := coordinator.Release(context.Background(), "shared-uid"); err == nil { - t.Fatal("an unscoped release matched custody across projects") - } -} - -// settledCounts waits until every named project's request count has stopped -// changing for a settling period, then returns the counts in order. -func settledCounts(t *testing.T, recorder *recordingHandlers, names ...multicluster.ClusterName) (int, int) { - t.Helper() - snapshot := func() []int { - out := make([]int, len(names)) - for i, name := range names { - out[i] = recorder.count(name) - } - return out - } - deadline := time.Now().Add(10 * time.Second) - last, stableSince := snapshot(), time.Now() - for time.Now().Before(deadline) { - time.Sleep(20 * time.Millisecond) - current := snapshot() - if !reflect.DeepEqual(current, last) { - last, stableSince = current, time.Now() - continue - } - if time.Since(stableSince) >= 500*time.Millisecond { - return last[0], last[1] - } - } - t.Fatalf("request counts for %v never settled: %v", names, last) - return 0, 0 -} - -// When a project leaves the consumer set with active custody, the manager -// only stops reconciling it: custody is not released, no status is -// rewritten, and its private records are not touched. Re-engagement resumes. -func TestDisengageWithActiveCustodyStopsReconcilingWithoutReleaseOrRewrite(t *testing.T) { +// When a project leaves the consumer set, the manager only stops reconciling +// it: no handler runs and no status is rewritten. Re-engagement resumes. +func TestDisengageStopsReconcilingWithoutRewrite(t *testing.T) { east := newConsumer(t, "east", mcNamespace("east-ns"), mcMachine("m", "east-machine", "general"), mcProfile("general", 1, 8, "32Gi")) - root := newMilo(t, map[string]types.UID{"east": "east-project", "provider": "provider-project"}) - private := newPrivate(t) - retainCustody(t, coordinatorFor(t, private), root.identity(t, "east"), root.identity(t, "provider"), getMachine(t, east, "m"), "east-ns") + root := newMilo(t, map[string]types.UID{"east": "east-project"}) recorder := newRecordingHandlers() provider := multiclustertest.NewProvider() - f := startFleet(t, provider, root, private, SetupOptions{HandlersFor: recorder.factory}) + f := startFleet(t, provider, root, SetupOptions{HandlersFor: recorder.factory}) cl := provider.Engage(t, context.Background(), east) eventually(t, "engaged and reconciled", func() bool { return recorder.count("east") > 0 && pinnedWith(t, east, "m", 8)() }) machineInformer, err := cl.FakeCache.InformerFor(fleetv1.GroupVersion.WithKind("Machine")) @@ -235,21 +81,9 @@ func TestDisengageWithActiveCustodyStopsReconcilingWithoutReleaseOrRewrite(t *te provider.Disengage("east") eventually(t, "unbound", func() bool { return f.projects.Get("east") == nil && !f.tracker.Engaged("east") }) eventually(t, "project sources stopped", func() bool { return machineInformer.HandlerCount() == 0 }) - handled, privateWrites, records, machine := recorder.count("east"), private.Writes(), privateSecrets(t, private), getMachine(t, east, "m") + handled, machine := recorder.count("east"), getMachine(t, east, "m") - // Private-record events, a stale queued request, and project events all - // arrive after departure. - var secrets corev1.SecretList - if err := private.Client.List(context.Background(), &secrets, client.InNamespace(testPrivateNamespace)); err != nil { - t.Fatal(err) - } - privateInformer, err := f.privateInformer(t) - if err != nil { - t.Fatal(err) - } - for i := range secrets.Items { - privateInformer.EmitUpdate(&secrets.Items[i], &secrets.Items[i]) - } + // A stale queued request and project events arrive after departure. machineInformer.EmitUpdate(machine, machine) request := ProjectRequest{ClusterName: "east", AuthorityID: testAuthority, ProjectUID: "east-project", Namespace: "default", Name: "m", UID: "east-machine"} if result, err := (ClusterProjectReconciler{Projects: f.projects, Owner: func(r *ProjectRuntime) *LifecycleOwner { return r.Machine }}).Reconcile(context.Background(), request); err != nil || !result.IsZero() { @@ -257,12 +91,11 @@ func TestDisengageWithActiveCustodyStopsReconcilingWithoutReleaseOrRewrite(t *te } consistently(t, "nothing reconciled or written after departure", func() bool { current := getMachine(t, east, "m") - return recorder.count("east") == handled && private.Writes() == privateWrites && - reflect.DeepEqual(privateSecrets(t, private), records) && + return recorder.count("east") == handled && current.ResourceVersion == machine.ResourceVersion && reflect.DeepEqual(current.Status, machine.Status) }) - // Re-engagement resumes reconciliation of the retained custody. + // Re-engagement resumes reconciliation. provider.Engage(t, context.Background(), east) eventually(t, "resumed after re-engagement", func() bool { return recorder.count("east") > handled }) } @@ -270,9 +103,8 @@ func TestDisengageWithActiveCustodyStopsReconcilingWithoutReleaseOrRewrite(t *te func TestPinnedRequestedHardwareSurvivesRestart(t *testing.T) { p := newConsumer(t, "restart", mcNamespace("ns"), mcMachine("m", "m-uid", "general"), mcProfile("general", 1, 8, "32Gi")) root := newMilo(t, map[string]types.UID{"restart": "restart-project"}) - private := newPrivate(t) provider := multiclustertest.NewProvider() - first := startFleet(t, provider, root, private, SetupOptions{}) + first := startFleet(t, provider, root, SetupOptions{}) provider.Engage(t, context.Background(), p) eventually(t, "pinned", pinnedWith(t, p, "m", 8)) accepted := *getMachine(t, p, "m").Status.RequestedHardware @@ -287,7 +119,7 @@ func TestPinnedRequestedHardwareSurvivesRestart(t *testing.T) { } writes, reads := p.Writes(), p.Reads("m") restarted := multiclustertest.NewProvider() - second := startFleet(t, restarted, root, private, SetupOptions{}) + second := startFleet(t, restarted, root, SetupOptions{}) restarted.Engage(t, context.Background(), p) eventually(t, "restarted manager re-read the Machine", func() bool { return second.tracker.Engaged("restart") && p.Reads("m") > reads }) consistently(t, "snapshot stays pinned across restart", func() bool { @@ -301,9 +133,8 @@ func TestEngagementFailsClosedOnIdentity(t *testing.T) { unknown := newConsumer(t, "unknown", mcNamespace("ns"), mcMachine("m", "m-uid", "general"), mcProfile("general", 1, 8, "32Gi")) alias := newConsumer(t, "alias", mcNamespace("ns"), mcMachine("m", "m-uid", "general"), mcProfile("general", 1, 8, "32Gi")) root := newMilo(t, map[string]types.UID{"known": "known-project", "alias": "known-project"}) - private := newPrivate(t) provider := multiclustertest.NewProvider() - f := startFleet(t, provider, root, private, SetupOptions{}) + f := startFleet(t, provider, root, SetupOptions{}) if _, err := provider.TryEngage(t, context.Background(), unknown); !errors.Is(err, ErrProjectIdentityUnavailable) { t.Fatalf("project without a Milo identity engaged: %v", err) diff --git a/internal/manager/power.go b/internal/manager/power.go new file mode 100644 index 00000000..586f4bbb --- /dev/null +++ b/internal/manager/power.go @@ -0,0 +1,128 @@ +package manager + +import ( + "context" + "errors" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "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" +) + +// PowerProjector is the only writer of Machine status.power. It reads the +// custody of the Machine's allocation in the provider project: while a +// recovery hold exists, or custody is unverified, power is Unknown, because +// nothing proves what the server did. Otherwise it is the power state the +// Device's last discovery observed. A Machine without an active allocation +// reports no power. +type PowerProjector struct { + Client client.Client + Project controller.ProjectIdentity + // Provider reads the provider project. It must read through. + Provider client.Reader + // Namespace is the Devices' namespace in the provider project. + Namespace string +} + +func (p PowerProjector) ReconcileEvent(ctx context.Context, request ProjectRequest) Outcome { + if p.Client == nil || p.Provider == nil || !p.Project.Valid() || !request.Valid() || !request.SameProject(p.Project.AuthorityID, p.Project.UID) { + return Outcome{RetryError: ErrEventWiringUnavailable} + } + consumer := ProjectConsumer(p.Project, p.Client) + machine := allocation.Machine{Consumer: consumer.Ref, ConsumerUID: consumer.UID, Namespace: request.Namespace, Name: request.Name, UID: request.UID} + if err := ProjectPower(ctx, p.Client, p.Provider, p.Namespace, machine); err != nil { + return Outcome{RetryError: err} + } + return Outcome{} +} + +// ProjectPower writes one Machine's status.power. The harness runners call +// it for their fixtures, so this stays the only power writer. +func ProjectPower(ctx context.Context, consumer client.Client, provider client.Reader, namespace string, machine allocation.Machine) error { + if consumer == nil || provider == nil || namespace == "" || !machine.Valid() { + return errors.New("power projection requires both projects and an exact Machine") + } + var current fleetv1.Machine + if err := consumer.Get(ctx, client.ObjectKey{Namespace: machine.Namespace, Name: machine.Name}, ¤t); apierrors.IsNotFound(err) { + return nil + } else if err != nil { + return err + } + if current.UID != machine.UID { + return nil + } + want, err := power(ctx, provider, namespace, machine) + if err != nil { + return err + } + if samePower(current.Status.Power, want) { + return nil + } + updated := current.DeepCopyObject().(*fleetv1.Machine) + updated.Status.Power = want + return consumer.Status().Update(ctx, updated) +} + +func samePower(a, b *fleetv1.PowerStatus) bool { + return (a == nil && b == nil) || (a != nil && b != nil && *a == *b) +} + +var unknown = &fleetv1.PowerStatus{State: "Unknown"} + +func power(ctx context.Context, provider client.Reader, namespace string, machine allocation.Machine) (*fleetv1.PowerStatus, error) { + current := &fleetv1.MachineAllocation{} + if err := provider.Get(ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Name(machine)}, current); apierrors.IsNotFound(err) { + return nil, nil + } else if err != nil { + return nil, err + } + if current.Labels[fleetv1.LabelMachineUID] != string(machine.UID) || current.Labels[fleetv1.LabelConsumerUID] != string(machine.ConsumerUID) || current.Status.Phase != fleetv1.AllocationActive { + return nil, nil + } + state := &ops.DeviceCustody{} + if err := provider.Get(ctx, client.ObjectKey{Namespace: namespace, Name: current.Spec.DeviceRef.Name}, state); apierrors.IsNotFound(err) { + return unknown, nil + } else if err != nil { + return nil, err + } + if state.Spec.RecoveryHold != nil || state.Spec.State != ops.CustodyVerified || state.Labels[ops.LabelDeviceUID] != current.Labels[fleetv1.LabelDeviceUID] { + return unknown, nil + } + device := &inventory.Device{} + if err := provider.Get(ctx, client.ObjectKey{Namespace: namespace, Name: current.Spec.DeviceRef.Name}, device); apierrors.IsNotFound(err) { + return unknown, nil + } else if err != nil { + return nil, err + } + if device.UID != types.UID(current.Labels[fleetv1.LabelDeviceUID]) || device.Status.Discovery == nil || device.Status.Discovery.Inventory == nil { + return unknown, nil + } + for _, system := range device.Status.Discovery.Inventory.Systems { + if strings.EqualFold(system.UUID, device.Spec.Identity.SystemUUID) { + switch system.PowerState { + case "On", "Off": + return &fleetv1.PowerStatus{State: system.PowerState}, nil + } + } + } + return unknown, nil +} + +// Chain runs projectors in order and stops at the first that must retry. +func Chain(handlers ...Handler) Handler { + return HandlerFunc(func(ctx context.Context, request ProjectRequest) Outcome { + for _, handler := range handlers { + if outcome := handler.ReconcileEvent(ctx, request); outcome.RetryError != nil || outcome.Deadline.Mode != DeadlineUnchanged { + return outcome + } + } + return Outcome{} + }) +} diff --git a/internal/manager/power_test.go b/internal/manager/power_test.go new file mode 100644 index 00000000..33dab277 --- /dev/null +++ b/internal/manager/power_test.go @@ -0,0 +1,109 @@ +package manager + +import ( + "context" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + "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/tenancy" +) + +// TestPowerFollowsCustodyAndDiscovery reports the discovered power state of +// the allocation's Device, Unknown while a recovery hold exists or custody +// is unverified, and nothing once the allocation is released. +func TestPowerFollowsCustodyAndDiscovery(t *testing.T) { + ctx := context.Background() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{fleetv1.AddToScheme, inventory.AddToScheme, ops.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + machine := allocation.Machine{Consumer: tenancy.Project("consumer-example"), ConsumerUID: "00000000-0000-4000-8000-000000000501", Namespace: "default", Name: "allocation", UID: "00000000-0000-4000-8000-000000000601"} + consumer := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Name: machine.Name, Namespace: machine.Namespace, UID: machine.UID}}).WithStatusSubresource(&fleetv1.Machine{}).Build() + const namespace, deviceUID = "fleet-provider", "00000000-0000-4000-8000-000000000101" + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001", Namespace: namespace, UID: deviceUID}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{SystemUUID: "00000000-0000-4000-8000-000000000201"}}, + Status: inventory.DeviceStatus{Discovery: &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{Systems: []inventory.ObservedSystem{{ID: "s", UUID: "00000000-0000-4000-8000-000000000201", PowerState: "On"}}}}}} + held := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: deviceUID}}, Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name}, State: ops.CustodyVerified, + Holder: ops.Holder{Type: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation.Name(machine)}}}} + active := &fleetv1.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: allocation.Name(machine), Namespace: namespace, Labels: map[string]string{ + fleetv1.LabelMachineUID: string(machine.UID), fleetv1.LabelConsumerUID: string(machine.ConsumerUID), fleetv1.LabelDeviceUID: deviceUID}}, Spec: fleetv1.MachineAllocationSpec{ + ConsumerRef: machine.Consumer, MachineRef: fleetv1.AllocatedMachineReference{Namespace: machine.Namespace, Name: machine.Name}, + DeviceRef: fleetv1.AllocatedDeviceReference{Name: device.Name}}, Status: fleetv1.MachineAllocationStatus{Phase: fleetv1.AllocationActive}} + provider := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, held, active).Build() + power := func() string { + t.Helper() + if err := ProjectPower(ctx, consumer, provider, namespace, machine); err != nil { + t.Fatal(err) + } + current := &fleetv1.Machine{} + if err := consumer.Get(ctx, client.ObjectKey{Namespace: machine.Namespace, Name: machine.Name}, current); err != nil { + t.Fatal(err) + } + if current.Status.Power == nil { + return "" + } + return current.Status.Power.State + } + if got := power(); got != "On" { + t.Fatalf("power = %q, want the discovered On", got) + } + update := func(change func(*ops.DeviceCustody)) { + t.Helper() + if err := provider.Get(ctx, client.ObjectKeyFromObject(held), held); err != nil { + t.Fatal(err) + } + change(held) + if err := provider.Update(ctx, held); err != nil { + t.Fatal(err) + } + } + update(func(c *ops.DeviceCustody) { + c.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceWipe", Name: "wipe"}, Fence: 3, Reason: "DeadlineExceeded"} + }) + if got := power(); got != "Unknown" { + t.Fatalf("power under a recovery hold = %q", got) + } + update(func(c *ops.DeviceCustody) { c.Spec.RecoveryHold, c.Spec.State = nil, ops.CustodyUnverified }) + if got := power(); got != "Unknown" { + t.Fatalf("power with unverified custody = %q", got) + } + update(func(c *ops.DeviceCustody) { c.Spec.State = ops.CustodyVerified }) + if got := power(); got != "On" { + t.Fatalf("power after the hold settled = %q", got) + } + // An allocation for another Machine or consumer incarnation under the + // same names reports nothing for this Machine. + for _, label := range []string{fleetv1.LabelMachineUID, fleetv1.LabelConsumerUID} { + original := active.Labels[label] + active.Labels[label] = "00000000-0000-4000-8000-000000000999" + if err := provider.Update(ctx, active); err != nil { + t.Fatal(err) + } + if got := power(); got != "" { + t.Fatalf("power from an allocation with another %s = %q", label, got) + } + active.Labels[label] = original + if err := provider.Update(ctx, active); err != nil { + t.Fatal(err) + } + if got := power(); got != "On" { + t.Fatalf("power after restoring %s = %q", label, got) + } + } + active.Status.Phase = fleetv1.AllocationReleased + if err := provider.Update(ctx, active); err != nil { + t.Fatal(err) + } + if got := power(); got != "" { + t.Fatalf("power after release = %q", got) + } +} diff --git a/internal/manager/predicates.go b/internal/manager/predicates.go index 9a57dc43..7983382c 100644 --- a/internal/manager/predicates.go +++ b/internal/manager/predicates.go @@ -1,11 +1,9 @@ package manager import ( - "bytes" "encoding/json" "reflect" - corev1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" @@ -30,19 +28,6 @@ func PrimaryPredicate() predicate.Predicate { } } -func PrivateRecordPredicate() predicate.Predicate { - return predicate.Funcs{ - CreateFunc: func(event.CreateEvent) bool { return true }, - DeleteFunc: func(event.DeleteEvent) bool { return true }, - GenericFunc: func(event.GenericEvent) bool { return true }, - UpdateFunc: func(e event.UpdateEvent) bool { - oldSecret, oldOK := e.ObjectOld.(*corev1.Secret) - newSecret, newOK := e.ObjectNew.(*corev1.Secret) - return !oldOK || !newOK || oldSecret.UID != newSecret.UID || oldSecret.Type != newSecret.Type || !reflect.DeepEqual(oldSecret.Labels, newSecret.Labels) || !reflect.DeepEqual(oldSecret.DeletionTimestamp, newSecret.DeletionTimestamp) || !bytes.Equal(oldSecret.Data["record.json"], newSecret.Data["record.json"]) - }, - } -} - // DependencyPredicate includes relevant spec, status, labels, UID, finalizers, // and deletion changes while ignoring resourceVersion and managed-field noise. func DependencyPredicate() predicate.Predicate { diff --git a/internal/manager/projects.go b/internal/manager/projects.go index 5a602b1f..8a40a8ed 100644 --- a/internal/manager/projects.go +++ b/internal/manager/projects.go @@ -16,7 +16,7 @@ import ( // ErrProjectConflict reports two engaged clusters claiming one project // lifetime. The second engagement is refused rather than allowed to share -// private custody. +// custody. var ErrProjectConflict = errors.New("project lifetime is already engaged under another cluster name") var ErrProjectEngagementReentrant = errors.New("nested project engagement cannot wait on an active route") diff --git a/internal/manager/provider_consumer_test.go b/internal/manager/provider_consumer_test.go index 0e1f45ec..25e9fa5f 100644 --- a/internal/manager/provider_consumer_test.go +++ b/internal/manager/provider_consumer_test.go @@ -5,7 +5,6 @@ import ( "sync/atomic" "testing" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -18,8 +17,8 @@ import ( // A project that is both the synthetic provider and a metal consumer engages // like any other consumer: requested hardware only, no lifecycle effect, no -// MachineCapacity status write, and no cross-routing of the synthetic -// consumer's private records into it. Readiness passes with it engaged. +// MachineCapacity status write, and capacity events on its runtime resolve +// only to its own Machines. Readiness passes with it engaged. func TestProviderProjectEngagesAsAnOrdinaryConsumer(t *testing.T) { var capacityStatusWrites atomic.Int64 countCapacity := func(object client.Object) { @@ -47,15 +46,11 @@ func TestProviderProjectEngagesAsAnOrdinaryConsumer(t *testing.T) { }) consumer := newConsumer(t, "consumer", mcNamespace("consumer-ns"), mcMachine("m", "shared-uid", "general"), mcProfile("general", 1, 16, "64Gi")) root := newMilo(t, map[string]types.UID{"provider": "provider-project", "consumer": "consumer-project"}) - providerIdentity, consumerIdentity := root.identity(t, "provider"), root.identity(t, "consumer") - private := newPrivate(t) - // The synthetic consumer's retained custody names the provider project - // and the provider's MachineCapacity. - retainCustody(t, coordinatorFor(t, private), consumerIdentity, providerIdentity, getMachine(t, consumer, "m"), "consumer-ns") + providerIdentity := root.identity(t, "provider") discovery := multiclustertest.NewProvider() providerCluster := provider.NewCluster() - f := startFleet(t, discovery, root, private, SetupOptions{ + f := startFleet(t, discovery, root, SetupOptions{ ProviderProject: providerIdentity, ProviderCluster: providerCluster, ProviderVerifier: root.verifierFor(providerIdentity), @@ -72,25 +67,13 @@ func TestProviderProjectEngagesAsAnOrdinaryConsumer(t *testing.T) { t.Fatalf("readiness with the provider among the consumers: %v", err) } - // Deterministic routing: the consumer's custody reaches only the consumer, - // and a MachineCapacity event on the provider's engaged runtime resolves - // only to the provider's own Machines. - var secrets corev1.SecretList - if err := private.Client.List(context.Background(), &secrets, client.InNamespace(testPrivateNamespace)); err != nil || len(secrets.Items) != 1 { - t.Fatalf("custody records = %d, %v", len(secrets.Items), err) - } - routed := privateHandler(f.projects, testPrivateNamespace, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { return m.RequestForPrivate })(context.Background(), &secrets.Items[0]) - if len(routed) != 1 || routed[0].ClusterName != "consumer" { - t.Fatalf("custody routed to %#v, want only the consumer", routed) - } + // Deterministic routing: a MachineCapacity event on the provider's engaged + // runtime resolves only to the provider's own Machines. providerRuntime := f.projects.Get("provider") if providerRuntime == nil || !providerRuntime.Binding.Project.SameLifetime(providerIdentity) { t.Fatal("the provider project is not engaged under its own identity") } - if got := providerRuntime.Mappers.RequestForPrivate(context.Background(), &secrets.Items[0]); len(got) != 0 { - t.Fatalf("the provider runtime mapped the consumer's custody: %#v", got) - } - route := providerRuntime.Mappers.Route(RouteMachineCapacity, "")(context.Background(), getCapacity(t, provider)) + route := providerRuntime.Mappers.Route(RouteMachineCapacity)(context.Background(), getCapacity(t, provider)) if len(route) != 1 { t.Fatalf("capacity route = %#v", route) } @@ -112,10 +95,9 @@ func TestProviderProjectEngagesAsAnOrdinaryConsumer(t *testing.T) { } current := getCapacity(t, provider) informer.EmitUpdate(current, current) - privateWrites := private.Writes() consistently(t, "no lifecycle effect in the provider project", func() bool { m := getMachine(t, provider, "m") - return capacityStatusWrites.Load() == 0 && private.Writes() == privateWrites && len(m.Finalizers) == 0 && len(m.Status.Conditions) == 1 && m.Status.Phase == "" && len(getCapacity(t, provider).Status.Conditions) == 0 + return capacityStatusWrites.Load() == 0 && len(m.Finalizers) == 0 && len(m.Status.Conditions) == 1 && m.Status.Phase == "" && len(getCapacity(t, provider).Status.Conditions) == 0 }) } diff --git a/internal/manager/reconcilers.go b/internal/manager/reconcilers.go index c4816ae3..83f97fcd 100644 --- a/internal/manager/reconcilers.go +++ b/internal/manager/reconcilers.go @@ -86,7 +86,7 @@ func (r ProjectReconciler) Reconcile(ctx context.Context, request ProjectRequest // runtime engaged under its cluster name, and only when that runtime's // identity matches the request. A request for a project that is not engaged, // or whose cluster now holds another project lifetime, is dropped with no -// effect: no handler runs, no private record or status is written. +// effect: no handler runs, no custody or status is written. type ClusterProjectReconciler struct { Projects *Projects Owner func(*ProjectRuntime) *LifecycleOwner diff --git a/internal/manager/requested_hardware.go b/internal/manager/requested_hardware.go index 5064f2d5..ebaf6dc3 100644 --- a/internal/manager/requested_hardware.go +++ b/internal/manager/requested_hardware.go @@ -13,7 +13,7 @@ import ( // status.requestedHardware and the RequestResolved condition. The manager // builds one per engaged project, bound to that project's identity and // client. It reads the Machine and its MachineProfile and performs no -// allocation, provider, quota, or private-record effect, so it runs in every +// allocation, provider, quota, or custody effect, so it runs in every // configuration, including the default one whose lifecycle handlers are // blocked. type RequestedHardwareProjector struct { diff --git a/internal/manager/routing.go b/internal/manager/routing.go index b9660b07..11bea12a 100644 --- a/internal/manager/routing.go +++ b/internal/manager/routing.go @@ -7,11 +7,8 @@ import ( "strings" quotav1alpha1 "go.miloapis.com/milo/pkg/apis/quota/v1alpha1" - corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" @@ -33,10 +30,8 @@ const ( RouteInstallation RouteKind = "Installation" RouteMachine RouteKind = "Machine" RouteMachineCapacity RouteKind = "MachineCapacity" - RoutePrivateUID RouteKind = "PrivateUID" RouteNetwork RouteKind = "Network" RouteQuota RouteKind = "Quota" - RouteEntitlement RouteKind = "Entitlement" RouteLocation RouteKind = "Location" RouteAvailability RouteKind = "ServiceAvailability" ) @@ -53,7 +48,6 @@ type RouteRequest struct { Name string UID types.UID Key string - Field string // Deleted marks a snapshot delivered by an informer Delete event. The // snapshot's UID and routing fields describe the dependency lifetime that // disappeared, so resolution must not compare it with a same-name @@ -76,24 +70,23 @@ func (r RouteRequest) Valid() bool { return strings.TrimSpace(r.AuthorityID) != "" && r.ProjectUID != "" && r.Kind != "" && r.Name != "" && r.UID != "" } -func (m Mappers) Route(kind RouteKind, field string) func(context.Context, client.Object) []RouteRequest { +func (m Mappers) Route(kind RouteKind) func(context.Context, client.Object) []RouteRequest { return func(_ context.Context, object client.Object) []RouteRequest { if object == nil || !m.Project.Valid() { return nil } - request := RouteRequest{ClusterName: m.ClusterName, AuthorityID: m.Project.AuthorityID, ProjectUID: m.Project.UID, Kind: kind, Namespace: object.GetNamespace(), Name: object.GetName(), UID: object.GetUID(), Field: field} + request := RouteRequest{ClusterName: m.ClusterName, AuthorityID: m.Project.AuthorityID, ProjectUID: m.Project.UID, Kind: kind, Namespace: object.GetNamespace(), Name: object.GetName(), UID: object.GetUID()} switch kind { case RouteMachineCapacity: encoded, _ := json.Marshal(object.GetLabels()) request.Key = string(encoded) - case RoutePrivateUID: - request.Key = string(object.GetUID()) case RouteNetwork: request.Key = object.GetNamespace() + "/" + object.GetName() case RouteQuota: + // A quota claim names its Machine only by this label; a claim + // without it wakes nothing. request.Key = object.GetLabels()["fleet.datumapis.com/machine-uid"] - case RouteEntitlement: - if object.GetName() != milo.EntitlementName { + if request.Key == "" { return nil } case RouteLocation: @@ -141,38 +134,10 @@ func (m Mappers) ResolveRoute(ctx context.Context, route RouteRequest) ([]Projec return nil, ErrEventWiringUnavailable } return m.claimsForMachineE(ctx, &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: route.Namespace, Name: route.Name, UID: route.UID, Labels: eventLabels}}) - case RoutePrivateUID: - return m.claimsForPrivateFieldE(ctx, route.Field, route.Key) case RouteNetwork: - claims, err := m.claimsByFieldE(ctx, IndexClaimNetwork, route.Key) - if err != nil { - return nil, err - } - retained, err := m.claimsForPrivateFieldE(ctx, IndexPrivateNetworkUID, string(route.UID)) - return uniqueRequests(append(claims, retained...)), err + return m.claimsByFieldE(ctx, IndexClaimNetwork, route.Key) case RouteQuota: - claims, err := m.claimsForPrivateFieldE(ctx, IndexPrivateQuotaUID, string(route.UID)) - if err != nil { - return nil, err - } - if route.Key != "" { - byClaim, listErr := m.claimsForPrivateFieldE(ctx, IndexPrivateClaimUID, route.Key) - if listErr != nil { - return nil, listErr - } - claims = append(claims, byClaim...) - } - return uniqueRequests(claims), nil - case RouteEntitlement: - claims, err := m.claimsForPrivateFieldE(ctx, IndexPrivateEntitlementUID, string(route.UID)) - if err != nil { - return nil, err - } - byProject, listErr := m.claimsForPrivateFieldE(ctx, IndexPrivatePendingEntitlementProject, projectIndexKey(m.Project.AuthorityID, m.Project.UID)) - if listErr != nil { - return nil, listErr - } - return uniqueRequests(append(claims, byProject...)), nil + return m.claimsByFieldE(ctx, IndexClaimUID, route.Key) case RouteLocation, RouteAvailability: return m.claimsByFieldE(ctx, IndexClaimLocationName, route.Key) default: @@ -213,25 +178,10 @@ func routeObject(route RouteRequest) (client.Object, error) { return &fleetv1.Machine{}, nil case RouteMachineCapacity: return &fleetv1.MachineCapacity{}, nil - case RoutePrivateUID: - switch route.Field { - case IndexPrivateNamespaceUID: - return &corev1.Namespace{}, nil - case IndexPrivateNICClaimUID: - return &networkingv1.NetworkInterfaceClaim{}, nil - case IndexPrivateInterfaceUID: - return &networkingv1.NetworkInterface{}, nil - default: - return nil, ErrEventWiringUnavailable - } case RouteNetwork: return &networkingv1.Network{}, nil case RouteQuota: return "av1alpha1.ResourceClaim{}, nil - case RouteEntitlement: - object := &unstructured.Unstructured{} - object.SetGroupVersionKind(schema.GroupVersionKind{Group: "services.miloapis.com", Version: "v1alpha1", Kind: "ServiceEntitlement"}) - return object, nil case RouteLocation: return &locationsv1alpha1.Location{}, nil case RouteAvailability: diff --git a/internal/manager/setup.go b/internal/manager/setup.go index 93eed40f..42018bfc 100644 --- a/internal/manager/setup.go +++ b/internal/manager/setup.go @@ -5,9 +5,6 @@ import ( "time" quotav1alpha1 "go.miloapis.com/milo/pkg/apis/quota/v1alpha1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/util/workqueue" "k8s.io/utils/clock" "sigs.k8s.io/controller-runtime/pkg/cache" @@ -23,6 +20,8 @@ import ( mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" networkingv1 "go.datum.net/network-services-operator/api/v1alpha" @@ -40,8 +39,6 @@ type Handlers struct { // SetupOptions configures the manager's controllers. Projects are not part of // the options: they arrive through discovery, one ProjectRuntime each. type SetupOptions struct { - PrivateNamespace string - PrivateCluster ctrlcluster.Cluster // HandlersFor builds each engaged project's handlers. Projects with no // production or synthetic integration get blocked lifecycle handlers and // the requested-hardware projector. @@ -64,14 +61,6 @@ func ProjectCacheOptions() cache.Options { return cache.Options{SyncPeriod: &zero} } -// PrivateCacheOptions confines the host cache to the service-owned namespace. -// RBAC remains the authorization boundary; this scope prevents accidental host -// API watches and keeps private records out of the routed project cache. -func PrivateCacheOptions(privateNamespace string) cache.Options { - zero := time.Duration(0) - return cache.Options{SyncPeriod: &zero, DefaultNamespaces: map[string]cache.Config{privateNamespace: {}}} -} - // NewProjects returns the engaged-project registry. resolve turns a cluster // name into its Milo project identity; verifierFor returns the per-project // verifier run before every reconcile. Pass its Aware method to @@ -95,19 +84,13 @@ var providerClustersOnly = []mcbuilder.EngageOptions{mcbuilder.WithEngageWithLoc // carries its cluster name and is reconciled only through that project's // runtime, with that project's identity, client, and verifier. func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, options SetupOptions) error { - if mgr == nil || projects == nil || projects.resolve == nil || projects.verifierFor == nil || options.PrivateCluster == nil || options.PrivateNamespace == "" || options.HandlersFor == nil { + if mgr == nil || projects == nil || projects.resolve == nil || projects.verifierFor == nil || options.HandlersFor == nil { return ErrEventWiringUnavailable } if err := RegisterProjectIndexes(ctx, mgr.GetFieldIndexer()); err != nil { return err } - if err := RegisterPrivateIndexes(ctx, options.PrivateCluster.GetFieldIndexer(), options.PrivateNamespace); err != nil { - return err - } local := mgr.GetLocalManager() - if err := local.Add(options.PrivateCluster); err != nil { - return err - } if options.ProviderCluster != nil { // The synthetic consumer must never be the provider; the provider may // still be engaged as an ordinary consumer. @@ -141,7 +124,6 @@ func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, optio if err := local.Add(installationDeadlines); err != nil { return err } - privateReader := options.PrivateCluster.GetCache() projects.mu.Lock() projects.build = func(binding ProjectBinding, reader client.Reader, verifier ProjectVerifier) (*ProjectRuntime, error) { if reader == nil || verifier == nil || binding.Client == nil { @@ -151,8 +133,8 @@ func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, optio // It engages like any other consumer: HandlersFor gives it blocked // lifecycle handlers and the projector, because only the configured // synthetic consumer (never the provider) gets the staging handler. - // Its engaged runtime only maps its own Machines and private records - // whose consumer is this project, so provider MachineCapacity events + // Its engaged runtime only maps its own Machines, so provider + // MachineCapacity events // on its runtime cannot reach the synthetic consumer's claims, and its // blocked handlers never write MachineCapacity status. handlers, err := options.HandlersFor(binding) @@ -166,7 +148,7 @@ func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, optio Binding: binding, Reader: reader, Verifier: verifier, - Mappers: Mappers{Reader: reader, PrivateReader: privateReader, Project: binding.Project, PrivateNamespace: options.PrivateNamespace, ClusterName: binding.ClusterName}, + Mappers: Mappers{Reader: reader, Project: binding.Project, ClusterName: binding.ClusterName}, Machine: NewLifecycleOwner(handlers.Machine, handlers.MachineProjector, claimDeadlines), Installation: NewLifecycleOwner(handlers.Installation, handlers.InstallationProjector, installationDeadlines), }, nil @@ -175,39 +157,37 @@ func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, optio machineOwner := func(r *ProjectRuntime) *LifecycleOwner { return r.Machine } installationOwner := func(r *ProjectRuntime) *LifecycleOwner { return r.Installation } - entitlement := &unstructured.Unstructured{} - entitlement.SetGroupVersionKind(schema.GroupVersionKind{Group: "services.miloapis.com", Version: "v1alpha1", Kind: "ServiceEntitlement"}) - privateSecrets := options.PrivateCluster.GetCache() claim := mcbuilder.TypedControllerManagedBy[ProjectRequest](mgr). Named("fleet-machine-events"). Watches(&fleetv1.Machine{}, projectHandler(projects, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { return m.RequestFor }), watchOptions(PrimaryPredicate())...). - WatchesRawSource(source.TypedKind(privateSecrets, client.Object(&corev1.Secret{}), typedMap(privateHandler(projects, options.PrivateNamespace, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { return m.RequestForPrivate })), PrivateRecordPredicate())). WatchesRawSource(deadlineSource(claimDeadlineEvents)) if err := claim.Complete(ClusterProjectReconciler{Projects: projects, Owner: machineOwner}); err != nil { return err } claimRoutes := mcbuilder.TypedControllerManagedBy[RouteRequest](mgr). Named("fleet-machine-routes"). - Watches(&fleetv1.MachineClass{}, routeHandler(projects, RouteClass, ""), watchOptions(DependencyPredicate())...). - Watches(&fleetv1.MachineProfile{}, routeHandler(projects, RouteProfile, ""), watchOptions(DependencyPredicate())...). - Watches(&fleetv1.Installation{}, routeHandler(projects, RouteInstallation, ""), watchOptions(PrimaryPredicate())...). - Watches(&fleetv1.MachineCapacity{}, routeHandler(projects, RouteMachineCapacity, ""), watchOptions(DependencyPredicate())...). - Watches(&corev1.Namespace{}, routeHandler(projects, RoutePrivateUID, IndexPrivateNamespaceUID), watchOptions(DependencyPredicate())...). - Watches(&networkingv1.Network{}, routeHandler(projects, RouteNetwork, ""), watchOptions(DependencyPredicate())...). - Watches(&networkingv1.NetworkInterfaceClaim{}, routeHandler(projects, RoutePrivateUID, IndexPrivateNICClaimUID), watchOptions(DependencyPredicate())...). - Watches(&networkingv1.NetworkInterface{}, routeHandler(projects, RoutePrivateUID, IndexPrivateInterfaceUID), watchOptions(DependencyPredicate())...). - Watches("av1alpha1.ResourceClaim{}, routeHandler(projects, RouteQuota, ""), watchOptions(DependencyPredicate())...). - Watches(entitlement, routeHandler(projects, RouteEntitlement, ""), watchOptions(DependencyPredicate())...). - Watches(&locationsv1alpha1.Location{}, routeHandler(projects, RouteLocation, ""), watchOptions(DependencyPredicate())...). - Watches(&servicesv1alpha1.ServiceAvailability{}, routeHandler(projects, RouteAvailability, ""), watchOptions(DependencyPredicate())...) + Watches(&fleetv1.MachineClass{}, routeHandler(projects, RouteClass), watchOptions(DependencyPredicate())...). + Watches(&fleetv1.MachineProfile{}, routeHandler(projects, RouteProfile), watchOptions(DependencyPredicate())...). + Watches(&fleetv1.Installation{}, routeHandler(projects, RouteInstallation), watchOptions(PrimaryPredicate())...). + Watches(&fleetv1.MachineCapacity{}, routeHandler(projects, RouteMachineCapacity), watchOptions(DependencyPredicate())...). + Watches(&networkingv1.Network{}, routeHandler(projects, RouteNetwork), watchOptions(DependencyPredicate())...). + Watches("av1alpha1.ResourceClaim{}, routeHandler(projects, RouteQuota), watchOptions(DependencyPredicate())...). + Watches(&locationsv1alpha1.Location{}, routeHandler(projects, RouteLocation), watchOptions(DependencyPredicate())...). + Watches(&servicesv1alpha1.ServiceAvailability{}, routeHandler(projects, RouteAvailability), watchOptions(DependencyPredicate())...) if err := claimRoutes.Complete(ClusterRouteReconciler{Projects: projects, Owner: machineOwner}); err != nil { return err } if options.ProviderCluster != nil { providerEvents := mcbuilder.TypedControllerManagedBy[ProviderEventRequest](mgr). Named("fleet-provider-machinecapacity-events"). - WatchesRawSource(source.TypedKind(options.ProviderCluster.GetCache(), client.Object(&fleetv1.MachineCapacity{}), typedProviderEventMap(options.ProviderProject), DependencyPredicate())) + WatchesRawSource(source.TypedKind(options.ProviderCluster.GetCache(), client.Object(&fleetv1.MachineCapacity{}), typedProviderEventMap(options.ProviderProject), DependencyPredicate())). + // Custody, allocation and Device changes wake the consumer's + // Machines, so the power projector reports a recovery hold or a + // discovered power change without a Machine event. + WatchesRawSource(source.TypedKind(options.ProviderCluster.GetCache(), client.Object(&ops.DeviceCustody{}), typedProviderEventMap(options.ProviderProject), DependencyPredicate())). + WatchesRawSource(source.TypedKind(options.ProviderCluster.GetCache(), client.Object(&fleetv1.MachineAllocation{}), typedProviderEventMap(options.ProviderProject), DependencyPredicate())). + WatchesRawSource(source.TypedKind(options.ProviderCluster.GetCache(), client.Object(&inventory.Device{}), typedProviderEventMap(options.ProviderProject), DependencyPredicate())) if err := providerEvents.Complete(ClusterProviderEventReconciler{Projects: projects, Consumer: options.ProviderConsumer, Provider: options.ProviderProject, ProviderVerifier: options.ProviderVerifier}); err != nil { return err } @@ -215,16 +195,13 @@ func Setup(ctx context.Context, mgr mcmanager.Manager, projects *Projects, optio installation := mcbuilder.TypedControllerManagedBy[ProjectRequest](mgr). Named("fleet-installation-events"). Watches(&fleetv1.Installation{}, projectHandler(projects, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { return m.RequestFor }), watchOptions(PrimaryPredicate())...). - WatchesRawSource(source.TypedKind(privateSecrets, client.Object(&corev1.Secret{}), typedMap(privateHandler(projects, options.PrivateNamespace, func(m Mappers) func(context.Context, client.Object) []ProjectRequest { - return m.RequestForPrivateInstallation - })), PrivateRecordPredicate())). WatchesRawSource(deadlineSource(installationDeadlineEvents)) if err := installation.Complete(ClusterProjectReconciler{Projects: projects, Owner: installationOwner}); err != nil { return err } installationRoutes := mcbuilder.TypedControllerManagedBy[RouteRequest](mgr). Named("fleet-installation-routes"). - Watches(&fleetv1.Machine{}, routeHandler(projects, RouteMachine, ""), watchOptions(PrimaryPredicate())...) + Watches(&fleetv1.Machine{}, routeHandler(projects, RouteMachine), watchOptions(PrimaryPredicate())...) return installationRoutes.Complete(ClusterRouteReconciler{Projects: projects, Owner: installationOwner}) } @@ -250,39 +227,18 @@ func projectHandler(projects *Projects, mapper func(Mappers) func(context.Contex } } -func routeHandler(projects *Projects, kind RouteKind, field string) mchandler.TypedEventHandlerFunc[client.Object, RouteRequest] { +func routeHandler(projects *Projects, kind RouteKind) mchandler.TypedEventHandlerFunc[client.Object, RouteRequest] { return func(name multicluster.ClusterName, _ ctrlcluster.Cluster) handler.TypedEventHandler[client.Object, RouteRequest] { return typedRouteMap(func(ctx context.Context, object client.Object) []RouteRequest { runtime := projects.Get(name) if runtime == nil { return nil } - return runtime.Mappers.Route(kind, field)(ctx, object) + return runtime.Mappers.Route(kind)(ctx, object) }) } } -// privateHandler routes a private record by the exact consumer project -// lifetime it records. It reaches only the runtime engaged for that lifetime; -// records of a project that is not engaged map to nothing. -func privateHandler(projects *Projects, privateNamespace string, mapper func(Mappers) func(context.Context, client.Object) []ProjectRequest) func(context.Context, client.Object) []ProjectRequest { - return func(ctx context.Context, object client.Object) []ProjectRequest { - secret, ok := object.(*corev1.Secret) - if !ok { - return nil - } - route, ok := routePrivate(secret, privateNamespace) - if !ok { - return nil - } - runtime := projects.ForProject(route.ConsumerProject.AuthorityID, route.ConsumerProject.UID) - if runtime == nil { - return nil - } - return mapper(runtime.Mappers)(ctx, object) - } -} - func deadlineEmitter(ctx context.Context, events chan<- event.TypedGenericEvent[ProjectRequest]) func(ProjectRequest) { return func(request ProjectRequest) { select { @@ -301,10 +257,6 @@ func deadlineSource(events <-chan event.TypedGenericEvent[ProjectRequest]) sourc })) } -func typedMap(fn func(context.Context, client.Object) []ProjectRequest) handler.TypedEventHandler[client.Object, ProjectRequest] { - return handler.TypedEnqueueRequestsFromMapFunc(fn) -} - func typedRouteMap(fn func(context.Context, client.Object) []RouteRequest) handler.TypedEventHandler[client.Object, RouteRequest] { mapObject := func(ctx context.Context, object client.Object, deleted bool) []RouteRequest { requests := fn(ctx, object) diff --git a/internal/milo/adapter.go b/internal/milo/adapter.go deleted file mode 100644 index c26db79e..00000000 --- a/internal/milo/adapter.go +++ /dev/null @@ -1,710 +0,0 @@ -package milo - -import ( - "context" - "errors" - "fmt" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - fleetnetwork "go.datum.net/fleet/internal/network" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" -) - -type Adapter struct { - Records *RecordStore - Projects ProjectResolver - Sources SourceAuthorizer - Entitlements EntitlementReader - Fence AdmissionFence - Custodian QuotaCustodian - Lifecycle *controller.Coordinator - afterLifecycleAllocate func() - afterAbortedHoldClear func() - afterAuthorityCreate func() error - afterCustodyEnsure func() error -} - -type PrepareRequest struct { - ConsumerRoute string - ProviderRoute string - NamespaceUID types.UID - Claim *fleetv1.Machine - LocalClass *fleetv1.MachineClass - SourceClass *fleetv1.MachineClass - LocalProfile *fleetv1.MachineProfile - SourceProfile *fleetv1.MachineProfile - PublicationRevision string - Location fleetnetwork.LocationAuthority -} - -type PreparedClaim struct { - Authority controller.AuthorityRef - ConsumerProject controller.ProjectIdentity - ProviderProject controller.ProjectIdentity - NamespaceUID types.UID - PrincipalUID string - DecisionID string - LocalClassName string - LocalClassUID types.UID - SourceClassUID types.UID - LocalProfileName string - LocalProfileUID types.UID - SourceProfileUID types.UID - Location fleetnetwork.LocationAuthority -} - -func (a *Adapter) PrepareClaim(ctx context.Context, request PrepareRequest) (PreparedClaim, error) { - if a == nil || a.Records == nil || a.Projects == nil || a.Lifecycle == nil || a.Sources == nil { - return PreparedClaim{}, ErrAuthorityUnavailable - } - if request.Claim == nil || request.LocalClass == nil || request.SourceClass == nil || request.LocalProfile == nil || request.NamespaceUID == "" || request.Claim.UID == "" || request.ConsumerRoute == "" || request.ProviderRoute == "" || request.PublicationRevision == "" || !request.Location.Valid() || request.Claim.Spec.LocationRef.Name != request.Location.Name { - return PreparedClaim{}, ErrAuthorityInvalid - } - if request.LocalClass.Name != request.Claim.Spec.MachineClassRef.Name || request.LocalProfile.Name != request.Claim.Spec.MachineProfileRef.Name { - return PreparedClaim{}, ErrAuthorityInvalid - } - if request.LocalClass.Spec.Source == nil { - if request.ConsumerRoute != request.ProviderRoute || request.LocalClass.UID != request.SourceClass.UID || request.LocalClass.Name != request.SourceClass.Name { - return PreparedClaim{}, ErrAuthorityInvalid - } - } else if request.LocalClass.Spec.Source.Project != request.ProviderRoute || request.LocalClass.Spec.Source.Name != request.SourceClass.Name { - return PreparedClaim{}, ErrAuthorityInvalid - } - consumer, _, err := a.Projects.Resolve(ctx, request.ConsumerRoute) - if err != nil { - return PreparedClaim{}, err - } - provider, _, err := a.Projects.Resolve(ctx, request.ProviderRoute) - if err != nil { - return PreparedClaim{}, err - } - if !consumer.Valid() || !provider.Valid() || consumer.RouteName != request.ConsumerRoute || provider.RouteName != request.ProviderRoute { - return PreparedClaim{}, ErrProjectLifetimeMismatch - } - if err := a.Projects.Verify(ctx, consumer); err != nil { - return PreparedClaim{}, ErrProjectLifetimeMismatch - } - if err := a.Projects.Verify(ctx, provider); err != nil { - return PreparedClaim{}, ErrProjectLifetimeMismatch - } - requirements, err := requirementsDigest(request.LocalProfile) - if err != nil { - return PreparedClaim{}, err - } - classDigest, err := digest(request.SourceClass.Spec) - if err != nil { - return PreparedClaim{}, err - } - kind := ProfileCustom - var sourceProfileUID types.UID - if request.SourceProfile != nil { - kind, sourceProfileUID = ProfilePublished, request.SourceProfile.UID - sourceDigest, err := requirementsDigest(request.SourceProfile) - if err != nil || sourceDigest != requirements { - return PreparedClaim{}, ErrAuthorityInvalid - } - } - source := SourceUseRequest{ConsumerProject: consumer, ProviderProject: provider, NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, LocalClassUID: request.LocalClass.UID, SourceClassUID: request.SourceClass.UID, SourceClassRevision: request.SourceClass.Status.EvaluatedRevision, SourceClassDigest: classDigest, LocalProfileUID: request.LocalProfile.UID, SourceProfileUID: sourceProfileUID, ProfileKind: kind, RequirementsDigest: requirements, PublicationRevision: request.PublicationRevision, Location: request.Location} - if err := source.Validate(); err != nil { - return PreparedClaim{}, err - } - receipt, err := a.Sources.AuthorizeSource(ctx, source) - if err != nil { - return PreparedClaim{}, fmt.Errorf("%w: %v", ErrAuthorityUnavailable, err) - } - if err := validateReceipt(source, receipt); err != nil { - return PreparedClaim{}, err - } - contract := struct { - Request SourceUseRequest `json:"request"` - Receipt SourceUseReceipt `json:"receipt"` - }{source, receipt} - contractDigest, err := digest(contract) - if err != nil { - return PreparedClaim{}, err - } - record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: shortDigest(contractDigest + "/" + string(request.Claim.UID)), State: StatePrepared, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, SourceRequest: source, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: request.LocalProfile.Spec} - ref, err := a.Records.Create(ctx, record) - if err != nil { - return PreparedClaim{}, err - } - if a.afterAuthorityCreate != nil { - if err := a.afterAuthorityCreate(); err != nil { - return PreparedClaim{}, err - } - } - admission := controller.AdmissionAuthority{PrincipalUID: receipt.PrincipalUID, DecisionID: receipt.DecisionID} - if err := a.Lifecycle.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, admission, consumer); err != nil { - return PreparedClaim{}, err - } - if a.afterCustodyEnsure != nil { - if err := a.afterCustodyEnsure(); err != nil { - return PreparedClaim{}, err - } - } - if err := a.Lifecycle.RetainClaimAuthority(ctx, request.Claim.UID, consumer, provider, ref); err != nil { - return PreparedClaim{}, err - } - return PreparedClaim{Authority: ref, ConsumerProject: consumer, ProviderProject: provider, NamespaceUID: request.NamespaceUID, PrincipalUID: receipt.PrincipalUID, DecisionID: receipt.DecisionID, LocalClassName: request.LocalClass.Name, LocalClassUID: request.LocalClass.UID, SourceClassUID: request.SourceClass.UID, LocalProfileName: request.LocalProfile.Name, LocalProfileUID: request.LocalProfile.UID, SourceProfileUID: sourceProfileUID, Location: request.Location}, nil -} - -// PrepareOrRecoverClaim returns the same durable prepared authority after a -// manager restart or finalizer event. Recovery validates current resolved -// inputs against the immutable authority record and never re-authorizes with a -// potentially different caller receipt. -func (a *Adapter) PrepareOrRecoverClaim(ctx context.Context, request PrepareRequest) (PreparedClaim, error) { - if a == nil || a.Records == nil || a.Projects == nil || a.Lifecycle == nil || request.Claim == nil || request.Claim.UID == "" || request.ConsumerRoute == "" { - return PreparedClaim{}, ErrAuthorityInvalid - } - consumer, _, err := a.Projects.Resolve(ctx, request.ConsumerRoute) - if err != nil { - return PreparedClaim{}, err - } - if !consumer.Valid() || consumer.RouteName != request.ConsumerRoute || a.Projects.Verify(ctx, consumer) != nil { - return PreparedClaim{}, ErrProjectLifetimeMismatch - } - record, ref, err := a.Records.GetForClaim(ctx, consumer, request.Claim.UID) - if apierrors.IsNotFound(err) { - hasCustody, custodyErr := a.Lifecycle.HasClaimCustody(ctx, consumer, request.Claim.UID) - if custodyErr != nil { - return PreparedClaim{}, custodyErr - } - if hasCustody { - return PreparedClaim{}, controller.ErrRecordInvalid - } - return a.PrepareClaim(ctx, request) - } - if err != nil { - return PreparedClaim{}, err - } - provider, _, err := a.Projects.Resolve(ctx, request.ProviderRoute) - if err != nil || !provider.Valid() || provider.RouteName != request.ProviderRoute || a.Projects.Verify(ctx, provider) != nil { - return PreparedClaim{}, ErrProjectLifetimeMismatch - } - if err := validateRecoveredPrepare(record, request, consumer, provider); err != nil { - return PreparedClaim{}, err - } - admission := controller.AdmissionAuthority{PrincipalUID: record.SourceReceipt.PrincipalUID, DecisionID: record.SourceReceipt.DecisionID} - if err := a.Lifecycle.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, admission, consumer); err != nil { - return PreparedClaim{}, err - } - if err := a.Lifecycle.RetainClaimAuthority(ctx, request.Claim.UID, consumer, provider, ref); err != nil { - return PreparedClaim{}, err - } - return PreparedClaim{ - Authority: ref, ConsumerProject: consumer, ProviderProject: provider, - NamespaceUID: request.NamespaceUID, PrincipalUID: record.SourceReceipt.PrincipalUID, DecisionID: record.SourceReceipt.DecisionID, - LocalClassName: request.LocalClass.Name, LocalClassUID: request.LocalClass.UID, SourceClassUID: request.SourceClass.UID, - LocalProfileName: request.LocalProfile.Name, LocalProfileUID: request.LocalProfile.UID, SourceProfileUID: record.SourceRequest.SourceProfileUID, - Location: request.Location, - }, nil -} - -func validateRecoveredPrepare(record *AuthorityRecord, request PrepareRequest, consumer, provider controller.ProjectIdentity) error { - if record == nil || request.Claim == nil || request.LocalClass == nil || request.SourceClass == nil || request.LocalProfile == nil || request.NamespaceUID == "" || request.PublicationRevision == "" || !request.Location.Valid() { - return ErrAuthorityInvalid - } - if record.ClaimNamespace != request.Claim.Namespace || record.ClaimName != request.Claim.Name || record.ClaimUID != request.Claim.UID || request.LocalClass.Name != request.Claim.Spec.MachineClassRef.Name || request.LocalProfile.Name != request.Claim.Spec.MachineProfileRef.Name { - return ErrAuthorityInvalid - } - if request.LocalClass.Spec.Source == nil { - if consumer != provider || request.LocalClass.UID != request.SourceClass.UID || request.LocalClass.Name != request.SourceClass.Name { - return ErrAuthorityInvalid - } - } else if request.LocalClass.Spec.Source.Project != request.ProviderRoute || request.LocalClass.Spec.Source.Name != request.SourceClass.Name { - return ErrAuthorityInvalid - } - requirements, err := requirementsDigest(request.LocalProfile) - if err != nil { - return err - } - classDigest, err := digest(request.SourceClass.Spec) - if err != nil { - return err - } - kind := ProfileCustom - var sourceProfileUID types.UID - if request.SourceProfile != nil { - kind, sourceProfileUID = ProfilePublished, request.SourceProfile.UID - sourceRequirements, sourceErr := requirementsDigest(request.SourceProfile) - if sourceErr != nil || sourceRequirements != requirements { - return ErrAuthorityInvalid - } - } - want := SourceUseRequest{ConsumerProject: consumer, ProviderProject: provider, NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, LocalClassUID: request.LocalClass.UID, SourceClassUID: request.SourceClass.UID, SourceClassRevision: request.SourceClass.Status.EvaluatedRevision, SourceClassDigest: classDigest, LocalProfileUID: request.LocalProfile.UID, SourceProfileUID: sourceProfileUID, ProfileKind: kind, RequirementsDigest: requirements, PublicationRevision: request.PublicationRevision, Location: request.Location} - if want.Validate() != nil || !sameLocationLifetime(record.SourceRequest.Location, want.Location) { - return ErrAuthorityInvalid - } - // A location revision is current eligibility evidence, not the location's - // lifetime identity. Preserve the admitted revision in the durable record, - // but do not strand an existing claim when Ready or ServiceAvailability - // status is re-observed for the same named Location UID. - want.Location.Revision = record.SourceRequest.Location.Revision - // MachineClass revision and content are mutable policy on one provider-owned - // class lifetime. The current resolver has already re-read that object; keep - // the originally admitted evidence in the record while allowing the same - // class UID to progress under its current authoritative policy. - want.SourceClassRevision = record.SourceRequest.SourceClassRevision - want.SourceClassDigest = record.SourceRequest.SourceClassDigest - if record.SourceRequest != want { - return ErrAuthorityInvalid - } - return nil -} - -func sameLocationLifetime(left, right fleetnetwork.LocationAuthority) bool { - return left.Name != "" && left.UID != "" && left.Name == right.Name && left.UID == right.UID -} - -// ReleaseClaim recovers release authority using only the exact consumer project -// and claim lifetime. Public claim/class/profile objects may already be gone. -func (a *Adapter) ReleaseClaim(ctx context.Context, consumer controller.ProjectIdentity, claimUID types.UID) (controller.ReleaseResult, error) { - if a == nil || a.Records == nil || a.Lifecycle == nil || !consumer.Valid() || claimUID == "" { - return controller.ReleaseResult{}, ErrAuthorityInvalid - } - record, ref, err := a.Records.GetForClaim(ctx, consumer, claimUID) - if apierrors.IsNotFound(err) { - hasCustody, custodyErr := a.Lifecycle.HasClaimCustody(ctx, consumer, claimUID) - if custodyErr != nil { - return controller.ReleaseResult{}, custodyErr - } - if hasCustody { - return controller.ReleaseResult{}, controller.ErrRecordInvalid - } - return controller.ReleaseResult{}, ErrClaimAuthorityNotFound - } - if err != nil { - return controller.ReleaseResult{}, err - } - return a.Release(ctx, PreparedClaim{Authority: ref, ConsumerProject: record.SourceRequest.ConsumerProject}, claimUID) -} - -func (a *Adapter) Allocate(ctx context.Context, prepared PreparedClaim, request controller.AllocationRequest) (*controller.AssetRecord, error) { - if a == nil || a.Records == nil || a.Projects == nil || a.Lifecycle == nil { - return nil, ErrAuthorityInvalid - } - if a.Fence == nil { - return nil, ErrAdmissionFenceUnavailable - } - if a.Custodian == nil { - return nil, ErrQuotaCustodyUnavailable - } - if a.Entitlements == nil { - return nil, ErrQuotaUnknown - } - record, err := a.Records.Get(ctx, prepared.Authority) - if err != nil { - return nil, err - } - if err := validatePreparedAllocation(record, prepared, request); err != nil { - return nil, ErrAuthorityInvalid - } - if request.Claim.DeletionTimestamp != nil || !containsFinalizer(request.Claim.Finalizers, controller.MachineFinalizer) { - return nil, ErrAuthorityInvalid - } - switch record.State { - case StateReleased, StateCleanupVerified, StateQuarantined: - return nil, ErrAuthorityInvalid - case StateQuotaReleasePending: - if record.QuotaHold == nil || record.AssetID != "" { - return nil, ErrAuthorityInvalid - } - if record.Settlement == nil { - receipt, settleErr := a.Custodian.Settle(ctx, record.SourceRequest.ConsumerProject, prepared.Authority, *record.QuotaHold) - if settleErr != nil || !validSettlement(prepared.Authority, *record.QuotaHold, receipt) { - return nil, ErrQuotaReleaseUnknown - } - if _, err := a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.Settlement != nil || current.QuotaHold == nil || *current.QuotaHold != *record.QuotaHold || current.AssetID != "" { - return ErrAuthorityInvalid - } - current.Settlement = &receipt - return nil - }); err != nil { - return nil, err - } - record.Settlement = &receipt - } - if err := a.finishAbortedSettlement(ctx, prepared.Authority, *record.QuotaHold, *record.Settlement); err != nil { - return nil, err - } - return nil, ErrQuotaPending - case StatePrepared, StateQuotaIntent, StateQuotaGranted, StateBound: - default: - return nil, ErrAuthorityInvalid - } - consumer, consumerClient, err := a.Projects.Resolve(ctx, prepared.ConsumerProject.RouteName) - if err != nil || consumer != prepared.ConsumerProject || a.Projects.Verify(ctx, consumer) != nil { - return nil, ErrProjectLifetimeMismatch - } - provider, _, err := a.Projects.Resolve(ctx, prepared.ProviderProject.RouteName) - if err != nil || provider != prepared.ProviderProject || a.Projects.Verify(ctx, provider) != nil { - return nil, ErrProjectLifetimeMismatch - } - request.NamespaceUID = prepared.NamespaceUID - request.Admission = controller.AdmissionAuthority{PrincipalUID: prepared.PrincipalUID, DecisionID: prepared.DecisionID} - request.LocalClassName, request.LocalClassUID = prepared.LocalClassName, prepared.LocalClassUID - request.LocalProfileName, request.LocalProfileUID = prepared.LocalProfileName, prepared.LocalProfileUID - request.ConsumerProject, request.ProviderProject, request.Authority = consumer, provider, prepared.Authority - request.Location = prepared.Location - if len(request.Claim.Spec.NetworkInterfaces) != 0 { - return nil, fmt.Errorf("%w: Milo adapter does not yet compose network admission into its fence", controller.ErrUnsupported) - } - if record.QuotaHold != nil && record.FenceReceipt != nil && (record.State == StateQuotaGranted || record.State == StateBound) { - request.ExternalHold = record.QuotaHold.Ref() - asset, allocateErr := a.Lifecycle.Allocate(ctx, request) - if allocateErr != nil { - return nil, allocateErr - } - if _, err := a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaGranted && current.State != StateBound { - return ErrAuthorityInvalid - } - if current.Settlement != nil { - return ErrAuthorityInvalid - } - current.State, current.AssetID, current.BindingID = StateBound, asset.AssetID, asset.BindingID - return nil - }); err != nil { - return nil, err - } - return asset, nil - } - if err := a.Lifecycle.CheckCapacity(request); err != nil { - return nil, err - } - // Do not create an external hold after release has made this claim lifetime - // terminal. RetainAllocationAuthority repeats this check after Acquire to - // close the race between this proof and the external effect. - if err := a.Lifecycle.VerifyAllocationAuthority(ctx, request.Claim.UID, consumer, provider, prepared.Authority); err != nil { - return nil, err - } - entitlement, err := a.Entitlements.Current(ctx, consumerClient) - if err != nil { - return nil, err - } - intent := QuotaIntentFor(consumer, request.Claim.Namespace, request.Claim.Name, request.Claim.UID) - if record.QuotaIntent == nil { - record, err = a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StatePrepared { - return ErrAuthorityInvalid - } - current.State, current.QuotaIntent, current.Entitlement, current.Settlement = StateQuotaIntent, &intent, &entitlement, nil - return nil - }) - if err != nil { - return nil, err - } - } else if *record.QuotaIntent != intent { - return nil, ErrAuthorityInvalid - } - hold, granted, acquireErr := a.Custodian.Acquire(ctx, consumer, prepared.Authority, intent) - if hold.UID != "" { - record, err = a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaIntent && current.State != StateQuotaGranted { - return ErrAuthorityInvalid - } - if current.QuotaIntent == nil || *current.QuotaIntent != intent { - return ErrAuthorityInvalid - } - if current.QuotaHold != nil && *current.QuotaHold != hold { - return ErrAuthorityInvalid - } - current.QuotaHold, current.Entitlement = &hold, &entitlement - if granted { - current.State = StateQuotaGranted - } - return nil - }) - if err != nil { - return nil, err - } - } - if acquireErr != nil { - return nil, acquireErr - } - if !granted || hold.UID == "" { - return nil, ErrQuotaPending - } - request.ExternalHold = hold.Ref() - if err := a.Lifecycle.RetainAllocationAuthority(ctx, request.Claim.UID, consumer, provider, prepared.Authority, hold.Ref()); err != nil { - return nil, a.settleAfterFailedAdmission(ctx, consumer, prepared.Authority, hold, err) - } - commit := AdmissionCommit{Authority: prepared.Authority, SourceUse: record.SourceRequest, Source: record.SourceReceipt, Entitlement: entitlement, Hold: hold} - commitDigest, err := digest(commit) - if err != nil { - return nil, err - } - fenceReceipt, err := a.Fence.Commit(ctx, commit) - if err != nil { - return nil, a.settleAfterFailedAdmission(ctx, consumer, prepared.Authority, hold, err) - } - if fenceReceipt.ContractDigest != prepared.Authority.ContractDigest || fenceReceipt.CommitDigest != commitDigest || fenceReceipt.FenceToken != record.SourceReceipt.FenceToken || fenceReceipt.CommitID == "" { - return nil, a.settleAfterFailedAdmission(ctx, consumer, prepared.Authority, hold, ErrAuthorityInvalid) - } - if _, err := a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaGranted || current.Settlement != nil { - return ErrAuthorityInvalid - } - current.FenceReceipt = &fenceReceipt - return nil - }); err != nil { - return nil, err - } - asset, err := a.Lifecycle.Allocate(ctx, request) - if err != nil { - if errors.Is(err, controller.ErrInsufficientCapacity) { - return nil, a.settleAfterFailedAdmission(ctx, consumer, prepared.Authority, hold, err) - } - return nil, err - } - if a.afterLifecycleAllocate != nil { - a.afterLifecycleAllocate() - } - if _, err := a.Records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaGranted || current.Settlement != nil || current.FenceReceipt == nil { - return ErrAuthorityInvalid - } - current.State, current.AssetID, current.BindingID = StateBound, asset.AssetID, asset.BindingID - return nil - }); err != nil { - return nil, err - } - return asset, nil -} - -func containsFinalizer(values []string, wanted string) bool { - for _, value := range values { - if value == wanted { - return true - } - } - return false -} - -func (a *Adapter) settleAfterFailedAdmission(ctx context.Context, consumer controller.ProjectIdentity, authority controller.AuthorityRef, hold QuotaHold, cause error) error { - if _, err := a.Records.Update(ctx, authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaGranted { - return ErrAuthorityInvalid - } - current.State = StateQuotaReleasePending - return nil - }); err != nil { - return err - } - receipt, err := a.Custodian.Settle(ctx, consumer, authority, hold) - if err != nil { - return errors.Join(cause, ErrQuotaReleaseUnknown, err) - } - if !validSettlement(authority, hold, receipt) { - return errors.Join(cause, ErrQuotaReleaseUnknown) - } - if _, err := a.Records.Update(ctx, authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.QuotaHold == nil || *current.QuotaHold != hold || current.Settlement != nil || current.AssetID != "" { - return ErrAuthorityInvalid - } - current.Settlement = &receipt - return nil - }); err != nil { - return err - } - if err := a.finishAbortedSettlement(ctx, authority, hold, receipt); err != nil { - return err - } - return cause -} - -func (a *Adapter) finishAbortedSettlement(ctx context.Context, authority controller.AuthorityRef, hold QuotaHold, receipt SettlementReceipt) error { - if !validSettlement(authority, hold, receipt) { - return ErrQuotaReleaseUnknown - } - if err := a.Lifecycle.ClearSettledExternalHold(ctx, hold.Intent.ClaimUID, authority, hold.Ref(), hold.Intent.ConsumerProject); err != nil { - return err - } - if a.afterAbortedHoldClear != nil { - a.afterAbortedHoldClear() - } - _, err := a.Records.Update(ctx, authority, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.QuotaHold == nil || *current.QuotaHold != hold || current.Settlement == nil || *current.Settlement != receipt || current.AssetID != "" { - return ErrAuthorityInvalid - } - current.State, current.LastSettledHold, current.LastSettlement = StatePrepared, &hold, &receipt - current.Entitlement, current.QuotaIntent, current.QuotaHold, current.FenceReceipt = nil, nil, nil, nil - current.Settlement = nil - return nil - }) - return err -} - -func validatePreparedAllocation(record *AuthorityRecord, prepared PreparedClaim, request controller.AllocationRequest) error { - if record == nil || request.Claim == nil || request.Class == nil || request.Profile == nil || prepared.Authority.ContractDigest != record.ContractDigest || record.SourceRequest.ConsumerProject != prepared.ConsumerProject || record.SourceRequest.ProviderProject != prepared.ProviderProject || record.SourceRequest.NamespaceUID != prepared.NamespaceUID || record.SourceReceipt.PrincipalUID != prepared.PrincipalUID || record.SourceReceipt.DecisionID != prepared.DecisionID || request.Claim.Namespace != record.ClaimNamespace || request.Claim.Name != record.ClaimName || request.Claim.UID != record.ClaimUID || prepared.LocalClassUID != record.SourceRequest.LocalClassUID || prepared.SourceClassUID != record.SourceRequest.SourceClassUID || prepared.LocalProfileUID != record.SourceRequest.LocalProfileUID || prepared.SourceProfileUID != record.SourceRequest.SourceProfileUID || !sameLocationLifetime(prepared.Location, record.SourceRequest.Location) || !sameLocationLifetime(request.Location, record.SourceRequest.Location) || request.Claim.Spec.LocationRef.Name != record.SourceRequest.Location.Name || request.Class.UID != record.SourceRequest.SourceClassUID || request.Class.Status.EvaluatedRevision == "" { - return ErrAuthorityInvalid - } - wantProfileUID := record.SourceRequest.LocalProfileUID - if record.SourceRequest.ProfileKind == ProfilePublished { - wantProfileUID = record.SourceRequest.SourceProfileUID - } - requirements, err := requirementsDigest(request.Profile) - acceptedDigest, acceptedErr := digest(record.AcceptedRequirements) - if err != nil || acceptedErr != nil || request.Profile.UID != wantProfileUID || requirements != record.SourceRequest.RequirementsDigest || acceptedDigest != record.SourceRequest.RequirementsDigest { - return ErrAuthorityInvalid - } - return nil -} - -func (a *Adapter) Release(ctx context.Context, prepared PreparedClaim, claimUID types.UID) (controller.ReleaseResult, error) { - if a == nil || a.Custodian == nil { - return controller.ReleaseResult{}, ErrQuotaCustodyUnavailable - } - record, ref, err := a.Records.GetForClaim(ctx, prepared.ConsumerProject, claimUID) - if err != nil { - return controller.ReleaseResult{}, err - } - if ref != prepared.Authority || record.SourceRequest.ConsumerProject != prepared.ConsumerProject { - return controller.ReleaseResult{}, ErrAuthorityInvalid - } - if record.State == StateQuarantined { - return controller.ReleaseResult{}, ErrAuthorityInvalid - } - consumer := record.SourceRequest.ConsumerProject - if record.State == StateQuotaIntent && record.QuotaHold == nil { - resolution, recoverErr := a.Custodian.Recover(ctx, consumer, ref, *record.QuotaIntent) - if recoverErr != nil { - return controller.ReleaseResult{State: controller.AssetCleanupVerified, ExternalSettlementRequired: true}, errors.Join(ErrQuotaUnknown, recoverErr) - } - if resolution.Hold == nil { - intentDigest, _ := digest(*record.QuotaIntent) - if resolution.NoHold == nil || resolution.NoHold.AuthorityRecordID != ref.RecordID || resolution.NoHold.IntentDigest != intentDigest || resolution.NoHold.AcknowledgmentID == "" { - return controller.ReleaseResult{State: controller.AssetCleanupVerified, ExternalSettlementRequired: true}, ErrQuotaUnknown - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateQuotaIntent || current.QuotaHold != nil { - return ErrAuthorityInvalid - } - current.State, current.NoHold, current.QuotaIntent, current.Entitlement = StatePrepared, resolution.NoHold, nil, nil - return nil - }); err != nil { - return controller.ReleaseResult{}, err - } - record, _, err = a.Records.GetForClaim(ctx, prepared.ConsumerProject, claimUID) - if err != nil { - return controller.ReleaseResult{}, err - } - } else { - hold := *resolution.Hold - if hold.Intent != *record.QuotaIntent || !hold.Ref().Valid() { - return controller.ReleaseResult{}, ErrAuthorityInvalid - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateQuotaIntent || current.QuotaHold != nil { - return ErrAuthorityInvalid - } - current.State, current.QuotaHold = StateQuotaGranted, &hold - return nil - }); err != nil { - return controller.ReleaseResult{}, err - } - record, _, err = a.Records.GetForClaim(ctx, prepared.ConsumerProject, claimUID) - if err != nil { - return controller.ReleaseResult{}, err - } - } - } - // A hold may have been durably retained immediately before the allocating - // process crashed. Attach its exact lifetime to core custody before asking - // core whether release is finalizer-safe, independent of grant phase. - if record.QuotaHold != nil { - if err := a.Lifecycle.RetainAllocationAuthority(ctx, claimUID, record.SourceRequest.ConsumerProject, record.SourceRequest.ProviderProject, ref, record.QuotaHold.Ref()); err != nil { - return controller.ReleaseResult{}, err - } - } - result, err := a.Lifecycle.ReleaseScoped(ctx, consumer, claimUID) - if err != nil || !result.ExternalSettlementRequired { - if err == nil && result.SafeToRemoveFinalizer && record.State == StateQuotaReleasePending && record.Settlement != nil { - _, updateErr := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.Settlement == nil { - return ErrAuthorityInvalid - } - current.State = StateReleased - return nil - }) - return result, updateErr - } - if err == nil && result.SafeToRemoveFinalizer && record.State == StatePrepared { - _, updateErr := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StatePrepared || current.QuotaIntent != nil || current.QuotaHold != nil { - return ErrAuthorityInvalid - } - current.State = StateReleased - return nil - }) - return result, updateErr - } - return result, err - } - if record.QuotaHold == nil { - return result, ErrAuthorityInvalid - } - if record.State == StateQuotaReleasePending && record.Settlement != nil { - completed, err := a.Lifecycle.CompleteExternalRelease(ctx, claimUID, ref, record.QuotaHold.Ref(), consumer) - if err != nil { - return result, err - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.Settlement == nil { - return ErrAuthorityInvalid - } - current.State = StateReleased - return nil - }); err != nil { - return result, err - } - return completed, nil - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateBound && current.State != StateQuotaIntent && current.State != StateQuotaGranted && current.State != StateCleanupVerified { - return ErrAuthorityInvalid - } - current.State = StateCleanupVerified - return nil - }); err != nil { - return result, err - } - receipt, err := a.Custodian.Settle(ctx, consumer, ref, *record.QuotaHold) - if err != nil { - return result, ErrQuotaReleaseUnknown - } - if !validSettlement(ref, *record.QuotaHold, receipt) { - return result, ErrQuotaReleaseUnknown - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateCleanupVerified { - return ErrAuthorityInvalid - } - current.State, current.Settlement = StateQuotaReleasePending, &receipt - return nil - }); err != nil { - return result, err - } - completed, err := a.Lifecycle.CompleteExternalRelease(ctx, claimUID, ref, record.QuotaHold.Ref(), consumer) - if err != nil { - return result, err - } - if _, err := a.Records.Update(ctx, ref, func(current *AuthorityRecord) error { - if current.State != StateQuotaReleasePending || current.Settlement == nil { - return ErrAuthorityInvalid - } - current.State = StateReleased - return nil - }); err != nil { - return result, err - } - return completed, nil -} - -func validSettlement(authority controller.AuthorityRef, hold QuotaHold, receipt SettlementReceipt) bool { - want, err := digest(hold) - return err == nil && receipt.AuthorityRecordID == authority.RecordID && receipt.Hold == hold.Ref() && receipt.HoldDigest == want && receipt.AcknowledgmentID != "" -} diff --git a/internal/milo/adapter_test.go b/internal/milo/adapter_test.go deleted file mode 100644 index e4526e53..00000000 --- a/internal/milo/adapter_test.go +++ /dev/null @@ -1,1042 +0,0 @@ -package milo - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "sync" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - 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" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - fleetnetwork "go.datum.net/fleet/internal/network" - "go.datum.net/fleet/internal/simulator" -) - -type testExecutor struct { - mu sync.Mutex - requests []simulator.Request -} - -func (e *testExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - e.mu.Lock() - defer e.mu.Unlock() - e.requests = append(e.requests, request) - now := time.Now() - digest, err := simulator.RequestDigest(request) - if err != nil { - return simulator.OperationResult{}, err - } - return simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind], InputDigest: digest, CompletedAt: &now}, nil -} -func (e *testExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return simulator.OperationResult{}, false, nil -} - -type testProjects struct { - identities map[string]controller.ProjectIdentity - clients map[string]client.Client - invalid map[string]bool -} - -func (p *testProjects) Resolve(_ context.Context, route string) (controller.ProjectIdentity, client.Client, error) { - if p.invalid[route] { - return controller.ProjectIdentity{}, nil, ErrProjectLifetimeMismatch - } - value, ok := p.identities[route] - if !ok { - return controller.ProjectIdentity{}, nil, ErrProjectLifetimeMismatch - } - return value, p.clients[route], nil -} -func (p *testProjects) Verify(_ context.Context, project controller.ProjectIdentity) error { - if p.invalid[project.RouteName] || p.identities[project.RouteName] != project { - return ErrProjectLifetimeMismatch - } - return nil -} - -type testSource struct{ deny error } - -func (s *testSource) AuthorizeSource(_ context.Context, request SourceUseRequest) (SourceUseReceipt, error) { - if s.deny != nil { - return SourceUseReceipt{}, s.deny - } - d, _ := digest(request) - return SourceUseReceipt{RequestDigest: d, PrincipalUID: "user-uid", DecisionID: "decision-1", PublicationRevision: request.PublicationRevision, FenceToken: "source-fence"}, nil -} - -type testEntitlement struct{} - -func (testEntitlement) Current(context.Context, client.Client) (EntitlementEvidence, error) { - return EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 3, ObservedGeneration: 3, ServiceName: ServiceName}, nil -} - -type testQuota struct { - mu sync.Mutex - calls int -} - -type pendingQuota struct{} - -func (pendingQuota) Acquire(context.Context, client.Client, QuotaIntent) (QuotaHold, bool, error) { - return QuotaHold{}, false, ErrQuotaUnknown -} - -type pendingHoldQuota struct{} - -func (pendingHoldQuota) Acquire(_ context.Context, _ client.Client, intent QuotaIntent) (QuotaHold, bool, error) { - return QuotaHold{Intent: intent, UID: "pending-quota-uid", Generation: 1, ObservedGeneration: 1}, false, nil -} - -func (q *testQuota) Acquire(_ context.Context, _ client.Client, intent QuotaIntent) (QuotaHold, bool, error) { - q.mu.Lock() - defer q.mu.Unlock() - q.calls++ - return QuotaHold{Intent: intent, UID: "quota-uid", Generation: 2, ObservedGeneration: 2}, true, nil -} - -type testFence struct { - mu sync.Mutex - reject bool - stale bool - calls int - entered chan struct{} - proceed chan struct{} -} - -func (f *testFence) Commit(_ context.Context, commit AdmissionCommit) (AdmissionCommitReceipt, error) { - f.mu.Lock() - f.calls++ - reject, stale := f.reject, f.stale - entered, proceed := f.entered, f.proceed - f.mu.Unlock() - if entered != nil { - select { - case entered <- struct{}{}: - default: - } - } - if proceed != nil { - <-proceed - } - if reject { - return AdmissionCommitReceipt{}, errors.New("revoked") - } - commitDigest, _ := digest(commit) - if stale { - commitDigest = "stale-hold-and-entitlement" - } - return AdmissionCommitReceipt{ContractDigest: commit.Authority.ContractDigest, CommitDigest: commitDigest, FenceToken: commit.Source.FenceToken, CommitID: "commit-1"}, nil -} - -type testCustodian struct { - mu sync.Mutex - fail bool - noHold bool - calls int - project controller.ProjectIdentity - quota QuotaManager - closed map[string]bool - acquireEntered chan struct{} - acquireProceed chan struct{} -} - -func (c *testCustodian) Acquire(ctx context.Context, project controller.ProjectIdentity, authority controller.AuthorityRef, intent QuotaIntent) (QuotaHold, bool, error) { - if c.acquireEntered != nil { - select { - case c.acquireEntered <- struct{}{}: - default: - } - } - if c.acquireProceed != nil { - <-c.acquireProceed - } - c.mu.Lock() - defer c.mu.Unlock() - c.project = project - if c.closed[authority.RecordID] { - return QuotaHold{}, false, ErrQuotaUnknown - } - return c.quota.Acquire(ctx, nil, intent) -} - -func (c *testCustodian) Recover(_ context.Context, project controller.ProjectIdentity, authority controller.AuthorityRef, intent QuotaIntent) (IntentResolution, error) { - c.mu.Lock() - defer c.mu.Unlock() - c.project = project - if c.fail { - return IntentResolution{}, errors.New("recovery unknown") - } - if c.noHold { - intentDigest, _ := digest(intent) - if c.closed == nil { - c.closed = map[string]bool{} - } - c.closed[authority.RecordID] = true - return IntentResolution{NoHold: &NoHoldReceipt{AuthorityRecordID: authority.RecordID, IntentDigest: intentDigest, AcknowledgmentID: "no-hold-1"}}, nil - } - hold := QuotaHold{Intent: intent, UID: "quota-uid", Generation: 2, ObservedGeneration: 2} - return IntentResolution{Hold: &hold}, nil -} - -func (c *testCustodian) Settle(_ context.Context, project controller.ProjectIdentity, authority controller.AuthorityRef, hold QuotaHold) (SettlementReceipt, error) { - c.mu.Lock() - defer c.mu.Unlock() - c.calls++ - c.project = project - if c.fail { - return SettlementReceipt{}, errors.New("settlement unknown") - } - holdDigest, _ := digest(hold) - return SettlementReceipt{AuthorityRecordID: authority.RecordID, Hold: hold.Ref(), HoldDigest: holdDigest, AcknowledgmentID: "settled-1"}, nil -} - -type adapterFixture struct { - adapter *Adapter - prepare PrepareRequest - allocation controller.AllocationRequest - executor *testExecutor - quota *testQuota - fence *testFence - custodian *testCustodian - records *RecordStore -} - -func newAdapterFixture(t *testing.T) *adapterFixture { - t.Helper() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - privateClient := fake.NewClientBuilder().WithScheme(scheme).Build() - consumerClient := fake.NewClientBuilder().WithScheme(scheme).Build() - providerClient := fake.NewClientBuilder().WithScheme(scheme).Build() - executor := &testExecutor{} - coordinator, err := controller.NewCoordinator(privateClient, "fleet-private", executor, controller.LocalDigestImageResolver{}, nil, time.Minute) - if err != nil { - t.Fatal(err) - } - records, err := NewRecordStore(privateClient, "fleet-private") - if err != nil { - t.Fatal(err) - } - consumer := controller.ProjectIdentity{AuthorityID: "milo-test", RouteName: "consumer", UID: "consumer-project-uid"} - provider := controller.ProjectIdentity{AuthorityID: "milo-test", RouteName: "provider", UID: "provider-project-uid"} - projects := &testProjects{identities: map[string]controller.ProjectIdentity{"consumer": consumer, "provider": provider}, clients: map[string]client.Client{"consumer": consumerClient, "provider": providerClient}, invalid: map[string]bool{}} - quota, fence := &testQuota{}, &testFence{} - custodian := &testCustodian{quota: quota, closed: map[string]bool{}} - adapter := &Adapter{Records: records, Projects: projects, Sources: &testSource{}, Entitlements: testEntitlement{}, Fence: fence, Custodian: custodian, Lifecycle: coordinator} - now := time.Now() - location := fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"} - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "allocation", UID: "claim-uid", Finalizers: []string{controller.MachineFinalizer}}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "published-class"}, MachineProfileRef: fleetv1.LocalReference{Name: "published-profile"}, LocationRef: fleetv1.LocalReference{Name: location.Name}}} - localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "published-class", UID: "local-class-uid"}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{Project: "provider", Name: "provider-class"}}} - sourceClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "provider-class", UID: "source-class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "inventory"}}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: "class-r1"}} - profileSpec := fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 8}, Memory: fleetv1.MemoryRequirement{Capacity: "8Gi"}} - localProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "published-profile", UID: "local-profile-uid"}, Spec: profileSpec} - sourceProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "source-profile", UID: "source-profile-uid"}, Spec: profileSpec} - machine := fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "inventory", Name: "machine-1", UID: "machine-uid", Generation: 1}, Spec: fleetv1.MachineCapacitySpec{AllocationPolicy: "Enabled", DeviceRef: fleetv1.LocalReference{Name: "server-1"}}, Status: fleetv1.MachineCapacityStatus{Hardware: fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 8}, Memory: fleetv1.HardwareMemory{Capacity: "8Gi"}}, Conditions: []metav1.Condition{{Type: "Prepared", Status: metav1.ConditionTrue, ObservedGeneration: 1}, {Type: "Healthy", Status: metav1.ConditionTrue, ObservedGeneration: 1}, {Type: "Available", Status: metav1.ConditionTrue, ObservedGeneration: 1}}}} - return &adapterFixture{adapter: adapter, prepare: PrepareRequest{ConsumerRoute: "consumer", ProviderRoute: "provider", NamespaceUID: "namespace-uid", Claim: claim, LocalClass: localClass, SourceClass: sourceClass, LocalProfile: localProfile, SourceProfile: sourceProfile, PublicationRevision: "publication-r1", Location: location}, allocation: controller.AllocationRequest{Claim: claim, Class: sourceClass, Profile: sourceProfile, Location: location, MachineCapacities: []fleetv1.MachineCapacity{machine}, EvidenceObservedAt: map[types.UID]time.Time{machine.UID: now}}, executor: executor, quota: quota, fence: fence, custodian: custodian, records: records} -} - -func TestAdapterAllocationAndReleaseRequiresExactSettlement(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - asset, err := f.adapter.Allocate(ctx, prepared, f.allocation) - if err != nil { - t.Fatal(err) - } - if !strings.HasPrefix(asset.AssetID, "milo-test/provider-project-uid/") { - t.Fatalf("asset ID = %q", asset.AssetID) - } - f.custodian.fail = true - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if !errors.Is(err, ErrQuotaReleaseUnknown) || result.State != controller.AssetCleanupVerified || result.SafeToRemoveFinalizer { - t.Fatalf("unknown release = %#v, %v", result, err) - } - f.custodian.fail = false - result, err = f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || result.State != controller.AssetReleased { - t.Fatalf("release = %#v, %v", result, err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StateReleased || record.Settlement == nil { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestAdapterRecoversPreparedAuthorityWithoutReauthorizing(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.adapter.Sources = &testSource{deny: errors.New("caller is no longer available")} - recovered, err := f.adapter.PrepareOrRecoverClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if recovered != prepared { - t.Fatalf("recovered = %#v, want %#v", recovered, prepared) - } - - changed := f.prepare - changed.LocalProfile = changed.LocalProfile.DeepCopyObject().(*fleetv1.MachineProfile) - changed.LocalProfile.Spec.Memory.Capacity = "16Gi" - if _, err := f.adapter.PrepareOrRecoverClaim(ctx, changed); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("changed retained inputs error = %v, want ErrAuthorityInvalid", err) - } -} - -func TestAdapterRecoveryAcceptsNewRevisionForSameLocationLifetime(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - if _, err := f.adapter.PrepareClaim(ctx, f.prepare); err != nil { - t.Fatal(err) - } - - current := f.prepare - current.Location.Revision = "location-r2" - prepared, err := f.adapter.PrepareOrRecoverClaim(ctx, current) - if err != nil { - t.Fatalf("recover after location status revision = %v", err) - } - if prepared.Location != current.Location { - t.Fatalf("prepared location = %#v, want current %#v", prepared.Location, current.Location) - } - replacement := current - replacement.Location.UID = "replacement-location-uid" - if _, err := f.adapter.PrepareOrRecoverClaim(ctx, replacement); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("replacement location lifetime error = %v, want ErrAuthorityInvalid", err) - } - - allocation := f.allocation - allocation.Location = current.Location - if _, err := f.adapter.Allocate(ctx, prepared, allocation); err != nil { - t.Fatalf("allocate after location status revision = %v", err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil { - t.Fatal(err) - } - if record.SourceRequest.Location.Revision != f.prepare.Location.Revision { - t.Fatalf("retained location revision = %q, want admitted %q", record.SourceRequest.Location.Revision, f.prepare.Location.Revision) - } -} - -func TestAdapterRecoveryAcceptsEditForSameSourceClassLifetime(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - if _, err := f.adapter.PrepareClaim(ctx, f.prepare); err != nil { - t.Fatal(err) - } - - current := f.prepare - current.SourceClass = f.prepare.SourceClass.DeepCopyObject().(*fleetv1.MachineClass) - current.SourceClass.Status.EvaluatedRevision = "class-r2" - current.SourceClass.Spec.Access = &fleetv1.AccessPolicy{PowerControl: true} - prepared, err := f.adapter.PrepareOrRecoverClaim(ctx, current) - if err != nil { - t.Fatalf("recover after source class edit = %v", err) - } - replacement := current - replacement.SourceClass = current.SourceClass.DeepCopyObject().(*fleetv1.MachineClass) - replacement.SourceClass.UID = "replacement-class-uid" - if _, err := f.adapter.PrepareOrRecoverClaim(ctx, replacement); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("replacement source class lifetime error = %v, want ErrAuthorityInvalid", err) - } - - allocation := f.allocation - allocation.Class = current.SourceClass - if _, err := f.adapter.Allocate(ctx, prepared, allocation); err != nil { - t.Fatalf("allocate after source class edit = %v", err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil { - t.Fatal(err) - } - if record.SourceRequest.SourceClassRevision != f.prepare.SourceClass.Status.EvaluatedRevision { - t.Fatalf("retained class revision = %q, want admitted %q", record.SourceRequest.SourceClassRevision, f.prepare.SourceClass.Status.EvaluatedRevision) - } -} - -func TestAdapterRepairsPartialPreparation(t *testing.T) { - for _, stage := range []string{"authority", "custody"} { - t.Run(stage, func(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - lost := errors.New("simulated manager crash") - if stage == "authority" { - f.adapter.afterAuthorityCreate = func() error { return lost } - } else { - f.adapter.afterCustodyEnsure = func() error { return lost } - } - if _, err := f.adapter.PrepareClaim(ctx, f.prepare); !errors.Is(err, lost) { - t.Fatalf("partial prepare error = %v, want simulated crash", err) - } - f.adapter.afterAuthorityCreate = nil - f.adapter.afterCustodyEnsure = nil - prepared, err := f.adapter.PrepareOrRecoverClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatalf("allocation after repaired preparation: %v", err) - } - }) - } -} - -func TestAdapterReleaseClaimNeedsNoPublicInputs(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatal(err) - } - result, err := f.adapter.ReleaseClaim(ctx, prepared.ConsumerProject, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || result.State != controller.AssetReleased { - t.Fatalf("release by retained claim lifetime = %#v, %v", result, err) - } -} - -func TestAdapterMissingAuthorityDoesNotBypassRetainedCustody(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - var authority corev1.Secret - if err := f.records.client.Get(ctx, client.ObjectKey{Namespace: "fleet-private", Name: prepared.Authority.RecordName}, &authority); err != nil { - t.Fatal(err) - } - if err := f.records.client.Delete(ctx, &authority); err != nil { - t.Fatal(err) - } - if _, err := f.adapter.ReleaseClaim(ctx, prepared.ConsumerProject, f.prepare.Claim.UID); !errors.Is(err, controller.ErrRecordInvalid) { - t.Fatalf("missing authority with retained custody error = %v, want ErrRecordInvalid", err) - } - if _, err := f.adapter.PrepareOrRecoverClaim(ctx, f.prepare); !errors.Is(err, controller.ErrRecordInvalid) { - t.Fatalf("reprepare with missing authority and retained custody error = %v, want ErrRecordInvalid", err) - } -} - -func TestAdapterProvesNeverAdmittedClaimHasNoAuthority(t *testing.T) { - f := newAdapterFixture(t) - consumer, _, err := f.adapter.Projects.Resolve(context.Background(), "consumer") - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.ReleaseClaim(context.Background(), consumer, "never-admitted"); !errors.Is(err, ErrClaimAuthorityNotFound) { - t.Fatalf("never-admitted release error = %v, want ErrClaimAuthorityNotFound", err) - } -} - -func TestAdapterFailsClosedWithoutProductionAuthorityProtocols(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - f.adapter.Sources = nil - if _, err := f.adapter.PrepareClaim(ctx, f.prepare); !errors.Is(err, ErrAuthorityUnavailable) { - t.Fatalf("source error = %v", err) - } - f = newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.adapter.Fence = nil - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrAdmissionFenceUnavailable) { - t.Fatalf("fence error = %v", err) - } - if f.quota.calls != 0 { - t.Fatalf("quota calls = %d", f.quota.calls) - } - f.adapter.Fence = &testFence{} - f.adapter.Custodian = nil - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrQuotaCustodyUnavailable) { - t.Fatalf("custody error = %v", err) - } -} - -func TestAllocationRejectsAuthoritySubstitutionBeforeEffects(t *testing.T) { - mutations := map[string]func(*controller.AllocationRequest){ - "claim lifetime": func(r *controller.AllocationRequest) { - r.Claim = r.Claim.DeepCopyObject().(*fleetv1.Machine) - r.Claim.UID = "replacement" - }, - "source class": func(r *controller.AllocationRequest) { - r.Class = r.Class.DeepCopyObject().(*fleetv1.MachineClass) - r.Class.UID = "replacement" - }, - "source profile": func(r *controller.AllocationRequest) { - r.Profile = r.Profile.DeepCopyObject().(*fleetv1.MachineProfile) - r.Profile.UID = "replacement" - }, - "requirements": func(r *controller.AllocationRequest) { - r.Profile = r.Profile.DeepCopyObject().(*fleetv1.MachineProfile) - r.Profile.Spec.CPU.Architecture = "arm64" - }, - "location": func(r *controller.AllocationRequest) { - r.Location.UID = "replacement" - }, - "claim location": func(r *controller.AllocationRequest) { - r.Claim = r.Claim.DeepCopyObject().(*fleetv1.Machine) - r.Claim.Spec.LocationRef.Name = "replacement" - }, - } - for name, mutate := range mutations { - t.Run(name, func(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - mutate(&f.allocation) - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("error = %v", err) - } - if f.quota.calls != 0 || f.fence.calls != 0 || len(f.executor.requests) != 0 { - t.Fatalf("effects: quota=%d fence=%d provider=%d", f.quota.calls, f.fence.calls, len(f.executor.requests)) - } - }) - } -} - -func TestAllocationRejectsDeletingOrUnprotectedClaimBeforeAdmissionEffects(t *testing.T) { - for _, mutate := range []func(*fleetv1.Machine){ - func(claim *fleetv1.Machine) { claim.Finalizers = nil }, - func(claim *fleetv1.Machine) { - now := metav1.Now() - claim.DeletionTimestamp = &now - }, - } { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.allocation.Claim = f.allocation.Claim.DeepCopyObject().(*fleetv1.Machine) - mutate(f.allocation.Claim) - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("allocation error = %v", err) - } - if f.quota.calls != 0 || f.fence.calls != 0 || len(f.executor.requests) != 0 { - t.Fatalf("effects: quota=%d fence=%d provider=%d", f.quota.calls, f.fence.calls, len(f.executor.requests)) - } - } -} - -func TestFenceInvalidationWinsAndSettlesBeforeRetry(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.fence.reject = true - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err == nil || f.custodian.calls != 1 { - t.Fatalf("allocation error = %v, settlements=%d", err, f.custodian.calls) - } - if len(f.executor.requests) != 0 { - t.Fatalf("provider effects = %#v", f.executor.requests) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StatePrepared || record.QuotaHold != nil { - t.Fatalf("record = %#v, %v", record, err) - } - f.fence.reject = false - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatal(err) - } -} - -func TestFenceReceiptCannotReplayAcrossHoldOrEntitlement(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.fence.stale = true - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("error = %v", err) - } - if f.custodian.calls != 1 || len(f.executor.requests) != 0 { - t.Fatalf("settlements=%d effects=%d", f.custodian.calls, len(f.executor.requests)) - } -} - -func TestFenceCommitWinsBeforeBinding(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.fence.entered, f.fence.proceed = make(chan struct{}, 1), make(chan struct{}) - done := make(chan error, 1) - go func() { _, err := f.adapter.Allocate(ctx, prepared, f.allocation); done <- err }() - <-f.fence.entered - close(f.fence.proceed) - if err := <-done; err != nil { - t.Fatal(err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StateBound || record.FenceReceipt == nil { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestDeleteAfterLostQuotaCreateResponseBlocksUntilCustodianRecovers(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.custodian.quota = pendingQuota{} - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrQuotaUnknown) { - t.Fatalf("allocation error = %v", err) - } - f.custodian.fail = true - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if !errors.Is(err, ErrQuotaUnknown) || result.SafeToRemoveFinalizer || !result.ExternalSettlementRequired { - t.Fatalf("unknown intent release = %#v, %v", result, err) - } - if len(f.executor.requests) != 0 { - t.Fatalf("provider effects = %#v", f.executor.requests) - } - f.custodian.fail = false - result, err = f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("recovered release = %#v, %v", result, err) - } -} - -func TestDeleteAfterQuotaIntentAcceptsOnlyExactNoHoldProof(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.custodian.quota = pendingQuota{} - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrQuotaUnknown) { - t.Fatalf("allocation error = %v", err) - } - f.custodian.noHold = true - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", result, err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.NoHold == nil || record.NoHold.AcknowledgmentID == "" { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestDelayedAllocationCannotResurrectReleasedAuthority(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - entered, proceed := make(chan struct{}), make(chan struct{}) - f.adapter.afterLifecycleAllocate = func() { close(entered); <-proceed } - allocateDone := make(chan error, 1) - go func() { _, err := f.adapter.Allocate(ctx, prepared, f.allocation); allocateDone <- err }() - <-entered - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", result, err) - } - close(proceed) - if err := <-allocateDone; !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("delayed allocation error = %v", err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StateReleased { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestRetryRecoversCoreBindingBeforeCurrentCapacityCheck(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - asset, err := f.adapter.Allocate(ctx, prepared, f.allocation) - if err != nil { - t.Fatal(err) - } - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State, current.AssetID, current.BindingID = StateQuotaGranted, "", "" - return nil - }); err != nil { - t.Fatal(err) - } - f.allocation.MachineCapacities = nil - recovered, err := f.adapter.Allocate(ctx, prepared, f.allocation) - if err != nil || recovered.BindingID != asset.BindingID { - t.Fatalf("recovered = %#v, %v", recovered, err) - } -} - -func TestReleaseRecoversPersistedSettlementReceiptWithoutSecondExternalEffect(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatal(err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil { - t.Fatal(err) - } - result, err := f.adapter.Lifecycle.ReleaseScoped(ctx, prepared.ConsumerProject, f.prepare.Claim.UID) - if err != nil || result.State != controller.AssetCleanupVerified { - t.Fatalf("cleanup = %#v, %v", result, err) - } - holdDigest, _ := digest(*record.QuotaHold) - receipt := SettlementReceipt{AuthorityRecordID: prepared.Authority.RecordID, Hold: record.QuotaHold.Ref(), HoldDigest: holdDigest, AcknowledgmentID: "persisted-ack"} - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State, current.Settlement = StateQuotaReleasePending, &receipt - return nil - }); err != nil { - t.Fatal(err) - } - before := f.custodian.calls - result, err = f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || f.custodian.calls != before { - t.Fatalf("recovery = %#v, %v, external calls %d->%d", result, err, before, f.custodian.calls) - } -} - -func TestReleaseInstallsHoldPersistedBeforeCoreCustody(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - intent := QuotaIntentFor(prepared.ConsumerProject, f.prepare.Claim.Namespace, f.prepare.Claim.Name, f.prepare.Claim.UID) - hold := QuotaHold{Intent: intent, UID: "crash-hold-uid", Generation: 1, ObservedGeneration: 1} - entitlement := EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 1, ObservedGeneration: 1, ServiceName: ServiceName} - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State, current.QuotaIntent, current.QuotaHold, current.Entitlement = StateQuotaGranted, &intent, &hold, &entitlement - return nil - }); err != nil { - t.Fatal(err) - } - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || f.custodian.calls != 1 { - t.Fatalf("release after hold-write crash = %#v, %v, settlements=%d", result, err, f.custodian.calls) - } -} - -func TestPendingHoldDeletionSettlesBeforeFinalizer(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.custodian.quota = pendingHoldQuota{} - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrQuotaPending) { - t.Fatalf("pending allocation = %v", err) - } - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || f.custodian.calls != 1 { - t.Fatalf("pending-hold release = %#v, %v, settlements=%d", result, err, f.custodian.calls) - } -} - -func TestAllocateRejectsTerminalAndCleanupStatesBeforeEffects(t *testing.T) { - for _, state := range []AuthorityState{StateCleanupVerified, StateReleased, StateQuarantined} { - t.Run(string(state), func(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State = state - if state == StateCleanupVerified { - intent := QuotaIntentFor(prepared.ConsumerProject, f.prepare.Claim.Namespace, f.prepare.Claim.Name, f.prepare.Claim.UID) - hold := QuotaHold{Intent: intent, UID: "cleanup-hold", Generation: 1, ObservedGeneration: 1} - entitlement := EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 1, ObservedGeneration: 1, ServiceName: ServiceName} - current.QuotaIntent, current.QuotaHold, current.Entitlement = &intent, &hold, &entitlement - } - return nil - }); err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("allocation error = %v", err) - } - if f.quota.calls != 0 || f.fence.calls != 0 || len(f.executor.requests) != 0 { - t.Fatalf("effects: quota=%d fence=%d provider=%d", f.quota.calls, f.fence.calls, len(f.executor.requests)) - } - }) - } -} - -func TestDelayedAbortedSettlementCannotOverwriteReleased(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - intent := QuotaIntentFor(prepared.ConsumerProject, f.prepare.Claim.Namespace, f.prepare.Claim.Name, f.prepare.Claim.UID) - hold := QuotaHold{Intent: intent, UID: "aborted-hold", Generation: 1, ObservedGeneration: 1} - entitlement := EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 1, ObservedGeneration: 1, ServiceName: ServiceName} - holdDigest, _ := digest(hold) - receipt := SettlementReceipt{AuthorityRecordID: prepared.Authority.RecordID, Hold: hold.Ref(), HoldDigest: holdDigest, AcknowledgmentID: "settled"} - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State, current.QuotaIntent, current.QuotaHold, current.Entitlement, current.Settlement = StateQuotaReleasePending, &intent, &hold, &entitlement, &receipt - return nil - }); err != nil { - t.Fatal(err) - } - if err := f.adapter.Lifecycle.RetainAllocationAuthority(ctx, f.prepare.Claim.UID, prepared.ConsumerProject, prepared.ProviderProject, prepared.Authority, hold.Ref()); err != nil { - t.Fatal(err) - } - entered, proceed := make(chan struct{}), make(chan struct{}) - f.adapter.afterAbortedHoldClear = func() { close(entered); <-proceed } - allocateDone := make(chan error, 1) - go func() { _, err := f.adapter.Allocate(ctx, prepared, f.allocation); allocateDone <- err }() - <-entered - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("concurrent release = %#v, %v", result, err) - } - close(proceed) - if err := <-allocateDone; !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("delayed settlement error = %v", err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StateReleased { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestReleaseUsesRetainedProjectWhenConsumerRouteUnavailableOrReused(t *testing.T) { - for _, mode := range []string{"unavailable", "reused"} { - t.Run(mode, func(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatal(err) - } - projects := f.adapter.Projects.(*testProjects) - if mode == "unavailable" { - projects.invalid["consumer"] = true - } else { - projects.identities["consumer"] = controller.ProjectIdentity{AuthorityID: "milo-test", RouteName: "consumer", UID: "replacement-project-uid"} - } - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", result, err) - } - if f.custodian.project != prepared.ConsumerProject { - t.Fatalf("custodian project = %#v", f.custodian.project) - } - }) - } -} - -func TestPersistedFenceReceiptIsRevalidatedOnDecode(t *testing.T) { - for _, corrupt := range []func(*AuthorityRecord){ - func(record *AuthorityRecord) { record.FenceReceipt.CommitDigest = "stale" }, - func(record *AuthorityRecord) { record.FenceReceipt.FenceToken = "replacement" }, - } { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); err != nil { - t.Fatal(err) - } - var secret corev1.Secret - key := client.ObjectKey{Namespace: "fleet-private", Name: prepared.Authority.RecordName} - if err := f.records.client.Get(ctx, key, &secret); err != nil { - t.Fatal(err) - } - var record AuthorityRecord - if err := json.Unmarshal(secret.Data[authorityDataKey], &record); err != nil { - t.Fatal(err) - } - corrupt(&record) - secret.Data[authorityDataKey], _ = json.Marshal(record) - if err := f.records.client.Update(ctx, &secret); err != nil { - t.Fatal(err) - } - if _, err := f.records.Get(ctx, prepared.Authority); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("corrupt record error = %v", err) - } - } -} - -func TestNoHoldClosureWinsAgainstPausedAcquire(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - f.custodian.noHold = true - f.custodian.acquireEntered = make(chan struct{}, 1) - f.custodian.acquireProceed = make(chan struct{}) - allocateDone := make(chan error, 1) - go func() { _, err := f.adapter.Allocate(ctx, prepared, f.allocation); allocateDone <- err }() - <-f.custodian.acquireEntered - result, err := f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("release = %#v, %v", result, err) - } - close(f.custodian.acquireProceed) - if err := <-allocateDone; !errors.Is(err, ErrQuotaUnknown) { - t.Fatalf("paused acquire error = %v", err) - } - if f.quota.calls != 0 { - t.Fatalf("quota acquire effects after closure = %d", f.quota.calls) - } -} - -func TestAllocationAfterCoreReleaseDoesNotAcquireQuotaAndReleaseSettles(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - result, err := f.adapter.Lifecycle.ReleaseScoped(ctx, prepared.ConsumerProject, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("core release = %#v, %v", result, err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, controller.ErrRecordInvalid) { - t.Fatalf("allocation after release error = %v", err) - } - if f.quota.calls != 0 { - t.Fatalf("quota acquire effects after core release = %d", f.quota.calls) - } - result, err = f.adapter.Release(ctx, prepared, f.prepare.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("adapter release = %#v, %v", result, err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StateReleased { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestAbortedHoldClearIsRetryableAfterCrash(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - intent := QuotaIntentFor(prepared.ConsumerProject, f.prepare.Claim.Namespace, f.prepare.Claim.Name, f.prepare.Claim.UID) - hold := QuotaHold{Intent: intent, UID: "aborted-hold", Generation: 1, ObservedGeneration: 1} - entitlement := EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 1, ObservedGeneration: 1, ServiceName: ServiceName} - holdDigest, _ := digest(hold) - receipt := SettlementReceipt{AuthorityRecordID: prepared.Authority.RecordID, Hold: hold.Ref(), HoldDigest: holdDigest, AcknowledgmentID: "settled"} - if _, err := f.records.Update(ctx, prepared.Authority, func(current *AuthorityRecord) error { - current.State, current.QuotaIntent, current.QuotaHold, current.Entitlement, current.Settlement = StateQuotaReleasePending, &intent, &hold, &entitlement, &receipt - return nil - }); err != nil { - t.Fatal(err) - } - if err := f.adapter.Lifecycle.RetainAllocationAuthority(ctx, f.prepare.Claim.UID, prepared.ConsumerProject, prepared.ProviderProject, prepared.Authority, hold.Ref()); err != nil { - t.Fatal(err) - } - if err := f.adapter.Lifecycle.ClearSettledExternalHold(ctx, f.prepare.Claim.UID, prepared.Authority, hold.Ref(), prepared.ConsumerProject); err != nil { - t.Fatal(err) - } - if _, err := f.adapter.Allocate(ctx, prepared, f.allocation); !errors.Is(err, ErrQuotaPending) { - t.Fatalf("restart = %v", err) - } - record, err := f.records.Get(ctx, prepared.Authority) - if err != nil || record.State != StatePrepared || record.QuotaHold != nil { - t.Fatalf("record = %#v, %v", record, err) - } -} - -func TestMalformedAuthorityStateShapesFailDecode(t *testing.T) { - mutations := []func(*AuthorityRecord){ - func(record *AuthorityRecord) { record.State = StateQuotaIntent }, - func(record *AuthorityRecord) { - intent := QuotaIntentFor(record.SourceRequest.ConsumerProject, record.ClaimNamespace, record.ClaimName, record.ClaimUID) - record.QuotaIntent = &intent - }, - func(record *AuthorityRecord) { - record.State = StateReleased - intent := QuotaIntentFor(record.SourceRequest.ConsumerProject, record.ClaimNamespace, record.ClaimName, record.ClaimUID) - entitlement := EntitlementEvidence{Name: EntitlementName, UID: "entitlement-uid", Generation: 1, ObservedGeneration: 1, ServiceName: ServiceName} - record.QuotaIntent, record.Entitlement = &intent, &entitlement - }, - } - for i, mutate := range mutations { - t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { - ctx := context.Background() - f := newAdapterFixture(t) - prepared, err := f.adapter.PrepareClaim(ctx, f.prepare) - if err != nil { - t.Fatal(err) - } - var secret corev1.Secret - key := client.ObjectKey{Namespace: "fleet-private", Name: prepared.Authority.RecordName} - if err := f.records.client.Get(ctx, key, &secret); err != nil { - t.Fatal(err) - } - var record AuthorityRecord - if err := json.Unmarshal(secret.Data[authorityDataKey], &record); err != nil { - t.Fatal(err) - } - mutate(&record) - secret.Data[authorityDataKey], _ = json.Marshal(record) - if err := f.records.client.Update(ctx, &secret); err != nil { - t.Fatal(err) - } - if _, err := f.records.Get(ctx, prepared.Authority); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("malformed record error = %v", err) - } - }) - } -} diff --git a/internal/milo/authority_test.go b/internal/milo/authority_test.go deleted file mode 100644 index f167a993..00000000 --- a/internal/milo/authority_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package milo - -import ( - "context" - "errors" - "sync" - "testing" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - fleetnetwork "go.datum.net/fleet/internal/network" -) - -func TestSourceReceiptRejectsEverySubstitution(t *testing.T) { - request := SourceUseRequest{ConsumerProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "consumer-uid"}, ProviderProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "provider-uid"}, NamespaceUID: "namespace-uid", ClaimUID: "claim-uid", LocalClassUID: "local-class", SourceClassUID: "source-class", SourceClassRevision: "r1", SourceClassDigest: "class-digest", LocalProfileUID: "local-profile", SourceProfileUID: "source-profile", ProfileKind: ProfilePublished, RequirementsDigest: "requirements", PublicationRevision: "publication", Location: fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"}} - receipt, err := (&testSource{}).AuthorizeSource(context.Background(), request) - if err != nil || validateReceipt(request, receipt) != nil { - t.Fatal(err) - } - mutations := map[string]func(*SourceUseRequest){"consumer lifetime": func(r *SourceUseRequest) { r.ConsumerProject.UID = "replacement" }, "namespace": func(r *SourceUseRequest) { r.NamespaceUID = "replacement" }, "class": func(r *SourceUseRequest) { r.SourceClassUID = "replacement" }, "profile": func(r *SourceUseRequest) { r.SourceProfileUID = "replacement" }, "requirements": func(r *SourceUseRequest) { r.RequirementsDigest = "replacement" }, "publication": func(r *SourceUseRequest) { r.PublicationRevision = "replacement" }, "location": func(r *SourceUseRequest) { r.Location.UID = "replacement" }} - for name, mutate := range mutations { - t.Run(name, func(t *testing.T) { - changed := request - mutate(&changed) - if validateReceipt(changed, receipt) == nil { - t.Fatal("substituted request accepted") - } - }) - } - bad := receipt - bad.PrincipalUID = "" - if validateReceipt(request, bad) == nil { - t.Fatal("receipt without retained principal accepted") - } -} - -func TestAuthorityRecordConcurrentCreateIsExactAndPrivate(t *testing.T) { - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - kube := fake.NewClientBuilder().WithScheme(scheme).Build() - store, _ := NewRecordStore(kube, "private") - accepted := fleetv1.MachineProfileSpec{} - requirements, _ := digest(accepted) - request := SourceUseRequest{ConsumerProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "consumer-uid"}, ProviderProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "provider-uid"}, NamespaceUID: "namespace-uid", ClaimUID: "claim-uid", LocalClassUID: "local-class", SourceClassUID: "source-class", SourceClassRevision: "r1", SourceClassDigest: "class-digest", LocalProfileUID: "local-profile", ProfileKind: ProfileCustom, RequirementsDigest: requirements, PublicationRevision: "publication", Location: fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"}} - receipt, _ := (&testSource{}).AuthorizeSource(context.Background(), request) - contract := struct { - Request SourceUseRequest `json:"request"` - Receipt SourceUseReceipt `json:"receipt"` - }{request, receipt} - contractDigest, _ := digest(contract) - record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: "record-id", State: StatePrepared, ClaimNamespace: "default", ClaimName: "allocation", ClaimUID: request.ClaimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: accepted} - mismatched := record - mismatched.ClaimUID = "other-claim" - if !errors.Is(validateAuthorityRecord(&mismatched), ErrAuthorityInvalid) { - t.Fatal("outer claim lifetime diverged from retained source request") - } - var wg sync.WaitGroup - errorsCh := make(chan error, 8) - for i := 0; i < 8; i++ { - wg.Add(1) - go func() { defer wg.Done(); _, err := store.Create(context.Background(), record); errorsCh <- err }() - } - wg.Wait() - close(errorsCh) - for err := range errorsCh { - if err != nil { - t.Fatal(err) - } - } - var secrets corev1.SecretList - if err := kube.List(context.Background(), &secrets); err != nil { - t.Fatal(err) - } - if len(secrets.Items) != 1 || secrets.Items[0].Type != authorityType { - t.Fatalf("records = %#v", secrets.Items) - } - if string(secrets.Items[0].Data[authorityDataKey]) == "" { - t.Fatal("private authority record is empty") - } - conflict := record - conflict.SourceRequest.ProviderProject.UID = "replacement" - if _, err := store.Create(context.Background(), conflict); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("conflict error = %v", err) - } -} - -func entitlementObject(generation int64, phase string) *unstructured.Unstructured { - object := &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": "services.miloapis.com/v1alpha1", "kind": "ServiceEntitlement", "metadata": map[string]interface{}{"name": EntitlementName, "uid": "entitlement-uid", "generation": generation}, "status": map[string]interface{}{"phase": phase, "serviceName": ServiceName, "conditions": []interface{}{map[string]interface{}{"type": "Ready", "status": "True", "observedGeneration": generation}}}}} - object.SetGroupVersionKind(entitlementGVK) - return object -} - -func TestEntitlementUsesReviewedActiveReadyShape(t *testing.T) { - active := entitlementObject(2, "Active") - _ = unstructured.SetNestedSlice(active.Object, []interface{}{map[string]interface{}{"type": "Ready", "status": "True", "observedGeneration": int64(2)}}, "status", "conditions") - stale := entitlementObject(2, "Active") - _ = unstructured.SetNestedSlice(stale.Object, []interface{}{map[string]interface{}{"type": "Ready", "status": "True", "observedGeneration": int64(1)}}, "status", "conditions") - for name, object := range map[string]*unstructured.Unstructured{"active": active, "inactive": entitlementObject(2, "Pending"), "stale": stale} { - t.Run(name, func(t *testing.T) { - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(entitlementGVK, &unstructured.Unstructured{}) - scheme.AddKnownTypeWithName(entitlementGVK.GroupVersion().WithKind("ServiceEntitlementList"), &unstructured.UnstructuredList{}) - kube := fake.NewClientBuilder().WithScheme(scheme).WithObjects(object).Build() - evidence, err := (ServiceEntitlementReader{}).Current(context.Background(), kube) - if name == "active" && (err != nil || evidence.UID == "") { - t.Fatalf("evidence = %#v, %v", evidence, err) - } - if name != "active" && !errors.Is(err, ErrEntitlementUnavailable) { - t.Fatalf("error = %v", err) - } - }) - } -} diff --git a/internal/milo/entitlement.go b/internal/milo/entitlement.go deleted file mode 100644 index 3cee9678..00000000 --- a/internal/milo/entitlement.go +++ /dev/null @@ -1,56 +0,0 @@ -package milo - -import ( - "context" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -var entitlementGVK = schema.GroupVersionKind{Group: "services.miloapis.com", Version: "v1alpha1", Kind: "ServiceEntitlement"} - -type ServiceEntitlementReader struct{} - -func (ServiceEntitlementReader) Current(ctx context.Context, kube client.Client) (EntitlementEvidence, error) { - if kube == nil { - return EntitlementEvidence{}, ErrEntitlementUnavailable - } - object := &unstructured.Unstructured{} - object.SetGroupVersionKind(entitlementGVK) - if err := kube.Get(ctx, client.ObjectKey{Name: EntitlementName}, object); err != nil { - return EntitlementEvidence{}, ErrEntitlementUnavailable - } - phase, _, _ := unstructured.NestedString(object.Object, "status", "phase") - service, _, _ := unstructured.NestedString(object.Object, "status", "serviceName") - conditions, _, _ := unstructured.NestedSlice(object.Object, "status", "conditions") - ready := findCondition(conditions, "Ready") - if object.GetUID() == "" || phase != "Active" || service != ServiceName || ready == nil || ready.Status != metav1.ConditionTrue || ready.ObservedGeneration != object.GetGeneration() { - return EntitlementEvidence{}, ErrEntitlementUnavailable - } - return EntitlementEvidence{Name: object.GetName(), UID: object.GetUID(), Generation: object.GetGeneration(), ObservedGeneration: ready.ObservedGeneration, ServiceName: service}, nil -} - -func findCondition(raw []interface{}, conditionType string) *metav1.Condition { - for _, item := range raw { - value, ok := item.(map[string]interface{}) - if !ok || value["type"] != conditionType { - continue - } - condition := &metav1.Condition{Type: conditionType} - if status, ok := value["status"].(string); ok { - condition.Status = metav1.ConditionStatus(status) - } - switch observed := value["observedGeneration"].(type) { - case int64: - condition.ObservedGeneration = observed - case float64: - condition.ObservedGeneration = int64(observed) - case int: - condition.ObservedGeneration = int64(observed) - } - return condition - } - return nil -} diff --git a/internal/milo/quota.go b/internal/milo/quota.go index 742ceb98..0f0235df 100644 --- a/internal/milo/quota.go +++ b/internal/milo/quota.go @@ -2,70 +2,130 @@ package milo import ( "context" + "crypto/sha256" + "encoding/hex" + "errors" "fmt" quotav1alpha1 "go.miloapis.com/milo/pkg/apis/quota/v1alpha1" 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/types" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/allocation" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/tenancy" ) -type ResourceClaimManager struct{} +var _ allocation.Quota = Quota{} -func QuotaIntentFor(project controller.ProjectIdentity, namespace, claimName string, claimUID types.UID) QuotaIntent { - return QuotaIntent{ConsumerProject: project, Namespace: namespace, ClaimName: claimName, ClaimUID: claimUID, ResourceType: MachineQuotaResource, Amount: 1, Name: "fleet-machine-" + shortDigest(string(project.UID)+"/"+string(claimUID))} +// Quota reserves one Machine's quota as a Milo ResourceClaim in the Machine's +// namespace. The claim is named from the Machine UID within its consumer +// project, as its allocation is, so a retried create collides. Only a Milo +// Project consumer has quota. +type Quota struct { + // Consumers resolves the Machine's consumer project and its API. + Consumers tenancy.Resolver } -func (ResourceClaimManager) Acquire(ctx context.Context, kube client.Client, intent QuotaIntent) (QuotaHold, bool, error) { - if kube == nil || !intent.ConsumerProject.Valid() || intent.Namespace == "" || intent.ClaimName == "" || intent.ClaimUID == "" || intent.ResourceType != MachineQuotaResource || intent.Amount != 1 || intent.Name != QuotaIntentFor(intent.ConsumerProject, intent.Namespace, intent.ClaimName, intent.ClaimUID).Name { - return QuotaHold{}, false, ErrAuthorityInvalid +// ClaimName is the only name a Machine's quota claim may have. +func ClaimName(machine allocation.Machine) string { + sum := sha256.Sum256([]byte(string(machine.ConsumerUID) + "/" + string(machine.UID))) + return "fleet-machine-" + hex.EncodeToString(sum[:])[:16] +} + +func desired(machine allocation.Machine) *quotav1alpha1.ResourceClaim { + return "av1alpha1.ResourceClaim{ + ObjectMeta: metav1.ObjectMeta{Name: ClaimName(machine), Namespace: machine.Namespace, Labels: map[string]string{ + "fleet.datumapis.com/quota-claim": "machine", fleetv1.LabelMachineUID: string(machine.UID), fleetv1.LabelConsumerUID: string(machine.ConsumerUID), + }}, + Spec: quotav1alpha1.ResourceClaimSpec{ + ConsumerRef: quotav1alpha1.ConsumerRef{APIGroup: machine.Consumer.APIGroup, Kind: machine.Consumer.Kind, Name: machine.Consumer.Name}, + Requests: []quotav1alpha1.ResourceRequest{{ResourceType: MachineQuotaResource, Amount: 1}}, + ResourceRef: "av1alpha1.UnversionedObjectReference{APIGroup: fleetv1.GroupVersion.Group, Kind: "Machine", Namespace: machine.Namespace, Name: machine.Name}, + }, + } +} + +func matches(machine allocation.Machine, claim *quotav1alpha1.ResourceClaim) bool { + want := desired(machine) + return claim.UID != "" && claim.Labels[fleetv1.LabelMachineUID] == want.Labels[fleetv1.LabelMachineUID] && + claim.Labels[fleetv1.LabelConsumerUID] == want.Labels[fleetv1.LabelConsumerUID] && + claim.Spec.ConsumerRef == want.Spec.ConsumerRef && claim.Spec.ResourceRef != nil && *claim.Spec.ResourceRef == *want.Spec.ResourceRef && + len(claim.Spec.Requests) == 1 && claim.Spec.Requests[0] == want.Spec.Requests[0] +} + +// Acquire creates the claim once and returns its name when Milo granted it. +func (q Quota) Acquire(ctx context.Context, machine allocation.Machine) (string, error) { + api, err := q.client(ctx, machine) + if err != nil { + return "", err } - key := client.ObjectKey{Namespace: intent.Namespace, Name: intent.Name} claim := "av1alpha1.ResourceClaim{} - if err := kube.Get(ctx, key, claim); apierrors.IsNotFound(err) { - claim = desiredResourceClaim(intent) - if err := kube.Create(ctx, claim); err != nil { - if apierrors.IsAlreadyExists(err) { - return ResourceClaimManager{}.Acquire(ctx, kube, intent) - } - return QuotaHold{}, false, fmt.Errorf("%w: create ResourceClaim: %v", ErrQuotaUnknown, err) + if err := api.Get(ctx, client.ObjectKey{Namespace: machine.Namespace, Name: ClaimName(machine)}, claim); apierrors.IsNotFound(err) { + if err := api.Create(ctx, desired(machine)); err != nil && !apierrors.IsAlreadyExists(err) { + return "", fmt.Errorf("%w: create ResourceClaim: %v", ErrQuotaUnknown, err) } - return QuotaHold{}, false, ErrQuotaPending + return "", ErrQuotaPending } else if err != nil { - return QuotaHold{}, false, fmt.Errorf("%w: read ResourceClaim: %v", ErrQuotaUnknown, err) + return "", fmt.Errorf("%w: read ResourceClaim: %v", ErrQuotaUnknown, err) } - if err := validateResourceClaim(intent, claim); err != nil { - return QuotaHold{}, false, err + if !matches(machine, claim) { + return "", ErrQuotaInvalid } - hold := QuotaHold{Intent: intent, UID: claim.UID, Generation: claim.Generation, ObservedGeneration: claim.Status.ObservedGeneration} - granted := apiMeta.FindStatusCondition(claim.Status.Conditions, quotav1alpha1.ResourceClaimGranted) if claim.DeletionTimestamp != nil { - return hold, false, ErrQuotaUnknown - } - if granted == nil || claim.Status.ObservedGeneration != claim.Generation { - return hold, false, ErrQuotaPending - } - if granted.Status == metav1.ConditionUnknown { - return hold, false, ErrQuotaUnknown + return "", ErrQuotaUnknown } - if granted.Status != metav1.ConditionTrue { - return hold, false, ErrQuotaPending + granted := apiMeta.FindStatusCondition(claim.Status.Conditions, quotav1alpha1.ResourceClaimGranted) + switch { + case granted == nil || claim.Status.ObservedGeneration != claim.Generation: + return "", ErrQuotaPending + case granted.Status == metav1.ConditionUnknown: + return "", ErrQuotaUnknown + case granted.Status != metav1.ConditionTrue: + return "", ErrQuotaPending } - return hold, true, nil + return claim.Name, nil } -func desiredResourceClaim(intent QuotaIntent) *quotav1alpha1.ResourceClaim { - return "av1alpha1.ResourceClaim{ObjectMeta: metav1.ObjectMeta{Name: intent.Name, Namespace: intent.Namespace, Labels: map[string]string{"fleet.datumapis.com/quota-claim": "machine", "fleet.datumapis.com/machine-uid": string(intent.ClaimUID), "fleet.datumapis.com/consumer-project-uid": string(intent.ConsumerProject.UID)}}, Spec: quotav1alpha1.ResourceClaimSpec{ConsumerRef: quotav1alpha1.ConsumerRef{APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: intent.ConsumerProject.RouteName}, Requests: []quotav1alpha1.ResourceRequest{{ResourceType: intent.ResourceType, Amount: intent.Amount}}, ResourceRef: "av1alpha1.UnversionedObjectReference{APIGroup: fleetv1.GroupVersion.Group, Kind: "Machine", Namespace: intent.Namespace, Name: intent.ClaimName}}} +// Release deletes the Machine's claim. It returns nil once the claim is +// gone. +func (q Quota) Release(ctx context.Context, machine allocation.Machine) error { + name := ClaimName(machine) + api, err := q.client(ctx, machine) + // A consumer that is gone, or was recreated, took its claims with it. + if errors.Is(err, tenancy.ErrConsumerGone) { + return nil + } else if err != nil { + return err + } + claim := "av1alpha1.ResourceClaim{} + if err := api.Get(ctx, client.ObjectKey{Namespace: machine.Namespace, Name: name}, claim); apierrors.IsNotFound(err) { + return nil + } else if err != nil { + return fmt.Errorf("%w: read ResourceClaim: %v", ErrQuotaUnknown, err) + } + if !matches(machine, claim) { + return ErrQuotaInvalid + } + uid := claim.UID + if err := api.Delete(ctx, claim, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("%w: delete ResourceClaim: %v", ErrQuotaUnknown, err) + } + // Deletion is observed, not assumed: the next call sees the claim gone. + return fmt.Errorf("%w: the claim is being deleted", ErrQuotaPending) } -func validateResourceClaim(intent QuotaIntent, claim *quotav1alpha1.ResourceClaim) error { - if claim == nil || claim.UID == "" || claim.Name != intent.Name || claim.Namespace != intent.Namespace || claim.Labels["fleet.datumapis.com/machine-uid"] != string(intent.ClaimUID) || claim.Labels["fleet.datumapis.com/consumer-project-uid"] != string(intent.ConsumerProject.UID) || claim.Spec.ConsumerRef.APIGroup != "resourcemanager.miloapis.com" || claim.Spec.ConsumerRef.Kind != "Project" || claim.Spec.ConsumerRef.Name != intent.ConsumerProject.RouteName || claim.Spec.ResourceRef == nil || claim.Spec.ResourceRef.APIGroup != fleetv1.GroupVersion.Group || claim.Spec.ResourceRef.Kind != "Machine" || claim.Spec.ResourceRef.Namespace != intent.Namespace || claim.Spec.ResourceRef.Name != intent.ClaimName || len(claim.Spec.Requests) != 1 || claim.Spec.Requests[0].ResourceType != intent.ResourceType || claim.Spec.Requests[0].Amount != intent.Amount { - return ErrAuthorityInvalid +// client resolves the Machine's consumer incarnation, which must be a Milo +// Project. +func (q Quota) client(ctx context.Context, machine allocation.Machine) (client.Client, error) { + if machine.Consumer.APIGroup != tenancy.ProjectGroup || machine.Consumer.Kind != tenancy.ProjectKind { + return nil, fmt.Errorf("%w: Milo quota serves Project consumers only", tenancy.ErrUnsupportedConsumer) + } + consumer, err := tenancy.Incarnation(ctx, q.Consumers, machine.Consumer, machine.ConsumerUID) + if err != nil { + return nil, err } - return nil + return consumer.Client, nil } diff --git a/internal/milo/quota_test.go b/internal/milo/quota_test.go index 14c12a79..401a52f4 100644 --- a/internal/milo/quota_test.go +++ b/internal/milo/quota_test.go @@ -8,64 +8,116 @@ import ( quotav1alpha1 "go.miloapis.com/milo/pkg/apis/quota/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" - "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/allocation" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" ) -func quotaScheme(t *testing.T) *runtime.Scheme { +func quotaClient(t *testing.T) client.Client { t.Helper() scheme := runtime.NewScheme() if err := quotav1alpha1.AddToScheme(scheme); err != nil { t.Fatal(err) } - return scheme + // Like the API server, the fake assigns a UID on create. + return fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.CreateOption) error { + object.SetUID(types.UID("uid-" + object.GetName())) + return api.Create(ctx, object, options...) + }}).Build() } -func TestResourceClaimExactnessAndLostCreateRecovery(t *testing.T) { +// consumers resolves every project to one incarnation and API. +func consumers(api client.Client, uid types.UID) tenancy.Resolver { + return tenancy.ResolverFunc(func(_ context.Context, ref fleetv1.TypedReference) (tenancy.Consumer, error) { + return tenancy.Consumer{Ref: ref, UID: uid, Client: api}, nil + }) +} + +var machine = allocation.Machine{Consumer: tenancy.Project("consumer-example"), ConsumerUID: "00000000-0000-4000-8000-000000000501", Namespace: "default", Name: "allocation", UID: "00000000-0000-4000-8000-000000000601"} + +// TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce creates the claim +// once, retries find it by name, and only a granted claim reserves quota. +func TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce(t *testing.T) { ctx := context.Background() - project := controller.ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "project-uid"} - intent := QuotaIntentFor(project, "default", "allocation", "claim-uid") - kube := fake.NewClientBuilder().WithScheme(quotaScheme(t)).Build() - manager := ResourceClaimManager{} - if _, granted, err := manager.Acquire(ctx, kube, intent); !errors.Is(err, ErrQuotaPending) || granted { - t.Fatalf("initial acquire = %v, %v", granted, err) + api := quotaClient(t) + quota := Quota{Consumers: consumers(api, machine.ConsumerUID)} + if _, err := quota.Acquire(ctx, machine); !errors.Is(err, ErrQuotaPending) { + t.Fatalf("first acquire = %v", err) } - var created quotav1alpha1.ResourceClaim - if err := kube.Get(ctx, client.ObjectKey{Namespace: intent.Namespace, Name: intent.Name}, &created); err != nil { - t.Fatal(err) + // A retry after a lost create response finds the same claim. + if _, err := quota.Acquire(ctx, machine); !errors.Is(err, ErrQuotaPending) { + t.Fatalf("retried acquire = %v", err) } - if len(created.OwnerReferences) != 0 { - t.Fatalf("quota claim has owner references: %#v", created.OwnerReferences) + var claims quotav1alpha1.ResourceClaimList + if err := api.List(ctx, &claims); err != nil || len(claims.Items) != 1 || claims.Items[0].Name != ClaimName(machine) { + t.Fatalf("claims = %+v, %v", claims.Items, err) } - created.UID, created.Generation = "quota-uid", 2 - created.Status.ObservedGeneration = 2 - created.Status.Conditions = []metav1.Condition{{Type: quotav1alpha1.ResourceClaimGranted, Status: metav1.ConditionTrue}} - if err := kube.Update(ctx, &created); err != nil { + claim := &claims.Items[0] + claim.Generation = 2 + claim.Status.ObservedGeneration = 2 + claim.Status.Conditions = []metav1.Condition{{Type: quotav1alpha1.ResourceClaimGranted, Status: metav1.ConditionTrue}} + if err := api.Update(ctx, claim); err != nil { t.Fatal(err) } - hold, granted, err := manager.Acquire(ctx, kube, intent) - if err != nil || !granted || hold.UID != "quota-uid" { - t.Fatalf("recovered hold = %#v, %v, %v", hold, granted, err) + if name, err := quota.Acquire(ctx, machine); err != nil || name != ClaimName(machine) { + t.Fatalf("granted acquire = %q, %v", name, err) } - created.Spec.Requests[0].Amount = 2 - if err := kube.Update(ctx, &created); err != nil { + // Another Machine with the same UID in another project gets its own name. + other := machine + other.ConsumerUID = "00000000-0000-4000-8000-000000000502" + if ClaimName(other) == ClaimName(machine) { + t.Fatal("two projects share a quota claim name") + } + claim.Spec.Requests[0].Amount = 2 + if err := api.Update(ctx, claim); err != nil { t.Fatal(err) } - if _, _, err := manager.Acquire(ctx, kube, intent); !errors.Is(err, ErrAuthorityInvalid) { - t.Fatalf("forged claim error = %v", err) + if _, err := quota.Acquire(ctx, machine); !errors.Is(err, ErrQuotaInvalid) { + t.Fatalf("altered claim = %v", err) + } +} + +// TestReleaseIsObservedNotAssumed deletes the claim and reports it released +// only once it is gone. +func TestReleaseIsObservedNotAssumed(t *testing.T) { + ctx := context.Background() + api := quotaClient(t) + quota := Quota{Consumers: consumers(api, machine.ConsumerUID)} + _, _ = quota.Acquire(ctx, machine) + if err := quota.Release(ctx, machine); !errors.Is(err, ErrQuotaPending) { + t.Fatalf("release while deleting = %v", err) + } + if err := quota.Release(ctx, machine); err != nil { + t.Fatalf("release after deletion = %v", err) } } -func TestResourceClaimMissingIsPendingNotSettlement(t *testing.T) { - project := controller.ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "project-uid"} - intent := QuotaIntentFor(project, "default", "allocation", "claim-uid") - kube := fake.NewClientBuilder().WithScheme(quotaScheme(t)).Build() - _, _, err := (ResourceClaimManager{}).Acquire(context.Background(), kube, intent) - if !errors.Is(err, ErrQuotaPending) { - t.Fatalf("missing ResourceClaim = %v, want pending", err) +// TestQuotaServesOnlyTheMachinesProjectIncarnation never claims quota in a +// project recreated under the Machine's project name, or for a consumer that +// is not a Milo Project, and finds nothing left to release in a recreated +// project. +func TestQuotaServesOnlyTheMachinesProjectIncarnation(t *testing.T) { + ctx := context.Background() + api := quotaClient(t) + recreated := Quota{Consumers: consumers(api, "00000000-0000-4000-8000-000000000509")} + if _, err := recreated.Acquire(ctx, machine); !errors.Is(err, tenancy.ErrConsumerGone) { + t.Fatalf("acquire in a recreated project = %v", err) + } + if err := recreated.Release(ctx, machine); err != nil { + t.Fatalf("release in a recreated project = %v", err) + } + namespaced := machine + namespaced.Consumer = tenancy.Namespace("consumer-example") + if _, err := (Quota{Consumers: consumers(api, machine.ConsumerUID)}).Acquire(ctx, namespaced); !errors.Is(err, tenancy.ErrUnsupportedConsumer) { + t.Fatalf("acquire for a Namespace consumer = %v", err) + } + var claims quotav1alpha1.ResourceClaimList + if err := api.List(ctx, &claims); err != nil || len(claims.Items) != 0 { + t.Fatalf("claims = %+v, %v", claims.Items, err) } - // ResourceClaimManager deliberately has no Settle method. Only an injected - // QuotaCustodian can produce the acknowledgment consumed by release. } diff --git a/internal/milo/records.go b/internal/milo/records.go deleted file mode 100644 index f8b1e547..00000000 --- a/internal/milo/records.go +++ /dev/null @@ -1,268 +0,0 @@ -package milo - -import ( - "context" - "encoding/json" - "fmt" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/util/retry" - "sigs.k8s.io/controller-runtime/pkg/client" - - "go.datum.net/fleet/internal/controller" -) - -const ( - authoritySchemaVersion = 1 - authorityDataKey = "record.json" - authorityType = corev1.SecretType("fleet.datumapis.com/private-milo-authority") -) - -// RecordStore persists private authority state in a service-controlled -// namespace. It must not be backed by a consumer-visible project namespace. -type RecordStore struct { - client client.Client - namespace string -} - -func NewRecordStore(kube client.Client, namespace string) (*RecordStore, error) { - if kube == nil || namespace == "" { - return nil, ErrAuthorityInvalid - } - return &RecordStore{client: kube, namespace: namespace}, nil -} - -func authorityRecordName(authorityID string, projectUID, claimUID types.UID) string { - return "fleet-milo-" + shortDigest(authorityID+"/"+string(projectUID)+"/"+string(claimUID)) -} - -func (s *RecordStore) Create(ctx context.Context, record AuthorityRecord) (controller.AuthorityRef, error) { - if err := validateAuthorityRecord(&record); err != nil { - return controller.AuthorityRef{}, err - } - name := authorityRecordName(record.SourceRequest.ConsumerProject.AuthorityID, record.SourceRequest.ConsumerProject.UID, record.ClaimUID) - secret := corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: s.namespace, Labels: map[string]string{"fleet.datumapis.com/private-record": "milo-authority", "fleet.datumapis.com/claim-uid": string(record.ClaimUID)}}, Type: authorityType} - if err := encodeAuthority(&secret, &record); err != nil { - return controller.AuthorityRef{}, err - } - if err := s.client.Create(ctx, &secret); apierrors.IsAlreadyExists(err) { - existing, _, getErr := s.getByName(ctx, name) - if getErr != nil { - return controller.AuthorityRef{}, getErr - } - if !sameAuthorityContract(existing, &record) { - return controller.AuthorityRef{}, fmt.Errorf("%w: authority record name is occupied by another lifetime", ErrAuthorityInvalid) - } - return authorityRef(name, existing), nil - } else if err != nil { - return controller.AuthorityRef{}, err - } - return authorityRef(name, &record), nil -} - -func (s *RecordStore) Get(ctx context.Context, ref controller.AuthorityRef) (*AuthorityRecord, error) { - if !ref.Valid() || ref.Provider != "milo" { - return nil, ErrAuthorityInvalid - } - record, _, err := s.getByName(ctx, ref.RecordName) - if err != nil { - return nil, err - } - if record.RecordID != ref.RecordID || record.ContractDigest != ref.ContractDigest { - return nil, ErrAuthorityInvalid - } - return record, nil -} - -func (s *RecordStore) GetForClaim(ctx context.Context, consumer controller.ProjectIdentity, claimUID types.UID) (*AuthorityRecord, controller.AuthorityRef, error) { - if !consumer.Valid() { - return nil, controller.AuthorityRef{}, ErrAuthorityInvalid - } - name := authorityRecordName(consumer.AuthorityID, consumer.UID, claimUID) - record, _, err := s.getByName(ctx, name) - if err != nil { - return nil, controller.AuthorityRef{}, err - } - return record, authorityRef(name, record), nil -} - -func (s *RecordStore) Update(ctx context.Context, ref controller.AuthorityRef, mutate func(*AuthorityRecord) error) (*AuthorityRecord, error) { - var result *AuthorityRecord - err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - record, secret, err := s.getByName(ctx, ref.RecordName) - if err != nil { - return err - } - if record.RecordID != ref.RecordID || record.ContractDigest != ref.ContractDigest { - return ErrAuthorityInvalid - } - if err := mutate(record); err != nil { - return err - } - if err := validateAuthorityRecord(record); err != nil { - return err - } - if err := encodeAuthority(secret, record); err != nil { - return err - } - if err := s.client.Update(ctx, secret); err != nil { - return err - } - result = record - return nil - }) - return result, err -} - -func (s *RecordStore) getByName(ctx context.Context, name string) (*AuthorityRecord, *corev1.Secret, error) { - var secret corev1.Secret - if err := s.client.Get(ctx, client.ObjectKey{Namespace: s.namespace, Name: name}, &secret); err != nil { - return nil, nil, err - } - record, err := decodeAuthoritySecret(&secret) - if err != nil { - // Authority records are read only by their claim's deterministic - // name, so an unreadable one blocks only that claim. - controller.ReportUndecodableRecord(ctx, "milo-authority", &secret, err) - return nil, &secret, fmt.Errorf("%w: %w", err, controller.ErrRecordUnreadable) - } - return record, &secret, err -} - -func decodeAuthoritySecret(secret *corev1.Secret) (*AuthorityRecord, error) { - var record AuthorityRecord - if secret == nil || secret.Type != authorityType || secret.Labels["fleet.datumapis.com/private-record"] != "milo-authority" || json.Unmarshal(secret.Data[authorityDataKey], &record) != nil || validateAuthorityRecord(&record) != nil || secret.Name != authorityRecordName(record.SourceRequest.ConsumerProject.AuthorityID, record.SourceRequest.ConsumerProject.UID, record.ClaimUID) || secret.Labels["fleet.datumapis.com/claim-uid"] != string(record.ClaimUID) { - return nil, ErrAuthorityInvalid - } - return &record, nil -} - -// DecodePrivateAuthorityRoute exposes routing identity only after the Milo -// owner validates the full authority record and deterministic Secret identity. -func DecodePrivateAuthorityRoute(secret *corev1.Secret) (controller.PrivateRecordRoute, error) { - record, err := decodeAuthoritySecret(secret) - if err != nil { - return controller.PrivateRecordRoute{}, err - } - route := controller.PrivateRecordRoute{RecordType: "milo-authority", ClaimNamespace: record.ClaimNamespace, ClaimName: record.ClaimName, ClaimUID: record.ClaimUID, ConsumerProject: record.SourceRequest.ConsumerProject, NamespaceUIDs: []types.UID{record.SourceRequest.NamespaceUID}, AuthorityRecordIDs: []string{record.RecordID}, PendingEntitlement: record.State == StatePrepared && record.Entitlement == nil} - if record.QuotaHold != nil { - route.QuotaUIDs = append(route.QuotaUIDs, record.QuotaHold.UID) - } - if record.Entitlement != nil { - route.EntitlementUIDs = append(route.EntitlementUIDs, record.Entitlement.UID) - } - return route, nil -} - -func encodeAuthority(secret *corev1.Secret, record *AuthorityRecord) error { - b, err := json.Marshal(record) - if err != nil { - return err - } - secret.Type = authorityType - secret.Data = map[string][]byte{authorityDataKey: b} - return nil -} - -func authorityRef(name string, record *AuthorityRecord) controller.AuthorityRef { - return controller.AuthorityRef{Provider: "milo", RecordName: name, RecordID: record.RecordID, ContractDigest: record.ContractDigest} -} - -func sameAuthorityContract(a, b *AuthorityRecord) bool { - left, _ := json.Marshal(a.AcceptedRequirements) - right, _ := json.Marshal(b.AcceptedRequirements) - return a.RecordID == b.RecordID && a.ClaimNamespace == b.ClaimNamespace && a.ClaimName == b.ClaimName && a.ClaimUID == b.ClaimUID && a.SourceRequest == b.SourceRequest && a.SourceReceipt == b.SourceReceipt && a.ContractDigest == b.ContractDigest && string(left) == string(right) -} - -func validateAuthorityRecord(r *AuthorityRecord) error { - if r.SchemaVersion != authoritySchemaVersion || r.RecordID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || r.ClaimUID != r.SourceRequest.ClaimUID || r.SourceRequest.Validate() != nil || validateReceipt(r.SourceRequest, r.SourceReceipt) != nil || r.ContractDigest == "" { - return ErrAuthorityInvalid - } - contract := struct { - Request SourceUseRequest `json:"request"` - Receipt SourceUseReceipt `json:"receipt"` - }{r.SourceRequest, r.SourceReceipt} - want, err := digest(contract) - if err != nil || want != r.ContractDigest { - return ErrAuthorityInvalid - } - requirements, err := digest(r.AcceptedRequirements) - if err != nil || requirements != r.SourceRequest.RequirementsDigest { - return ErrAuthorityInvalid - } - switch r.State { - case StatePrepared: - if r.Entitlement != nil || r.QuotaIntent != nil || r.QuotaHold != nil || r.FenceReceipt != nil || r.Settlement != nil || r.AssetID != "" || r.BindingID != "" { - return ErrAuthorityInvalid - } - case StateQuotaIntent: - if r.QuotaIntent == nil || r.Entitlement == nil || r.FenceReceipt != nil || r.Settlement != nil || r.AssetID != "" || r.BindingID != "" { - return ErrAuthorityInvalid - } - case StateQuotaGranted: - if r.QuotaIntent == nil || r.QuotaHold == nil || r.Entitlement == nil || r.Settlement != nil || r.AssetID != "" || r.BindingID != "" { - return ErrAuthorityInvalid - } - case StateBound: - if r.QuotaIntent == nil || r.QuotaHold == nil || r.Entitlement == nil || r.FenceReceipt == nil || r.Settlement != nil || r.AssetID == "" || r.BindingID == "" { - return ErrAuthorityInvalid - } - case StateCleanupVerified: - if r.QuotaIntent == nil || r.QuotaHold == nil || r.Entitlement == nil || r.Settlement != nil { - return ErrAuthorityInvalid - } - case StateQuotaReleasePending: - if r.QuotaIntent == nil || r.QuotaHold == nil || r.Entitlement == nil { - return ErrAuthorityInvalid - } - case StateReleased: - activeQuota := r.QuotaIntent != nil || r.QuotaHold != nil || r.Entitlement != nil || r.Settlement != nil - if activeQuota && (r.QuotaIntent == nil || r.QuotaHold == nil || r.Entitlement == nil || r.Settlement == nil) { - return ErrAuthorityInvalid - } - if !activeQuota && (r.FenceReceipt != nil || r.AssetID != "" || r.BindingID != "") { - return ErrAuthorityInvalid - } - case StateQuarantined: - default: - return ErrAuthorityInvalid - } - if (r.AssetID == "") != (r.BindingID == "") { - return ErrAuthorityInvalid - } - if r.QuotaHold != nil && (!r.QuotaHold.Ref().Valid() || r.QuotaIntent == nil || r.QuotaHold.Intent != *r.QuotaIntent) { - return ErrAuthorityInvalid - } - if r.QuotaIntent != nil && !r.QuotaIntent.Valid() || r.QuotaHold != nil && !r.QuotaHold.Valid() || r.Entitlement != nil && !r.Entitlement.Valid() { - return ErrAuthorityInvalid - } - if r.QuotaIntent != nil && (r.QuotaIntent.ConsumerProject != r.SourceRequest.ConsumerProject || r.QuotaIntent.Namespace != r.ClaimNamespace || r.QuotaIntent.ClaimName != r.ClaimName || r.QuotaIntent.ClaimUID != r.ClaimUID) { - return ErrAuthorityInvalid - } - if r.FenceReceipt != nil { - if r.QuotaHold == nil || r.Entitlement == nil { - return ErrAuthorityInvalid - } - ref := authorityRef(authorityRecordName(r.SourceRequest.ConsumerProject.AuthorityID, r.SourceRequest.ConsumerProject.UID, r.ClaimUID), r) - commitDigest, digestErr := digest(AdmissionCommit{Authority: ref, SourceUse: r.SourceRequest, Source: r.SourceReceipt, Entitlement: *r.Entitlement, Hold: *r.QuotaHold}) - if digestErr != nil || r.FenceReceipt.ContractDigest != r.ContractDigest || r.FenceReceipt.CommitDigest != commitDigest || r.FenceReceipt.FenceToken != r.SourceReceipt.FenceToken || r.FenceReceipt.CommitID == "" { - return ErrAuthorityInvalid - } - } - if r.State == StateReleased && r.QuotaHold != nil && r.Settlement == nil { - return ErrAuthorityInvalid - } - if r.Settlement != nil && (r.QuotaHold == nil || !validSettlement(controller.AuthorityRef{RecordID: r.RecordID}, *r.QuotaHold, *r.Settlement)) { - return ErrAuthorityInvalid - } - if r.NoHold != nil && (r.NoHold.AuthorityRecordID != r.RecordID || r.NoHold.IntentDigest == "" || r.NoHold.AcknowledgmentID == "") { - return ErrAuthorityInvalid - } - if (r.LastSettledHold == nil) != (r.LastSettlement == nil) || r.LastSettlement != nil && !validSettlement(controller.AuthorityRef{RecordID: r.RecordID}, *r.LastSettledHold, *r.LastSettlement) { - return ErrAuthorityInvalid - } - return nil -} diff --git a/internal/milo/types.go b/internal/milo/types.go index 47d43654..893580c7 100644 --- a/internal/milo/types.go +++ b/internal/milo/types.go @@ -1,32 +1,19 @@ +// Package milo holds Fleet's Milo service identity and its quota claim for a +// Machine. package milo -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "strings" - - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - fleetnetwork "go.datum.net/fleet/internal/network" -) +import "errors" var ( - ErrAuthorityUnavailable = errors.New("caller-preserving source authority is unavailable") - ErrAdmissionFenceUnavailable = errors.New("atomic admission fence is unavailable") - ErrQuotaCustodyUnavailable = errors.New("protected quota custody is unavailable") - ErrProjectLifetimeMismatch = errors.New("project lifetime does not match retained authority") - ErrAuthorityInvalid = errors.New("retained Milo authority is invalid") - ErrEntitlementUnavailable = errors.New("current Fleet entitlement is unavailable") - ErrQuotaPending = errors.New("Milo quota grant is pending") - ErrQuotaUnknown = errors.New("Milo quota outcome is unknown") - ErrQuotaReleaseUnknown = errors.New("Milo quota release is not acknowledged") - ErrClaimAuthorityNotFound = errors.New("claim has no Milo authority or lifecycle custody") + // ErrQuotaPending means the quota claim exists and Milo has not granted + // it yet. The allocator retries. + ErrQuotaPending = errors.New("Milo quota grant is pending") + // ErrQuotaUnknown means the claim could not be read or written, or is + // being deleted; its outcome is unknown. + ErrQuotaUnknown = errors.New("Milo quota outcome is unknown") + // ErrQuotaInvalid means a claim with the Machine's name is not the claim + // Fleet would create for it. + ErrQuotaInvalid = errors.New("the quota claim does not match the Machine") ) const ( @@ -34,219 +21,3 @@ const ( EntitlementName = "metal" MachineQuotaResource = "metal.datumapis.com/machines" ) - -type ProjectResolver interface { - Resolve(context.Context, string) (controller.ProjectIdentity, client.Client, error) - Verify(context.Context, controller.ProjectIdentity) error -} - -type ProfileKind string - -const ( - ProfileCustom ProfileKind = "Custom" - ProfilePublished ProfileKind = "Published" -) - -type SourceUseRequest struct { - ConsumerProject controller.ProjectIdentity `json:"consumerProject"` - ProviderProject controller.ProjectIdentity `json:"providerProject"` - NamespaceUID types.UID `json:"namespaceUID"` - ClaimUID types.UID `json:"claimUID"` - LocalClassUID types.UID `json:"localClassUID"` - SourceClassUID types.UID `json:"sourceClassUID"` - SourceClassRevision string `json:"sourceClassRevision"` - SourceClassDigest string `json:"sourceClassDigest"` - LocalProfileUID types.UID `json:"localProfileUID"` - SourceProfileUID types.UID `json:"sourceProfileUID,omitempty"` - ProfileKind ProfileKind `json:"profileKind"` - RequirementsDigest string `json:"requirementsDigest"` - PublicationRevision string `json:"publicationRevision"` - Location fleetnetwork.LocationAuthority `json:"location"` -} - -func (r SourceUseRequest) Validate() error { - if !r.ConsumerProject.Valid() || !r.ProviderProject.Valid() || r.NamespaceUID == "" || r.ClaimUID == "" || r.LocalClassUID == "" || r.SourceClassUID == "" || r.SourceClassRevision == "" || r.SourceClassDigest == "" || r.LocalProfileUID == "" || r.RequirementsDigest == "" || r.PublicationRevision == "" || !r.Location.Valid() { - return ErrAuthorityInvalid - } - if r.ProfileKind == ProfilePublished && r.SourceProfileUID == "" || r.ProfileKind == ProfileCustom && r.SourceProfileUID != "" || r.ProfileKind != ProfilePublished && r.ProfileKind != ProfileCustom { - return ErrAuthorityInvalid - } - return nil -} - -type SourceUseReceipt struct { - RequestDigest string `json:"requestDigest"` - PrincipalUID string `json:"principalUID"` - DecisionID string `json:"decisionID"` - PublicationRevision string `json:"publicationRevision"` - FenceToken string `json:"fenceToken"` -} - -type SourceAuthorizer interface { - AuthorizeSource(context.Context, SourceUseRequest) (SourceUseReceipt, error) -} - -type EntitlementEvidence struct { - Name string `json:"name"` - UID types.UID `json:"uid"` - Generation int64 `json:"generation"` - ObservedGeneration int64 `json:"observedGeneration"` - ServiceName string `json:"serviceName"` -} - -func (e EntitlementEvidence) Valid() bool { - return e.Name == EntitlementName && e.UID != "" && e.Generation > 0 && e.ObservedGeneration == e.Generation && e.ServiceName == ServiceName -} - -type EntitlementReader interface { - Current(context.Context, client.Client) (EntitlementEvidence, error) -} - -type QuotaIntent struct { - ConsumerProject controller.ProjectIdentity `json:"consumerProject"` - Namespace string `json:"namespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - ResourceType string `json:"resourceType"` - Amount int64 `json:"amount"` - Name string `json:"name"` -} - -func (i QuotaIntent) Valid() bool { - return i.ConsumerProject.Valid() && i.Namespace != "" && i.ClaimName != "" && i.ClaimUID != "" && i.ResourceType == MachineQuotaResource && i.Amount == 1 && i.Name == QuotaIntentFor(i.ConsumerProject, i.Namespace, i.ClaimName, i.ClaimUID).Name -} - -type QuotaHold struct { - Intent QuotaIntent `json:"intent"` - UID types.UID `json:"uid"` - Generation int64 `json:"generation"` - ObservedGeneration int64 `json:"observedGeneration"` -} - -func (h QuotaHold) Valid() bool { - return h.Intent.Valid() && h.UID != "" && h.Generation > 0 && h.ObservedGeneration == h.Generation -} - -func (h QuotaHold) Ref() controller.ExternalHoldRef { - return controller.ExternalHoldRef{Provider: "milo", Namespace: h.Intent.Namespace, Name: h.Intent.Name, UID: h.UID} -} - -type QuotaManager interface { - Acquire(context.Context, client.Client, QuotaIntent) (QuotaHold, bool, error) -} - -type SettlementReceipt struct { - AuthorityRecordID string `json:"authorityRecordID"` - Hold controller.ExternalHoldRef `json:"hold"` - HoldDigest string `json:"holdDigest"` - AcknowledgmentID string `json:"acknowledgmentID"` -} - -// QuotaCustodian is the protected owner of an intent's complete lifetime. -// Implementations must serialize Acquire with Recover/NoHold closure and -// Settle so an acquire effect cannot occur after a NoHoldReceipt closes the -// exact project/authority/intent tuple. -type QuotaCustodian interface { - Acquire(context.Context, controller.ProjectIdentity, controller.AuthorityRef, QuotaIntent) (QuotaHold, bool, error) - Recover(context.Context, controller.ProjectIdentity, controller.AuthorityRef, QuotaIntent) (IntentResolution, error) - Settle(context.Context, controller.ProjectIdentity, controller.AuthorityRef, QuotaHold) (SettlementReceipt, error) -} - -type IntentResolution struct { - Hold *QuotaHold `json:"hold,omitempty"` - NoHold *NoHoldReceipt `json:"noHold,omitempty"` -} - -type NoHoldReceipt struct { - AuthorityRecordID string `json:"authorityRecordID"` - IntentDigest string `json:"intentDigest"` - AcknowledgmentID string `json:"acknowledgmentID"` -} - -type AdmissionCommit struct { - Authority controller.AuthorityRef `json:"authority"` - SourceUse SourceUseRequest `json:"sourceUse"` - Source SourceUseReceipt `json:"source"` - Entitlement EntitlementEvidence `json:"entitlement"` - Hold QuotaHold `json:"hold"` -} - -type AdmissionCommitReceipt struct { - ContractDigest string `json:"contractDigest"` - CommitDigest string `json:"commitDigest"` - FenceToken string `json:"fenceToken"` - CommitID string `json:"commitID"` -} - -type AdmissionFence interface { - Commit(context.Context, AdmissionCommit) (AdmissionCommitReceipt, error) -} - -type AuthorityState string - -const ( - StatePrepared AuthorityState = "Prepared" - StateQuotaIntent AuthorityState = "QuotaIntent" - StateQuotaGranted AuthorityState = "QuotaGranted" - StateBound AuthorityState = "Bound" - StateCleanupVerified AuthorityState = "CleanupVerified" - StateQuotaReleasePending AuthorityState = "QuotaReleasePending" - StateReleased AuthorityState = "Released" - StateQuarantined AuthorityState = "Quarantined" -) - -// AuthorityRecord is the private Milo authority state for one claim lifetime. -type AuthorityRecord struct { - SchemaVersion int `json:"schemaVersion"` - RecordID string `json:"recordID"` - State AuthorityState `json:"state"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - SourceRequest SourceUseRequest `json:"sourceRequest"` - SourceReceipt SourceUseReceipt `json:"sourceReceipt"` - ContractDigest string `json:"contractDigest"` - AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` - Entitlement *EntitlementEvidence `json:"entitlement,omitempty"` - QuotaIntent *QuotaIntent `json:"quotaIntent,omitempty"` - QuotaHold *QuotaHold `json:"quotaHold,omitempty"` - FenceReceipt *AdmissionCommitReceipt `json:"fenceReceipt,omitempty"` - AssetID string `json:"assetID,omitempty"` - BindingID string `json:"bindingID,omitempty"` - Settlement *SettlementReceipt `json:"settlement,omitempty"` - LastSettledHold *QuotaHold `json:"lastSettledHold,omitempty"` - LastSettlement *SettlementReceipt `json:"lastSettlement,omitempty"` - NoHold *NoHoldReceipt `json:"noHold,omitempty"` -} - -func digest(value any) (string, error) { - b, err := json.Marshal(value) - if err != nil { - return "", err - } - sum := sha256.Sum256(b) - return hex.EncodeToString(sum[:]), nil -} - -func shortDigest(value string) string { - sum := sha256.Sum256([]byte(value)) - return hex.EncodeToString(sum[:12]) -} - -func requirementsDigest(profile *fleetv1.MachineProfile) (string, error) { - if profile == nil { - return "", ErrAuthorityInvalid - } - return digest(profile.Spec) -} - -func validateReceipt(request SourceUseRequest, receipt SourceUseReceipt) error { - want, err := digest(request) - if err != nil { - return err - } - if receipt.RequestDigest != want || strings.TrimSpace(receipt.PrincipalUID) == "" || strings.TrimSpace(receipt.DecisionID) == "" || receipt.PublicationRevision != request.PublicationRevision || strings.TrimSpace(receipt.FenceToken) == "" { - return ErrAuthorityInvalid - } - return nil -} diff --git a/internal/multiplane/location_adversarial_test.go b/internal/multiplane/location_adversarial_test.go index eee7c3d6..c1af29c0 100644 --- a/internal/multiplane/location_adversarial_test.go +++ b/internal/multiplane/location_adversarial_test.go @@ -4,66 +4,63 @@ import ( "context" "errors" "testing" - "time" + "go.datum.net/fleet/internal/allocation" fleet "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" - core "k8s.io/api/core/v1" + "go.datum.net/fleet/internal/tenancy" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" ) +// TestAdversarialRejectNonlocalMachineBeforeAllocation refuses a Machine for +// another location before any allocation, finalizer or custody claim: the +// provider project and custody are never touched. func TestAdversarialRejectNonlocalMachineBeforeAllocation(t *testing.T) { ctx := context.Background() scheme := Scheme() - private := fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.CreateOption) error { - object.SetUID(types.UID("private-" + object.GetName())) - return api.Create(ctx, object, options...) - }}).Build() - coordinator, err := controller.NewCoordinator(private, PrivateNamespace, &disconnected{}, controller.LocalDigestImageResolver{}, nil, time.Hour) - if err != nil { - t.Fatal(err) + var providerWrites int + countWrites := interceptor.Funcs{ + Create: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.CreateOption) error { + providerWrites++ + return api.Create(ctx, object, options...) + }, + Update: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.UpdateOption) error { + providerWrites++ + return api.Update(ctx, object, options...) + }, } profile := &fleet.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "local-profile", UID: "source-profile"}} profile.Spec.CPU.Architecture = "amd64" profile.Spec.CPU.Cores = 2 profile.Spec.Memory.Capacity = "2Gi" - class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} - capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} - for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) - } + class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: DeviceNamespace}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "not-the-local-location"}, PowerState: "Off"}} - namespace := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: "consumer-namespace"}} - localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "consumer-class"}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} + localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "consumer-class"}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{PublisherRef: tenancy.Project("provider"), Name: "local-class"}}} localProfile := profile.DeepCopyObject().(*fleet.MachineProfile) localProfile.UID = "consumer-profile" runner := Runner{ - Config: Config{Cell: "only-local-cell"}, Private: private, Coordinator: coordinator, - Provider: Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(class, profile, capacity).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}, + Config: Config{Cell: "only-local-cell"}, + Provider: Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(class, profile).WithInterceptorFuncs(countWrites).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}, } - runner.Consumers[0] = Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(machine, namespace, localClass, localProfile).WithStatusSubresource(&fleet.Machine{}).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "consumer", UID: "consumer-project"}} - if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + runner.Consumers[0] = Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(machine, localClass, localProfile).WithStatusSubresource(&fleet.Machine{}).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "consumer", UID: "consumer-project"}} + // Allocate runs the location check first; it never reaches the + // allocator, which this runner does not have. + if err := runner.Allocate(ctx); !errors.Is(err, ErrLocationNotServed) { t.Fatalf("nonlocal Machine was not rejected by location: %v", err) } - // Rejection precedes custody, synthetic authority records and finalizers. - var secrets core.SecretList - if err := private.List(ctx, &secrets); err != nil { - t.Fatal(err) - } - if len(secrets.Items) != 0 { - t.Fatalf("wrong-location request retained %d private records", len(secrets.Items)) + if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + t.Fatalf("nonlocal Machine was not rejected by location: %v", err) } var stored fleet.Machine if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { t.Fatal(err) } - if len(stored.Finalizers) != 0 { - t.Fatal("wrong-location request installed a lifecycle finalizer") + if len(stored.Finalizers) != 0 || providerWrites != 0 { + t.Fatalf("wrong-location request left a finalizer %v or wrote the provider project %d times", stored.Finalizers, providerWrites) } // The served location is still refused when no cell is configured. stored.Spec.LocationRef.Name = Location @@ -75,34 +72,14 @@ func TestAdversarialRejectNonlocalMachineBeforeAllocation(t *testing.T) { t.Fatalf("location accepted without a bound cell: %v", err) } runner.Config.Cell = "only-local-cell" - req, err := runner.request(ctx, 0) - if err != nil { - t.Fatalf("served location rejected: %v", err) - } - if _, err := coordinator.ReleaseScoped(ctx, req.ConsumerProject, req.Claim.UID); err != nil { - t.Fatal(err) - } - result, err := coordinator.CompleteExternalRelease(ctx, req.Claim.UID, req.Authority, req.ExternalHold, req.ConsumerProject) - if err != nil || !result.SafeToRemoveFinalizer { - t.Fatalf("release: %+v %v", result, err) - } - if err := publishRelease(ctx, runner.Consumers[0].API, req.Claim); err != nil { - t.Fatal(err) - } if _, err := runner.request(ctx, 0); err != nil { - t.Fatal(err) - } - if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { - t.Fatal(err) - } - if len(stored.Finalizers) != 0 { - t.Fatal("request restored finalizer after terminal custody") + t.Fatalf("served location rejected: %v", err) } } func TestAdversarialReleaseRemovesFinalizerAfterStatus(t *testing.T) { ctx := context.Background() - m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine", Finalizers: []string{"other.example/keep", controller.MachineFinalizer}}} + m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine", Finalizers: []string{"other.example/keep", allocation.MachineFinalizer}}} m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: "installed"} install := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "installed", Namespace: Namespace}, Status: fleet.InstallationStatus{Phase: "Ready", Conditions: []metav1.Condition{condition("Ready", metav1.ConditionTrue, 0, "Installed")}}} api := fake.NewClientBuilder().WithScheme(Scheme()).WithObjects(m, install).WithStatusSubresource(&fleet.Machine{}, &fleet.Installation{}).Build() diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 869cb956..f69aaffa 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -1,12 +1,11 @@ // Package multiplane is an explicit local acceptance composition of the shared -// lifecycle, real Milo project APIs, and the Karmada executor transport. -// Admission, quota, catalog publication and hardware evidence are synthetic. +// allocator on Device custody, real Milo project APIs, and the Karmada +// federation transport. Admission, quota, catalog publication and discovery +// are synthetic. package multiplane import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -15,82 +14,184 @@ import ( "strings" "time" - fleet "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/coordination" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/manager" rm "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" core "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" meta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "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/controller" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/tenancy" ) const Namespace = "default" -const PrivateNamespace = "fleet-system-private" + +// DeviceNamespace holds the provider project's Devices, capacities, +// allocations, custody and operations. +const DeviceNamespace = "fleet-provider" + +// Device is the one Device the acceptance allocates. +const Device = "synthetic-device-central-01" // Location is the only location this acceptance composition serves. It is bound // to exactly one Karmada member, Config.Cell, and to the one local capacity // fixture. There is no location catalog: any other Machine locationRef is -// rejected before claim custody, authority records, finalizers, or allocation, -// so a request for elsewhere can never reserve or effect local hardware. +// rejected before any allocation or finalizer, so a request for elsewhere +// can never reserve or effect local hardware. const Location = "local" var ErrLocationNotServed = errors.New("machine location is not served by the configured cell") -type Config struct{ State, HubKubeconfig, PrivateKubeconfig, Cell, Image string } +// errPending means a phase's effect has not finished; the phase is retried. +var errPending = errors.New("not finished yet") + +type Config struct { + State, HubKubeconfig, Cell, Image string + // Enrollment is the cell's fixture enrollment of each Device it serves. + Enrollment fixture.Enrollment +} + type Project struct { API client.Client Identity controller.ProjectIdentity } + type Runner struct { - Config Config - Provider Project - Consumers [2]Project - Private client.Client - Hub *coordination.Hub - Coordinator *controller.Coordinator + Config Config + Provider Project + Consumers [2]Project + Allocator *allocation.Allocator + Hub *coordination.Hub } func Scheme() *runtime.Scheme { s := runtime.NewScheme() _ = core.AddToScheme(s) _ = fleet.AddToScheme(s) + _ = inventory.AddToScheme(s) + _ = ops.AddToScheme(s) _ = rm.AddToScheme(s) return s } -func API(path string) (client.Client, error) { + +func restConfig(path string) (*rest.Config, error) { c, err := clientcmd.BuildConfigFromFlags("", path) if err != nil { return nil, err } c.Timeout = 30 * time.Second - return client.New(c, client.Options{Scheme: Scheme()}) + return c, nil } -func New(ctx context.Context, c Config) (*Runner, error) { - r := &Runner{Config: c} - var err error - r.Private, err = API(c.PrivateKubeconfig) + +func API(path string) (client.Client, error) { + c, err := restConfig(path) if err != nil { return nil, err } - cfg, err := clientcmd.BuildConfigFromFlags("", c.HubKubeconfig) + return client.New(c, client.Options{Scheme: Scheme()}) +} + +// Principals are the provider project's Fleet identities, one per component. +// The local Milo authenticates each with its own static token. +func principals(ctx context.Context, state string) (custody.Principals, ops.Creator, ops.Creator, error) { + provider, err := identity(ctx, filepath.Join(state, "provider", "management-project.json")) + if err != nil { + return nil, ops.Creator{}, ops.Creator{}, err + } + release, err := identity(ctx, filepath.Join(state, "provider", "release-project.json")) + if err != nil { + return nil, ops.Creator{}, ops.Creator{}, err + } + p := custody.Principals{custody.CreatorMetalProvider: {{Username: provider.Username, UID: provider.UID}}, custody.CreatorReleaseController: {{Username: release.Username, UID: release.UID}}} + return p, provider, release, p.Validate() +} + +func identity(ctx context.Context, path string) (ops.Creator, error) { + c, err := restConfig(path) + if err != nil { + return ops.Creator{}, err + } + return allocation.Creator(ctx, c) +} + +// coordinator builds the custody coordinator with the Karmada hub as the +// one site serving the Device. +func coordinator(ctx context.Context, c Config, registry *custody.Registry) (*custody.Coordinator, *coordination.Hub, *delivery.Sites, client.Client, error) { + api, err := API(filepath.Join(c.State, "provider", "coordinator-project.json")) + if err != nil { + return nil, nil, nil, nil, err + } + hubConfig, err := restConfig(c.HubKubeconfig) + if err != nil { + return nil, nil, nil, nil, err + } + dynamicHub, err := dynamic.NewForConfig(hubConfig) + if err != nil { + return nil, nil, nil, nil, err + } + hub := &coordination.Hub{API: dynamicHub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} + sites := &delivery.Sites{Sites: map[string]delivery.Site{c.Cell: hub}, Devices: map[string][]string{}} + for key := range c.Enrollment { + namespace, name, _ := strings.Cut(key, "/") + if namespace == DeviceNamespace { + sites.Devices[name] = []string{c.Cell} + } + } + p, _, _, err := principals(ctx, c.State) + if err != nil { + return nil, nil, nil, nil, err + } + return &custody.Coordinator{Client: api, Registry: registry, Sites: sites, Config: custody.Config{Namespace: DeviceNamespace, Principals: p}}, hub, sites, api, nil +} + +// Coordinate is the coordinator process: the custody loop, delivering +// through Karmada, and fixture discovery for the cell's Devices under the +// discovery identity. +func Coordinate(ctx context.Context, c Config, onError func(error)) error { + registry, err := custody.DefaultRegistry() + if err != nil { + return err + } + coord, _, sites, api, err := coordinator(ctx, c, registry) + if err != nil { + return err + } + discovery, err := API(filepath.Join(c.State, "provider", "discovery-project.json")) + if err != nil { + return err + } + loop := &delivery.Loop{Client: api, Coordinator: coord, Namespace: DeviceNamespace, OnError: onError, + 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) +} + +func New(ctx context.Context, c Config) (*Runner, error) { + r := &Runner{Config: c} + registry, err := custody.DefaultRegistry() if err != nil { return nil, err } - cfg.Timeout = 30 * time.Second - hub, err := dynamic.NewForConfig(cfg) + coord, hub, _, _, err := coordinator(ctx, c, registry) if err != nil { return nil, err } - r.Hub = &coordination.Hub{API: hub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} - r.Coordinator, err = controller.NewCoordinator(r.Private, PrivateNamespace, r.Hub, controller.LocalDigestImageResolver{}, nil, time.Hour) + r.Hub = hub + _, providerCreator, releaseCreator, err := principals(ctx, c.State) if err != nil { return nil, err } @@ -114,14 +215,29 @@ func New(ctx context.Context, c Config) (*Runner, error) { r.Consumers[index-1] = p } } + releaser, err := API(filepath.Join(c.State, "provider", "release-project.json")) + if err != nil { + return nil, err + } + r.Allocator = &allocation.Allocator{ + Provider: r.Provider.API, ProviderCreator: providerCreator, + Releaser: releaser, ReleaseCreator: releaseCreator, + Custody: coord, Namespace: DeviceNamespace, + Cleaning: func(name string) (string, error) { + if name != "local-cleaning" { + return "", fmt.Errorf("no fixture cleaning policy %q", name) + } + return custody.SpecDigest(`{"method":"overwrite","disks":"all"}`) + }, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + } return r, nil } -func (r *Runner) ScopedAsset() string { - return r.Provider.Identity.AuthorityID + "/" + string(r.Provider.Identity.UID) + "/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" -} + func condition(kind string, status metav1.ConditionStatus, generation int64, reason string) metav1.Condition { return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, Reason: reason, Message: "Local multi-plane acceptance; synthetic IAM, quota, catalog and networkless fixtures", LastTransitionTime: metav1.Now()} } + func ensure(ctx context.Context, c client.Client, obj client.Object) error { before, _ := json.Marshal(obj) var want map[string]interface{} @@ -144,198 +260,63 @@ func ensure(ctx context.Context, c client.Client, obj client.Object) error { return nil } -// Seed uses bootstrap only for provider facts/publication; requests use distinct -// customer credentials and a watch starts before each create. -func Seed(ctx context.Context, c Config) error { - var profile fleet.MachineProfile - var class fleet.MachineClass - var capacity fleet.MachineCapacity - if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-profile"},"spec":{"cpu":{"architecture":"amd64","cores":2},"memory":{"capacity":"2Gi"}}}`), &profile); err != nil { - return err - } - if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-class"},"spec":{"profilePolicy":{"allowedProfiles":[{"name":"local-profile"}],"customProfiles":{"enabled":false}},"capacity":{"machineCapacities":{"namespace":"fleet-provider","selector":{"matchLabels":{"pool":"local"}}}}}}`), &class); err != nil { - return err - } - if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-capacity","namespace":"fleet-provider","labels":{"pool":"local"}},"spec":{"deviceRef":{"name":"synthetic-device-central-01"},"allocationPolicy":"Enabled","cleaningPolicyRef":{"name":"local-cleaning"},"reclaimPolicy":"Retain"}}`), &capacity); err != nil { - return err - } - provider, err := API(filepath.Join(c.State, "provider", "bootstrap-project.json")) - if err != nil { - return err - } - for _, obj := range []client.Object{&profile, &class, &capacity} { - if err := ensure(ctx, provider, obj); err != nil { - return err - } - } - class.Status.EvaluatedRevision = "local-fixture-v1" - if err := provider.Status().Update(ctx, &class); err != nil { - return err - } - capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} - for _, kind := range []string{"Available", "Verified", "Prepared", "Healthy"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, capacity.Generation, "SyntheticHardwareObservation")) - } - if err := provider.Status().Update(ctx, &capacity); err != nil { - return err - } - var routing []map[string]string - for _, name := range []string{"consumer-a", "consumer-b"} { - api, err := API(filepath.Join(c.State, name, "bootstrap-project.json")) - if err != nil { - return err - } - cp := profile.DeepCopyObject().(*fleet.MachineProfile) - cp.ObjectMeta = metav1.ObjectMeta{Name: profile.Name} - cc := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: class.Name}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: class.Name}}} - if err := ensure(ctx, api, cp); err != nil { - return err - } - if err := ensure(ctx, api, cc); err != nil { - return err - } - customer, err := clientcmd.BuildConfigFromFlags("", filepath.Join(c.State, name, "customer-project.json")) - if err != nil { - return err - } - d, err := dynamic.NewForConfig(customer) - if err != nil { - return err - } - gvr := fleet.GroupVersion.WithResource("machines") - seconds := int64(30) - w, err := d.Resource(gvr).Namespace(Namespace).Watch(ctx, metav1.ListOptions{TimeoutSeconds: &seconds}) - if err != nil { - return err - } - user, err := API(filepath.Join(c.State, name, "customer-project.json")) - if err != nil { - w.Stop() - return err - } - machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}, PowerState: "Off"}} - if err := ensure(ctx, user, machine); err != nil { - w.Stop() - return err - } - select { - case event, ok := <-w.ResultChan(): - observed, typed := event.Object.(metav1.Object) - if !ok || event.Type != "ADDED" || !typed || observed.GetUID() != machine.UID || observed.GetName() != machine.Name || observed.GetNamespace() != Namespace { - w.Stop() - return errors.New("Milo create watch did not deliver Added") - } - case <-ctx.Done(): - w.Stop() - return ctx.Err() - } - w.Stop() - installation := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "debian-pxe", Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: machine.Name}, ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: c.Image}}} - if err := ensure(ctx, user, installation); err != nil { - return err - } - var ns core.Namespace - if err := api.Get(ctx, client.ObjectKey{Name: Namespace}, &ns); err != nil { - return err - } - root, err := API(filepath.Join(c.State, name, "management-root.json")) - if err != nil { - return err - } - identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) - if err != nil { - return err - } - routing = append(routing, map[string]string{"route": name, "namespace": Namespace, "namespaceUID": string(ns.UID), "projectUID": string(identity.UID), "machineUID": string(machine.UID), "watch": "Added exact UID"}) - - } - evidence, err := json.MarshalIndent(routing, "", " ") - if err != nil { - return err - } - return os.WriteFile(filepath.Join(c.State, "routing.json"), evidence, 0600) - +// request is one consumer's Machine, resolved against the provider's +// published class and profile. Location is checked before anything else. +type request struct { + project Project + machine *fleet.Machine + alloc allocation.Request } -func (r *Runner) request(ctx context.Context, index int) (controller.AllocationRequest, error) { + +func (r *Runner) request(ctx context.Context, index int) (*request, error) { p := r.Consumers[index] var m fleet.Machine - var ns core.Namespace - var class fleet.MachineClass - var profile fleet.MachineProfile - var capacity fleet.MachineCapacity - var localClass fleet.MachineClass - var localProfile fleet.MachineProfile + var class, localClass fleet.MachineClass + var profile, localProfile fleet.MachineProfile objects := []struct { api client.Client key client.ObjectKey obj client.Object - }{{p.API, client.ObjectKey{Namespace: Namespace, Name: "allocation"}, &m}, {p.API, client.ObjectKey{Name: Namespace}, &ns}, {r.Provider.API, client.ObjectKey{Name: "local-class"}, &class}, {r.Provider.API, client.ObjectKey{Name: "local-profile"}, &profile}, {r.Provider.API, client.ObjectKey{Namespace: "fleet-provider", Name: "local-capacity"}, &capacity}, {p.API, client.ObjectKey{Name: "local-class"}, &localClass}, {p.API, client.ObjectKey{Name: "local-profile"}, &localProfile}} + }{{p.API, client.ObjectKey{Namespace: Namespace, Name: "allocation"}, &m}, {r.Provider.API, client.ObjectKey{Name: "local-class"}, &class}, {r.Provider.API, client.ObjectKey{Name: "local-profile"}, &profile}, {p.API, client.ObjectKey{Name: "local-class"}, &localClass}, {p.API, client.ObjectKey{Name: "local-profile"}, &localProfile}} for _, o := range objects { if err := o.api.Get(ctx, o.key, o.obj); err != nil { - return controller.AllocationRequest{}, err + return nil, err } } if m.Spec.LocationRef.Name != Location || r.Config.Cell == "" || r.Hub != nil && r.Hub.Cell != r.Config.Cell { - return controller.AllocationRequest{}, fmt.Errorf("%w: %q", ErrLocationNotServed, m.Spec.LocationRef.Name) - } - if localClass.Spec.Source == nil || localClass.Spec.Source.Project != "provider" || localClass.Spec.Source.Name != class.Name { - return controller.AllocationRequest{}, errors.New("publication source mismatch") - } - observed := meta.FindStatusCondition(capacity.Status.Conditions, "Verified") - if observed == nil { - return controller.AllocationRequest{}, errors.New("missing hardware fixture evidence") - } - admission := controller.AdmissionAuthority{PrincipalUID: "local-fixture:" + string(p.Identity.UID), DecisionID: "local-fixture:" + string(m.UID)} - if err := r.Coordinator.EnsureClaimCustody(ctx, &m, ns.UID, admission, p.Identity); err != nil { - return controller.AllocationRequest{}, err - } - // Retain a concrete synthetic contract record, not just an invented reference. - contract, _ := json.Marshal(struct { - Consumer, Provider controller.ProjectIdentity - Claim, Capacity, Class, Profile types.UID - }{p.Identity, r.Provider.Identity, m.UID, capacity.UID, class.UID, profile.UID}) - sum := sha256.Sum256(contract) - digest := hex.EncodeToString(sum[:]) - name := "mp-authority-" + digest[:24] - secret := &core.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: PrivateNamespace}, Data: map[string][]byte{"contract.json": contract}} - if err := r.Private.Create(ctx, secret); apierrors.IsAlreadyExists(err) { - var existing core.Secret - if err := r.Private.Get(ctx, client.ObjectKeyFromObject(secret), &existing); err != nil { - return controller.AllocationRequest{}, err - } - if string(existing.Data["contract.json"]) != string(contract) { - return controller.AllocationRequest{}, errors.New("retained synthetic authority conflict") - } - secret = &existing - } else if err != nil { - return controller.AllocationRequest{}, err + return nil, fmt.Errorf("%w: %q", ErrLocationNotServed, m.Spec.LocationRef.Name) } - authority := controller.AuthorityRef{Provider: "local-fixture", RecordName: name, RecordID: string(secret.UID), ContractDigest: digest} - hold := controller.ExternalHoldRef{Provider: "local-fixture", Namespace: PrivateNamespace, Name: name, UID: secret.UID} - if err := r.Coordinator.RetainClaimAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority); err != nil { - return controller.AllocationRequest{}, err + if localClass.Spec.Source == nil || localClass.Spec.Source.Name != class.Name { + return nil, errors.New("publication source mismatch") } - if err := r.Coordinator.RetainAllocationAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority, hold); err != nil { - return controller.AllocationRequest{}, err + if _, err := tenancy.Incarnation(ctx, r.publishers(), localClass.Spec.Source.PublisherRef, r.Provider.Identity.UID); err != nil { + return nil, fmt.Errorf("publication source mismatch: %w", err) } - hasFinalizer := false - for _, f := range m.Finalizers { - if f == controller.MachineFinalizer { - hasFinalizer = true - } - } - released, err := r.Coordinator.ClaimReleased(ctx, p.Identity, m.UID) + consumer, err := r.Resolve(ctx, tenancy.Project(p.Identity.RouteName)) if err != nil { - return controller.AllocationRequest{}, err + return nil, err } - if !hasFinalizer && !released { - m.Finalizers = append(m.Finalizers, controller.MachineFinalizer) - if err := p.API.Update(ctx, &m); err != nil { - return controller.AllocationRequest{}, err + return &request{project: p, machine: &m, alloc: allocation.Request{ + Machine: allocation.MachineOf(consumer, &m), + Class: &class, Profile: &profile, + Authority: fleet.AllocationAuthority{Principal: "local-fixture:" + p.Identity.RouteName, Decision: "local-fixture:" + m.Namespace + "/" + m.Name}, + }}, nil +} + +// protect adds the finalizer that keeps the Machine until it is released. +func (q *request) protect(ctx context.Context) error { + for _, f := range q.machine.Finalizers { + if f == allocation.MachineFinalizer { + return nil } } - return controller.AllocationRequest{Claim: &m, Class: &class, Profile: &profile, MachineCapacities: []fleet.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: observed.LastTransitionTime.Time}, NamespaceUID: ns.UID, Admission: admission, LocalClassName: localClass.Name, LocalClassUID: localClass.UID, LocalProfileName: localProfile.Name, LocalProfileUID: localProfile.UID, ConsumerProject: p.Identity, ProviderProject: r.Provider.Identity, Authority: authority, ExternalHold: hold}, nil + if q.machine.DeletionTimestamp != nil { + return nil + } + q.machine.Finalizers = append(q.machine.Finalizers, allocation.MachineFinalizer) + return q.project.API.Update(ctx, q.machine) } + func (r *Runner) Allocate(ctx context.Context) error { a, err := r.request(ctx, 0) if err != nil { @@ -345,88 +326,178 @@ func (r *Runner) Allocate(ctx context.Context) error { if err != nil { return err } - if a.NamespaceUID == b.NamespaceUID || a.ConsumerProject.SameLifetime(b.ConsumerProject) { + if a.project.Identity.SameLifetime(b.project.Identity) { return errors.New("consumer control planes do not have distinct identities") } - if _, err = r.Coordinator.Allocate(ctx, a); err != nil { + if err := r.verified(ctx); err != nil { + return err + } + for _, q := range []*request{a, b} { + if err := q.protect(ctx); err != nil { + return err + } + } + if _, err := r.Allocator.Allocate(ctx, a.alloc); err != nil { return err } - if _, err = r.Coordinator.Allocate(ctx, b); !errors.Is(err, controller.ErrInsufficientCapacity) { + if _, err := r.Allocator.Allocate(ctx, b.alloc); !errors.Is(err, allocation.ErrInsufficientCapacity) { return fmt.Errorf("contention must retain one winner: %v", err) } - for index, request := range []controller.AllocationRequest{a, b} { - m := request.Claim + for index, q := range []*request{a, b} { phase, reason := "Bound", "AwaitingVerifiedInstallation" status := metav1.ConditionTrue if index == 1 { phase, reason, status = "Pending", "InsufficientCapacity", metav1.ConditionFalse } - m.Status.Phase = phase - m.Status.Conditions = []metav1.Condition{condition("Bound", status, m.Generation, reason), condition("Ready", metav1.ConditionFalse, m.Generation, reason)} - if err := r.Consumers[index].API.Status().Update(ctx, m); err != nil { + q.machine.Status.Phase = phase + q.machine.Status.Conditions = []metav1.Condition{condition("Bound", status, q.machine.Generation, reason), condition("Ready", metav1.ConditionFalse, q.machine.Generation, reason)} + if err := q.project.API.Status().Update(ctx, q.machine); err != nil { + return err + } + if err := r.projectPower(ctx, q); err != nil { return err } } return nil } -func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } -// InstallSecond installs consumer B's Installation after it reused the -// capacity, through the same lifecycle and federation path. -func (r *Runner) InstallSecond(ctx context.Context) error { return r.InstallIndex(ctx, 1) } +// verified waits for custody of the Device to be Verified, which needs the +// coordinator process and the cell's fence report. +func (r *Runner) verified(ctx context.Context) error { + state := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, state); err != nil { + return fmt.Errorf("%w: custody: %v", errPending, err) + } + if state.Spec.State != ops.CustodyVerified { + return fmt.Errorf("%w: custody is %s", errPending, state.Spec.State) + } + return nil +} -func (r *Runner) InstallIndex(ctx context.Context, index int) error { - request, err := r.request(ctx, index) +func (r *Runner) projectPower(ctx context.Context, q *request) error { + return manager.ProjectPower(ctx, q.project.API, r.Provider.API, DeviceNamespace, q.alloc.Machine) +} + +// installation creates the consumer's DeviceInstallation once and returns +// it with the allocation. +func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet.MachineAllocation, *fleet.Installation, *ops.DeviceInstallation, error) { + q, err := r.request(ctx, index) if err != nil { - return err + return nil, nil, nil, nil, err + } + current, err := r.Allocator.Get(ctx, q.alloc.Machine) + if err != nil { + return nil, nil, nil, nil, err + } + if current == nil || current.Status.Phase != fleet.AllocationActive { + return nil, nil, nil, nil, errors.New("the consumer has no active allocation") } var install fleet.Installation - if err := r.Consumers[index].API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + return nil, nil, nil, nil, err + } + operation := &ops.DeviceInstallation{} + name := custody.InstallationName(current.Name, string(install.UID)) + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: name}, operation); apierrors.IsNotFound(err) { + previous := "" + if ref := q.machine.Status.CurrentInstallationRef; ref != nil { + previous = ref.Name + } + if operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &install, Current: previous}); err != nil { + return nil, nil, nil, nil, err + } + } else if err != nil { + return nil, nil, nil, nil, err + } + return q, current, &install, operation, nil +} + +// ErrAdmittedUnknown reports that an installation is admitted and delivered +// but its result is still unknown. The admit-install phase expects it. +var ErrAdmittedUnknown = errors.New("installation admitted; its result remains unknown") + +// AdmitInstall creates consumer A's installation and returns +// ErrAdmittedUnknown once custody admitted it and its handoff exists. +func (r *Runner) AdmitInstall(ctx context.Context) error { + _, _, _, operation, err := r.installation(ctx, 0) + if err != nil { return err } - result, err := r.Coordinator.Install(ctx, controller.InstallationRequest{Claim: request.Claim, Installation: &install, NamespaceUID: request.NamespaceUID, ConsumerProject: request.ConsumerProject, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: request.Admission.PrincipalUID, DecisionID: "local-install:" + string(install.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + imageDigest(install.Spec.ImageRef.Name)}}) + switch phase := operation.Status.Phase; { + case phase == ops.PhaseSucceeded: + return errors.New("the installation already completed; run before the cell dispatches") + case phase.Ended(): + return fmt.Errorf("the installation ended %s: %s", phase, operation.Status.Reason) + case phase == ops.PhasePending || phase == "": + return fmt.Errorf("%w: the installation is %s", errPending, phase) + } + return ErrAdmittedUnknown +} + +func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } + +// InstallSecond installs consumer B's Installation after it reused the +// capacity, through the same allocator and federation path. +func (r *Runner) InstallSecond(ctx context.Context) error { return r.InstallIndex(ctx, 1) } + +func (r *Runner) InstallIndex(ctx context.Context, index int) error { + q, _, install, operation, err := r.installation(ctx, index) if err != nil { return err } - verified, found, err := r.Hub.Lookup(ctx, result.Record.OperationID) - if err != nil || !found || verified.InputDigest != result.RequestDigest { - return executor.ErrOutcomeUnknown + switch phase := operation.Status.Phase; { + case phase.Ended() && phase != ops.PhaseSucceeded: + return fmt.Errorf("%w: the installation ended %s: %s", errTerminal, phase, operation.Status.Reason) + case phase != ops.PhaseSucceeded: + return fmt.Errorf("%w: the installation is %s", errPending, phase) } install.Status.Phase = "Ready" install.Status.Conditions = []metav1.Condition{condition("Ready", metav1.ConditionTrue, install.Generation, "LocalPXEVerifiedViaKarmada")} - if err := r.Consumers[index].API.Status().Update(ctx, &install); err != nil { + if err := q.project.API.Status().Update(ctx, install); err != nil { return err } - m := request.Claim + m := q.machine m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: install.Name} m.Status.Phase = "Ready" meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionTrue, m.Generation, "LocalPXEVerifiedViaKarmada")) - return r.Consumers[index].API.Status().Update(ctx, m) + if err := q.project.API.Status().Update(ctx, m); err != nil { + return err + } + return r.projectPower(ctx, q) } + +// errTerminal marks an error that retrying cannot fix. +var errTerminal = errors.New("terminal") + +// Terminal reports whether a phase must stop retrying. +func Terminal(err error) bool { return errors.Is(err, errTerminal) } + +// Pending reports whether a phase is waiting for an effect. +func Pending(err error) bool { return errors.Is(err, errPending) } + func (r *Runner) Release(ctx context.Context) error { return r.ReleaseIndex(ctx, 0) } func (r *Runner) ReleaseSecond(ctx context.Context) error { return r.ReleaseIndex(ctx, 1) } + +// ReleaseIndex advances the consumer's release one step; the phase repeats +// it until the allocation is Released, then publishes the Machine Released. +// The acceptance releases a Machine that still exists, as the consumer's +// release request; the management identity cannot delete Machines. func (r *Runner) ReleaseIndex(ctx context.Context, index int) error { - request, err := r.request(ctx, index) - if err != nil { - return err - } - result, err := r.Coordinator.ReleaseScoped(ctx, request.ConsumerProject, request.Claim.UID) + q, err := r.request(ctx, index) if err != nil { return err } - if result.ExternalSettlementRequired { - result, err = r.Coordinator.CompleteExternalRelease(ctx, request.Claim.UID, request.Authority, request.ExternalHold, request.ConsumerProject) - if err != nil { - return err - } + released, err := r.Allocator.ReleaseMachine(ctx, q.alloc.Machine) + if errors.Is(err, allocation.ErrWipeFailed) { + return fmt.Errorf("%w: %v", errTerminal, err) } - if !result.SafeToRemoveFinalizer { - return executor.ErrOutcomeUnknown + if err != nil || !released { + return fmt.Errorf("%w: the release is not finished (%v)", errPending, err) } - return publishRelease(ctx, r.Consumers[index].API, request.Claim) + return publishRelease(ctx, q.project.API, q.machine) } -// publishRelease runs only after verified cleanup made removal safe. Status is +// publishRelease runs only after the allocation is Released. Status is // written first because a status response overwrites the in-memory object, // including metadata, from the server; the finalizer is removed afterwards // from that fresh copy so the removal is not silently reverted. @@ -456,29 +527,34 @@ func publishRelease(ctx context.Context, api client.Client, m *fleet.Machine) er } retainedFinalizers := make([]string, 0, len(m.Finalizers)) for _, f := range m.Finalizers { - if f != controller.MachineFinalizer { + if f != allocation.MachineFinalizer { retainedFinalizers = append(retainedFinalizers, f) } } m.Finalizers = retainedFinalizers return api.Update(ctx, m) } + func (r *Runner) Reuse(ctx context.Context) error { b, err := r.request(ctx, 1) if err != nil { return err } - if _, err = r.Coordinator.Allocate(ctx, b); err != nil { + if _, err = r.Allocator.Allocate(ctx, b.alloc); err != nil { return err } - // Public status follows only the coordinator's committed reuse binding; - // readiness still requires a verified installation for this allocation. - m := b.Claim + // Public status follows the active allocation; readiness still requires + // a verified installation for it. + m := b.machine m.Status.Phase = "Bound" meta.SetStatusCondition(&m.Status.Conditions, condition("Bound", metav1.ConditionTrue, m.Generation, "AwaitingVerifiedInstallation")) meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionFalse, m.Generation, "AwaitingVerifiedInstallation")) - return r.Consumers[1].API.Status().Update(ctx, m) + if err := r.Consumers[1].API.Status().Update(ctx, m); err != nil { + return err + } + return r.projectPower(ctx, b) } + func ReadConfig(path string) (Config, error) { var c Config b, err := os.ReadFile(path) @@ -489,4 +565,21 @@ func ReadConfig(path string) (Config, error) { return c, err } -func imageDigest(value string) string { _, digest, _ := strings.Cut(value, "@"); return digest } +// Resolve resolves a consumer project of the lab to its recorded identity +// and API. +func (r *Runner) Resolve(_ context.Context, ref fleet.TypedReference) (tenancy.Consumer, error) { + if err := tenancy.Supported(ref); err != nil { + return tenancy.Consumer{}, err + } + for _, p := range r.Consumers { + if ref.Kind == tenancy.ProjectKind && p.Identity.RouteName == ref.Name { + return tenancy.Consumer{Ref: ref, UID: p.Identity.UID, Client: p.API}, nil + } + } + return tenancy.Consumer{}, fmt.Errorf("%w: project %s is not a lab consumer", tenancy.ErrConsumerGone, ref.Name) +} + +// publishers resolves the lab's one provider project. +func (r *Runner) publishers() tenancy.Resolver { + return tenancy.Fixed(tenancy.Consumer{Ref: tenancy.Project(r.Provider.Identity.RouteName), UID: r.Provider.Identity.UID, Client: r.Provider.API}) +} diff --git a/internal/multiplane/runner_test.go b/internal/multiplane/runner_test.go deleted file mode 100644 index 6bbdb1f2..00000000 --- a/internal/multiplane/runner_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package multiplane - -import ( - "context" - "errors" - "sync" - "testing" - "time" - - fleet "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - "sigs.k8s.io/controller-runtime/pkg/client/interceptor" -) - -type disconnected struct{ calls int } - -func (d *disconnected) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { - d.calls++ - return simulator.OperationResult{}, executor.ErrOutcomeUnknown -} -func (d *disconnected) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown -} -func TestIndependentProjectsContendAndUnknownRetainsCustody(t *testing.T) { - ctx := context.Background() - s := Scheme() - private := fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { - obj.SetUID(types.UID("private-" + obj.GetName())) - return c.Create(ctx, obj, opts...) - }}).Build() - var profile fleet.MachineProfile - profile.Name = "local-profile" - profile.UID = "source-profile" - profile.Spec.CPU.Architecture = "amd64" - profile.Spec.CPU.Cores = 2 - profile.Spec.Memory.Capacity = "2Gi" - class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} - capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} - for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { - capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) - } - provider := fake.NewClientBuilder().WithScheme(s).WithObjects(class, &profile, capacity).Build() - backend := &disconnected{} - coordinator, err := controller.NewCoordinator(private, PrivateNamespace, backend, controller.LocalDigestImageResolver{}, nil, time.Hour) - if err != nil { - t.Fatal(err) - } - r := Runner{Config: Config{Cell: "cell-a"}, Private: private, Coordinator: coordinator, Provider: Project{API: provider, Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}} - for index, name := range []string{"a", "b"} { - ns := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: types.UID(name + "-namespace")}} - // Identical namespace, Machine name AND UID: only project authority separates them. - m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "same-machine-uid"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "local"}, PowerState: "Off"}} - localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: types.UID(name + "-class")}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} - cp := profile.DeepCopyObject().(*fleet.MachineProfile) - cp.UID = types.UID(name + "-profile") - r.Consumers[index] = Project{API: fake.NewClientBuilder().WithScheme(s).WithObjects(ns, m, localClass, cp).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: name, UID: types.UID(name + "-project")}} - } - a, err := r.request(ctx, 0) - if err != nil { - t.Fatal(err) - } - b, err := r.request(ctx, 1) - if err != nil { - t.Fatal(err) - } - results := make([]error, 2) - var wg sync.WaitGroup - for i, q := range []controller.AllocationRequest{a, b} { - wg.Add(1) - go func() { defer wg.Done(); _, results[i] = r.Coordinator.Allocate(ctx, q) }() - } - wg.Wait() - winner, loser := -1, -1 - for i, err := range results { - if err == nil { - if winner != -1 { - t.Fatal("both projects won") - } - winner = i - } else if errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid) { - loser = i - } else { - t.Fatal(err) - } - } - if winner < 0 || loser < 0 { - t.Fatal("contention did not produce one winner", results) - } - claims := []controller.AllocationRequest{a, b} - _, err = r.Coordinator.ReleaseScoped(ctx, claims[winner].ConsumerProject, claims[winner].Claim.UID) - if !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("disconnected cleanup must be unknown: %v", err) - } - _, err = r.Coordinator.Allocate(ctx, claims[loser]) - if !(errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid)) { - t.Fatalf("unknown cleanup exposed capacity: %v", err) - } -} diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go new file mode 100644 index 00000000..216a8284 --- /dev/null +++ b/internal/multiplane/seed.go @@ -0,0 +1,170 @@ +package multiplane + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + "strings" + + core "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/tenancy" +) + +// Seed uses bootstrap only for provider facts and publication: the profile, +// class and capacity, and one Device for each enrolled Device. Requests use +// distinct customer credentials, and a watch starts before each create. +// Creating a Device sends nothing and makes no capacity Available: custody +// starts Unverified until the cell reports its fence. +func Seed(ctx context.Context, c Config) error { + var profile fleet.MachineProfile + var class fleet.MachineClass + var capacity fleet.MachineCapacity + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-profile"},"spec":{"cpu":{"architecture":"amd64","cores":2},"memory":{"capacity":"2Gi"}}}`), &profile); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-class"},"spec":{"profilePolicy":{"allowedProfiles":[{"name":"local-profile"}],"customProfiles":{"enabled":false}},"capacity":{"machineCapacities":{"namespace":"fleet-provider","selector":{"matchLabels":{"pool":"local"}}}}}}`), &class); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-capacity","namespace":"fleet-provider","labels":{"pool":"local"}},"spec":{"deviceRef":{"name":"`+Device+`"},"allocationPolicy":"Enabled","cleaningPolicyRef":{"name":"local-cleaning"},"reclaimPolicy":"Retain"}}`), &capacity); err != nil { + return err + } + provider, err := API(filepath.Join(c.State, "provider", "bootstrap-project.json")) + if err != nil { + return err + } + devices, err := enrolledDevices(c) + if err != nil { + return err + } + for _, obj := range append([]client.Object{&profile, &class, &capacity}, devices...) { + if err := ensure(ctx, provider, obj); err != nil { + return err + } + } + class.Status.EvaluatedRevision = "local-fixture-v1" + if err := provider.Status().Update(ctx, &class); err != nil { + return err + } + // 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")) + if err != nil { + return err + } + cp := profile.DeepCopyObject().(*fleet.MachineProfile) + cp.ObjectMeta = metav1.ObjectMeta{Name: profile.Name} + cc := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: class.Name}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{PublisherRef: tenancy.Project("provider"), Name: class.Name}}} + if err := ensure(ctx, api, cp); err != nil { + return err + } + if err := ensure(ctx, api, cc); err != nil { + return err + } + customer, err := clientcmd.BuildConfigFromFlags("", filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + return err + } + d, err := dynamic.NewForConfig(customer) + if err != nil { + return err + } + gvr := fleet.GroupVersion.WithResource("machines") + seconds := int64(30) + w, err := d.Resource(gvr).Namespace(Namespace).Watch(ctx, metav1.ListOptions{TimeoutSeconds: &seconds}) + if err != nil { + return err + } + user, err := API(filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + w.Stop() + return err + } + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}, PowerState: "Off"}} + if err := ensure(ctx, user, machine); err != nil { + w.Stop() + return err + } + select { + case event, ok := <-w.ResultChan(): + observed, typed := event.Object.(metav1.Object) + if !ok || event.Type != "ADDED" || !typed || observed.GetUID() != machine.UID || observed.GetName() != machine.Name || observed.GetNamespace() != Namespace { + w.Stop() + return errors.New("Milo create watch did not deliver Added") + } + case <-ctx.Done(): + w.Stop() + return ctx.Err() + } + w.Stop() + installation := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "debian-pxe", Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: machine.Name}, ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: c.Image}}} + if err := ensure(ctx, user, installation); err != nil { + return err + } + var ns core.Namespace + if err := api.Get(ctx, client.ObjectKey{Name: Namespace}, &ns); err != nil { + return err + } + root, err := API(filepath.Join(c.State, name, "management-root.json")) + if err != nil { + return err + } + identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) + if err != nil { + return err + } + routing = append(routing, map[string]string{"route": name, "namespace": Namespace, "namespaceUID": string(ns.UID), "projectUID": string(identity.UID), "machineUID": string(machine.UID), "watch": "Added exact UID"}) + } + evidence, err := json.MarshalIndent(routing, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(c.State, "routing.json"), evidence, 0600) +} + +// enrolledDevices is one synthetic Device for each Device the cell enrolls, +// with the identity the enrollment records. +func enrolledDevices(c Config) ([]client.Object, error) { + keys := make([]string, 0, len(c.Enrollment)) + for key := range c.Enrollment { + keys = append(keys, key) + } + sort.Strings(keys) + var out []client.Object + for _, key := range keys { + namespace, name, _ := strings.Cut(key, "/") + if namespace != DeviceNamespace { + 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{ + ClaimRef: inventory.LocalReference{Name: "claim-" + name}, + Identity: inventory.DeviceIdentity{Model: "synthetic", Serial: "serial-" + name, SystemUUID: target.SystemUUID}, + BMC: &inventory.BMC{Endpoint: target.BMCEndpoint}, + Interfaces: []inventory.Interface{{Name: "primary", MACAddress: target.BootMACAddress}}, + }}) + } + if len(out) == 0 { + return nil, errors.New("the cell enrolls no Device") + } + return out, nil +} diff --git a/internal/projectdiscovery/config.go b/internal/projectdiscovery/config.go index 1bd6d829..6cb386ba 100644 --- a/internal/projectdiscovery/config.go +++ b/internal/projectdiscovery/config.go @@ -34,7 +34,7 @@ type Config struct { APIVersion string `json:"apiVersion"` Kind string `json:"kind"` // AuthorityID names the configured Milo authority recorded in every - // project identity and private custody record. + // project identity. AuthorityID string `json:"authorityID"` Discovery DiscoveryConfig `json:"discovery"` } diff --git a/internal/projectdiscovery/discovery.go b/internal/projectdiscovery/discovery.go index e62ef77e..dec83adc 100644 --- a/internal/projectdiscovery/discovery.go +++ b/internal/projectdiscovery/discovery.go @@ -74,8 +74,8 @@ type ConsumerDiscovery struct { // When a project leaves the consumer set the manager stops reconciling it and // nothing else happens: no Fleet record is deleted, no custody is released, // no status is rewritten, and no ServiceConsumer finalizer gates deletion. -// Retained custody for a departed project stays in the private namespace and -// resumes if the project is engaged again. +// Retained custody for a departed project is left as it is and resumes if +// the project is engaged again. // // tune, if given, adjusts the provider-project manager's options (tests use // it to relax controller-name validation). diff --git a/internal/projectdiscovery/runtime.go b/internal/projectdiscovery/runtime.go index 781a8ea6..150aca8b 100644 --- a/internal/projectdiscovery/runtime.go +++ b/internal/projectdiscovery/runtime.go @@ -160,18 +160,10 @@ func (d StaticDiscovery) Expected(context.Context) ([]multicluster.ClusterName, return append([]multicluster.ClusterName(nil), d...), nil } -// NamedCache is an additional cache whose initial sync gates readiness, such -// as the manager's private-record cache. -type NamedCache struct { - Name string - Cache interface{ WaitForCacheSync(context.Context) bool } -} - // AddHealthChecks registers liveness and the readiness boundary: discovery -// has synced, every expected project is engaged, every engaged project cache -// has synced, and every named cache has synced. Readiness never depends on a -// provider integration. -func AddHealthChecks(mgr mcmanager.Manager, discovery Discovery, tracker *EngageTracker, caches ...NamedCache) error { +// has synced, every expected project is engaged, and every engaged project +// cache has synced. Readiness never depends on a provider integration. +func AddHealthChecks(mgr mcmanager.Manager, discovery Discovery, tracker *EngageTracker) error { if mgr == nil || discovery == nil || tracker == nil { return errors.New("health checks require a manager, discovery, and engagement tracker") } @@ -184,30 +176,7 @@ func AddHealthChecks(mgr mcmanager.Manager, discovery Discovery, tracker *Engage if err := mgr.AddReadyzCheck("projects-engaged", ProjectsEngagedCheck(discovery, tracker)); err != nil { return err } - if err := mgr.AddReadyzCheck("project-caches-synced", EngagedCachesSyncedCheck(tracker)); err != nil { - return err - } - for _, c := range caches { - if c.Name == "" || c.Cache == nil { - return errors.New("named readiness cache requires a name and a cache") - } - if err := mgr.AddReadyzCheck(c.Name+"-synced", CacheSyncedCheck(c)); err != nil { - return err - } - } - return nil -} - -// CacheSyncedCheck fails until c has completed its initial sync. -func CacheSyncedCheck(c NamedCache) healthz.Checker { - return func(req *http.Request) error { - ctx, cancel := context.WithTimeout(req.Context(), readinessProbeBudget) - defer cancel() - if !c.Cache.WaitForCacheSync(ctx) { - return fmt.Errorf("%s cache has not synced", c.Name) - } - return nil - } + return mgr.AddReadyzCheck("project-caches-synced", EngagedCachesSyncedCheck(tracker)) } func DiscoverySyncedCheck(discovery Discovery) healthz.Checker { diff --git a/internal/projectdiscovery/runtime_test.go b/internal/projectdiscovery/runtime_test.go index bab48908..35c62983 100644 --- a/internal/projectdiscovery/runtime_test.go +++ b/internal/projectdiscovery/runtime_test.go @@ -52,7 +52,7 @@ func testScheme(t *testing.T) *runtime.Scheme { // startManager runs NewManager and the health checks over provider, with no // controllers. The host config is never contacted. -func startManager(t *testing.T, provider multicluster.Provider, discovery Discovery, caches ...NamedCache) (mcmanager.Manager, *EngageTracker) { +func startManager(t *testing.T, provider multicluster.Provider, discovery Discovery) (mcmanager.Manager, *EngageTracker) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) mgr, tracker, err := NewManager(&rest.Config{Host: "https://host.example.test"}, provider, manager.Options{ @@ -64,7 +64,7 @@ func startManager(t *testing.T, provider multicluster.Provider, discovery Discov cancel() t.Fatal(err) } - if err := AddHealthChecks(mgr, discovery, tracker, caches...); err != nil { + if err := AddHealthChecks(mgr, discovery, tracker); err != nil { cancel() t.Fatal(err) } @@ -77,16 +77,11 @@ func startManager(t *testing.T, provider multicluster.Provider, discovery Discov return mgr, tracker } -type syncedCache struct{ synced bool } - -func (c *syncedCache) WaitForCacheSync(context.Context) bool { return c.synced } - func TestReadinessRequiresDiscoveryEngagementAndSyncedCaches(t *testing.T) { p := multiclustertest.NewProject(t, "ready", multiclustertest.ProjectOptions{Scheme: testScheme(t)}) provider := multiclustertest.NewProvider() discovery := discoveryFunc{expected: []multicluster.ClusterName{"ready"}} - private := &syncedCache{} - mgr, tracker := startManager(t, provider, discovery, NamedCache{Name: "private-records", Cache: private}) + mgr, tracker := startManager(t, provider, discovery) if err := probe(DiscoverySyncedCheck(discoveryFunc{synced: errors.New("not synced")})); err == nil { t.Fatal("unsynced discovery reported ready") @@ -99,13 +94,6 @@ func TestReadinessRequiresDiscoveryEngagementAndSyncedCaches(t *testing.T) { if err := probe(EngagedCachesSyncedCheck(tracker)); err != nil { t.Fatalf("synced caches reported unready: %v", err) } - if err := probe(CacheSyncedCheck(NamedCache{Name: "private-records", Cache: private})); err == nil { - t.Fatal("an unsynced private cache reported ready") - } - private.synced = true - if err := probe(CacheSyncedCheck(NamedCache{Name: "private-records", Cache: private})); err != nil { - t.Fatal(err) - } cl.FakeCache.Synced = ptr.To(false) if err := probe(EngagedCachesSyncedCheck(tracker)); err == nil { diff --git a/internal/redfish/boot.go b/internal/redfish/boot.go deleted file mode 100644 index 7dd7d1e2..00000000 --- a/internal/redfish/boot.go +++ /dev/null @@ -1,217 +0,0 @@ -package redfish - -import ( - "crypto/sha256" - "crypto/subtle" - "encoding/hex" - "fmt" - "io" - "net/http" - "os" - "path/filepath" - "strconv" - "strings" - "time" -) - -// The provisioning network is site infrastructure: its DHCP hands every -// enrolled NIC the same static script, which chains to a per-MAC URL. The MAC -// is routing information, not authentication. Only a retained operation whose -// enrolled target has that MAC and whose boot admission is open receives a -// script, and that script carries the operation's scoped capability. -const chainScript = "#!ipxe\nchain %s/pxe/${net0/mac:hexhyp}/boot.ipxe\n" - -func (p *Provider) admissionOpen(j journal, r *record) bool { - if j.Closed || j.Image != p.image || r.BootClosed || len(r.BootToken) != 64 || !p.clock().Before(r.BootExpires) { - return false - } - if r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence { - return false - } - for _, ph := range phases[r.Request.Kind] { - if ph.mode != "" && (r.Stage == ph.name+"-requested" || r.Stage == ph.name+"-started") { - return true - } - } - return false -} - -func mode(r *record) string { - if r.Request.Kind == "cleanup" { - return "wipe" - } - return "install" -} - -// BootHandler never serves a caller-selected path. It reads the atomically -// replaced journal on every request and writes only delivery evidence. -func (p *Provider) BootHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { - w.Header().Set("Cache-Control", "no-store") - deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } - parts := strings.Split(q.URL.Path, "/") - if q.Method != http.MethodGet || q.URL.RawQuery != "" { - deny() - return - } - if q.URL.Path == "/pxe/boot.ipxe" { - fmt.Fprintf(w, chainScript, p.origin) - return - } - j, err := p.read() - if err != nil || len(parts) != 4 { - deny() - return - } - var r *record - var name string - if parts[1] == "pxe" && parts[3] == "boot.ipxe" { - mac, ok := normalizeMAC(parts[2]) - for _, c := range j.Operations { - if ok && c.Target.MAC == mac && p.admissionOpen(j, c) { - r, name = c, "boot.ipxe" - } - } - } else { - for _, c := range j.Operations { - if key(c.Request.ID)[:16] == parts[1] && len(c.BootToken) == 64 && subtle.ConstantTimeCompare([]byte(parts[2]), []byte(c.BootToken)) == 1 && p.admissionOpen(j, c) { - r, name = c, parts[3] - } - } - } - if r == nil || (name != "boot.ipxe" && name != "kernel" && name != "installer.gz") || (name == "boot.ipxe" && parts[1] != "pxe") { - deny() - return - } - var data []byte - var artifact *os.File - var size int64 - if name == "boot.ipxe" { - base := p.origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, mode(r), base)) - size = int64(len(data)) - } else { - // Hash the pinned artifact, then serve the same open file. - if artifact, err = os.Open(p.artifacts + "/" + name); err != nil { - deny() - return - } - defer artifact.Close() - manifest, e := os.ReadFile(p.artifacts + "/SHA256SUMS") - sum := sha256.Sum256(manifest) - h := sha256.New() - size, err = io.Copy(h, artifact) - if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { - deny() - return - } - if _, err = artifact.Seek(0, io.SeekStart); err != nil { - deny() - return - } - } - if err := p.evidence(r, "admitted", name, size); err != nil { - deny() - return - } - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) - var n int64 - var werr error - if artifact != nil { - n, werr = io.Copy(w, artifact) - } else { - var written int - written, werr = w.Write(data) - n = int64(written) - } - // A completed server write is not proof of client receipt or boot. - if werr == nil && n == size { - _ = p.evidence(r, "write-complete", name, n) - } - }) -} - -// evidence appends one line without URLs, headers, receipts or capabilities. -func (p *Provider) evidence(r *record, event, name string, size int64) error { - dir := p.bootDirectory(r) - if err := os.MkdirAll(dir, 0700); err != nil { - return err - } - f, err := os.OpenFile(filepath.Join(dir, "boot-delivery.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) - if err != nil { - return err - } - _, err = fmt.Fprintf(f, "%s %s %s bytes=%d\n", p.clock().Format(time.RFC3339), event, name, size) - if err == nil { - err = f.Sync() - } - if cerr := f.Close(); err == nil { - err = cerr - } - if err == nil { - err = syncDir(dir) - } - return err -} - -// ServeBoot listens on :8080. The write bound covers an emulated firmware -// fetching the initrd through the site's NAT path. -func (p *Provider) ServeBoot() error { - s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} - return s.ListenAndServe() -} - -// CheckClosedBoot probes a live boot listener after every admission closed: -// each retained operation's MAC script and capability URLs, an unsupported -// artifact, an unguarded artifact and an unknown identity must be denied. -func (p *Provider) CheckClosedBoot(origin string, extraMACs []string) (string, error) { - origin, err := ParseBootOrigin(origin) - if err != nil { - return "", err - } - j, err := p.read() - if err != nil { - return "", err - } - client := &http.Client{Timeout: 10 * time.Second} - count := 0 - probe := func(u string) error { - resp, err := client.Get(u) - if err != nil { - return fmt.Errorf("boot denial probe unavailable") - } - resp.Body.Close() - if resp.StatusCode != http.StatusForbidden { - return fmt.Errorf("closed or unknown boot access allowed") - } - count++ - return nil - } - for _, r := range j.Operations { - if !r.BootClosed { - return "", fmt.Errorf("boot admission not closed") - } - base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken - macPath := strings.ReplaceAll(r.Target.MAC, ":", "-") - for _, u := range []string{origin + "/pxe/" + macPath + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", base + "/boot.ipxe"} { - if err := probe(u); err != nil { - return "", err - } - } - } - for _, mac := range extraMACs { - if err := probe(origin + "/pxe/" + strings.ReplaceAll(mac, ":", "-") + "/boot.ipxe"); err != nil { - return "", err - } - } - for _, u := range []string{origin + "/kernel", origin + "/unknown/unknown/kernel", origin + "/pxe/not-a-mac/boot.ipxe"} { - if err := probe(u); err != nil { - return "", err - } - } - if len(j.Operations) == 0 { - return "", fmt.Errorf("no retained admission to probe") - } - return fmt.Sprintf("PASS %d live HTTP denials: closed per-MAC scripts and capabilities of %d operations, other enrolled MACs, unsupported and unguarded artifacts, unknown identity", count, len(j.Operations)), nil -} diff --git a/internal/redfish/dhcp.go b/internal/redfish/dhcp.go deleted file mode 100644 index b9af3f8c..00000000 --- a/internal/redfish/dhcp.go +++ /dev/null @@ -1,221 +0,0 @@ -package redfish - -import ( - "bufio" - "context" - "crypto/subtle" - "encoding/json" - "errors" - "io" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - "go.datum.net/fleet/internal/bootnet" -) - -// withdrawalWindow bounds how long a worker waits, after the network boot -// closed, for every DHCP instance that served the reservation to report it -// withdrawn. Past it the outcome stays unknown and replay waits again. -const withdrawalWindow = 10 * time.Minute - -const dhcpLog = "dhcp-applied.log" - -// report is one retained applied report: when the boot service accepted it, -// which DHCP instance applied which exact feed. -type report struct { - At time.Time `json:"at"` - Instance string `json:"instance"` - Feed bootnet.Feed `json:"feed"` -} - -// reserved reports whether the operation's boot NIC should hold its -// provisioning address now: the same admission the boot handler serves, -// widened to the stages before power-on so DHCP is ready when firmware asks. -func (p *Provider) reserved(j journal, r *record, now time.Time) bool { - return r.Target.Provisioning != (Provisioning{}) && !j.Closed && j.Image == p.image && r.Stage != "done" && !r.BootClosed && len(r.BootToken) == 64 && now.Before(r.BootExpires) && - r.Request.BindingID == j.Binding && r.Request.Epoch == j.Epoch && r.Request.FenceToken == j.Fence -} - -// Reservations is the complete desired reservation set derived from the -// journal. It is empty when no network boot is admitted. -func (p *Provider) Reservations() (bootnet.Feed, error) { - j, err := p.read() - if err != nil { - return bootnet.Feed{}, err - } - now := p.clock() - rs := []bootnet.Reservation{} - for _, r := range j.Operations { - if p.reserved(j, r, now) { - rs = append(rs, bootnet.Reservation{MAC: r.Target.MAC, Address: r.Target.Provisioning.Address, Gateway: r.Target.Provisioning.Gateway, Expires: r.BootExpires}) - } - } - return bootnet.NewFeed(rs) -} - -// DHCPHandler serves the reservation feed and accepts applied reports from -// the DHCP owner's synchronizer, authenticated by a shared bearer token. It -// is never served on the firmware-facing boot listener. -func (p *Provider) DHCPHandler(token string) (http.Handler, error) { - if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { - return nil, errors.New("DHCP synchronizer token must be at least 32 characters without whitespace") - } - return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { - w.Header().Set("Cache-Control", "no-store") - got, ok := strings.CutPrefix(q.Header.Get("Authorization"), "Bearer ") - if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - switch { - case q.Method == http.MethodGet && q.URL.Path == "/dhcp/v1/reservations" && q.URL.RawQuery == "": - feed, err := p.Reservations() - if err != nil { - http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(feed) - case q.Method == http.MethodPost && q.URL.Path == "/dhcp/v1/applied" && q.URL.RawQuery == "": - var a bootnet.Applied - d := json.NewDecoder(io.LimitReader(q.Body, 64<<10)) - d.DisallowUnknownFields() - if d.Decode(&a) != nil || d.Decode(&struct{}{}) != io.EOF || a.Verify() != nil { - http.Error(w, "invalid applied report", http.StatusBadRequest) - return - } - if err := p.retainReport(a); err != nil { - http.Error(w, "applied report not retained", http.StatusServiceUnavailable) - return - } - w.WriteHeader(http.StatusNoContent) - default: - http.Error(w, "not found", http.StatusNotFound) - } - }), nil -} - -// ServeDHCP listens on :8081, separate from the boot listener. -func (p *Provider) ServeDHCP(token string) error { - h, err := p.DHCPHandler(token) - if err != nil { - return err - } - s := &http.Server{Addr: ":8081", Handler: h, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} - return s.ListenAndServe() -} - -// retainReport appends one report and syncs it before acknowledging. -func (p *Provider) retainReport(a bootnet.Applied) error { - b, err := json.Marshal(report{At: p.clock(), Instance: a.Instance, Feed: a.Feed}) - if err != nil { - return err - } - if err := os.MkdirAll(p.bootRoot, 0700); err != nil { - return err - } - f, err := os.OpenFile(filepath.Join(p.bootRoot, dhcpLog), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) - if err != nil { - return err - } - _, err = f.Write(append(b, '\n')) - if err == nil { - err = f.Sync() - } - if cerr := f.Close(); err == nil { - err = cerr - } - if err == nil { - err = syncDir(p.bootRoot) - } - return err -} - -// reports reads every retained report in order. An unreadable line is -// corruption, never evidence in either direction. -func (p *Provider) reports() ([]report, error) { - f, err := os.Open(filepath.Join(p.bootRoot, dhcpLog)) - if os.IsNotExist(err) { - return nil, nil - } - if err != nil { - return nil, err - } - defer f.Close() - var out []report - s := bufio.NewScanner(f) - s.Buffer(make([]byte, 0, 64<<10), 1<<20) - for s.Scan() { - var r report - if json.Unmarshal(s.Bytes(), &r) != nil || r.At.IsZero() || (bootnet.Applied{Instance: r.Instance, Feed: r.Feed}).Verify() != nil { - return nil, errors.New("invalid retained DHCP report") - } - out = append(out, r) - } - return out, s.Err() -} - -// awaitReservation waits, without any effect, until some DHCP instance reports -// serving the target's exact provisioning address for this operation. -func (p *Provider) awaitReservation(ctx context.Context, r *record) error { - poll, _, _, _ := p.durations() - for { - reports, err := p.reports() - if err != nil { - return err - } - for _, a := range reports { - if a.At.After(r.Result.CreatedAt) && a.Feed.Has(r.Target.MAC, r.Target.Provisioning.Address) { - return nil - } - } - if !p.clock().Before(r.BootExpires) { - return errors.New("DHCP did not apply the boot reservation before boot admission expired") - } - if err := sleep(ctx, poll); err != nil { - return err - } - } -} - -// awaitWithdrawal requires that every DHCP instance which served the boot NIC -// during this operation now reports a feed without it. A silent instance -// keeps the outcome unknown: its reservation may still be served. -func (p *Provider) awaitWithdrawal(ctx context.Context, r *record) error { - poll, _, _, _ := p.durations() - deadline := p.clock().Add(withdrawalWindow) - for { - reports, err := p.reports() - if err != nil { - return err - } - served, latest := map[string]bool{}, map[string]bootnet.Feed{} - for _, a := range reports { - if !a.At.After(r.Result.CreatedAt) { - continue - } - if a.Feed.Serves(r.Target.MAC) { - served[a.Instance] = true - } - latest[a.Instance] = a.Feed - } - withdrawn := len(served) > 0 - for instance := range served { - if latest[instance].Serves(r.Target.MAC) { - withdrawn = false - } - } - if withdrawn { - return nil - } - if p.clock().After(deadline) { - return errors.New("DHCP has not reported the boot reservation withdrawn") - } - if err := sleep(ctx, poll); err != nil { - return err - } - } -} diff --git a/internal/redfish/dhcp_test.go b/internal/redfish/dhcp_test.go deleted file mode 100644 index 9e60e1cc..00000000 --- a/internal/redfish/dhcp_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package redfish - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "sync" - "testing" - "time" - - "go.datum.net/fleet/internal/bootnet" - "go.datum.net/fleet/internal/executor" -) - -const syncToken = "synthetic-dhcp-synchronizer-token-0123456789" - -// fakeSync stands in for the DHCP owner's synchronizer: each instance applies -// the current feed and reports it whenever its revision changes. Withholding -// an instance's reports models a DHCP instance that may still serve. -type fakeSync struct { - t *testing.T - h http.Handler - mu sync.Mutex - silent map[string]bool - applied map[string]string - stop chan struct{} - done sync.WaitGroup -} - -func startSync(t *testing.T, p *Provider, instances ...string) *fakeSync { - t.Helper() - h, err := p.DHCPHandler(syncToken) - if err != nil { - t.Fatal(err) - } - s := &fakeSync{t: t, h: h, silent: map[string]bool{}, applied: map[string]string{}, stop: make(chan struct{})} - s.done.Add(1) - go func() { - defer s.done.Done() - for { - select { - case <-s.stop: - return - case <-time.After(2 * time.Millisecond): - } - for _, instance := range instances { - s.cycle(instance) - } - } - }() - t.Cleanup(s.close) - return s -} - -func (s *fakeSync) close() { - select { - case <-s.stop: - default: - close(s.stop) - } - s.done.Wait() -} - -func (s *fakeSync) silence(instance string, v bool) { - s.mu.Lock() - s.silent[instance] = v - s.mu.Unlock() -} - -func (s *fakeSync) cycle(instance string) { - s.mu.Lock() - defer s.mu.Unlock() - if s.silent[instance] { - return - } - w := httptest.NewRecorder() - q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) - q.Header.Set("Authorization", "Bearer "+syncToken) - s.h.ServeHTTP(w, q) - var feed bootnet.Feed - if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &feed) != nil || s.applied[instance] == feed.Revision { - return - } - if code := post(s.h, syncToken, bootnet.Applied{Instance: instance, Feed: feed}); code != http.StatusNoContent { - return - } - s.applied[instance] = feed.Revision -} - -func post(h http.Handler, token string, a any) int { - b, _ := json.Marshal(a) - w := httptest.NewRecorder() - q := httptest.NewRequest(http.MethodPost, "/dhcp/v1/applied", bytes.NewReader(b)) - q.Header.Set("Authorization", "Bearer "+token) - h.ServeHTTP(w, q) - return w.Code -} - -func TestEnrollmentRecordsPhysicalAttachments(t *testing.T) { - target := func(asset, endpoint, system, uuid, mac, prov string) string { - return fmt.Sprintf(`{"assetID":%q,"endpoint":%q,"systemID":%q,"systemUUID":%q,"mac":%q%s,"diskBytes":1,"console":"c.log"}`, asset, endpoint, system, uuid, mac, prov) - } - prov := func(address string) string { - return `,"provisioning":{"address":"` + address + `","gateway":"198.51.100.1"}` - } - // Physical BMCs each expose one System with the same ID: identity is the - // endpoint plus System, so two "Self" systems on two BMCs are distinct. - e, err := ParseEnrollment([]byte(`{"dhcp":"synced","targets":[` + - target("a", "https://192.0.2.20:443", "Self", uuidA, "00-00-5E-00-53-20", prov("198.51.100.21/24")) + `,` + - target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`)) - if err != nil { - t.Fatal(err) - } - if got := e.Targets[0]; got.Endpoint != "https://192.0.2.20:443" || got.MAC != "00:00:5e:00:53:20" || got.Provisioning != (Provisioning{Address: "198.51.100.21/24", Gateway: "198.51.100.1"}) { - t.Fatalf("enrollment not canonical: %+v", got) - } - for name, body := range map[string]string{ - "same System on one BMC": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + - target("b", "https://192.0.2.20:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`, - "shared provisioning address": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + - target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.21/24")) + `]}`, - "synced without attachment": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, - "static with attachment": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `]}`, - "gateway outside prefix": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", `,"provisioning":{"address":"198.51.100.21/24","gateway":"203.0.113.1"}`) + `]}`, - "network address as host": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.0/24")) + `]}`, - "BMC endpoint with a path": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443/redfish", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, - "missing DHCP mode": `{"targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, - "retired site-wide BMC endpoint": `{"dhcp":"static","endpoint":"https://192.0.2.20:443","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, - } { - if _, err := ParseEnrollment([]byte(body)); err == nil { - t.Errorf("%s: accepted", name) - } - } -} - -func TestSyncedInstallServesAndWithdrawsTheReservation(t *testing.T) { - f := newDHCPFixture(t, time.Second, DHCPSynced) - ctx := context.Background() - if feed, err := f.p.Reservations(); err != nil || len(feed.Reservations) != 0 { - t.Fatalf("reservations published with no admitted boot: %+v %v", feed, err) - } - s := startSync(t, f.p, "kea-0") - q := f.install(1) - if r, err := f.p.Execute(ctx, q); err != nil || r.Result != "installed" { - t.Fatalf("install: %v %+v", err, r) - } - f.bmc.wg.Wait() - s.close() - reports, err := f.p.reports() - if err != nil { - t.Fatal(err) - } - var served, withdrawn bool - for _, a := range reports { - if a.Feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { - served = true - } else if served { - withdrawn = true - } - if a.Feed.Serves("52:54:00:77:01:0b") { - t.Fatal("the other enrolled target's attachment was published") - } - } - if !served || !withdrawn { - t.Fatalf("reports do not show the reservation served then withdrawn: %+v", reports) - } - if feed, _ := f.p.Reservations(); len(feed.Reservations) != 0 { - t.Fatalf("reservation outlived the operation: %+v", feed) - } - if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, dhcpLog)); strings.Contains(string(b), syncToken) { - t.Fatal("DHCP evidence contains the synchronizer token") - } -} - -func TestSyncedBootWaitsForDHCPWithoutEffects(t *testing.T) { - f := newDHCPFixture(t, time.Second, DHCPSynced) - q := f.install(1) - ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) - defer cancel() - if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("network boot proceeded without DHCP evidence: %v", err) - } - if got := strings.Join(f.bmc.mutationsFor("System-1"), ","); strings.Contains(got, "Pxe") || strings.Contains(got, "On") { - t.Fatalf("boot effects before DHCP applied the reservation: %s", got) - } - // A report from before this operation is not evidence for it. - feed, _ := f.p.Reservations() - if len(feed.Reservations) != 1 || !feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { - t.Fatalf("admitted operation not published: %+v", feed) - } - startSync(t, f.p, "kea-0") - if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { - t.Fatalf("replay after DHCP applied: %v %+v", err, r) - } - f.bmc.wg.Wait() - if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { - t.Fatalf("unexpected Redfish effects: %v", got) - } -} - -func TestUnwithdrawnReservationKeepsTheOutcomeUnknown(t *testing.T) { - f := newDHCPFixture(t, time.Second, DHCPSynced) - s := startSync(t, f.p, "kea-0", "kea-1") - q := f.install(1) - result := make(chan error, 1) - go func() { - r, err := f.p.Execute(context.Background(), q) - if err == nil && r.Result != "installed" { - err = fmt.Errorf("unexpected result %+v", r) - } - result <- err - }() - waitFor := func(what string, ok func() bool) { - t.Helper() - for deadline := time.Now().Add(5 * time.Second); !ok(); time.Sleep(2 * time.Millisecond) { - if time.Now().After(deadline) { - t.Fatal("timed out waiting for " + what) - } - } - } - // Both instances serve the reservation; then kea-1 goes silent, so it - // never reports the withdrawal and may still be serving. - waitFor("both instances to serve", func() bool { - reports, _ := f.p.reports() - served := map[string]bool{} - for _, a := range reports { - if a.Feed.Serves("52:54:00:77:01:0a") { - served[a.Instance] = true - } - } - return len(served) == 2 - }) - s.silence("kea-1", true) - waitFor("the withdrawal gate", func() bool { return f.stage(t, q.ID) == "disk-verified" }) - time.Sleep(50 * time.Millisecond) - observer := *f.p - observer.readOnly = true - if _, found, err := observer.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("completed while one DHCP instance may still serve: %v %v", found, err) - } - s.silence("kea-1", false) - if err := <-result; err != nil { - t.Fatalf("withdrawal by every serving instance did not complete the operation: %v", err) - } - f.bmc.wg.Wait() -} - -func TestDHCPHandlerAuthenticatesAndRejectsForgedReports(t *testing.T) { - f := newDHCPFixture(t, time.Second, DHCPSynced) - if _, err := f.p.DHCPHandler("short"); err == nil { - t.Fatal("a weak token was accepted") - } - h, _ := f.p.DHCPHandler(syncToken) - for _, auth := range []string{"", "Bearer wrong-token-wrong-token-wrong-token-0000", "Basic " + syncToken} { - w := httptest.NewRecorder() - q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) - if auth != "" { - q.Header.Set("Authorization", auth) - } - h.ServeHTTP(w, q) - if w.Code != http.StatusUnauthorized { - t.Fatalf("%q: %d", auth, w.Code) - } - } - if code := post(h, "wrong-token-wrong-token-wrong-token-0000", bootnet.Applied{Instance: "kea-0", Feed: bootnet.Feed{Reservations: []bootnet.Reservation{}}}); code != http.StatusUnauthorized { - t.Fatalf("unauthenticated report: %d", code) - } - valid, _ := bootnet.NewFeed([]bootnet.Reservation{{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Minute)}}) - forged := valid - forged.Reservations = []bootnet.Reservation{} - for name, a := range map[string]any{ - "revision of another set": bootnet.Applied{Instance: "kea-0", Feed: forged}, - "bad instance": bootnet.Applied{Instance: "Kea 0", Feed: valid}, - "unknown field": map[string]any{"instance": "kea-0", "feed": valid, "extra": true}, - } { - if code := post(h, syncToken, a); code != http.StatusBadRequest { - t.Fatalf("%s: %d", name, code) - } - } - if reports, _ := f.p.reports(); len(reports) != 0 { - t.Fatalf("rejected reports were retained: %+v", reports) - } - if code := post(h, syncToken, bootnet.Applied{Instance: "kea-0", Feed: valid}); code != http.StatusNoContent { - t.Fatalf("valid report: %d", code) - } - w := httptest.NewRecorder() - q := httptest.NewRequest(http.MethodGet, "/pxe/boot.ipxe", nil) - q.Header.Set("Authorization", "Bearer "+syncToken) - h.ServeHTTP(w, q) - if w.Code != http.StatusNotFound { - t.Fatalf("DHCP listener served a boot path: %d", w.Code) - } - os.WriteFile(filepath.Join(f.p.bootRoot, dhcpLog), []byte("not json\n"), 0600) - if _, err := f.p.reports(); err == nil { - t.Fatal("corrupt DHCP evidence was read as evidence") - } -} - -func TestShippedLabEnrollmentIsValidAndStatic(t *testing.T) { - b, err := os.ReadFile("../../config/site/redfish/graph/kustomization.yaml") - if err != nil { - t.Fatal(err) - } - _, value, ok := strings.Cut(string(b), "- name: FLEET_REDFISH_ENROLLMENT\n value: '") - value, _, _ = strings.Cut(value, "'\n") - e, err := ParseEnrollment([]byte(value)) - if !ok || err != nil || e.DHCP != DHCPStatic || len(e.Targets) != 2 { - t.Fatalf("shipped lab enrollment: %v %+v", err, e) - } -} diff --git a/internal/redfish/enrollment.go b/internal/redfish/enrollment.go new file mode 100644 index 00000000..4f9ddfd7 --- /dev/null +++ b/internal/redfish/enrollment.go @@ -0,0 +1,166 @@ +package redfish + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +// Target is one enrolled server: the Device it is, its BMC endpoint, its +// exact Redfish System, its boot NIC and, when the site's DHCP is +// synchronized, the provisioning attachment the network owner assigned to +// it. Console names the serial-console capture file for the target (a lab +// seam; see the operations guide). Enrollment is site configuration and is +// never inferred. +type Target struct { + // Device is "/" in the provider project. + Device string `json:"device"` + Endpoint string `json:"endpoint"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + MAC string `json:"mac"` + Provisioning Provisioning `json:"provisioning,omitzero"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` +} + +// Provisioning is the asset's address on the provisioning network, in prefix +// form, and that network's gateway. Networking/IPAM allocates it; Fleet only +// publishes it while the asset's network boot is admitted. +type Provisioning struct { + Address string `json:"address"` + Gateway string `json:"gateway"` +} + +// DHCP modes. Static: the site's DHCP is configured independently of Fleet. +// Synced: Fleet publishes boot reservations and a network boot requires +// evidence that DHCP applied the reservation and later withdrew it. +const ( + DHCPStatic = "static" + DHCPSynced = "synced" +) + +// Enrollment is the site's explicit Device to BMC mapping. +type Enrollment struct { + DHCP string `json:"dhcp"` + Targets []Target `json:"targets"` +} + +// Target returns the enrolled server of a "/" Device. +func (e Enrollment) Target(device string) (Target, bool) { + for _, t := range e.Targets { + if t.Device == device { + return t, true + } + } + return Target{}, false +} + +func normalizeMAC(v string) (string, bool) { + return bootnet.NormalizeMAC(strings.ReplaceAll(v, "-", ":")) +} + +func ParseEnrollment(b []byte) (Enrollment, error) { + var e Enrollment + d := json.NewDecoder(strings.NewReader(string(b))) + d.DisallowUnknownFields() + if err := d.Decode(&e); err != nil || len(e.Targets) == 0 || (e.DHCP != DHCPStatic && e.DHCP != DHCPSynced) { + return Enrollment{}, errors.New("invalid Redfish enrollment") + } + seen := map[string]bool{} + for i, t := range e.Targets { + mac, ok := normalizeMAC(t.MAC) + endpoint, err := ParseEndpoint(t.Endpoint) + // A Redfish System ID is unique only within its BMC. + system := "s" + endpoint + " " + t.SystemID + if !ok || err != nil || !validDevice(t.Device) || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.Device] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") + } + seen["a"+t.Device], seen[system], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true + e.Targets[i].MAC, e.Targets[i].Endpoint = mac, endpoint + if e.DHCP == DHCPStatic { + if t.Provisioning != (Provisioning{}) { + return Enrollment{}, errors.New("a static-DHCP enrollment carries no provisioning attachment") + } + continue + } + feed, err := bootnet.NewFeed([]bootnet.Reservation{{MAC: mac, Address: t.Provisioning.Address, Gateway: t.Provisioning.Gateway, Expires: time.Unix(1, 0)}}) + if err != nil { + return Enrollment{}, errors.New("invalid provisioning attachment for enrolled target " + t.Device) + } + r := feed.Reservations[0] + address := "p" + strings.SplitN(r.Address, "/", 2)[0] + if seen[address] { + return Enrollment{}, errors.New("duplicate provisioning address") + } + seen[address] = true + e.Targets[i].Provisioning = Provisioning{Address: r.Address, Gateway: r.Gateway} + } + return e, nil +} + +// ParseBootOrigin accepts only a literal http://IPv4:port origin. +func ParseBootOrigin(value string) (string, error) { + u, err := url.Parse(value) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("a boot origin must be http://IPv4:port") + } + ip := net.ParseIP(u.Hostname()) + port, err := strconv.Atoi(u.Port()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("a boot origin must be http://IPv4:port") + } + return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// VerifyArtifacts derives the admitted image from the exact two-artifact manifest. +func VerifyArtifacts(dir string) (string, error) { + b, err := os.ReadFile(dir + "/SHA256SUMS") + if err != nil { + return "", err + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + seen := map[string]bool{} + for _, line := range lines { + f := strings.Fields(line) + if len(lines) != 2 || len(f) != 2 || (f[1] != "kernel" && f[1] != "installer.gz") || seen[f[1]] { + return "", errors.New("invalid artifact manifest") + } + seen[f[1]] = true + if sum, err := fileSHA256(dir + "/" + f[1]); err != nil || sum != f[0] { + return "", errors.New("artifact digest mismatch") + } + } + sum := sha256.Sum256(b) + return "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]), nil +} + +func fileSHA256(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +func validDevice(device string) bool { + namespace, name, ok := strings.Cut(device, "/") + return ok && namespace != "" && name != "" && !strings.Contains(name, "/") +} diff --git a/internal/redfish/enrollment_test.go b/internal/redfish/enrollment_test.go new file mode 100644 index 00000000..69d77cb1 --- /dev/null +++ b/internal/redfish/enrollment_test.go @@ -0,0 +1,46 @@ +package redfish + +import ( + "strings" + "testing" +) + +const ( + uuidA = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a" + uuidB = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b" +) + +func enrollment(targets string) string { + return `{"dhcp":"static","targets":[` + targets + `]}` +} + +const targetA = `{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"` + uuidA + `","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}` + +// TestEnrollmentNamesEachDeviceOnce accepts an explicit Device to BMC +// mapping and refuses a target without a Device, a duplicate, or another +// incomplete target. +func TestEnrollmentNamesEachDeviceOnce(t *testing.T) { + parsed, err := ParseEnrollment([]byte(enrollment(targetA))) + if err != nil { + t.Fatal(err) + } + if target, ok := parsed.Target("fleet-provider/server-example-001"); !ok || target.SystemUUID != uuidA { + t.Fatalf("target = %+v, %v", target, ok) + } + if _, ok := parsed.Target("fleet-provider/server-example-002"); ok { + t.Fatal("an unenrolled Device has a target") + } + for name, body := range map[string]string{ + "no device": strings.Replace(targetA, `"device":"fleet-provider/server-example-001",`, "", 1), + "device name only": strings.Replace(targetA, "fleet-provider/server-example-001", "server-example-001", 1), + "duplicate device": targetA + "," + strings.NewReplacer(uuidA, uuidB, "System-1", "System-2", "01:0a", "01:0b").Replace(targetA), + "duplicate system": targetA + "," + strings.NewReplacer("server-example-001", "server-example-002", "01:0a", "01:0b").Replace(targetA), + "no console": strings.Replace(targetA, `"target-a.log"`, `""`, 1), + "no disk": strings.Replace(targetA, `2147483648`, `0`, 1), + "unknown field": strings.Replace(targetA, `"console"`, `"extra":1,"console"`, 1), + } { + if _, err := ParseEnrollment([]byte(enrollment(body))); err == nil { + t.Errorf("%s: enrollment accepted", name) + } + } +} diff --git a/internal/redfish/provider.go b/internal/redfish/provider.go deleted file mode 100644 index b97d029e..00000000 --- a/internal/redfish/provider.go +++ /dev/null @@ -1,868 +0,0 @@ -package redfish - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/url" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "go.datum.net/fleet/internal/bootnet" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" - "golang.org/x/sys/unix" -) - -const ( - // Root holds the journal; the site mounts its journal subpath here. - Root = "/var/lib/fleet-local" - artifacts = "/opt/fleet-local/artifacts" - // LibvirtSocketDir is the hypervisor socket path of the libvirt mode. Its - // presence in a Redfish worker is a configuration error, never a fallback. - LibvirtSocketDir = "/run/fleet-libvirt" - bootWindow = 20 * time.Minute - maxPowerOn = 3 -) - -// Target is one enrolled physical asset: its BMC endpoint, its exact Redfish -// System, its boot NIC and, when the site's DHCP is synchronized, the -// provisioning attachment the network owner assigned to it. Console names the -// serial-console capture file for the target (a lab seam; see the operations -// guide). Enrollment is retained before effects and never inferred. -type Target struct { - AssetID string `json:"assetID"` - Endpoint string `json:"endpoint"` - SystemID string `json:"systemID"` - SystemUUID string `json:"systemUUID"` - MAC string `json:"mac"` - Provisioning Provisioning `json:"provisioning,omitzero"` - DiskBytes int64 `json:"diskBytes"` - Console string `json:"console"` -} - -// Provisioning is the asset's address on the provisioning network, in prefix -// form, and that network's gateway. Networking/IPAM allocates it; Fleet only -// publishes it while the asset's network boot is admitted. -type Provisioning struct { - Address string `json:"address"` - Gateway string `json:"gateway"` -} - -// DHCP modes. Static: the site's DHCP is configured independently of Fleet. -// Synced: Fleet publishes boot reservations and a network boot requires -// evidence that DHCP applied the reservation and later withdrew it. -const ( - DHCPStatic = "static" - DHCPSynced = "synced" -) - -// Enrollment is the site's explicit asset to BMC mapping. -type Enrollment struct { - DHCP string `json:"dhcp"` - Targets []Target `json:"targets"` -} - -func (e Enrollment) target(asset string) (Target, bool) { - for _, t := range e.Targets { - if t.AssetID == asset { - return t, true - } - } - return Target{}, false -} - -func normalizeMAC(v string) (string, bool) { - return bootnet.NormalizeMAC(strings.ReplaceAll(v, "-", ":")) -} - -func ParseEnrollment(b []byte) (Enrollment, error) { - var e Enrollment - d := json.NewDecoder(strings.NewReader(string(b))) - d.DisallowUnknownFields() - if err := d.Decode(&e); err != nil || len(e.Targets) == 0 || (e.DHCP != DHCPStatic && e.DHCP != DHCPSynced) { - return Enrollment{}, errors.New("invalid Redfish enrollment") - } - seen := map[string]bool{} - for i, t := range e.Targets { - mac, ok := normalizeMAC(t.MAC) - endpoint, err := ParseEndpoint(t.Endpoint) - // A Redfish System ID is unique only within its BMC. - system := "s" + endpoint + " " + t.SystemID - if !ok || err != nil || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || - seen["a"+t.AssetID] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { - return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") - } - seen["a"+t.AssetID], seen[system], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true - e.Targets[i].MAC, e.Targets[i].Endpoint = mac, endpoint - if e.DHCP == DHCPStatic { - if t.Provisioning != (Provisioning{}) { - return Enrollment{}, errors.New("a static-DHCP enrollment carries no provisioning attachment") - } - continue - } - feed, err := bootnet.NewFeed([]bootnet.Reservation{{MAC: mac, Address: t.Provisioning.Address, Gateway: t.Provisioning.Gateway, Expires: time.Unix(1, 0)}}) - if err != nil { - return Enrollment{}, errors.New("invalid provisioning attachment for enrolled target " + t.AssetID) - } - r := feed.Reservations[0] - address := "p" + strings.SplitN(r.Address, "/", 2)[0] - if seen[address] { - return Enrollment{}, errors.New("duplicate provisioning address") - } - seen[address] = true - e.Targets[i].Provisioning = Provisioning{Address: r.Address, Gateway: r.Gateway} - } - return e, nil -} - -// phase is one boot of the target: a one-time boot override, power on, and an -// exact console receipt followed by power off. -type phase struct{ name, boot, marker, mode string } - -var phases = map[string][]phase{ - "install": {{"installer", "Pxe", "FLEET-INSTALLED:", "install"}, {"disk", "Hdd", "FLEET-DISK-BOOT:", ""}}, - "cleanup": {{"wipe", "Pxe", "FLEET-WIPED:", "wipe"}}, -} - -type record struct { - Request simulator.Request `json:"request"` - Result simulator.OperationResult `json:"result"` - Receipt string `json:"receipt"` - Stage string `json:"stage"` - BootToken string `json:"bootToken,omitempty"` - BootExpires time.Time `json:"bootExpires"` - BootClosed bool `json:"bootClosed"` - Target Target `json:"target"` - System *System `json:"system,omitempty"` - PowerOn map[string]int `json:"powerOnRequests,omitempty"` - RequestedAt map[string]time.Time `json:"requestedAt,omitempty"` -} - -type journal struct { - Provider string `json:"provider"` - Image string `json:"image"` - Epoch int64 `json:"epoch"` - Binding string `json:"binding"` - Fence string `json:"fence"` - Closed bool `json:"closed"` - Operations map[string]*record `json:"operations"` -} - -// Provider is the Redfish executor. The effectful provider runs only in a -// per-operation worker; read-only providers serve the boot and observer roles. -type Provider struct { - root, bootRoot, consoleRoot, artifacts string - origin, image string - enrollment Enrollment - clients map[string]*Client - readOnly bool - now func() time.Time - poll, settle, offGrace, outage time.Duration -} - -func (p *Provider) clock() time.Time { - if p.now != nil { - return p.now().UTC() - } - return time.Now().UTC() -} - -// Open builds the effectful worker provider from its environment. It refuses -// any libvirt configuration: Redfish workers have no hypervisor fallback. -func Open() (*Provider, error) { - if os.Getenv("FLEET_LIBVIRT_URI") != "" { - return nil, errors.New("redfish provider refuses a libvirt URI") - } - if _, err := os.Stat(LibvirtSocketDir); err == nil { - return nil, errors.New("redfish provider refuses a mounted libvirt socket") - } - p, err := open() - if err != nil { - return nil, err - } - enrollment, err := ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) - if err != nil { - return nil, err - } - credentials := os.Getenv("FLEET_REDFISH_CREDENTIALS") - user, err1 := os.ReadFile(filepath.Join(credentials, "username")) - password, err2 := os.ReadFile(filepath.Join(credentials, "password")) - if credentials == "" || err1 != nil || err2 != nil { - return nil, errors.New("redfish credentials are unavailable") - } - p.clients = map[string]*Client{} - for _, t := range enrollment.Targets { - if p.clients[t.Endpoint] != nil { - continue - } - if p.clients[t.Endpoint], err = NewClient(t.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second); err != nil { - return nil, err - } - } - p.consoleRoot = os.Getenv("FLEET_REDFISH_CONSOLE") - if !filepath.IsAbs(p.consoleRoot) { - return nil, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") - } - p.enrollment = enrollment - return p, p.retainEnrollment() -} - -// OpenReadOnly serves the boot service and observer. It holds no credential, -// cannot lock the journal and cannot execute. -func OpenReadOnly() (*Provider, error) { - p, err := open() - if err != nil { - return nil, err - } - p.readOnly = true - return p, nil -} - -func open() (*Provider, error) { - if os.Getenv("FLEET_SITE_PROVIDER") != "redfish" { - return nil, errors.New("redfish provider requires FLEET_SITE_PROVIDER=redfish") - } - origin, err := ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) - if err != nil { - return nil, err - } - bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") - if !filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot { - return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") - } - p := &Provider{root: Root, bootRoot: bootRoot, origin: origin, artifacts: artifacts} - if p.image, err = verifyArtifacts(p.artifacts); err != nil { - return nil, err - } - return p, nil -} - -// ParseBootOrigin accepts only a literal http://IPv4:port origin. -func ParseBootOrigin(value string) (string, error) { - u, err := url.Parse(value) - if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { - return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") - } - ip := net.ParseIP(u.Hostname()) - port, err := strconv.Atoi(u.Port()) - if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { - return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") - } - return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil -} - -// verifyArtifacts derives the admitted image from the exact two-artifact manifest. -func verifyArtifacts(dir string) (string, error) { - b, err := os.ReadFile(dir + "/SHA256SUMS") - if err != nil { - return "", err - } - lines := strings.Split(strings.TrimSpace(string(b)), "\n") - seen := map[string]bool{} - for _, line := range lines { - f := strings.Fields(line) - if len(lines) != 2 || len(f) != 2 || (f[1] != "kernel" && f[1] != "installer.gz") || seen[f[1]] { - return "", errors.New("invalid artifact manifest") - } - seen[f[1]] = true - if sum, err := fileSHA256(dir + "/" + f[1]); err != nil || sum != f[0] { - return "", errors.New("artifact digest mismatch") - } - } - sum := sha256.Sum256(b) - return "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]), nil -} - -func fileSHA256(path string) (string, error) { - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - h := sha256.New() - if _, err := io.Copy(h, f); err != nil { - return "", err - } - return hex.EncodeToString(h.Sum(nil)), nil -} - -func (p *Provider) lock() (*os.File, error) { - f, err := os.OpenFile(p.root+"/lock", os.O_CREATE|os.O_RDWR, 0600) - if err != nil { - return nil, err - } - if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { - f.Close() - return nil, err - } - return f, nil -} - -func syncDir(path string) error { - d, err := os.Open(path) - if err != nil { - return err - } - defer d.Close() - return d.Sync() -} - -// retainEnrollment records the enrollment once; a changed enrollment for a -// retained journal is a re-mapping that requires an explicit migration. -func (p *Provider) retainEnrollment() error { - // No journal lock: a worker that only opens must never contend with an - // executing worker or a concurrently delivered one. The first writer - // creates the record atomically (link of a synced file); every other - // worker compares it. - if err := os.MkdirAll(p.root, 0700); err != nil { - return err - } - want, _ := json.Marshal(p.enrollment) - path := p.root + "/enrollment.json" - got, err := os.ReadFile(path) - if os.IsNotExist(err) { - tmp, cerr := os.CreateTemp(p.root, ".enrollment-") - if cerr != nil { - return cerr - } - defer os.Remove(tmp.Name()) - _, werr := tmp.Write(want) - if werr == nil { - werr = tmp.Sync() - } - if cerr := tmp.Close(); werr == nil { - werr = cerr - } - if werr != nil { - return werr - } - if lerr := os.Link(tmp.Name(), path); lerr == nil { - return syncDir(p.root) - } else if !os.IsExist(lerr) { - return lerr - } - got, err = os.ReadFile(path) - } - if err != nil { - return err - } - if string(got) != string(want) { - return errors.New("redfish enrollment differs from the retained enrollment; re-mapping is not authorized") - } - return nil -} - -var stages = func() map[string]bool { - m := map[string]bool{"admitted": true, "discovered": true} - for _, list := range phases { - for _, ph := range list { - for _, s := range []string{"armed", "requested", "started", "verified"} { - m[ph.name+"-"+s] = true - } - } - } - return m -}() - -func (p *Provider) read() (journal, error) { - var j journal - b, err := os.ReadFile(p.root + "/journal.json") - if os.IsNotExist(err) { - return journal{Provider: "redfish", Operations: map[string]*record{}}, nil - } - if err != nil { - return j, err - } - if err = json.Unmarshal(b, &j); err != nil || j.Provider != "redfish" || j.Operations == nil { - return j, errors.New("invalid redfish journal") - } - for id, r := range j.Operations { - if r == nil || len(r.Receipt) != 64 { - return j, errors.New("invalid retained operation") - } - if _, err := hex.DecodeString(r.Receipt); err != nil { - return j, errors.New("invalid receipt") - } - if r.Stage == "done" { - if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { - return j, errors.New("invalid terminal result") - } - } else if !stages[r.Stage] || r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { - return j, errors.New("invalid pending result") - } - d, err := simulator.RequestDigest(r.Request) - if err != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Target.AssetID != r.Request.AssetID { - return j, errors.New("invalid retained request") - } - } - return j, nil -} - -func (p *Provider) save(j journal) error { - b, err := json.MarshalIndent(j, "", " ") - if err != nil { - return err - } - f, err := os.OpenFile(p.root+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) - if err != nil { - return err - } - _, err = f.Write(b) - if err == nil { - err = f.Sync() - } - if cerr := f.Close(); err == nil { - err = cerr - } - if err != nil { - return err - } - if err = os.Rename(p.root+"/journal.tmp", p.root+"/journal.json"); err != nil { - return err - } - return syncDir(p.root) -} - -func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } - -// Lookup reports only terminal retained results; a retained unfinished -// operation is not found with Unknown, which authorizes exact replay. -func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { - if !p.readOnly { - f, err := p.lock() - if err != nil { - return simulator.OperationResult{}, false, err - } - defer f.Close() - } - j, err := p.read() - if err != nil { - return simulator.OperationResult{}, false, err - } - r := j.Operations[id] - if r == nil { - return simulator.OperationResult{}, false, nil - } - if r.Stage != "done" { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown - } - return r.Result, true, nil -} - -func (p *Provider) validate(q simulator.Request) (Target, error) { - if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { - return Target{}, executor.ErrInvalid - } - t, ok := p.enrollment.target(q.AssetID) - if !ok || (q.Kind != "install" && q.Kind != "cleanup") { - return Target{}, executor.ErrInvalid - } - if q.Kind == "install" { - var in struct { - Image string `json:"image"` - } - d := json.NewDecoder(strings.NewReader(string(q.Inputs))) - d.DisallowUnknownFields() - if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { - return Target{}, executor.ErrInvalid - } - } - if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { - return Target{}, executor.ErrInvalid - } - return t, nil -} - -// Execute runs or resumes exactly one retained operation. The exact request, -// enrolled target, receipt and boot capability are durable before any -// Redfish request; replay under the same ID never repeats an effect that may -// have happened. HTTP success is never success: only observed power state and -// the exact console receipt complete a phase. -func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { - if p.readOnly || len(p.clients) == 0 { - return simulator.OperationResult{}, executor.ErrInvalid - } - ctx, cancel := context.WithTimeout(ctx, 40*time.Minute) - defer cancel() - f, err := p.lock() - if err != nil { - return simulator.OperationResult{}, err - } - defer f.Close() - target, err := p.validate(q) - if err != nil { - return simulator.OperationResult{}, err - } - digest, err := simulator.RequestDigest(q) - if err != nil { - return simulator.OperationResult{}, err - } - j, err := p.read() - if err != nil { - return simulator.OperationResult{}, err - } - if j.Image != "" && j.Image != p.image { - return simulator.OperationResult{}, executor.ErrConflict - } - j.Image = p.image - r := j.Operations[q.ID] - if r != nil { - if r.Result.InputDigest != digest || r.Target != target { - return simulator.OperationResult{}, executor.ErrConflict - } - if r.Stage == "done" { - return r.Result, nil - } - } else { - for _, old := range j.Operations { - if old.Stage != "done" { - return simulator.OperationResult{}, executor.ErrOutcomeUnknown - } - } - if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { - return simulator.OperationResult{}, executor.ErrFenced - } - j.Epoch, j.Binding, j.Fence, j.Closed = q.Epoch, q.BindingID, q.FenceToken, false - receipt, token := make([]byte, 32), make([]byte, 32) - if _, err = rand.Read(receipt); err == nil { - _, err = rand.Read(token) - } - if err != nil { - return simulator.OperationResult{}, err - } - r = &record{Request: q, Receipt: hex.EncodeToString(receipt), Stage: "admitted", Target: target, - BootToken: hex.EncodeToString(token), BootExpires: p.clock().Add(bootWindow), PowerOn: map[string]int{}, RequestedAt: map[string]time.Time{}, - Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: p.clock()}} - j.Operations[q.ID] = r - if err = p.save(j); err != nil { - return simulator.OperationResult{}, err - } - } - if err = p.run(ctx, &j, r); err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) - } - now := p.clock() - r.Stage, r.Result.Phase, r.Result.CompletedAt, r.Result.Result = "done", "Succeeded", &now, "installed" - if q.Kind == "cleanup" { - r.Result.Result = "clean" - j.Closed = true - } - if err = p.save(j); err != nil { - return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) - } - return r.Result, nil -} - -func (p *Provider) durations() (poll, settle, offGrace, outage time.Duration) { - poll, settle, offGrace, outage = p.poll, p.settle, p.offGrace, p.outage - if poll == 0 { - poll = 2 * time.Second - } - if settle == 0 { - settle = 45 * time.Second - } - if offGrace == 0 { - offGrace = 30 * time.Second - } - if outage == 0 { - outage = 5 * time.Minute - } - return -} - -func sleep(ctx context.Context, d time.Duration) error { - t := time.NewTimer(d) - defer t.Stop() - select { - case <-ctx.Done(): - return ctx.Err() - case <-t.C: - return nil - } -} - -func (p *Provider) run(ctx context.Context, j *journal, r *record) error { - poll, _, _, _ := p.durations() - if r.Stage == "admitted" { - // GETs only: a rejected credential, a missing capability or a - // mismatched identity leaves the operation admitted with no effect. - sys, err := p.bmc(r).Discover(ctx, r.Target) - if err != nil { - return fmt.Errorf("discovery: %w", err) - } - r.System, r.Stage = &sys, "discovered" - if err := p.save(*j); err != nil { - return err - } - } - if r.System == nil { - return errors.New("retained operation lacks its discovered System") - } - before := "discovered" - for _, ph := range phases[r.Request.Kind] { - if r.Stage == before { - // Pre-boot: power off and arm the one-time override. Both are - // idempotent here because no boot of this phase was requested. - if err := p.powerOff(ctx, r); err != nil { - return err - } - if ph.mode != "" && (r.BootClosed || !p.clock().Before(r.BootExpires)) { - return errors.New("boot admission expired or closed before network boot") - } - if ph.mode != "" && p.enrollment.DHCP == DHCPSynced { - if err := p.awaitReservation(ctx, r); err != nil { - return err - } - } - if err := p.bmc(r).SetBootOnce(ctx, *r.System, ph.boot); err != nil { - return fmt.Errorf("arm %s boot: %w", ph.boot, err) - } - r.Stage = ph.name + "-armed" - if err := p.save(*j); err != nil { - return err - } - } - if r.Stage == ph.name+"-armed" { - if err := p.requestPowerOn(ctx, j, r, ph); err != nil { - return err - } - } - for r.Stage == ph.name+"-requested" { - started, err := p.started(ctx, j, r, ph) - if err != nil { - return err - } - if started { - r.Stage = ph.name + "-started" - if err := p.save(*j); err != nil { - return err - } - break - } - if err := sleep(ctx, poll); err != nil { - return err - } - } - if r.Stage == ph.name+"-started" { - if err := p.complete(ctx, r, ph); err != nil { - return err - } - if ph.mode != "" { - r.BootClosed = true - } - r.Stage = ph.name + "-verified" - if err := p.save(*j); err != nil { - return err - } - } - before = ph.name + "-verified" - } - if r.Stage != before { - return errors.New("unexpected operation stage " + r.Stage) - } - if p.enrollment.DHCP == DHCPSynced { - return p.awaitWithdrawal(ctx, r) - } - return nil -} - -// bmc is the client of the target's own enrolled BMC. -func (p *Provider) bmc(r *record) *Client { return p.clients[r.Target.Endpoint] } - -func (p *Provider) powerOff(ctx context.Context, r *record) error { - sys := *r.System - poll, _, _, _ := p.durations() - deadline := p.clock().Add(5 * time.Minute) - requested := false - for { - pw, err := p.bmc(r).Observe(ctx, sys) - if err != nil { - return fmt.Errorf("observe before boot: %w", err) - } - if pw.State == "Off" { - return nil - } - if !requested { - // A slow or lost ForceOff response is observed, not trusted: - // power-off before this phase's boot is idempotent. - if err := p.bmc(r).Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { - return fmt.Errorf("power off: %w", err) - } - requested = true - } - if p.clock().After(deadline) { - return errors.New("target did not power off") - } - if err := sleep(ctx, poll); err != nil { - return err - } - } -} - -// requestPowerOn retains the request, then posts On. A lost or failed -// response leaves the phase requested; recovery observes before any repeat. -func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph phase) error { - if r.PowerOn == nil { - r.PowerOn, r.RequestedAt = map[string]int{}, map[string]time.Time{} - } - if r.PowerOn[ph.name] >= maxPowerOn { - return errors.New("power-on request budget exhausted; outcome requires inspection") - } - r.PowerOn[ph.name]++ - r.RequestedAt[ph.name] = p.clock() - r.Stage = ph.name + "-requested" - if err := p.save(*j); err != nil { - return err - } - if err := p.bmc(r).Reset(ctx, *r.System, "On"); err != nil { - return fmt.Errorf("power on (%s) response: %w", ph.name, err) - } - return nil -} - -// started reports whether a requested boot may have begun. Any sign of a boot -// (power not Off, the one-time override consumed, a boot delivery or receipt) -// means it may have run, and it is never requested again. Only a target that -// is still Off, still armed and silent after the settle window gets a repeated -// On, within a small retained budget. -func (p *Provider) started(ctx context.Context, j *journal, r *record, ph phase) (bool, error) { - _, settle, _, _ := p.durations() - pw, err := p.bmc(r).Observe(ctx, *r.System) - if err != nil { - if errors.Is(err, ErrIdentity) { - return false, err - } - return false, fmt.Errorf("observe requested boot: %w", err) - } - seen, err := p.receipts(r, ph) - if err != nil { - return false, err - } - delivered := ph.mode != "" && p.deliveryStarted(r) - if pw.State != "Off" || pw.OverrideEnabled != "Once" || pw.OverrideTarget != ph.boot || seen > 0 || delivered { - return true, nil - } - if p.clock().Sub(r.RequestedAt[ph.name]) < settle { - return false, nil - } - return false, p.requestPowerOn(ctx, j, r, ph) -} - -// complete waits for exactly one console receipt for this operation and the -// target powered off. BMC outages are tolerated for a bounded period. -func (p *Provider) complete(ctx context.Context, r *record, ph phase) error { - poll, _, offGrace, outage := p.durations() - var offSince, failingSince time.Time - for { - pw, err := p.bmc(r).Observe(ctx, *r.System) - switch { - case errors.Is(err, ErrIdentity): - return err - case err != nil: - if failingSince.IsZero() { - failingSince = p.clock() - } - if p.clock().Sub(failingSince) > outage { - return fmt.Errorf("BMC unavailable while observing %s: %w", ph.name, err) - } - default: - failingSince = time.Time{} - seen, err := p.receipts(r, ph) - if err != nil { - return err - } - if pw.State == "Off" { - if seen == 1 { - if ph.mode != "" { - return p.verifyDelivery(r) - } - return nil - } - if offSince.IsZero() { - offSince = p.clock() - } - if p.clock().Sub(offSince) > offGrace { - return fmt.Errorf("target powered off without the exact %s receipt", ph.name) - } - } else { - offSince = time.Time{} - } - } - if err := sleep(ctx, poll); err != nil { - return err - } - } -} - -// receipts counts exact receipt lines for this operation on the target's -// console. More than one is a duplicate execution and never succeeds. -func (p *Provider) receipts(r *record, ph phase) (int, error) { - b, err := os.ReadFile(filepath.Join(p.consoleRoot, r.Target.Console)) - if os.IsNotExist(err) { - return 0, nil - } - if err != nil { - return 0, err - } - want := ph.marker + r.Receipt - if ph.name == "wipe" { - want += ":" + strconv.FormatInt(r.Target.DiskBytes, 10) - } - n := 0 - for _, line := range strings.Split(string(b), "\n") { - if strings.TrimSpace(line) == want { - n++ - } - } - if ph.name == "disk" { - installed, _ := p.receipts(r, phases["install"][0]) - if installed != 1 { - return 0, errors.New("disk receipt without exactly one installer receipt") - } - } - if n > 1 { - return 0, fmt.Errorf("duplicate %s receipt: the phase ran more than once", ph.name) - } - return n, nil -} - -func (p *Provider) bootDirectory(r *record) string { - return filepath.Join(p.bootRoot, key(r.Request.ID)) -} - -func (p *Provider) deliveries(r *record) map[string]bool { - b, _ := os.ReadFile(filepath.Join(p.bootDirectory(r), "boot-delivery.log")) - done := map[string]bool{} - for _, line := range strings.Split(string(b), "\n") { - f := strings.Fields(line) - if len(f) == 4 && (f[1] == "write-complete" || f[1] == "admitted") && strings.HasPrefix(f[3], "bytes=") { - done[f[1]+" "+f[2]] = true - } - } - return done -} - -func (p *Provider) deliveryStarted(r *record) bool { return p.deliveries(r)["admitted boot.ipxe"] } - -func (p *Provider) verifyDelivery(r *record) error { - d := p.deliveries(r) - for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { - if !d["write-complete "+name] { - return fmt.Errorf("missing network delivery: %s", name) - } - } - return nil -} - -// ImageReference is the locally verified artifact manifest identity. -func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/redfish/provider_test.go b/internal/redfish/provider_test.go deleted file mode 100644 index 2d2f643f..00000000 --- a/internal/redfish/provider_test.go +++ /dev/null @@ -1,642 +0,0 @@ -package redfish - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "go/parser" - "go/token" - "io" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "regexp" - "strings" - "sync" - "testing" - "time" - - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -const ( - assetA = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" - assetB = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02" - uuidA = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a" - uuidB = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b" -) - -// fakeSystem is BMC state plus a fake guest that behaves like the lab -// installer: it fetches its script and artifacts from the boot handler, -// prints exactly one receipt on its console, and powers off. -type fakeSystem struct { - id, uuid, mac, console string - power, enabled, target string - disk string // receipt of the installed OS, "" when blank - boots []string -} - -type fakeBMC struct { - t *testing.T - mu sync.Mutex - systems map[string]*fakeSystem - mutations []string - rejectAuth, hideOn, dropOnce, ignoreOnce bool - dropSkip int - hold time.Duration - boot string // boot handler origin - wg sync.WaitGroup -} - -func (b *fakeBMC) handler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - write := func(v any) { _ = json.NewEncoder(w).Encode(v) } - if r.URL.Path == "/redfish/v1/" { - write(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) - return - } - user, pass, ok := r.BasicAuth() - b.mu.Lock() - reject := b.rejectAuth - b.mu.Unlock() - if !ok || user != "operator" || pass != "synthetic" || reject { - w.WriteHeader(http.StatusUnauthorized) - return - } - if r.URL.Path == "/redfish/v1/Systems" { - write(map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/System-1"}, map[string]string{"@odata.id": "/redfish/v1/Systems/System-2"}}}) - return - } - m := regexp.MustCompile(`^/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?$`).FindStringSubmatch(r.URL.Path) - if m == nil { - w.WriteHeader(http.StatusNotFound) - return - } - b.mu.Lock() - s := b.systems[m[1]] - types := []string{"On", "ForceOff", "ForceRestart"} - if b.hideOn { - types = types[1:] - } - switch { - case r.Method == http.MethodGet && m[2] == "": - v := map[string]any{"@odata.id": r.URL.Path, "Id": s.id, "UUID": s.uuid, "PowerState": s.power, - "Boot": map[string]any{"BootSourceOverrideEnabled": s.enabled, "BootSourceOverrideTarget": s.target, - "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"None", "Pxe", "Hdd"}, "BootSourceOverrideEnabled@Redfish.AllowableValues": []string{"Disabled", "Once"}}, - "Actions": map[string]any{"#ComputerSystem.Reset": map[string]string{"target": r.URL.Path + "/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": r.URL.Path + "/ResetActionInfo"}}} - b.mu.Unlock() - write(v) - case r.Method == http.MethodGet && m[2] == "/ResetActionInfo": - b.mu.Unlock() - // Shaped like the DMTF emulator 1.2.2 template, including its - // off-schema string "Required". - write(map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "Required": "true", "DataType": "String", "AllowableValues": types}}}) - case r.Method == http.MethodPatch && m[2] == "": - var body struct{ Boot map[string]string } - _ = json.NewDecoder(r.Body).Decode(&body) - s.enabled, s.target = body.Boot["BootSourceOverrideEnabled"], body.Boot["BootSourceOverrideTarget"] - b.mutations = append(b.mutations, s.id+" PATCH "+s.target) - b.mu.Unlock() - w.WriteHeader(http.StatusOK) - write(map[string]any{}) - case r.Method == http.MethodPost && m[2] != "": - var body struct{ ResetType string } - _ = json.NewDecoder(r.Body).Decode(&body) - b.mutations = append(b.mutations, s.id+" POST "+body.ResetType) - allowed := false - for _, t := range types { - allowed = allowed || t == body.ResetType - } - if !allowed { - b.mu.Unlock() - w.WriteHeader(http.StatusBadRequest) - return - } - if body.ResetType == "On" && b.ignoreOnce { - b.ignoreOnce = false - b.mu.Unlock() - w.WriteHeader(http.StatusNoContent) - return - } - drop := false - if body.ResetType == "On" && s.power == "Off" { - boot := "Hdd" - if s.enabled == "Once" { - boot = s.target - } - s.enabled, s.target, s.power = "Disabled", "None", "On" - s.boots = append(s.boots, boot) - if b.dropOnce && b.dropSkip > 0 { - b.dropSkip-- - } else { - drop, b.dropOnce = b.dropOnce, false - } - b.wg.Add(1) - go b.guest(s, boot) - } - if body.ResetType == "ForceOff" { - s.power = "Off" - } - b.mu.Unlock() - if drop { - time.Sleep(b.hold) - } - w.WriteHeader(http.StatusNoContent) - default: - b.mu.Unlock() - w.WriteHeader(http.StatusMethodNotAllowed) - } - }) -} - -func (b *fakeBMC) console(s *fakeSystem, line string) { - f, err := os.OpenFile(s.console, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) - if err == nil { - fmt.Fprintln(f, line) - f.Close() - } -} - -func (b *fakeBMC) guest(s *fakeSystem, boot string) { - defer b.wg.Done() - time.Sleep(20 * time.Millisecond) - line := "" - if boot == "Pxe" { - mac := strings.ReplaceAll(s.mac, ":", "-") - script := get(b.boot + "/pxe/" + mac + "/boot.ipxe") - f := regexp.MustCompile(`kernel (\S+) .*fleet\.receipt=([0-9a-f]{64}) fleet\.mode=(\w+)\ninitrd (\S+)`).FindStringSubmatch(script) - if f != nil && get(f[1]) != "" && get(f[4]) != "" { - b.mu.Lock() - if f[3] == "wipe" { - s.disk = "" - line = "FLEET-WIPED:" + f[2] + ":2147483648" - } else { - s.disk = f[2] - line = "FLEET-INSTALLED:" + f[2] - } - b.mu.Unlock() - } - } else if s.disk != "" { - line = "FLEET-DISK-BOOT:" + s.disk - } - if line != "" { - b.console(s, line) - } - time.Sleep(20 * time.Millisecond) - b.mu.Lock() - s.power = "Off" - b.mu.Unlock() -} - -func get(u string) string { - resp, err := http.Get(u) - if err != nil { - return "" - } - defer resp.Body.Close() - b, _ := io.ReadAll(resp.Body) - if resp.StatusCode != http.StatusOK { - return "" - } - return string(b) -} - -func (b *fakeBMC) mutationsFor(id string) []string { - b.mu.Lock() - defer b.mu.Unlock() - var out []string - for _, m := range b.mutations { - if strings.HasPrefix(m, id+" ") { - out = append(out, strings.TrimPrefix(m, id+" ")) - } - } - return out -} - -type fixture struct { - p *Provider - bmc *fakeBMC - dir string -} - -func newFixture(t *testing.T, timeout time.Duration) *fixture { - t.Helper() - return newDHCPFixture(t, timeout, DHCPStatic) -} - -// newDHCPFixture builds the fixture with the given site DHCP mode. Synced -// targets carry documentation-range provisioning attachments. -func newDHCPFixture(t *testing.T, timeout time.Duration, dhcp string) *fixture { - t.Helper() - dir := t.TempDir() - for _, d := range []string{"journal", "boot", "console", "artifacts"} { - if err := os.Mkdir(filepath.Join(dir, d), 0700); err != nil { - t.Fatal(err) - } - } - os.WriteFile(filepath.Join(dir, "artifacts/kernel"), []byte("kernel"), 0600) - os.WriteFile(filepath.Join(dir, "artifacts/installer.gz"), []byte("initrd"), 0600) - sums := "" - for _, n := range []string{"kernel", "installer.gz"} { - s, _ := fileSHA256(filepath.Join(dir, "artifacts", n)) - sums += s + " " + n + "\n" - } - os.WriteFile(filepath.Join(dir, "artifacts/SHA256SUMS"), []byte(sums), 0600) - image, err := verifyArtifacts(filepath.Join(dir, "artifacts")) - if err != nil { - t.Fatal(err) - } - bmc := &fakeBMC{t: t, hold: 3 * timeout, systems: map[string]*fakeSystem{ - "System-1": {id: "System-1", uuid: uuidA, mac: "52:54:00:77:01:0a", console: filepath.Join(dir, "console/target-a.log"), power: "On", enabled: "Disabled", target: "None"}, - "System-2": {id: "System-2", uuid: uuidB, mac: "52:54:00:77:01:0b", console: filepath.Join(dir, "console/target-b.log"), power: "Off", enabled: "Disabled", target: "None"}}} - rf := httptest.NewServer(bmc.handler()) - t.Cleanup(rf.Close) - provA, provB := "", "" - if dhcp == DHCPSynced { - provA = `,"provisioning":{"address":"192.0.2.10/24","gateway":"192.0.2.1"}` - provB = `,"provisioning":{"address":"192.0.2.11/24","gateway":"192.0.2.1"}` - } - enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"dhcp":%q,"targets":[ - {"assetID":%q,"endpoint":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a"%s,"diskBytes":2147483648,"console":"target-a.log"}, - {"assetID":%q,"endpoint":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b"%s,"diskBytes":2147483648,"console":"target-b.log"}]}`, - dhcp, assetA, rf.URL, uuidA, provA, assetB, rf.URL, uuidB, provB))) - if err != nil { - t.Fatal(err) - } - client, err := NewClient(rf.URL, "operator", "synthetic", timeout) - if err != nil { - t.Fatal(err) - } - p := &Provider{root: filepath.Join(dir, "journal"), bootRoot: filepath.Join(dir, "boot"), consoleRoot: filepath.Join(dir, "console"), artifacts: filepath.Join(dir, "artifacts"), - image: image, enrollment: enrollment, clients: map[string]*Client{enrollment.Targets[0].Endpoint: client}, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} - boot := httptest.NewServer(p.BootHandler()) - t.Cleanup(boot.Close) - p.origin, bmc.boot = boot.URL, boot.URL - t.Cleanup(bmc.wg.Wait) - return &fixture{p: p, bmc: bmc, dir: dir} -} - -func (f *fixture) install(epoch int64) simulator.Request { - return simulator.Request{ID: fmt.Sprintf("install-%d", epoch), Kind: "install", AssetID: assetA, BindingID: fmt.Sprintf("binding-%d", epoch), Epoch: epoch, - FenceToken: fmt.Sprintf("fence-%d", epoch), Inputs: json.RawMessage(`{"image":"` + f.p.image + `"}`)} -} - -func cleanup(q simulator.Request) simulator.Request { - q.ID, q.Kind, q.Inputs = strings.Replace(q.ID, "install", "cleanup", 1), "cleanup", nil - return q -} - -func (f *fixture) stage(t *testing.T, id string) string { - j, err := f.p.read() - if err != nil { - t.Fatal(err) - } - return j.Operations[id].Stage -} - -func TestInstallDiskBootCleanupAndReuseThroughRedfish(t *testing.T) { - f := newFixture(t, time.Second) - ctx := context.Background() - q := f.install(1) - r, err := f.p.Execute(ctx, q) - if err != nil || r.Result != "installed" { - t.Fatalf("install: %v %+v", err, r) - } - f.bmc.wg.Wait() - if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { - t.Fatalf("unexpected Redfish effects: %v", got) - } - if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { - t.Fatalf("expected one network install and one disk boot, got %v", got) - } - // Exact replay is a verified no-op. - same := func(a, b simulator.OperationResult) bool { - return a.ID == b.ID && a.InputDigest == b.InputDigest && a.Result == b.Result && a.CompletedAt.Equal(*b.CompletedAt) - } - if again, err := f.p.Execute(ctx, q); err != nil || !same(again, r) || len(f.bmc.mutationsFor("System-1")) != 5 { - t.Fatalf("replay repeated effects: %v", err) - } - if got, found, err := f.p.Lookup(ctx, q.ID); !found || err != nil || !same(got, r) { - t.Fatalf("lookup: %v %v", found, err) - } - c := cleanup(q) - if r, err := f.p.Execute(ctx, c); err != nil || r.Result != "clean" { - t.Fatalf("cleanup: %v %+v", err, r) - } - f.bmc.wg.Wait() - if f.bmc.systems["System-1"].disk != "" { - t.Fatal("cleanup did not boot the wipe environment") - } - // Stale authority after the closed epoch is fenced before any request. - stale := q - stale.ID = "install-replay" - if _, err := f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { - t.Fatalf("stale epoch replay: %v", err) - } - // Reuse in a new epoch installs again with a distinct receipt. - if r, err := f.p.Execute(ctx, f.install(2)); err != nil || r.Result != "installed" { - t.Fatalf("reuse install: %v", err) - } - f.bmc.wg.Wait() - if got := f.bmc.mutationsFor("System-2"); len(got) != 0 { - t.Fatalf("the other enrolled target received effects: %v", got) - } - if b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-b.log")); len(b) != 0 { - t.Fatal("the other enrolled target booted") - } -} - -func TestDiscoveryFailuresIssueNoEffects(t *testing.T) { - for name, inject := range map[string]func(*fixture){ - "rejected credential": func(f *fixture) { f.bmc.rejectAuth = true }, - "unsupported reset": func(f *fixture) { f.bmc.hideOn = true }, - "renumbered system": func(f *fixture) { f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" }, - "swapped system UUIDs": func(f *fixture) { f.bmc.systems["System-1"].uuid, f.bmc.systems["System-2"].uuid = uuidB, uuidA }, - } { - t.Run(name, func(t *testing.T) { - f := newFixture(t, time.Second) - inject(f) - q := f.install(1) - if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("expected Unknown, got %v", err) - } - if got := f.bmc.mutations; len(got) != 0 { - t.Fatalf("effects issued before verified discovery: %v", got) - } - if s := f.stage(t, q.ID); s != "admitted" { - t.Fatalf("stage %s", s) - } - if _, found, err := f.p.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatal("unfinished operation must look up as not found and Unknown") - } - }) - } - f := newFixture(t, time.Second) - f.bmc.rejectAuth = true - q := f.install(1) - f.p.Execute(context.Background(), q) - f.bmc.rejectAuth = false - if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { - t.Fatalf("repaired credential did not resume: %v", err) - } -} - -func TestLostResponseAfterEffectRecoversWithoutRepeat(t *testing.T) { - f := newFixture(t, 100*time.Millisecond) - f.bmc.dropOnce = true - q := f.install(1) - if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost response must be Unknown: %v", err) - } - if s := f.stage(t, q.ID); s != "installer-requested" { - t.Fatalf("stage after lost response %s", s) - } - if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { - t.Fatalf("recovery: %v", err) - } - f.bmc.wg.Wait() - if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { - t.Fatalf("lost response caused a repeated boot: %v", got) - } - ons := 0 - for _, m := range f.bmc.mutationsFor("System-1") { - if m == "POST On" { - ons++ - } - } - if ons != 2 { - t.Fatalf("expected one On per phase, got %d", ons) - } -} - -func TestLostDiskBootResponseRecoversWithoutRepeat(t *testing.T) { - f := newFixture(t, 100*time.Millisecond) - f.bmc.dropOnce, f.bmc.dropSkip = true, 1 - q := f.install(1) - if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost disk-boot response must be Unknown: %v", err) - } - if s := f.stage(t, q.ID); s != "disk-requested" { - t.Fatalf("stage after lost response %s", s) - } - f.bmc.wg.Wait() - if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { - t.Fatalf("recovery: %v", err) - } - j, _ := f.p.read() - if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" || j.Operations[q.ID].PowerOn["disk"] != 1 { - t.Fatalf("lost disk-boot response caused a repeat: %v %v", got, j.Operations[q.ID].PowerOn) - } -} - -func TestLostRequestIsRepeatedOnlyWhileArmedAndSilent(t *testing.T) { - f := newFixture(t, time.Second) - f.bmc.ignoreOnce = true - q := f.install(1) - if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { - t.Fatalf("install: %v", err) - } - f.bmc.wg.Wait() - j, _ := f.p.read() - if j.Operations[q.ID].PowerOn["installer"] != 2 || strings.Join(f.bmc.systems["System-1"].boots, ",") != "Pxe,Hdd" { - t.Fatalf("expected one repeated On and one boot: %+v %v", j.Operations[q.ID].PowerOn, f.bmc.systems["System-1"].boots) - } -} - -func TestDuplicateReceiptAndIdentityChangeNeverSucceed(t *testing.T) { - f := newFixture(t, time.Second) - q := f.install(1) - if _, err := f.p.Execute(context.Background(), q); err != nil { - t.Fatal(err) - } - f.bmc.wg.Wait() - b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-a.log")) - f.bmc.console(f.bmc.systems["System-1"], strings.Split(string(b), "\n")[0]) - c := cleanup(q) - j, _ := f.p.read() - r := j.Operations[q.ID] - if _, err := f.p.receipts(r, phases["install"][0]); err == nil { - t.Fatal("duplicate installer receipt accepted") - } - f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" - if _, err := f.p.Execute(context.Background(), c); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.bmc.mutationsFor("System-1")) != 5 { - t.Fatalf("identity change: %v %v", err, f.bmc.mutationsFor("System-1")) - } -} - -func TestChangedRetryConflictsAndConcurrentWorkerIsExcluded(t *testing.T) { - f := newFixture(t, time.Second) - f.bmc.rejectAuth = true - q := f.install(1) - f.p.Execute(context.Background(), q) - changed := q - changed.FenceToken = "other" - if _, err := f.p.Execute(context.Background(), changed); !errors.Is(err, executor.ErrConflict) { - t.Fatalf("changed retry: %v", err) - } - other := cleanup(f.install(1)) - other.ID = "unrelated" - if _, err := f.p.Execute(context.Background(), other); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("an unfinished operation must block later ones: %v", err) - } - guard, err := f.p.lock() - if err != nil { - t.Fatal(err) - } - if _, err := f.p.Execute(context.Background(), q); err == nil || errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("second worker was not excluded by the journal lock: %v", err) - } - guard.Close() - ro := &Provider{root: f.p.root, readOnly: true} - if _, err := ro.Execute(context.Background(), q); !errors.Is(err, executor.ErrInvalid) { - t.Fatal("read-only provider executed") - } - bad := q - bad.AssetID = "fleet-provider/fleet.datumapis.com/Device/not-enrolled" - if _, err := f.p.Execute(context.Background(), bad); !errors.Is(err, executor.ErrInvalid) { - t.Fatal("unenrolled asset accepted") - } -} - -func TestEnrollmentIsRetainedOnceWithoutContendingForTheJournalLock(t *testing.T) { - f := newFixture(t, time.Second) - guard, err := f.p.lock() // an executing worker holds the journal lock - if err != nil { - t.Fatal(err) - } - defer guard.Close() - var wg sync.WaitGroup - errs := make(chan error, 8) - for i := 0; i < 8; i++ { - wg.Add(1) - go func() { defer wg.Done(); errs <- f.p.retainEnrollment() }() - } - wg.Wait() - close(errs) - for err := range errs { - if err != nil { - t.Fatalf("concurrent open failed: %v", err) - } - } - changed := *f.p - changed.enrollment = Enrollment{DHCP: f.p.enrollment.DHCP, Targets: f.p.enrollment.Targets[:1]} - if err := changed.retainEnrollment(); err == nil { - t.Fatal("a changed enrollment was accepted for the retained journal") - } -} - -func TestBootHandlerScopesByMACCapabilityAndAdmission(t *testing.T) { - f := newFixture(t, time.Second) - q := f.install(1) - j := journal{Provider: "redfish", Image: f.p.image, Epoch: 1, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{}} - digest, _ := simulator.RequestDigest(q) - target, _ := f.p.enrollment.target(assetA) - r := &record{Request: q, Receipt: strings.Repeat("a", 64), Stage: "installer-requested", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute), Target: target, - Result: simulator.OperationResult{ID: q.ID, Kind: "install", InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now()}} - j.Operations[q.ID] = r - save := func() { - if err := f.p.save(j); err != nil { - t.Fatal(err) - } - } - save() - base := f.p.origin + "/" + key(q.ID)[:16] + "/" - if s := get(f.p.origin + "/pxe/52-54-00-77-01-0a/boot.ipxe"); !strings.Contains(s, "fleet.mode=install") || !strings.Contains(s, base+r.BootToken+"/kernel") { - t.Fatalf("admitted MAC not served: %q", s) - } - if get(f.p.origin+"/pxe/boot.ipxe") == "" || get(base+r.BootToken+"/kernel") != "kernel" { - t.Fatal("chain script or admitted artifact not served") - } - for _, u := range []string{f.p.origin + "/pxe/52-54-00-77-01-0b/boot.ipxe", base + strings.Repeat("c", 64) + "/kernel", base + r.BootToken + "/SHA256SUMS", base + r.BootToken + "/boot.ipxe"} { - if get(u) != "" { - t.Fatalf("served %s", u) - } - } - for _, mutate := range []func(){func() { r.BootClosed = true }, func() { r.BootExpires = time.Now().Add(-time.Second) }, func() { r.Stage = "disk-requested" }, func() { j.Fence = "superseded" }} { - saved := *r - fence := j.Fence - mutate() - save() - if get(f.p.origin+"/pxe/52-54-00-77-01-0a/boot.ipxe") != "" || get(base+r.BootToken+"/kernel") != "" { - t.Fatal("closed, expired, non-boot or fenced admission served") - } - *r, j.Fence = saved, fence - } - if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, key(q.ID), "boot-delivery.log")); strings.Contains(string(b), r.BootToken) || strings.Contains(string(b), r.Receipt) { - t.Fatal("delivery evidence contains a capability or receipt") - } -} - -func TestWorkerRefusesHypervisorConfiguration(t *testing.T) { - t.Setenv("FLEET_LIBVIRT_URI", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock") - if _, err := Open(); err == nil || !strings.Contains(err.Error(), "libvirt") { - t.Fatalf("Open accepted a libvirt URI: %v", err) - } - t.Setenv("FLEET_LIBVIRT_URI", "") - t.Setenv("FLEET_SITE_PROVIDER", "libvirt") - if _, err := OpenReadOnly(); err == nil { - t.Fatal("redfish provider opened outside Redfish mode") - } -} - -// The executor package must have no direct hypervisor path: no process -// execution, no libvirt client and no dependency on the lab VM provider. -func TestPackageHasNoHypervisorPath(t *testing.T) { - files, _ := filepath.Glob("*.go") - for _, name := range files { - if strings.HasSuffix(name, "_test.go") { - continue - } - src, err := os.ReadFile(name) - if err != nil { - t.Fatal(err) - } - parsed, err := parser.ParseFile(token.NewFileSet(), name, src, parser.ImportsOnly) - if err != nil { - t.Fatal(err) - } - for _, imp := range parsed.Imports { - path := strings.Trim(imp.Path.Value, `"`) - if path == "os/exec" || path == "syscall" || strings.Contains(path, "libvirt") || strings.HasSuffix(path, "/internal/localvm") { - t.Fatalf("%s imports %s", name, path) - } - } - if strings.Contains(string(src), "virsh") || strings.Contains(string(src), "qemu:///") { - t.Fatalf("%s references a hypervisor control path", name) - } - } -} - -func TestClientNeverLeaksCredentialOrFollowsForeignPaths(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/redfish/v1/": - json.NewEncoder(w).Encode(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) - case "/redfish/v1/Systems": - json.NewEncoder(w).Encode(map[string]any{"Members": []any{map[string]string{"@odata.id": "/other/../redfish/v1/Systems/x"}}}) - default: - http.Redirect(w, r, "http://198.51.100.1/", http.StatusFound) - } - })) - defer srv.Close() - c, err := NewClient(srv.URL, "operator", "synthetic-secret", time.Second) - if err != nil { - t.Fatal(err) - } - _, err = c.Discover(context.Background(), Target{SystemID: "x", SystemUUID: uuidA}) - if !errors.Is(err, ErrIdentity) || strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString([]byte("operator:synthetic-secret"))) { - t.Fatalf("foreign member path: %v", err) - } - if _, err := c.Observe(context.Background(), System{Path: "/redfish/v1/Managers", ID: "x", UUID: uuidA}); !errors.As(err, new(Status)) { - t.Fatalf("followed a redirect: %v", err) - } - for _, bad := range []string{"ftp://10.0.0.1:1", "http://bmc.example:80", "http://10.0.0.1:80/path", "http://user@10.0.0.1:80"} { - if _, err := NewClient(bad, "u", "p", time.Second); err == nil { - t.Fatalf("accepted endpoint %s", bad) - } - } -} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index da35f813..db0ecb6a 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -4,13 +4,18 @@ import ( "net/http" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "go.datum.net/fleet/internal/custody/creatorwebhook" ) -// Transport serves the validating webhook and a transport probe. Both sit -// behind the same mutually authenticated TLS listener. -func (handler *Handler) Transport() http.Handler { +// Transport serves the validating webhooks and a transport probe. All sit +// behind the same mutually authenticated TLS listener. The operation creator +// webhook shares this server: it has the same caller, the same transport +// and the same provider scope, and it keeps no state. +func (handler *Handler) Transport(creator *creatorwebhook.Handler) http.Handler { mux := http.NewServeMux() mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) + mux.Handle(creatorwebhook.Path, &admission.Webhook{Handler: creator}) mux.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) }) diff --git a/internal/simulator/binding_adversarial_test.go b/internal/simulator/binding_adversarial_test.go deleted file mode 100644 index 9f35720f..00000000 --- a/internal/simulator/binding_adversarial_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package simulator - -import ( - "errors" - "path/filepath" - "reflect" - "testing" -) - -func TestAdversarialReplayCannotRetargetAuthorityAfterRestart(t *testing.T) { - for name, mutate := range map[string]func(*Request){ - "asset": func(r *Request) { r.AssetID = "other-asset" }, - "binding": func(r *Request) { r.BindingID = "other-binding" }, - "epoch": func(r *Request) { r.Epoch++ }, - "fence": func(r *Request) { r.FenceToken = "other-fence" }, - "image": func(r *Request) { r.Inputs = []byte(`{"image":"different-image"}`) }, - } { - t.Run(name, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "state.json") - store := openStore(t, path) - request := operationRequest("retained-install", "install", 1, `{"image":"synthetic-image"}`) - if _, _, err := store.Submit(request); err != nil { - t.Fatal(err) - } - store = openStore(t, path) - before := store.Snapshot() - mutate(&request) - if _, _, err := store.Submit(request); !errors.Is(err, ErrConflict) { - t.Fatalf("retargeted replay: %v", err) - } - if !reflect.DeepEqual(before, store.Snapshot()) { - t.Fatal("rejected replay changed authority or effects") - } - }) - } -} diff --git a/internal/simulator/server.go b/internal/simulator/server.go deleted file mode 100644 index d0810215..00000000 --- a/internal/simulator/server.go +++ /dev/null @@ -1,178 +0,0 @@ -package simulator - -import ( - "crypto/subtle" - "encoding/json" - "errors" - "io" - "log/slog" - "net/http" - "strings" -) - -const maxRequestBodyBytes = maxInputsBytes + 8*maxIdentifierBytes - -type BearerTokenSource func() (string, error) - -func RuntimeHandler(store *Store, bearerToken string, logger *slog.Logger) http.Handler { - if bearerToken == "" { - panic("runtime bearer token must not be empty") - } - return RuntimeHandlerWithTokenSource(store, func() (string, error) { return bearerToken, nil }, logger) -} - -func RuntimeHandlerWithTokenSource(store *Store, tokenSource BearerTokenSource, logger *slog.Logger) http.Handler { - if tokenSource == nil { - panic("runtime bearer token source must not be nil") - } - if logger == nil { - logger = slog.Default() - } - mux := http.NewServeMux() - mux.Handle("POST /v1/operations", requireBearer(tokenSource, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var req Request - if err := decodeRequest(w, r, &req); err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "request body is invalid") - return - } - op, lost, err := store.Submit(req) - if err != nil { - switch { - case errors.Is(err, ErrInvalid): - writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) - case errors.Is(err, ErrConflict): - writeError(w, http.StatusConflict, "operation_conflict", err.Error()) - case errors.Is(err, ErrFenced): - writeError(w, http.StatusConflict, "operation_fenced", err.Error()) - case errors.Is(err, ErrOutcomeUnknown): - logger.Error("operation persistence outcome is unknown", "operationID", req.ID, "error", err) - writeError(w, http.StatusServiceUnavailable, "outcome_unknown", "recover the operation by ID before retrying") - default: - logger.Error("submit simulator operation", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "operation outcome could not be returned") - } - return - } - if lost { - writeError(w, http.StatusServiceUnavailable, "response_lost", "durable effect completed; recover the operation by ID") - return - } - writeJSON(w, http.StatusOK, op.ResultView()) - }))) - mux.Handle("GET /v1/operations/{id}", requireBearer(tokenSource, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - op, ok := store.Get(r.PathValue("id")) - if !ok { - writeError(w, http.StatusNotFound, "not_found", "operation was not found") - return - } - writeJSON(w, http.StatusOK, op.ResultView()) - }))) - mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) - mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) { - if err := store.Ready(); err != nil { - logger.Error("simulator readiness check failed", "error", err) - writeError(w, http.StatusServiceUnavailable, "not_ready", "durable state is unavailable") - return - } - w.WriteHeader(http.StatusOK) - }) - return mux -} - -func AdminHandler(store *Store, bearerToken string, logger *slog.Logger) http.Handler { - if bearerToken == "" { - panic("admin bearer token must not be empty") - } - return AdminHandlerWithTokenSource(store, func() (string, error) { return bearerToken, nil }, logger) -} - -func AdminHandlerWithTokenSource(store *Store, tokenSource BearerTokenSource, logger *slog.Logger) http.Handler { - if tokenSource == nil { - panic("admin bearer token source must not be nil") - } - if logger == nil { - logger = slog.Default() - } - mux := http.NewServeMux() - mux.Handle("PUT /v1/faults/{name}", requireBearer(tokenSource, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var body struct { - Enabled bool `json:"enabled"` - } - if err := decodeRequest(w, r, &body); err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "request body is invalid") - return - } - name := strings.TrimSpace(r.PathValue("name")) - if err := store.SetFault(name, body.Enabled); err != nil { - if errors.Is(err, ErrInvalid) { - writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) - return - } - if errors.Is(err, ErrOutcomeUnknown) { - logger.Error("fault persistence outcome is unknown", "fault", name, "error", err) - writeError(w, http.StatusServiceUnavailable, "outcome_unknown", "read retained state before retrying") - return - } - logger.Error("set simulator fault", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "fault state could not be persisted") - return - } - w.WriteHeader(http.StatusNoContent) - }))) - mux.Handle("GET /v1/state", requireBearer(tokenSource, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, store.Snapshot()) - }))) - mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) - return mux -} - -func requireBearer(tokenSource BearerTokenSource, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token, err := tokenSource() - if err != nil || token == "" { - writeError(w, http.StatusServiceUnavailable, "authentication_unavailable", "current bearer authentication is unavailable") - return - } - want := []byte("Bearer " + token) - got := []byte(r.Header.Get("Authorization")) - if len(got) != len(want) || subtle.ConstantTimeCompare(got, want) != 1 { - w.Header().Set("WWW-Authenticate", "Bearer") - writeError(w, http.StatusUnauthorized, "unauthorized", "valid bearer authentication is required") - return - } - next.ServeHTTP(w, r) - }) -} - -func decodeRequest(w http.ResponseWriter, r *http.Request, target any) error { - r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes) - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - if err := decoder.Decode(target); err != nil { - return err - } - if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { - if err == nil { - return errors.New("multiple JSON values are not allowed") - } - return err - } - return nil -} - -type errorResponse struct { - Code string `json:"code"` - Message string `json:"message"` -} - -func writeError(w http.ResponseWriter, status int, code, message string) { - writeJSON(w, status, errorResponse{Code: code, Message: message}) -} - -func writeJSON(w http.ResponseWriter, status int, value any) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(value) -} diff --git a/internal/simulator/server_test.go b/internal/simulator/server_test.go deleted file mode 100644 index 45deab52..00000000 --- a/internal/simulator/server_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package simulator - -import ( - "bytes" - "errors" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" -) - -const ( - runtimeToken = "runtime-secret" - adminToken = "admin-secret" -) - -func TestRuntimeAndAdminHandlersRequireSeparateAuthentication(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - runtime := RuntimeHandler(store, runtimeToken, discardLogger()) - admin := AdminHandler(store, adminToken, discardLogger()) - body := `{"id":"op","kind":"install","assetID":"asset","bindingID":"binding","epoch":1,"fenceToken":"fence","inputs":{"image":"debian@sha256:1"}}` - - assertStatus(t, runtime, http.MethodPost, "/v1/operations", body, "", http.StatusUnauthorized) - assertStatus(t, runtime, http.MethodPost, "/v1/operations", body, adminToken, http.StatusUnauthorized) - recorder := assertStatus(t, runtime, http.MethodPost, "/v1/operations", body, runtimeToken, http.StatusOK) - if recorder.Header().Get("Cache-Control") != "no-store" || recorder.Header().Get("X-Content-Type-Options") != "nosniff" { - t.Fatalf("authenticated response can be cached or sniffed: %#v", recorder.Header()) - } - response := recorder.Body.String() - for _, secret := range []string{"fence", "binding", "debian@sha256:1", "inputs", "fenceToken"} { - if strings.Contains(response, secret) { - t.Fatalf("runtime response exposed retained authority %q: %s", secret, response) - } - } - assertStatus(t, runtime, http.MethodGet, "/v1/state", "", runtimeToken, http.StatusNotFound) - assertStatus(t, admin, http.MethodGet, "/v1/state", "", runtimeToken, http.StatusUnauthorized) - assertStatus(t, admin, http.MethodGet, "/v1/state", "", adminToken, http.StatusOK) - assertStatus(t, admin, http.MethodPost, "/v1/operations", body, adminToken, http.StatusNotFound) -} - -func TestRuntimeHandlerReloadsRotatedTokenWhileRunning(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - tokenFile := filepath.Join(t.TempDir(), "token") - if err := os.WriteFile(tokenFile, []byte("first\n"), 0o600); err != nil { - t.Fatal(err) - } - tokenSource := func() (string, error) { - value, err := os.ReadFile(tokenFile) - return strings.TrimSpace(string(value)), err - } - handler := RuntimeHandlerWithTokenSource(store, tokenSource, discardLogger()) - assertStatus(t, handler, http.MethodGet, "/v1/operations/missing", "", "first", http.StatusNotFound) - - rotated := tokenFile + ".rotated" - if err := os.WriteFile(rotated, []byte("second\n"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.Rename(rotated, tokenFile); err != nil { - t.Fatal(err) - } - assertStatus(t, handler, http.MethodGet, "/v1/operations/missing", "", "first", http.StatusUnauthorized) - assertStatus(t, handler, http.MethodGet, "/v1/operations/missing", "", "second", http.StatusNotFound) - - if err := os.Remove(tokenFile); err != nil { - t.Fatal(err) - } - assertStatus(t, handler, http.MethodGet, "/v1/operations/missing", "", "second", http.StatusServiceUnavailable) -} - -func TestLostResponseRecoversThroughSanitizedLookup(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - runtime := RuntimeHandler(store, runtimeToken, discardLogger()) - admin := AdminHandler(store, adminToken, discardLogger()) - assertStatus(t, admin, http.MethodPut, "/v1/faults/lost-response", `{"enabled":true}`, adminToken, http.StatusNoContent) - body := `{"id":"op-lost","kind":"install","assetID":"asset","bindingID":"binding","epoch":1,"fenceToken":"fence","inputs":{"image":"debian@sha256:1"}}` - assertStatus(t, runtime, http.MethodPost, "/v1/operations", body, runtimeToken, http.StatusServiceUnavailable) - recorder := assertStatus(t, runtime, http.MethodGet, "/v1/operations/op-lost", "", runtimeToken, http.StatusOK) - if !strings.Contains(recorder.Body.String(), `"result":"installed"`) { - t.Fatalf("lookup did not expose verified result: %s", recorder.Body.String()) - } -} - -func TestHTTPInputBoundariesAndErrorClassification(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - handler := RuntimeHandler(store, runtimeToken, discardLogger()) - valid := `{"id":"op","kind":"install","assetID":"asset","bindingID":"binding","epoch":1,"fenceToken":"fence","inputs":{"image":"debian@sha256:1"}}` - - assertStatus(t, handler, http.MethodPost, "/v1/operations", valid+` {}`, runtimeToken, http.StatusBadRequest) - assertStatus(t, handler, http.MethodPost, "/v1/operations", strings.Replace(valid, `"id":"op"`, `"id":"op","unknown":true`, 1), runtimeToken, http.StatusBadRequest) - assertStatus(t, handler, http.MethodPost, "/v1/operations", strings.Repeat("x", maxRequestBodyBytes+1), runtimeToken, http.StatusBadRequest) - assertStatus(t, handler, http.MethodPost, "/v1/operations", strings.Replace(valid, `"image":"debian@sha256:1"`, `"image":""`, 1), runtimeToken, http.StatusBadRequest) - - assertStatus(t, handler, http.MethodPost, "/v1/operations", valid, runtimeToken, http.StatusOK) - conflict := strings.Replace(valid, `debian@sha256:1`, `other@sha256:2`, 1) - assertStatus(t, handler, http.MethodPost, "/v1/operations", conflict, runtimeToken, http.StatusConflict) -} - -func TestInternalPersistenceErrorsAreNotDisclosed(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - store.persist = func(string, persisted) (bool, error) { return false, errors.New("secret filesystem path") } - handler := RuntimeHandler(store, runtimeToken, discardLogger()) - body := `{"id":"op","kind":"cleanup","assetID":"asset","bindingID":"binding","epoch":1,"fenceToken":"fence"}` - recorder := assertStatus(t, handler, http.MethodPost, "/v1/operations", body, runtimeToken, http.StatusInternalServerError) - if strings.Contains(recorder.Body.String(), "filesystem") { - t.Fatalf("internal error leaked to client: %s", recorder.Body.String()) - } - - store.persist = func(string, persisted) (bool, error) { return true, errors.New("directory sync uncertain") } - recorder = assertStatus(t, handler, http.MethodPost, "/v1/operations", body, runtimeToken, http.StatusServiceUnavailable) - if !strings.Contains(recorder.Body.String(), `"code":"outcome_unknown"`) { - t.Fatalf("post-rename outcome was not classified for recovery: %s", recorder.Body.String()) - } - assertStatus(t, handler, http.MethodGet, "/v1/operations/op", "", runtimeToken, http.StatusOK) -} - -func TestReadinessChecksDurableStatePath(t *testing.T) { - dir := t.TempDir() - store := openStore(t, filepath.Join(dir, "state.json")) - handler := RuntimeHandler(store, runtimeToken, discardLogger()) - assertStatus(t, handler, http.MethodGet, "/readyz", "", "", http.StatusOK) - - blockingFile := filepath.Join(dir, "not-a-directory") - if err := os.WriteFile(blockingFile, []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - store.path = filepath.Join(blockingFile, "state.json") - assertStatus(t, handler, http.MethodGet, "/healthz", "", "", http.StatusOK) - assertStatus(t, handler, http.MethodGet, "/readyz", "", "", http.StatusServiceUnavailable) -} - -func assertStatus(t *testing.T, handler http.Handler, method, target, body, token string, want int) *httptest.ResponseRecorder { - t.Helper() - request := httptest.NewRequest(method, target, bytes.NewBufferString(body)) - if token != "" { - request.Header.Set("Authorization", "Bearer "+token) - } - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - if recorder.Code != want { - t.Fatalf("%s %s: got %d want %d: %s", method, target, recorder.Code, want, recorder.Body.String()) - } - return recorder -} - -func discardLogger() *slog.Logger { - return slog.New(slog.NewTextHandler(io.Discard, nil)) -} diff --git a/internal/simulator/store.go b/internal/simulator/store.go deleted file mode 100644 index cc70acde..00000000 --- a/internal/simulator/store.go +++ /dev/null @@ -1,579 +0,0 @@ -package simulator - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - "time" - "unicode" - "unicode/utf8" -) - -const ( - currentSchemaVersion = 1 - maxIdentifierBytes = 256 - maxFenceTokenBytes = 1024 - maxInputsBytes = 1 << 20 -) - -var ( - ErrConflict = errors.New("operation identity conflicts with retained input") - ErrFenced = errors.New("operation is fenced by retained asset authority") - ErrInvalid = errors.New("invalid operation request") - ErrOutcomeUnknown = errors.New("operation persistence outcome is unknown") -) - -type Request struct { - ID string `json:"id"` - Kind string `json:"kind"` - AssetID string `json:"assetID"` - BindingID string `json:"bindingID"` - Epoch int64 `json:"epoch"` - FenceToken string `json:"fenceToken"` - Inputs json.RawMessage `json:"inputs,omitempty"` -} - -type Operation struct { - Request - InputDigest string `json:"inputDigest"` - Phase string `json:"phase"` - Result string `json:"result,omitempty"` - CreatedAt time.Time `json:"createdAt"` - CompletedAt *time.Time `json:"completedAt,omitempty"` -} - -type OperationResult struct { - ID string `json:"id"` - InputDigest string `json:"inputDigest,omitempty"` - Kind string `json:"kind"` - Phase string `json:"phase"` - Result string `json:"result,omitempty"` - CreatedAt time.Time `json:"createdAt"` - CompletedAt *time.Time `json:"completedAt,omitempty"` -} - -func (o Operation) ResultView() OperationResult { - return OperationResult{ - ID: o.ID, InputDigest: o.InputDigest, Kind: o.Kind, Phase: o.Phase, - Result: o.Result, CreatedAt: o.CreatedAt, CompletedAt: cloneTime(o.CompletedAt), - } -} - -type Asset struct { - ID string `json:"id"` - BindingID string `json:"bindingID,omitempty"` - Epoch int64 `json:"epoch"` - FenceToken string `json:"fenceToken,omitempty"` - AuthorityClosed bool `json:"authorityClosed,omitempty"` - InstalledImage string `json:"installedImage,omitempty"` - Dirty bool `json:"dirty"` - PowerState string `json:"powerState"` -} - -type persisted struct { - SchemaVersion int `json:"schemaVersion"` - Assets map[string]*Asset `json:"assets"` - Operations map[string]*Operation `json:"operations"` - Faults map[string]bool `json:"faults"` -} - -type persistFunc func(path string, state persisted) (renamed bool, err error) - -type Store struct { - mu sync.Mutex - readyMu sync.Mutex - path string - state persisted - persist persistFunc -} - -func Open(path string) (*Store, error) { - state := emptyState() - b, err := os.ReadFile(path) - if err == nil { - var loaded persisted - if err := json.Unmarshal(b, &loaded); err != nil { - return nil, fmt.Errorf("decode simulator state: %w", err) - } - state = loaded - } else if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("read simulator state: %w", err) - } - if err := validateState(state); err != nil { - return nil, fmt.Errorf("validate simulator state: %w", err) - } - return &Store{path: path, state: state, persist: persistState}, nil -} - -func emptyState() persisted { - return persisted{ - SchemaVersion: currentSchemaVersion, - Assets: map[string]*Asset{}, - Operations: map[string]*Operation{}, - Faults: map[string]bool{}, - } -} - -func (s *Store) Submit(req Request) (Operation, bool, error) { - s.mu.Lock() - defer s.mu.Unlock() - - req, err := validateRequest(req) - if err != nil { - return Operation{}, false, err - } - d := digest(req) - if old := s.state.Operations[req.ID]; old != nil { - if old.InputDigest != d { - return Operation{}, false, ErrConflict - } - return cloneOperation(*old), false, nil - } - - next, err := cloneState(s.state) - if err != nil { - return Operation{}, false, fmt.Errorf("clone simulator state: %w", err) - } - asset := next.Assets[req.AssetID] - if asset == nil { - asset = &Asset{ID: req.AssetID, PowerState: "Off"} - next.Assets[req.AssetID] = asset - } - if err := admitAuthority(asset, req); err != nil { - return Operation{}, false, err - } - - lost := next.Faults["lost-response"] - if lost { - next.Faults["lost-response"] = false - } - now := time.Now().UTC() - op := &Operation{ - Request: req, InputDigest: d, Phase: "Succeeded", - CreatedAt: now, CompletedAt: &now, - } - apply(asset, op) - next.Operations[req.ID] = op - - renamed, err := s.persist(s.path, next) - if renamed { - s.state = next - } - if err != nil { - if renamed { - return Operation{}, false, fmt.Errorf("%w: %v", ErrOutcomeUnknown, err) - } - return Operation{}, false, fmt.Errorf("persist operation: %w", err) - } - return cloneOperation(*op), lost, nil -} - -func admitAuthority(asset *Asset, req Request) error { - if req.Epoch < asset.Epoch { - return ErrFenced - } - if req.Epoch == asset.Epoch && asset.Epoch != 0 { - if asset.AuthorityClosed || asset.BindingID != req.BindingID || asset.FenceToken != req.FenceToken { - return ErrFenced - } - return nil - } - if asset.Epoch != 0 && !asset.AuthorityClosed { - return ErrFenced - } - asset.Epoch = req.Epoch - asset.BindingID = req.BindingID - asset.FenceToken = req.FenceToken - asset.AuthorityClosed = false - return nil -} - -func apply(asset *Asset, op *Operation) { - switch op.Kind { - case "install": - var in installInputs - mustDecode(op.Inputs, &in) - asset.Dirty = true - asset.InstalledImage = in.Image - op.Result = "installed" - case "cleanup": - asset.InstalledImage = "" - asset.Dirty = false - asset.PowerState = "Off" - asset.AuthorityClosed = true - op.Result = "clean" - case "power": - var in powerInputs - mustDecode(op.Inputs, &in) - asset.PowerState = in.State - op.Result = in.State - default: - panic("validated operation kind became unsupported") - } -} - -func (s *Store) Get(id string) (Operation, bool) { - s.mu.Lock() - defer s.mu.Unlock() - op, ok := s.state.Operations[id] - if !ok { - return Operation{}, false - } - return cloneOperation(*op), true -} - -func (s *Store) Snapshot() persisted { - s.mu.Lock() - defer s.mu.Unlock() - out, err := cloneState(s.state) - if err != nil { - panic(fmt.Sprintf("clone validated simulator state: %v", err)) - } - return out -} - -func (s *Store) SetFault(name string, enabled bool) error { - s.mu.Lock() - defer s.mu.Unlock() - if name != "lost-response" { - return fmt.Errorf("%w: unsupported fault %q", ErrInvalid, name) - } - next, err := cloneState(s.state) - if err != nil { - return fmt.Errorf("clone simulator state: %w", err) - } - next.Faults[name] = enabled - renamed, err := s.persist(s.path, next) - if renamed { - s.state = next - } - if err != nil { - if renamed { - return fmt.Errorf("%w: %v", ErrOutcomeUnknown, err) - } - return fmt.Errorf("persist fault: %w", err) - } - return nil -} - -func (s *Store) Ready() error { - s.readyMu.Lock() - defer s.readyMu.Unlock() - dir := filepath.Dir(s.path) - if err := os.MkdirAll(dir, 0o750); err != nil { - return err - } - f, err := os.CreateTemp(dir, ".fleet-ready-*") - if err != nil { - return err - } - name := f.Name() - defer os.Remove(name) - if _, err := f.Write([]byte("ready")); err != nil { - _ = f.Close() - return err - } - if err := f.Sync(); err != nil { - _ = f.Close() - return err - } - if err := f.Close(); err != nil { - return err - } - if err := os.Remove(name); err != nil { - return err - } - d, err := os.Open(dir) - if err != nil { - return err - } - defer d.Close() - return d.Sync() -} - -type installInputs struct { - Image string `json:"image"` -} - -type powerInputs struct { - State string `json:"state"` -} - -func validateRequest(req Request) (Request, error) { - if err := validateIdentifier("id", req.ID, maxIdentifierBytes); err != nil { - return Request{}, err - } - if err := validateIdentifier("assetID", req.AssetID, maxIdentifierBytes); err != nil { - return Request{}, err - } - if err := validateIdentifier("bindingID", req.BindingID, maxIdentifierBytes); err != nil { - return Request{}, err - } - if err := validateIdentifier("fenceToken", req.FenceToken, maxFenceTokenBytes); err != nil { - return Request{}, err - } - if req.Epoch < 1 { - return Request{}, fmt.Errorf("%w: epoch must be positive", ErrInvalid) - } - if len(req.Inputs) > maxInputsBytes { - return Request{}, fmt.Errorf("%w: inputs exceed %d bytes", ErrInvalid, maxInputsBytes) - } - - switch req.Kind { - case "install": - var in installInputs - if err := decodeExactInputs(req.Inputs, &in, false); err != nil { - return Request{}, fmt.Errorf("%w: install inputs: %v", ErrInvalid, err) - } - if strings.TrimSpace(in.Image) == "" { - return Request{}, fmt.Errorf("%w: install image is required", ErrInvalid) - } - case "power": - var in powerInputs - if err := decodeExactInputs(req.Inputs, &in, false); err != nil { - return Request{}, fmt.Errorf("%w: power inputs: %v", ErrInvalid, err) - } - if in.State != "On" && in.State != "Off" { - return Request{}, fmt.Errorf("%w: power state must be On or Off", ErrInvalid) - } - case "cleanup": - var in struct{} - if err := decodeExactInputs(req.Inputs, &in, true); err != nil { - return Request{}, fmt.Errorf("%w: cleanup inputs: %v", ErrInvalid, err) - } - default: - return Request{}, fmt.Errorf("%w: unsupported operation kind %q", ErrInvalid, req.Kind) - } - - req.Inputs = append(json.RawMessage(nil), req.Inputs...) - return req, nil -} - -func validateIdentifier(field, value string, limit int) error { - if value == "" { - return fmt.Errorf("%w: %s is required", ErrInvalid, field) - } - if len(value) > limit || !utf8.ValidString(value) { - return fmt.Errorf("%w: %s is invalid or exceeds %d bytes", ErrInvalid, field, limit) - } - for _, r := range value { - if unicode.IsControl(r) { - return fmt.Errorf("%w: %s contains control characters", ErrInvalid, field) - } - } - return nil -} - -func decodeExactInputs(raw json.RawMessage, target any, allowEmpty bool) error { - trimmed := bytes.TrimSpace(raw) - if len(trimmed) == 0 { - if allowEmpty { - return nil - } - return errors.New("object is required") - } - if trimmed[0] != '{' { - return errors.New("JSON object is required") - } - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.DisallowUnknownFields() - if err := decoder.Decode(target); err != nil { - return err - } - if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { - if err == nil { - return errors.New("multiple JSON values are not allowed") - } - return err - } - return nil -} - -func mustDecode(raw json.RawMessage, target any) { - if err := json.Unmarshal(raw, target); err != nil { - panic("validated simulator input became invalid") - } -} - -func validateState(state persisted) error { - if state.SchemaVersion != currentSchemaVersion { - return fmt.Errorf("unsupported schema version %d", state.SchemaVersion) - } - if state.Assets == nil || state.Operations == nil || state.Faults == nil { - return errors.New("state maps must be present") - } - for key, asset := range state.Assets { - if asset == nil || asset.ID != key || asset.Epoch < 0 { - return fmt.Errorf("invalid asset entry %q", key) - } - if asset.Epoch > 0 && (asset.BindingID == "" || asset.FenceToken == "") { - return fmt.Errorf("asset %q has incomplete authority", key) - } - if asset.PowerState != "On" && asset.PowerState != "Off" { - return fmt.Errorf("asset %q has invalid power state", key) - } - if err := validateIdentifier("asset.id", asset.ID, maxIdentifierBytes); err != nil { - return fmt.Errorf("asset %q: %w", key, err) - } - if asset.Epoch > 0 { - if err := validateIdentifier("asset.bindingID", asset.BindingID, maxIdentifierBytes); err != nil { - return fmt.Errorf("asset %q: %w", key, err) - } - if err := validateIdentifier("asset.fenceToken", asset.FenceToken, maxFenceTokenBytes); err != nil { - return fmt.Errorf("asset %q: %w", key, err) - } - } - if asset.AuthorityClosed && (asset.Dirty || asset.PowerState != "Off" || asset.InstalledImage != "") { - return fmt.Errorf("asset %q has closed authority without verified cleanup", key) - } - if asset.Dirty != (asset.InstalledImage != "") { - return fmt.Errorf("asset %q has inconsistent installation state", key) - } - } - for key, op := range state.Operations { - if op == nil || op.ID != key { - return fmt.Errorf("invalid operation entry %q", key) - } - req, err := validateRequest(op.Request) - if err != nil { - return fmt.Errorf("operation %q: %w", key, err) - } - if op.InputDigest != digest(req) || op.Phase != "Succeeded" || op.CreatedAt.IsZero() || op.CompletedAt == nil || op.CompletedAt.IsZero() { - return fmt.Errorf("operation %q has invalid retained result", key) - } - if op.CompletedAt.Before(op.CreatedAt) { - return fmt.Errorf("operation %q completed before it was created", key) - } - asset := state.Assets[op.AssetID] - if asset == nil || op.Epoch > asset.Epoch { - return fmt.Errorf("operation %q has no compatible retained asset", key) - } - if op.Epoch == asset.Epoch && (op.BindingID != asset.BindingID || op.FenceToken != asset.FenceToken) { - return fmt.Errorf("operation %q conflicts with current asset authority", key) - } - switch op.Kind { - case "install": - if op.Result != "installed" { - return fmt.Errorf("operation %q has invalid install result", key) - } - case "cleanup": - if op.Result != "clean" || (op.Epoch == asset.Epoch && !asset.AuthorityClosed) { - return fmt.Errorf("operation %q has invalid cleanup result", key) - } - case "power": - var in powerInputs - mustDecode(op.Inputs, &in) - if op.Result != in.State { - return fmt.Errorf("operation %q has invalid power result", key) - } - } - } - for name := range state.Faults { - if name != "lost-response" { - return fmt.Errorf("unsupported retained fault %q", name) - } - } - return nil -} - -func persistState(path string, state persisted) (bool, error) { - b, err := json.MarshalIndent(state, "", " ") - if err != nil { - return false, err - } - dir := filepath.Dir(path) - if err := os.MkdirAll(dir, 0o750); err != nil { - return false, err - } - f, err := os.CreateTemp(dir, ".fleet-state-*") - if err != nil { - return false, err - } - tmp := f.Name() - renamed := false - defer func() { - if !renamed { - _ = os.Remove(tmp) - } - }() - if err := f.Chmod(0o600); err != nil { - _ = f.Close() - return false, err - } - if _, err := f.Write(b); err != nil { - _ = f.Close() - return false, err - } - if err := f.Sync(); err != nil { - _ = f.Close() - return false, err - } - if err := f.Close(); err != nil { - return false, err - } - if err := os.Rename(tmp, path); err != nil { - return false, err - } - renamed = true - d, err := os.Open(dir) - if err != nil { - return true, err - } - defer d.Close() - if err := d.Sync(); err != nil { - return true, err - } - return true, nil -} - -func cloneState(in persisted) (persisted, error) { - b, err := json.Marshal(in) - if err != nil { - return persisted{}, err - } - var out persisted - if err := json.Unmarshal(b, &out); err != nil { - return persisted{}, err - } - return out, nil -} - -func cloneOperation(in Operation) Operation { - in.Inputs = append(json.RawMessage(nil), in.Inputs...) - in.CompletedAt = cloneTime(in.CompletedAt) - return in -} - -func cloneTime(in *time.Time) *time.Time { - if in == nil { - return nil - } - out := *in - return &out -} - -func RequestDigest(request Request) (string, error) { - request.ID = "" - encoded, err := json.Marshal(request) - if err != nil { - return "", err - } - sum := sha256.Sum256(encoded) - return hex.EncodeToString(sum[:]), nil -} - -func digest(r Request) string { - value, err := RequestDigest(r) - if err != nil { - panic("marshal validated simulator request") - } - return value -} diff --git a/internal/simulator/store_test.go b/internal/simulator/store_test.go deleted file mode 100644 index f209d797..00000000 --- a/internal/simulator/store_test.go +++ /dev/null @@ -1,283 +0,0 @@ -package simulator - -import ( - "encoding/json" - "errors" - "os" - "path/filepath" - "sync" - "testing" -) - -func TestPersistenceIdempotencyFencingAndCleanupRetirement(t *testing.T) { - path := filepath.Join(t.TempDir(), "state.json") - store := openStore(t, path) - install := operationRequest("op-install", "install", 1, `{"image":"debian@sha256:1"}`) - - op, lost, err := store.Submit(install) - if err != nil || lost || op.Result != "installed" { - t.Fatalf("submit install: op=%#v lost=%v err=%v", op, lost, err) - } - for i := range install.Inputs { - install.Inputs[i] = 'x' - } - got, ok := store.Get("op-install") - if !ok || string(got.Inputs) != `{"image":"debian@sha256:1"}` { - t.Fatalf("retained input aliases caller memory: %#v", got) - } - got.Inputs[0] = 'x' - gotAgain, _ := store.Get("op-install") - if string(gotAgain.Inputs) != `{"image":"debian@sha256:1"}` { - t.Fatalf("returned operation aliases retained state: %#v", gotAgain) - } - - retry := operationRequest("op-install", "install", 1, `{"image":"debian@sha256:1"}`) - if _, lost, err := store.Submit(retry); err != nil || lost { - t.Fatalf("idempotent retry: lost=%v err=%v", lost, err) - } - conflict := retry - conflict.Inputs = json.RawMessage(`{"image":"other"}`) - if _, _, err := store.Submit(conflict); !errors.Is(err, ErrConflict) { - t.Fatalf("want operation conflict, got %v", err) - } - sameEpochOtherToken := operationRequest("op-other-token", "power", 1, `{"state":"On"}`) - sameEpochOtherToken.FenceToken = "other-token" - if _, _, err := store.Submit(sameEpochOtherToken); !errors.Is(err, ErrFenced) { - t.Fatalf("want same-epoch token fenced, got %v", err) - } - prematureBinding := operationRequest("op-premature-binding", "power", 2, `{"state":"On"}`) - prematureBinding.BindingID = "binding-b" - prematureBinding.FenceToken = "token-b" - if _, _, err := store.Submit(prematureBinding); !errors.Is(err, ErrFenced) { - t.Fatalf("want new binding fenced before cleanup, got %v", err) - } - - cleanup := operationRequest("op-cleanup", "cleanup", 1, "") - if _, _, err := store.Submit(cleanup); err != nil { - t.Fatalf("cleanup: %v", err) - } - late := operationRequest("op-late", "power", 1, `{"state":"On"}`) - if _, _, err := store.Submit(late); !errors.Is(err, ErrFenced) { - t.Fatalf("want cleaned binding fenced, got %v", err) - } - - newBinding := operationRequest("op-new-binding", "power", 2, `{"state":"On"}`) - newBinding.BindingID = "binding-b" - newBinding.FenceToken = "token-b" - if _, _, err := store.Submit(newBinding); err != nil { - t.Fatalf("new binding: %v", err) - } - - reopened := openStore(t, path) - snapshot := reopened.Snapshot() - asset := snapshot.Assets["asset-1"] - if asset == nil || asset.Epoch != 2 || asset.BindingID != "binding-b" || asset.PowerState != "On" || asset.AuthorityClosed { - t.Fatalf("unexpected recovered asset: %#v", asset) - } - if recovered, ok := reopened.Get("op-cleanup"); !ok || recovered.Result != "clean" { - t.Fatalf("cleanup operation not recovered: %#v ok=%v", recovered, ok) - } -} - -func TestLostResponseIsConsumedWithDurableEffect(t *testing.T) { - path := filepath.Join(t.TempDir(), "state.json") - store := openStore(t, path) - if err := store.SetFault("lost-response", true); err != nil { - t.Fatal(err) - } - req := operationRequest("op-lost", "install", 1, `{"image":"debian@sha256:1"}`) - if _, lost, err := store.Submit(req); err != nil || !lost { - t.Fatalf("want durable lost response, lost=%v err=%v", lost, err) - } - - reopened := openStore(t, path) - if op, ok := reopened.Get(req.ID); !ok || op.Result != "installed" { - t.Fatalf("lost response effect was not durable: %#v ok=%v", op, ok) - } - if _, lost, err := reopened.Submit(req); err != nil || lost { - t.Fatalf("recovery lookup/retry re-fired fault: lost=%v err=%v", lost, err) - } - next := operationRequest("op-next", "power", 1, `{"state":"On"}`) - if _, lost, err := reopened.Submit(next); err != nil || lost { - t.Fatalf("one-shot fault leaked to next operation: lost=%v err=%v", lost, err) - } -} - -func TestInvalidRequestsHaveNoAuthorityOrEffect(t *testing.T) { - tests := map[string]Request{ - "unsupported kind": operationRequest("op", "erase", 1, `{}`), - "missing image": operationRequest("op", "install", 1, `{}`), - "unknown input": operationRequest("op", "install", 1, `{"image":"x","extra":true}`), - "malformed input": operationRequest("op", "install", 1, `{"image":`), - "invalid power": operationRequest("op", "power", 1, `{"state":"Reboot"}`), - "cleanup input": operationRequest("op", "cleanup", 1, `{"force":true}`), - "zero epoch": operationRequest("op", "cleanup", 0, ""), - "empty id": operationRequest("", "cleanup", 1, ""), - } - for name, req := range tests { - t.Run(name, func(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - if _, _, err := store.Submit(req); !errors.Is(err, ErrInvalid) { - t.Fatalf("want invalid request, got %v", err) - } - snapshot := store.Snapshot() - if len(snapshot.Assets) != 0 || len(snapshot.Operations) != 0 { - t.Fatalf("invalid request mutated state: %#v", snapshot) - } - }) - } -} - -func TestPersistenceFailureKeepsMemoryAlignedWithRenameBoundary(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - req := operationRequest("op", "install", 1, `{"image":"debian@sha256:1"}`) - - store.persist = func(string, persisted) (bool, error) { return false, errors.New("write failed") } - if _, _, err := store.Submit(req); err == nil { - t.Fatal("want pre-rename persistence error") - } - if _, ok := store.Get(req.ID); ok { - t.Fatal("pre-rename failure changed in-memory state") - } - - store.persist = func(string, persisted) (bool, error) { return true, errors.New("directory sync uncertain") } - if _, _, err := store.Submit(req); !errors.Is(err, ErrOutcomeUnknown) { - t.Fatalf("want post-rename unknown outcome, got %v", err) - } - if op, ok := store.Get(req.ID); !ok || op.Result != "installed" { - t.Fatalf("post-rename state not retained for lookup: %#v ok=%v", op, ok) - } -} - -func TestSetFaultUsesTransactionalPersistence(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - store.persist = func(string, persisted) (bool, error) { return false, errors.New("write failed") } - if err := store.SetFault("lost-response", true); err == nil { - t.Fatal("want persistence error") - } - if store.Snapshot().Faults["lost-response"] { - t.Fatal("failed pre-rename fault write changed memory") - } - - store.persist = func(string, persisted) (bool, error) { return true, errors.New("sync uncertain") } - if err := store.SetFault("lost-response", true); !errors.Is(err, ErrOutcomeUnknown) { - t.Fatalf("want post-rename unknown outcome, got %v", err) - } - if !store.Snapshot().Faults["lost-response"] { - t.Fatal("post-rename fault state did not remain queryable") - } -} - -func TestOpenRejectsCorruptOrIncompatibleState(t *testing.T) { - tests := map[string]string{ - "invalid json": `{`, - "missing version": `{"assets":{},"operations":{},"faults":{}}`, - "null asset": `{"schemaVersion":1,"assets":{"a":null},"operations":{},"faults":{}}`, - "incomplete authority": `{"schemaVersion":1,"assets":{"a":{"id":"a","epoch":1,"powerState":"Off"}},"operations":{},"faults":{}}`, - "closed dirty asset": `{"schemaVersion":1,"assets":{"a":{"id":"a","bindingID":"b","epoch":1,"fenceToken":"f","authorityClosed":true,"dirty":true,"powerState":"Off"}},"operations":{},"faults":{}}`, - } - for name, content := range tests { - t.Run(name, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "state.json") - if err := os.WriteFile(path, []byte(content), 0o600); err != nil { - t.Fatal(err) - } - if _, err := Open(path); err == nil { - t.Fatal("want corrupt state to fail closed") - } - }) - } -} - -func TestOpenRejectsOperationWithoutRetainedAsset(t *testing.T) { - path := filepath.Join(t.TempDir(), "state.json") - store := openStore(t, path) - req := operationRequest("op", "install", 1, `{"image":"debian@sha256:1"}`) - if _, _, err := store.Submit(req); err != nil { - t.Fatal(err) - } - state := store.Snapshot() - delete(state.Assets, req.AssetID) - b, err := json.Marshal(state) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, b, 0o600); err != nil { - t.Fatal(err) - } - if _, err := Open(path); err == nil { - t.Fatal("operation without retained asset was accepted") - } -} - -func TestConcurrentIdempotentSubmissionsCreateOneOperation(t *testing.T) { - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - const operations = 32 - req := operationRequest("op", "power", 1, `{"state":"On"}`) - var wg sync.WaitGroup - for attempt := 0; attempt < operations; attempt++ { - wg.Add(1) - go func() { - defer wg.Done() - _, _, err := store.Submit(req) - if err != nil { - t.Errorf("idempotent submit: %v", err) - } - }() - } - wg.Wait() - state := store.Snapshot() - if len(state.Operations) != 1 || state.Assets["asset-1"].Epoch != 1 { - t.Fatalf("concurrent retries produced duplicate state: %#v", state) - } -} - -func openStore(t *testing.T, path string) *Store { - t.Helper() - store, err := Open(path) - if err != nil { - t.Fatal(err) - } - return store -} - -func TestResultDigestCommitsExactRequestWithoutExposingInputs(t *testing.T) { - request := operationRequest("digest-operation", "install", 1, `{"image":"debian@sha256:1"}`) - store := openStore(t, filepath.Join(t.TempDir(), "state.json")) - operation, _, err := store.Submit(request) - if err != nil { - t.Fatal(err) - } - want, err := RequestDigest(request) - if err != nil || len(want) != 64 || operation.ResultView().InputDigest != want { - t.Fatalf("request commitment mismatch: %v", err) - } - for _, field := range []string{"asset", "binding", "epoch", "fence", "image", "kind"} { - changed := request - switch field { - case "asset": - changed.AssetID += "-other" - case "binding": - changed.BindingID += "-other" - case "epoch": - changed.Epoch++ - case "fence": - changed.FenceToken += "-other" - case "image": - changed.Inputs = json.RawMessage(`{"image":"debian@sha256:2"}`) - case "kind": - changed.Kind = "cleanup" - } - got, err := RequestDigest(changed) - if err != nil || got == want { - t.Fatalf("digest did not bind %s: %v", field, err) - } - } -} - -func operationRequest(id, kind string, epoch int64, inputs string) Request { - return Request{ - ID: id, Kind: kind, AssetID: "asset-1", BindingID: "binding-a", - Epoch: epoch, FenceToken: "token-a", Inputs: json.RawMessage(inputs), - } -} diff --git a/internal/site/config.go b/internal/site/config.go index 0e831754..8e43b80e 100644 --- a/internal/site/config.go +++ b/internal/site/config.go @@ -2,18 +2,32 @@ package site import ( "context" + "crypto/sha256" + "encoding/hex" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" "go.datum.net/fleet/internal/bmcdiscovery" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" ) -// SecretCredentials reads per-Device BMC credential Secrets in the site -// cluster, using the contract BMC discovery uses. The approved pin comes from -// the same Secret. +// CredentialSecretName is the only name a Device's BMC credential Secret +// may have at a site. It derives from the "/" Device, so the +// worker of an operation can be granted get on exactly its Device's Secret +// and nothing else. +func CredentialSecretName(device string) string { + sum := sha256.Sum256([]byte(device)) + return "bmc-" + hex.EncodeToString(sum[:])[:20] +} + +// SecretCredentials reads one Device's BMC credential Secret in the site +// cluster, by its derived name and with a direct get: a worker may read only +// its own Device's credential and may list none. The Secret must still meet +// the contract BMC discovery uses, naming this Device in this project, and +// the approved pin comes from it. type SecretCredentials struct { Reader client.Reader Namespace string @@ -22,11 +36,13 @@ type SecretCredentials struct { } func (s SecretCredentials) Lookup(ctx context.Context, device string) (bmcdiscovery.Credential, bool, error) { - var secrets corev1.SecretList - if err := s.Reader.List(ctx, &secrets, client.InNamespace(s.Namespace), client.MatchingLabels{bmcdiscovery.CredentialLabel: "true"}); err != nil { + secret := &corev1.Secret{} + if err := s.Reader.Get(ctx, client.ObjectKey{Namespace: s.Namespace, Name: CredentialSecretName(device)}, secret); apierrors.IsNotFound(err) { + return bmcdiscovery.Credential{}, false, nil + } else if err != nil { return bmcdiscovery.Credential{}, false, err } - return bmcdiscovery.CredentialFor(secrets.Items, s.Project, device) + return bmcdiscovery.CredentialFor([]corev1.Secret{*secret}, s.Project, device) } // StaticTargets is a site's explicit enrollment, keyed by diff --git a/internal/site/config_test.go b/internal/site/config_test.go index e15305f1..d0f01db5 100644 --- a/internal/site/config_test.go +++ b/internal/site/config_test.go @@ -2,6 +2,7 @@ package site import ( "context" + "errors" "strings" "testing" @@ -12,7 +13,9 @@ import ( 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" ) func credentialSecret(name, project, device string, data map[string]string) *corev1.Secret { @@ -26,31 +29,40 @@ func credentialSecret(name, project, device string, data map[string]string) *cor return secret } -func TestSecretCredentialsUseThePerDeviceContract(t *testing.T) { +// TestSecretCredentialsGetOnlyTheDevicesOwnSecret reads a Device's +// credential by its derived name with one get, and never lists: a reader +// that refuses every list still works. The Secret must name the Device in +// the project; a Secret of another name, project or Device is not used. +func TestSecretCredentialsGetOnlyTheDevicesOwnSecret(t *testing.T) { scheme := runtime.NewScheme() if err := corev1.AddToScheme(scheme); err != nil { t.Fatal(err) } pin := strings.Repeat("ab", 32) + own := CredentialSecretName("default/server-example-001") reader := fake.NewClientBuilder().WithScheme(scheme).WithObjects( - credentialSecret("server-a", "provider-example", "server-example-001", map[string]string{"username": "operator", "password": "synthetic-secret", "tlsPublicKeySHA256": pin}), - credentialSecret("server-b", "provider-example", "server-example-002", map[string]string{"username": "operator", "password": "synthetic-secret"}), - credentialSecret("server-b-2", "provider-example", "server-example-002", map[string]string{"username": "other", "password": "synthetic-secret"}), - credentialSecret("elsewhere", "provider-other", "server-example-003", map[string]string{"username": "operator", "password": "synthetic-secret"}), - ).Build() + credentialSecret(own, "provider-example", "server-example-001", map[string]string{"username": "operator", "password": "synthetic-secret", "tlsPublicKeySHA256": pin}), + // Named for server-example-002 but bound to server-example-001. + credentialSecret(CredentialSecretName("default/server-example-002"), "provider-example", "server-example-001", map[string]string{"username": "operator", "password": "synthetic-secret"}), + // Bound to server-example-003 but not under its derived name. + credentialSecret("server-example-003", "provider-example", "server-example-003", map[string]string{"username": "operator", "password": "synthetic-secret"}), + credentialSecret(CredentialSecretName("default/server-example-004"), "provider-other", "server-example-004", map[string]string{"username": "operator", "password": "synthetic-secret"}), + ).WithInterceptorFuncs(interceptor.Funcs{List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return errors.New("a worker may not list credential Secrets") + }}).Build() credentials := SecretCredentials{Reader: reader, Namespace: "fleet-site", Project: "provider-example"} ctx := context.Background() credential, found, err := credentials.Lookup(ctx, "default/server-example-001") if err != nil || !found || credential.Username != "operator" || credential.Pin != pin { t.Fatalf("credential = %+v %v %v", credential, found, err) } - // Two Secrets naming one Device are a conflict, never a choice. - if _, _, err := credentials.Lookup(ctx, "default/server-example-002"); err == nil { - t.Fatal("two credential Secrets for one Device were accepted") + for _, device := range []string{"default/server-example-002", "default/server-example-003", "default/server-example-004"} { + if _, found, err := credentials.Lookup(ctx, device); found || err != nil { + t.Errorf("%s: found = %v, err = %v; want no credential", device, found, err) + } } - // A Secret for another project's Device is not this Device's. - if _, found, _ := credentials.Lookup(ctx, "default/server-example-003"); found { - t.Fatal("another project's credential was used") + if CredentialSecretName("default/server-example-001") == CredentialSecretName("other/server-example-001") { + t.Fatal("two Devices share a credential Secret name") } } diff --git a/internal/site/fixture/access.go b/internal/site/fixture/access.go new file mode 100644 index 00000000..7638fad7 --- /dev/null +++ b/internal/site/fixture/access.go @@ -0,0 +1,54 @@ +// Package fixture is how a site reaches synthetic Devices that have no BMC, +// such as the simulator's and the local VM's: an enrollment of each Device's +// identity, an access type that checks the admitted snapshot against it, and +// fixture discovery. It is never a production access type. +package fixture + +import ( + "context" + "strings" + + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// Target is one enrolled synthetic Device: the identity its fixture Device +// records, the key digest its fixture discovery records, and its disks. +type Target struct { + BMCEndpoint string `json:"bmcEndpoint"` + SystemUUID string `json:"systemUUID"` + BootMACAddress string `json:"bootMACAddress"` + BMCPublicKeySHA256 string `json:"bmcPublicKeySHA256"` + Disks []string `json:"disks"` +} + +// Enrollment maps "/" to each Device the site serves. +type Enrollment map[string]Target + +// Connection is what Access prepares: the enrolled target. +type Connection struct { + Device string + Target Target +} + +// Access checks the admitted snapshot against the site's enrollment, as +// RedfishAccess does against a real BMC. A synthetic Device has no +// credential; its pin is the enrolled key digest. +type Access struct{ Enrollment Enrollment } + +var _ site.Access = Access{} + +func (a Access) Prepare(_ context.Context, assignment site.Assignment) (any, *custody.Refusal) { + target, ok := a.Enrollment[assignment.Device] + if !ok { + return nil, &custody.Refusal{Reason: site.ReasonNotEnrolled, Message: "this site does not serve the Device"} + } + snapshot := assignment.Snapshot + if !strings.EqualFold(target.SystemUUID, snapshot.SystemUUID) || target.BMCEndpoint != snapshot.BMCEndpoint || (snapshot.BootMACAddress != "" && !strings.EqualFold(target.BootMACAddress, snapshot.BootMACAddress)) { + return nil, &custody.Refusal{Reason: custody.ReasonDeviceIdentityMismatch, Message: "the site's enrollment does not match the admitted snapshot"} + } + if target.BMCPublicKeySHA256 != snapshot.BMCPublicKeySHA256 { + return nil, &custody.Refusal{Reason: site.ReasonPublicKeyMismatch, Message: "the enrolled key differs from the key discovery recorded at admission"} + } + return &Connection{Device: assignment.Device, Target: target}, nil +} diff --git a/internal/site/fixture/discovery.go b/internal/site/fixture/discovery.go new file mode 100644 index 00000000..1585c85e --- /dev/null +++ b/internal/site/fixture/discovery.go @@ -0,0 +1,70 @@ +package fixture + +import ( + "context" + "errors" + "strings" + "time" + + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +// Discover is fixture discovery for a site's synthetic Devices. BMC +// discovery runs at the site and writes only the status of the Devices that +// site serves; a synthetic Device has no BMC, so this writes what discovery +// would observe: the enrolled key at the recorded endpoint, the enrolled +// system identity, and power off. A Device whose recorded identity differs +// from the enrollment gets IdentityMatched False. +func Discover(ctx context.Context, api client.Client, enrollment Enrollment, now time.Time) error { + var failed error + for key, target := range enrollment { + namespace, name, _ := strings.Cut(key, "/") + device := &inventory.Device{} + if err := api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, device); err != nil { + failed = errors.Join(failed, client.IgnoreNotFound(err)) + continue + } + if device.Spec.BMC == nil { + continue + } + observed := metav1.NewTime(now.UTC().Truncate(time.Second)) + endpoint := device.Spec.BMC.Endpoint + matched := endpoint == target.BMCEndpoint && strings.EqualFold(device.Spec.Identity.SystemUUID, target.SystemUUID) + device.Status.Discovery = &inventory.DeviceDiscovery{ + LastAttemptAt: &observed, + LastAttemptEndpoint: endpoint, + TLS: &inventory.ObservedTLS{ObservedAt: observed, Endpoint: endpoint, PublicKeySHA256: target.BMCPublicKeySHA256}, + Inventory: &inventory.ObservedInventory{ObservedAt: observed, Endpoint: endpoint, Systems: []inventory.ObservedSystem{{ + ID: "simulated", UUID: target.SystemUUID, PowerState: "Off", + }}}, + } + status, reason := metav1.ConditionTrue, "FixtureEnrollment" + if !matched { + status, reason = metav1.ConditionFalse, "FixtureEnrollmentDiffers" + } + apiMeta.SetStatusCondition(&device.Status.Conditions, metav1.Condition{Type: inventory.ConditionIdentityMatched, Status: status, Reason: reason, Message: "Synthetic discovery from the simulator site's enrollment.", ObservedGeneration: device.Generation}) + if err := api.Status().Update(ctx, device); err != nil { + failed = errors.Join(failed, err) + } + } + return failed +} + +// Run writes fixture discovery now and then every interval, as BMC +// discovery refreshes a real Device, until the context ends. +func Run(ctx context.Context, api client.Client, enrollment Enrollment, interval time.Duration, onError func(error)) { + for { + if err := Discover(ctx, api, enrollment, time.Now()); err != nil && ctx.Err() == nil && onError != nil { + onError(err) + } + select { + case <-ctx.Done(): + return + case <-time.After(interval): + } + } +} diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go new file mode 100644 index 00000000..06af2582 --- /dev/null +++ b/internal/site/redfishwork/boot.go @@ -0,0 +1,256 @@ +package redfishwork + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +// The provisioning network is site infrastructure: its DHCP hands every +// enrolled NIC the same static script, which chains to a per-MAC URL. The MAC +// is routing, not authentication. Only an open admission for that MAC, at the +// Device's stored fence, receives a script, and the script carries the +// operation's capability. +const chainScript = "#!ipxe\nchain %s/pxe/${net0/mac:hexhyp}/boot.ipxe\n" + +// BootServer serves network boots from the site store's admissions. +type BootServer struct { + Store *site.Store + // Origin is the boot server's URL as firmware reaches it. + Origin string + // Artifacts holds the installer kernel, initrd and their SHA256SUMS. + Artifacts string + // Image is the artifact manifest's identity. + Image string + // BootRoot holds the per-operation delivery evidence and the retained + // DHCP reports the workers read. + BootRoot string + // Enrollment names each Device's provisioning attachment when the + // site's DHCP is synchronized. + Enrollment redfish.Enrollment + Now func() time.Time +} + +func (b BootServer) now() time.Time { + if b.Now != nil { + return b.Now() + } + return time.Now() +} + +// Key is an operation's key in capability URLs. +func Key(operationUID string) string { + sum := sha256.Sum256([]byte(operationUID)) + return hex.EncodeToString(sum[:])[:16] +} + +// open returns the open admission whose key and token match, at the +// Device's stored fence. +func (b BootServer) open(key, token string) (Boot, bool) { + records, err := b.Store.Records(bootRecords) + if err != nil { + return Boot{}, false + } + for _, record := range records { + var boot Boot + if json.Unmarshal(record.Data, &boot) != nil || Key(boot.Operation) != key || len(boot.Token) != 64 || subtle.ConstantTimeCompare([]byte(token), []byte(boot.Token)) != 1 || boot.Phase == "" || boot.Closed || !b.now().Before(boot.Expires) { + continue + } + if fence, _, err := b.Store.Peek(record.Device); err == nil && fence == boot.Fence { + return boot, true + } + } + return Boot{}, false +} + +// Handler never serves a caller-selected path, and records deliveries +// without URLs, headers, receipts or capabilities. +func (b BootServer) Handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(request.URL.Path, "/") + if request.Method != http.MethodGet || request.URL.RawQuery != "" { + deny() + return + } + if request.URL.Path == "/pxe/boot.ipxe" { + fmt.Fprintf(w, chainScript, b.Origin) + return + } + if len(parts) != 4 { + deny() + return + } + var boot Boot + var name string + if parts[1] == "pxe" && parts[3] == "boot.ipxe" { + mac, ok := bootnet.NormalizeMAC(strings.ReplaceAll(parts[2], "-", ":")) + if !ok { + deny() + return + } + found, open, err := OpenAdmission(b.Store, mac, b.now()) + if err != nil || !open { + deny() + return + } + boot, name = found, "boot.ipxe" + } else { + found, open := b.open(parts[1], parts[2]) + if !open || (parts[3] != "kernel" && parts[3] != "installer.gz") { + deny() + return + } + boot, name = found, parts[3] + } + var data []byte + var artifact *os.File + var size int64 + if name == "boot.ipxe" { + base := b.Origin + "/" + Key(boot.Operation) + "/" + boot.Token + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, boot.Mode, base)) + size = int64(len(data)) + } else { + // Hash the pinned artifact, then serve the same open file. + var err error + if artifact, err = os.Open(filepath.Join(b.Artifacts, name)); err != nil { + deny() + return + } + defer artifact.Close() + manifest, manifestErr := os.ReadFile(filepath.Join(b.Artifacts, "SHA256SUMS")) + sum := sha256.Sum256(manifest) + hash := sha256.New() + size, err = io.Copy(hash, artifact) + if manifestErr != nil || err != nil || b.Image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(hash.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + } + dir := BootDirectory(b.BootRoot, boot.Operation) + if err := appendEvidence(dir, "boot-delivery.log", fmt.Sprintf("%s admitted %s bytes=%d\n", b.now().UTC().Format(time.RFC3339), name, size)); err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var written int64 + var err error + if artifact != nil { + written, err = io.Copy(w, artifact) + } else { + var n int + n, err = w.Write(data) + written = int64(n) + } + // A completed write is not proof that the client received it. + if err == nil && written == size { + _ = appendEvidence(dir, "boot-delivery.log", fmt.Sprintf("%s write-complete %s bytes=%d\n", b.now().UTC().Format(time.RFC3339), name, written)) + } + }) +} + +func appendEvidence(dir, name, line string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + file, err := os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + return err + } + _, err = file.WriteString(line) + if err == nil { + err = file.Sync() + } + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + parent, err := os.Open(dir) + if err != nil { + return err + } + defer parent.Close() + return parent.Sync() +} + +// Serve listens on :8080. The write bound covers emulated firmware fetching +// the initrd through the site's NAT path. +func (b BootServer) Serve(window time.Duration) error { + server := &http.Server{Addr: ":8080", Handler: b.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} + return server.ListenAndServe() +} + +// CheckClosedBoot probes a live boot server after every admission closed: +// each admission's per-MAC script and capability URLs, other enrolled MACs, +// an unsupported and an unguarded artifact, and an unknown identity must +// all be denied. It prints no capability URL. +func (b BootServer) CheckClosedBoot(origin string, extraMACs []string) (string, error) { + records, err := b.Store.Records(bootRecords) + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + probe := func(url string) error { + response, err := client.Get(url) + if err != nil { + return fmt.Errorf("the boot denial probe is unavailable") + } + response.Body.Close() + if response.StatusCode != http.StatusForbidden { + return fmt.Errorf("a closed or unknown boot was served") + } + count++ + return nil + } + for _, record := range records { + var boot Boot + if err := json.Unmarshal(record.Data, &boot); err != nil { + return "", err + } + if !boot.Closed { + return "", fmt.Errorf("a boot admission is not closed") + } + base := origin + "/" + Key(boot.Operation) + "/" + boot.Token + for _, url := range []string{origin + "/pxe/" + strings.ReplaceAll(boot.MAC, ":", "-") + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", base + "/boot.ipxe"} { + if err := probe(url); err != nil { + return "", err + } + } + } + for _, mac := range extraMACs { + if err := probe(origin + "/pxe/" + strings.ReplaceAll(mac, ":", "-") + "/boot.ipxe"); err != nil { + return "", err + } + } + for _, url := range []string{origin + "/kernel", origin + "/unknown/unknown/kernel", origin + "/pxe/not-a-mac/boot.ipxe"} { + if err := probe(url); err != nil { + return "", err + } + } + if len(records) == 0 { + return "", fmt.Errorf("no boot admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed per-MAC scripts and capabilities of %d operations, other enrolled MACs, unsupported and unguarded artifacts, unknown identity", count, len(records)), nil +} diff --git a/internal/site/redfishwork/dhcp.go b/internal/site/redfishwork/dhcp.go new file mode 100644 index 00000000..6f64e616 --- /dev/null +++ b/internal/site/redfishwork/dhcp.go @@ -0,0 +1,211 @@ +package redfishwork + +import ( + "bufio" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +// withdrawalWindow bounds how long a worker waits, after the network boot +// closed, for every DHCP instance that served the reservation to report it +// withdrawn. Past it the outcome stays unknown, and a resumed worker waits +// again. +const withdrawalWindow = 10 * time.Minute + +const dhcpLog = "dhcp-applied.log" + +// report is one retained applied report: when the boot server accepted it, +// and which DHCP instance applied which exact feed. +type report struct { + At time.Time `json:"at"` + Instance string `json:"instance"` + Feed bootnet.Feed `json:"feed"` +} + +// Reservations is the complete desired reservation set: each boot NIC whose +// admission is not closed, unexpired and at the Device's stored fence holds +// its provisioning address. It is empty when no network boot is admitted. +func (b BootServer) Reservations() (bootnet.Feed, error) { + records, err := b.Store.Records(bootRecords) + if err != nil { + return bootnet.Feed{}, err + } + reservations := []bootnet.Reservation{} + for _, record := range records { + var boot Boot + if json.Unmarshal(record.Data, &boot) != nil || boot.Closed || !b.now().Before(boot.Expires) { + continue + } + target, ok := b.Enrollment.Target(record.Device) + if !ok || target.Provisioning == (redfish.Provisioning{}) { + continue + } + if fence, _, err := b.Store.Peek(record.Device); err != nil || fence != boot.Fence { + continue + } + reservations = append(reservations, bootnet.Reservation{MAC: target.MAC, Address: target.Provisioning.Address, Gateway: target.Provisioning.Gateway, Expires: boot.Expires}) + } + return bootnet.NewFeed(reservations) +} + +// DHCPHandler serves the reservation feed and accepts applied reports from +// the DHCP owner's synchronizer, authenticated by a bearer token. It is +// never served on the firmware-facing boot listener. +func (b BootServer) DHCPHandler(token string) (http.Handler, error) { + if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { + return nil, errors.New("the DHCP synchronizer token must be at least 32 characters without whitespace") + } + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + w.Header().Set("Cache-Control", "no-store") + got, ok := strings.CutPrefix(request.Header.Get("Authorization"), "Bearer ") + if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + switch { + case request.Method == http.MethodGet && request.URL.Path == "/dhcp/v1/reservations" && request.URL.RawQuery == "": + feed, err := b.Reservations() + if err != nil { + http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(feed) + case request.Method == http.MethodPost && request.URL.Path == "/dhcp/v1/applied" && request.URL.RawQuery == "": + var applied bootnet.Applied + decoder := json.NewDecoder(io.LimitReader(request.Body, 64<<10)) + decoder.DisallowUnknownFields() + if decoder.Decode(&applied) != nil || decoder.Decode(&struct{}{}) != io.EOF || applied.Verify() != nil { + http.Error(w, "invalid applied report", http.StatusBadRequest) + return + } + if err := b.retain(applied); err != nil { + http.Error(w, "applied report not retained", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "not found", http.StatusNotFound) + } + }), nil +} + +// ServeDHCP listens on :8081, apart from the boot listener. +func (b BootServer) ServeDHCP(token string) error { + handler, err := b.DHCPHandler(token) + if err != nil { + return err + } + server := &http.Server{Addr: ":8081", Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + return server.ListenAndServe() +} + +// retain appends one report and syncs it before acknowledging. +func (b BootServer) retain(applied bootnet.Applied) error { + data, err := json.Marshal(report{At: b.now().UTC(), Instance: applied.Instance, Feed: applied.Feed}) + if err != nil { + return err + } + return appendEvidence(b.BootRoot, dhcpLog, string(data)+"\n") +} + +// reports reads every retained report in order. An unreadable line is +// corruption, never evidence in either direction. +func reports(root string) ([]report, error) { + file, err := os.Open(filepath.Join(root, dhcpLog)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + defer file.Close() + var out []report + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 0, 64<<10), 1<<20) + for scanner.Scan() { + var r report + if json.Unmarshal(scanner.Bytes(), &r) != nil || r.At.IsZero() || (bootnet.Applied{Instance: r.Instance, Feed: r.Feed}).Verify() != nil { + return nil, errors.New("invalid retained DHCP report") + } + out = append(out, r) + } + return out, scanner.Err() +} + +// awaitReservation waits, without any effect, until some DHCP instance +// reports serving the target's exact provisioning address since this +// operation's boot admission was created. +func (c Config) awaitReservation(ctx context.Context, work *site.Work, boot Boot) error { + poll, _, _, _ := c.durations() + target := conn(work).Target + for { + retained, err := reports(c.BootRoot) + if err != nil { + return err + } + for _, r := range retained { + if r.At.After(boot.Created) && r.Feed.Has(target.MAC, target.Provisioning.Address) { + return nil + } + } + if !c.now().Before(boot.Expires) { + return errors.New("DHCP did not apply the boot reservation before the boot admission expired") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// awaitWithdrawal requires every DHCP instance that served the boot NIC +// during this operation to now report a feed without it. A silent instance +// keeps the outcome unknown: its reservation may still be served. +func (c Config) awaitWithdrawal(ctx context.Context, work *site.Work, boot Boot) error { + poll, _, _, _ := c.durations() + mac := conn(work).Target.MAC + deadline := c.now().Add(withdrawalWindow) + for { + retained, err := reports(c.BootRoot) + if err != nil { + return err + } + served, latest := map[string]bool{}, map[string]bootnet.Feed{} + for _, r := range retained { + if !r.At.After(boot.Created) { + continue + } + if r.Feed.Serves(mac) { + served[r.Instance] = true + } + latest[r.Instance] = r.Feed + } + withdrawn := len(served) > 0 + for instance := range served { + if latest[instance].Serves(mac) { + withdrawn = false + } + } + if withdrawn { + return nil + } + if c.now().After(deadline) { + return errors.New("DHCP has not reported the boot reservation withdrawn") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go new file mode 100644 index 00000000..139952c4 --- /dev/null +++ b/internal/site/redfishwork/dhcp_test.go @@ -0,0 +1,111 @@ +package redfishwork + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +const syncToken = "synthetic-dhcp-synchronizer-token-0123456789" + +// TestSyncedDHCPFollowsTheOpenAdmission serves a reservation only for an +// open admission at the Device's stored fence, retains the DHCP owner's +// applied reports, and makes a worker wait for the reservation before a +// network boot and for its withdrawal before it reports. +func TestSyncedDHCPFollowsTheOpenAdmission(t *testing.T) { + root := t.TempDir() + for _, dir := range []string{"store", "boot"} { + if err := os.Mkdir(filepath.Join(root, dir), 0o700); err != nil { + t.Fatal(err) + } + } + store, err := site.OpenStore(filepath.Join(root, "store"), nil) + if err != nil { + t.Fatal(err) + } + const device = "fleet-provider/server-example-001" + target := redfish.Target{Device: device, MAC: "52:54:00:77:01:0a", Provisioning: redfish.Provisioning{Address: "192.0.2.20/24", Gateway: "192.0.2.1"}} + now := time.Now().UTC().Truncate(time.Second) + clock := func() time.Time { return now } + if err := store.Raise(device, 3); err != nil { + t.Fatal(err) + } + boot := Boot{Operation: "00000000-0000-4000-8000-000000000301", Fence: 3, MAC: target.MAC, Token: strings.Repeat("a", 64), Created: now.Add(-time.Minute), Expires: now.Add(time.Hour)} + if err := store.PutRecord(device, 3, bootRecords, boot.Operation, boot); err != nil { + t.Fatal(err) + } + server := BootServer{Store: store, BootRoot: filepath.Join(root, "boot"), Enrollment: redfish.Enrollment{DHCP: redfish.DHCPSynced, Targets: []redfish.Target{target}}, Now: clock} + feed, err := server.Reservations() + if err != nil || !feed.Has(target.MAC, target.Provisioning.Address) { + t.Fatalf("feed = %+v, %v", feed, err) + } + handler, err := server.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) + } + feedServer := httptest.NewServer(handler) + defer feedServer.Close() + post := func(applied bootnet.Applied) { + t.Helper() + data, _ := json.Marshal(applied) + request, _ := newRequest("POST", feedServer.URL+"/dhcp/v1/applied", string(data)) + response, err := feedServer.Client().Do(request) + if err != nil || response.StatusCode != 204 { + t.Fatalf("applied report = %v, %v", response, err) + } + response.Body.Close() + } + request, _ := newRequest("GET", feedServer.URL+"/dhcp/v1/reservations", "") + request.Header.Del("Authorization") + if response, err := feedServer.Client().Do(request); err != nil || response.StatusCode != 401 { + t.Fatalf("unauthenticated feed = %v, %v", response, err) + } + + config := Config{BootRoot: server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true} + work := &site.Work{Connection: &site.RedfishConnection{Target: target}} + short := func() context.Context { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + t.Cleanup(cancel) + return ctx + } + if err := config.awaitReservation(short(), work, boot); err == nil { + t.Fatal("a worker booted before DHCP applied the reservation") + } + post(bootnet.Applied{Instance: "dhcp-a", Feed: feed}) + if err := config.awaitReservation(short(), work, boot); err != nil { + t.Fatalf("applied reservation not seen: %v", err) + } + if err := config.awaitWithdrawal(short(), work, boot); err == nil { + t.Fatal("a reservation still served counted as withdrawn") + } + empty, _ := bootnet.NewFeed(nil) + post(bootnet.Applied{Instance: "dhcp-a", Feed: empty}) + if err := config.awaitWithdrawal(short(), work, boot); err != nil { + t.Fatalf("withdrawal not seen: %v", err) + } + // A newer fence supersedes the admission: its reservation goes. + if err := store.Raise(device, 4); err != nil { + t.Fatal(err) + } + if feed, err := server.Reservations(); err != nil || len(feed.Reservations) != 0 { + t.Fatalf("feed after a newer fence = %+v, %v", feed, err) + } +} + +func newRequest(method, url, body string) (*http.Request, error) { + request, err := http.NewRequest(method, url, strings.NewReader(body)) + if err == nil { + request.Header.Set("Authorization", "Bearer "+syncToken) + } + return request, err +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index cb616ec6..19b2a678 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -65,7 +65,11 @@ type Config struct { // PowerOffBound bounds how long the server may take to power off. It // defaults to five minutes. PowerOffBound time.Duration - Now func() time.Time + // Synced means the site's DHCP is synchronized: a network boot waits + // until DHCP applied the boot NIC's reservation, and the operation ends + // only once every DHCP instance that served it withdrew it. + Synced bool + Now func() time.Time } func (c Config) now() time.Time { @@ -197,13 +201,16 @@ type powerOn struct { // boot only while an admission is open and its fence is still the Device's // stored fence. type Boot struct { - Operation string `json:"operation"` - Fence int64 `json:"fence"` - Mode string `json:"mode"` - MAC string `json:"mac"` - Receipt string `json:"receipt"` - Token string `json:"token"` - Expires time.Time `json:"expires"` + Operation string `json:"operation"` + Fence int64 `json:"fence"` + Mode string `json:"mode"` + MAC string `json:"mac"` + Receipt string `json:"receipt"` + Token string `json:"token"` + // Created is when the admission was created; DHCP reports before it + // are not this operation's. + Created time.Time `json:"created"` + Expires time.Time `json:"expires"` // Phase is the network-booting phase, set while it may boot. Phase string `json:"phase,omitempty"` Closed bool `json:"closed,omitempty"` @@ -216,7 +223,7 @@ const bootRecords = "boot" func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, error) { store := work.Store() var boot Boot - found, err := store.GetRecord(work.Device, bootRecords, work.Operation.UID, &boot) + found, err := store.GetRecord(work.Device, bootRecords, work.Key(), &boot) if err != nil || found { return boot, err } @@ -228,12 +235,12 @@ func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, e return boot, err } _, _, _, window := c.durations() - boot = Boot{Operation: work.Operation.UID, Fence: work.Fence, Mode: mode, MAC: strings.ToLower(conn(work).Target.MAC), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: c.now().Add(window).UTC()} - return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Operation.UID, boot) + boot = Boot{Operation: work.Key(), Fence: work.Fence, Mode: mode, MAC: strings.ToLower(conn(work).Target.MAC), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Created: c.now().UTC(), Expires: c.now().Add(window).UTC()} + return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } func (c Config) saveBoot(work *site.Work, boot Boot) error { - return work.Store().PutRecord(work.Device, work.Fence, bootRecords, work.Operation.UID, boot) + return work.Store().PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops.StepEvidence, error) { @@ -271,6 +278,11 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops return nil, err } } + if ph.mode != "" && c.Synced && !requested { + if err := c.awaitReservation(ctx, work, boot); err != nil { + return nil, err + } + } // Power on is sent once. After a crash or lost response it is // observed: any sign that the boot began counts, and no sign leaves // the outcome unknown rather than sending it again. @@ -297,6 +309,11 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops } evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) } + if c.Synced { + if err := c.awaitWithdrawal(ctx, work, boot); err != nil { + return nil, err + } + } return evidence, nil } @@ -440,7 +457,7 @@ func BootDirectory(root, operationUID string) string { } func (c Config) deliveries(work *site.Work) map[string]bool { - data, _ := os.ReadFile(filepath.Join(BootDirectory(c.BootRoot, work.Operation.UID), "boot-delivery.log")) + data, _ := os.ReadFile(filepath.Join(BootDirectory(c.BootRoot, work.Key()), "boot-delivery.log")) done := map[string]bool{} for _, line := range strings.Split(string(data), "\n") { fields := strings.Fields(line) @@ -488,7 +505,7 @@ func OpenAdmission(store *site.Store, mac string, now time.Time) (Boot, bool, er if json.Unmarshal(record.Data, &boot) != nil || boot.MAC != strings.ToLower(mac) || boot.Phase == "" || boot.Closed || !now.Before(boot.Expires) { continue } - fence, _, err := store.Current(record.Device) + fence, _, err := store.Peek(record.Device) if err != nil { return Boot{}, false, err } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 79fa21c2..264ecbc5 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -193,7 +193,7 @@ func runner(t *testing.T, l *lab) *site.Runner { return &site.Runner{ Site: "site-example-a", Store: store, Results: site.NewResults(store), Access: site.RedfishAccess{Credentials: credentials{pin: l.pin()}, - Targets: site.StaticTargets{device: {AssetID: "server-example-001", Endpoint: l.server.URL, SystemID: "A", SystemUUID: uuid, MAC: mac, DiskBytes: diskBytes, Console: filepath.Base(l.console)}}}, + Targets: site.StaticTargets{device: {Device: "server-example-001", Endpoint: l.server.URL, SystemID: "A", SystemUUID: uuid, MAC: mac, DiskBytes: diskBytes, Console: filepath.Base(l.console)}}}, Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}, "DeviceWipe": Wipe{config}}, Poll: 10 * time.Millisecond, } @@ -202,16 +202,18 @@ func runner(t *testing.T, l *lab) *site.Runner { func assignment(l *lab, kind, uid string, fence int64, spec any) site.Assignment { inputs, _ := json.Marshal(spec) sum := sha256.Sum256(inputs) - l.operation = uid - return site.Assignment{ - Device: device, Operation: ops.OperationReference{Kind: kind, Name: "alloc-example-" + uid, UID: uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), + a := site.Assignment{ + Device: device, Operation: ops.OperationReference{Kind: kind, Name: "alloc-example-" + uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), Snapshot: ops.DeviceSnapshot{BMCEndpoint: l.server.URL, SystemUUID: uuid, BootMACAddress: mac, BMCPublicKeySHA256: l.pin()}, InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, } + // The lab finds the boot record by the admission's site key. + l.operation = a.Key() + return a } func installSpec() ops.DeviceInstallationSpec { - return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, RequestUID: "request-1"} + return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} } func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { diff --git a/internal/site/results.go b/internal/site/results.go index 36a2571f..95b8d744 100644 --- a/internal/site/results.go +++ b/internal/site/results.go @@ -18,7 +18,8 @@ type Results struct{ store *Store } func NewResults(store *Store) *Results { return &Results{store: store} } -type storedResult struct { +// Stored is one result the site holds, with its "/" Device. +type Stored struct { Device string `json:"device"` Result custody.SiteResult `json:"result"` } @@ -37,7 +38,7 @@ func (r *Results) Put(device string, result custody.SiteResult) (custody.SiteRes if err := os.MkdirAll(dir, 0o700); err != nil { return result, err } - data, err := json.Marshal(storedResult{Device: device, Result: result}) + data, err := json.Marshal(Stored{Device: device, Result: result}) if err != nil { return result, err } @@ -61,7 +62,7 @@ func (r *Results) Put(device string, result custody.SiteResult) (custody.SiteRes // content, so a reader never sees a partial result. if err := os.Link(file.Name(), filepath.Join(dir, resultName(result))); err != nil { if os.IsExist(err) { - stored, found, readErr := r.Get(device, result.Operation.UID, result.Fence) + stored, found, readErr := r.Get(device, result.Operation, result.Fence) if readErr != nil || !found { return result, errors.New("site: a stored result is unreadable") } @@ -78,15 +79,15 @@ func (r *Results) Put(device string, result custody.SiteResult) (custody.SiteRes } // Get returns the stored result for an operation and fence. -func (r *Results) Get(device, operation string, fence int64) (custody.SiteResult, bool, error) { - data, err := os.ReadFile(filepath.Join(r.dir(device), resultName(custody.SiteResult{Operation: ops.OperationReference{UID: operation}, Fence: fence}))) +func (r *Results) Get(device string, operation ops.OperationReference, fence int64) (custody.SiteResult, bool, error) { + data, err := os.ReadFile(filepath.Join(r.dir(device), resultName(custody.SiteResult{Operation: operation, Fence: fence}))) if os.IsNotExist(err) { return custody.SiteResult{}, false, nil } if err != nil { return custody.SiteResult{}, false, err } - var stored storedResult + var stored Stored if err := json.Unmarshal(data, &stored); err != nil { return custody.SiteResult{}, false, errors.New("site: a stored result is unreadable") } @@ -94,25 +95,25 @@ func (r *Results) Get(device, operation string, fence int64) (custody.SiteResult } func resultName(result custody.SiteResult) string { - return result.Operation.UID + "-" + jsonInt(result.Fence) + ".json" + return custody.OperationKey(result.Operation, result.Fence) + ".json" } func jsonInt(value int64) string { data, _ := json.Marshal(value); return string(data) } // Pending returns every stored result, oldest file name first. -func (r *Results) Pending() ([]storedResult, error) { +func (r *Results) Pending() ([]Stored, error) { paths, err := filepath.Glob(filepath.Join(r.store.root, "devices", "*", "results", "*.json")) if err != nil { return nil, err } sort.Strings(paths) - var out []storedResult + var out []Stored for _, path := range paths { data, err := os.ReadFile(path) if err != nil { return nil, err } - var stored storedResult + var stored Stored if err := json.Unmarshal(data, &stored); err != nil { return nil, errors.New("site: a stored result is unreadable") } @@ -121,6 +122,15 @@ func (r *Results) Pending() ([]storedResult, error) { return out, nil } +// Forget deletes the site's copy of a result after the coordinator accepted +// it or rejected it for a stale fence. +func (r *Results) Forget(device string, result custody.SiteResult) error { + if err := os.Remove(filepath.Join(r.dir(device), resultName(result))); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + // Deliver offers every stored result to accept, which reports it to the // coordinator. The site deletes its copy once the coordinator accepts it or // rejects it for a stale fence. Any other error keeps the copy for the next @@ -137,7 +147,7 @@ func (r *Results) Deliver(ctx context.Context, accept func(context.Context, cust failed = errors.Join(failed, err) continue } - if err := os.Remove(filepath.Join(r.dir(stored.Device), resultName(stored.Result))); err != nil && !os.IsNotExist(err) { + if err := r.Forget(stored.Device, stored.Result); err != nil { return err } } diff --git a/internal/site/runner.go b/internal/site/runner.go index c82f831c..d8eba1c3 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -37,6 +37,10 @@ type Assignment struct { const maxInputs = 16 << 10 +// Key names this admission at the site: the journal, results and boot +// records are keyed by it. +func (a Assignment) Key() string { return custody.OperationKey(a.Operation, a.Fence) } + // Validate checks the payload's shape. It does not check the inputs // against their digest; the worker does, before anything is sent. func (a Assignment) Validate() error { @@ -44,8 +48,8 @@ func (a Assignment) Validate() error { switch { case !ok || namespace == "" || name == "" || strings.Contains(name, "/"): return errors.New("site: an assignment names one Device as namespace/name") - case a.Operation.Kind == "" || a.Operation.Name == "" || a.Operation.UID == "": - return errors.New("site: an assignment names one operation incarnation") + case a.Operation.Kind == "" || a.Operation.Name == "": + return errors.New("site: an assignment names one operation") case a.Fence < 1 || a.AdmittedAt.IsZero() || a.Deadline.IsZero() || !a.AdmittedAt.Before(a.Deadline) || a.InputDigest == "": return errors.New("site: an assignment carries a fence, its admission time, a later deadline and an input digest") case len(a.Inputs) == 0 || len(a.Inputs) > maxInputs: @@ -134,7 +138,7 @@ func (w *Work) JournaledAt(step string) (time.Time, bool) { return time.Time{}, false } for _, entry := range journal { - if entry.Operation == w.Operation.UID && entry.Step == step && entry.State == StepDone { + if entry.Operation == w.Key() && entry.Step == step && entry.State == StepDone { return entry.At, true } } @@ -159,7 +163,7 @@ func (w *Work) Step(ctx context.Context, step Step) error { payload = data } name := step.Name - prior, recorded, err := w.store.IntendWithPayload(w.Device, w.Fence, w.Operation.UID, name, payload) + prior, recorded, err := w.store.IntendWithPayload(w.Device, w.Fence, w.Key(), name, payload) switch { case errors.Is(err, ErrStaleFence): return errSuperseded @@ -200,7 +204,7 @@ func (w *Work) Step(ctx context.Context, step Step) error { return err } } - if err := w.store.Done(w.Device, w.Fence, w.Operation.UID, name); errors.Is(err, ErrStaleFence) { + if err := w.store.Done(w.Device, w.Fence, w.Key(), name); errors.Is(err, ErrStaleFence) { return errSuperseded } else if err != nil { return err @@ -310,7 +314,7 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe return custody.SiteResult{}, err } // A redelivered assignment that already has a result returns it. - if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation.UID, assignment.Fence); err != nil || found { + if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation, assignment.Fence); err != nil || found { return stored, err } result := custody.SiteResult{Site: r.Site, Device: deviceName(assignment.Device), Operation: assignment.Operation, Fence: assignment.Fence} @@ -326,7 +330,7 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe if err != nil { return false, err } - return slices.ContainsFunc(journal, func(entry Entry) bool { return entry.Operation == assignment.Operation.UID }), nil + return slices.ContainsFunc(journal, func(entry Entry) bool { return entry.Operation == assignment.Key() }), nil } lock, err := r.acquire(ctx, assignment) switch { @@ -357,7 +361,7 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe // A worker for this same assignment may have stored its result while // this one waited for the lock. Return that result; running the kind // again could send to the server after the outcome was recorded. - if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation.UID, assignment.Fence); err != nil || found { + if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation, assignment.Fence); err != nil || found { return stored, err } parent := ctx diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go index 10abee89..550fddc1 100644 --- a/internal/site/runner_test.go +++ b/internal/site/runner_test.go @@ -193,7 +193,7 @@ func newFixture(t *testing.T, uuid string) *fixture { Site: "site-example-a", Store: store, Results: NewResults(store), Access: &RedfishAccess{ Credentials: fixedCredentials{credential: bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret", Pin: b.pin()}, found: true}, - Targets: StaticTargets{testDevice: {AssetID: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}}, + Targets: StaticTargets{testDevice: {Device: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}}, }, Kinds: map[string]Kind{"DeviceInstallation": kind}, Poll: 10 * time.Millisecond, @@ -203,12 +203,17 @@ func newFixture(t *testing.T, uuid string) *fixture { func (f *fixture) access() *RedfishAccess { return f.runner.Access.(*RedfishAccess) } +// testKey is the site key of the fixture's installation at fence. +func testKey(fence int64, uid string) string { + return custody.OperationKey(ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-" + uid}, fence) +} + func (f *fixture) assignment(fence int64, uid string) Assignment { inputs := json.RawMessage(`{"image":"debian-12"}`) sum := sha256.Sum256(inputs) return Assignment{ Device: testDevice, - Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-" + uid, UID: uid}, + Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-" + uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), @@ -401,7 +406,7 @@ func TestAReplayedStepIsObservedNotSentAgain(t *testing.T) { if err := f.runner.Store.Raise(testDevice, 1); err != nil { t.Fatal(err) } - if _, err := f.runner.Store.Intend(testDevice, 1, "op-replay", "power-off"); err != nil { + if _, err := f.runner.Store.Intend(testDevice, 1, testKey(1, "op-replay"), "power-off"); err != nil { t.Fatal(err) } var observed atomic.Int32 @@ -422,7 +427,7 @@ func TestAReplayedStepIsObservedNotSentAgain(t *testing.T) { if err := g.runner.Store.Raise(testDevice, 1); err != nil { t.Fatal(err) } - if _, err := g.runner.Store.Intend(testDevice, 1, "op-replay", "power-off"); err != nil { + if _, err := g.runner.Store.Intend(testDevice, 1, testKey(1, "op-replay"), "power-off"); err != nil { t.Fatal(err) } g.kind.observe = func(context.Context, json.RawMessage) (bool, error) { return false, nil } @@ -439,15 +444,15 @@ func TestResultsAreDeletedOnceTheCoordinatorAnswers(t *testing.T) { t.Fatal(err) } } - answers := map[string]error{"op-a": nil, "op-b": custody.ErrStaleFence, "op-c": errors.New("coordinator unreachable")} + answers := map[string]error{"alloc-example-install-op-a": nil, "alloc-example-install-op-b": custody.ErrStaleFence, "alloc-example-install-op-c": errors.New("coordinator unreachable")} err := f.runner.Results.Deliver(context.Background(), func(_ context.Context, result custody.SiteResult) error { - return answers[result.Operation.UID] + return answers[result.Operation.Name] }) if err == nil { t.Fatal("the failed delivery was not reported") } pending, _ := f.runner.Results.Pending() - if len(pending) != 1 || pending[0].Result.Operation.UID != "op-c" { + if len(pending) != 1 || pending[0].Result.Operation.Name != "alloc-example-install-op-c" { t.Fatalf("pending = %+v", pending) } } @@ -461,7 +466,7 @@ func TestAssignmentValidation(t *testing.T) { for name, mutate := range map[string]func(*Assignment){ "device": func(a *Assignment) { a.Device = "server-example-001" }, "nested": func(a *Assignment) { a.Device = "default/a/b" }, - "uid": func(a *Assignment) { a.Operation.UID = "" }, + "name": func(a *Assignment) { a.Operation.Name = "" }, "fence": func(a *Assignment) { a.Fence = 0 }, "deadline": func(a *Assignment) { a.Deadline = time.Time{} }, "inputs": func(a *Assignment) { a.Inputs = make(json.RawMessage, maxInputs+1) }, @@ -494,7 +499,7 @@ func TestAResumedWorkerThatCannotReachTheBMCReportsUnknown(t *testing.T) { if err := f.runner.Store.Raise(testDevice, 1); err != nil { t.Fatal(err) } - if _, err := f.runner.Store.Intend(testDevice, 1, "op-resumed", "power-off"); err != nil { + if _, err := f.runner.Store.Intend(testDevice, 1, testKey(1, "op-resumed"), "power-off"); err != nil { t.Fatal(err) } f.access().Credentials = fixedCredentials{} @@ -538,7 +543,7 @@ func TestALateStartIsStaleAndSendsNothing(t *testing.T) { if err := g.runner.Store.Raise(testDevice, 1); err != nil { t.Fatal(err) } - if _, err := g.runner.Store.Intend(testDevice, 1, "op-resume-late", "power-off"); err != nil { + if _, err := g.runner.Store.Intend(testDevice, 1, testKey(1, "op-resume-late"), "power-off"); err != nil { t.Fatal(err) } g.kind.observe = func(context.Context, json.RawMessage) (bool, error) { return true, nil } @@ -610,7 +615,7 @@ func TestARedeliveryWhileTheSameOperationRunsStoresNothing(t *testing.T) { if _, err := f.runner.Run(context.Background(), again); !errors.Is(err, ErrAlreadyRunning) { t.Fatalf("redelivery: %v", err) } - if _, found, _ := f.runner.Results.Get(testDevice, "op-same", 1); found { + if _, found, _ := f.runner.Results.Get(testDevice, ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-op-same"}, 1); found { t.Fatal("the redelivery stored a result while the first worker ran") } close(f.kind.block) @@ -723,7 +728,7 @@ func TestAWorkerStoppedFromOutsideStoresNoResult(t *testing.T) { if _, err := f.runner.Run(ctx, f.assignment(1, "op-shutdown")); !errors.Is(err, context.Canceled) { t.Fatalf("shutdown: %v", err) } - if _, found, _ := f.runner.Results.Get(testDevice, "op-shutdown", 1); found { + if _, found, _ := f.runner.Results.Get(testDevice, ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-op-shutdown"}, 1); found { t.Fatal("a worker shut down from outside stored a result") } } @@ -740,7 +745,7 @@ func TestAShutdownWhileWaitingForTheRunLockStoresNothing(t *testing.T) { if _, err := f.runner.Run(ctx, f.assignment(2, "op-waiting")); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("shutdown while waiting: %v", err) } - if _, found, _ := f.runner.Results.Get(testDevice, "op-waiting", 2); found { + if _, found, _ := f.runner.Results.Get(testDevice, ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-op-waiting"}, 2); found { t.Fatal("a worker shut down while waiting stored a result") } } @@ -758,7 +763,7 @@ func TestALostLockWithJournaledStepsIsUnknown(t *testing.T) { if err := f.runner.Store.Raise(testDevice, 2); err != nil { t.Fatal(err) } - if _, err := f.runner.Store.Intend(testDevice, 2, "op-journaled", "power-off"); err != nil { + if _, err := f.runner.Store.Intend(testDevice, 2, testKey(2, "op-journaled"), "power-off"); err != nil { t.Fatal(err) } newer := f.assignment(2, "op-journaled") @@ -797,7 +802,7 @@ func TestAShutdownDuringTheChecksStoresNothing(t *testing.T) { if _, err := f.runner.Run(ctx, f.assignment(1, "op-checks")); !errors.Is(err, context.Canceled) { t.Fatalf("shutdown during checks: %v", err) } - if _, found, _ := f.runner.Results.Get(testDevice, "op-checks", 1); found { + if _, found, _ := f.runner.Results.Get(testDevice, ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-op-checks"}, 1); found { t.Fatal("a worker shut down during its checks stored a result") } } diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go new file mode 100644 index 00000000..545f12be --- /dev/null +++ b/internal/site/simwork/kinds.go @@ -0,0 +1,192 @@ +// Package simwork is the simulator site's install and wipe workers for +// synthetic Devices that have no BMC. The site reaches them through +// fixture.Access. The simulated server is a +// record in the site's store, so every effect goes through the same fenced +// journal as a real one, and a site restart keeps both. It is never a +// production executor. +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" +) + +// Server is the simulated server's state. +type Server struct { + // Image is the digest written to the disks, or empty after a wipe. + Image string `json:"image,omitempty"` + // Booted is the digest the server last booted from disk. + Booted string `json:"booted,omitempty"` +} + +const serverRecords = "simulator" + +// serverName is the one record name for a Device's simulated server. +const serverName = "server" + +func read(work *site.Work) (Server, error) { + var server Server + _, err := work.Store().GetRecord(work.Device, serverRecords, serverName, &server) + return server, err +} + +func write(work *site.Work, server Server) error { + return work.Store().PutRecord(work.Device, work.Fence, serverRecords, serverName, server) +} + +// ReadServer returns a Device's simulated server, for evidence checks. +func ReadServer(store *site.Store, device string) (Server, error) { + var server Server + _, err := store.GetRecord(device, serverRecords, serverName, &server) + return server, err +} + +func connection(work *site.Work) *fixture.Connection { + connection, _ := work.Connection.(*fixture.Connection) + return connection +} + +func checkDisks(work *site.Work, disks []string) *custody.Refusal { + if connection(work) == nil { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site does not run the simulator"} + } + if len(disks) == 0 || !slices.Equal(slices.Sorted(slices.Values(disks)), slices.Sorted(slices.Values(connection(work).Target.Disks))) { + return &custody.Refusal{Reason: custody.ReasonTargetDisks, Message: "the target disks are not the site's enrolled disks"} + } + return nil +} + +// Installation is the simulator's DeviceInstallation worker. +type Installation struct{} + +// Wipe is the simulator's DeviceWipe worker. +type Wipe struct{} + +var ( + _ site.Kind = Installation{} + _ site.Kind = Wipe{} +) + +func installSpec(work *site.Work) (ops.DeviceInstallationSpec, *custody.Refusal) { + var spec ops.DeviceInstallationSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.Image.Digest == "" { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceInstallation spec"} + } + return spec, nil +} + +func (Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { + spec, refusal := installSpec(work) + if refusal != nil { + return refusal + } + if spec.Bootstrap != nil { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} + } + return checkDisks(work, spec.TargetDisks) +} + +func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := installSpec(work) + if refusal != nil { + return nil, refusal + } + var evidence ops.InstallationEvidence + steps := []site.Step{ + { + Name: "write-image", + Send: func(context.Context) error { + server, err := read(work) + if err != nil { + return err + } + server.Image, server.Booted = spec.Image.Digest, "" + return write(work, server) + }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + server, err := read(work) + return server.Image == spec.Image.Digest, err + }, + }, + { + Name: "boot-disk", + Send: func(context.Context) error { + server, err := read(work) + if err != nil { + return err + } + server.Booted = server.Image + return write(work, server) + }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + server, err := read(work) + return server.Booted == spec.Image.Digest, err + }, + }, + } + for _, step := range steps { + if err := work.Step(ctx, step); err != nil { + return nil, err + } + at, _ := work.JournaledAt(step.Name) + evidence.Steps = append(evidence.Steps, ops.StepEvidence{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}) + } + server, err := read(work) + if err != nil { + return nil, err + } + if server.Booted != spec.Image.Digest { + return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "the simulated server did not boot the installed image"} + } + return evidence, nil +} + +func wipeSpec(work *site.Work) (ops.DeviceWipeSpec, *custody.Refusal) { + var spec ops.DeviceWipeSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.CleaningPolicyDigest == "" { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceWipe spec"} + } + return spec, nil +} + +func (Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { + spec, refusal := wipeSpec(work) + if refusal != nil { + return refusal + } + return checkDisks(work, spec.TargetDisks) +} + +func (Wipe) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := wipeSpec(work) + if refusal != nil { + return nil, refusal + } + step := site.Step{ + Name: "wipe", + Send: func(context.Context) error { return write(work, Server{}) }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + server, err := read(work) + return server == Server{}, err + }, + // Wiping a wiped disk again changes nothing. + Idempotent: true, + } + if err := work.Step(ctx, step); err != nil { + return nil, err + } + at, _ := work.JournaledAt(step.Name) + return ops.WipeEvidence{ + Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, + WipedDisks: slices.Clone(spec.TargetDisks), + PolicyDigest: spec.CleaningPolicyDigest, + }, nil +} diff --git a/internal/site/siteapi/api_test.go b/internal/site/siteapi/api_test.go new file mode 100644 index 00000000..090a18ec --- /dev/null +++ b/internal/site/siteapi/api_test.go @@ -0,0 +1,133 @@ +package siteapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "sync/atomic" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +const ( + token = "synthetic-site-token" + device = "fleet-provider/server-example-001" +) + +// access admits every assignment; the kind counts its runs. +type access struct{} + +func (access) Prepare(context.Context, site.Assignment) (any, *custody.Refusal) { return nil, nil } + +type counting struct{ runs atomic.Int32 } + +func (*counting) Check(context.Context, *site.Work) *custody.Refusal { return nil } +func (k *counting) Run(ctx context.Context, work *site.Work) (any, error) { + k.runs.Add(1) + if err := work.Step(ctx, site.Step{Name: "effect", Send: func(context.Context) error { time.Sleep(50 * time.Millisecond); return nil }}); err != nil { + return nil, err + } + return map[string]string{"done": "true"}, nil +} + +func assignment(t *testing.T) site.Assignment { + inputs := json.RawMessage(`{"step":1}`) + digest, err := custody.SpecDigest(map[string]int{"step": 1}) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + return site.Assignment{Device: device, Operation: ops.OperationReference{Kind: "DeviceTestKind", Name: "op-example"}, Fence: 2, + AdmittedAt: now, Deadline: now.Add(time.Minute), InputDigest: digest, Inputs: inputs, + Snapshot: ops.DeviceSnapshot{BMCEndpoint: "https://[2001:db8::1]", SystemUUID: "00000000-0000-4000-8000-000000000001", BMCPublicKeySHA256: "aa"}} +} + +// TestTheSiteAPI authenticates every call but readiness, runs a redelivered +// assignment once, reports the site's fence and stored result, and forgets +// a result only when the coordinator answers it. +func TestTheSiteAPI(t *testing.T) { + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + kind := &counting{} + results := site.NewResults(store) + runner := &site.Runner{Site: "site-example-a", Store: store, Results: results, Access: access{}, Kinds: map[string]site.Kind{"DeviceTestKind": kind}, Poll: 10 * time.Millisecond} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatcher := &Dispatcher{Runner: runner, Context: ctx} + server := httptest.NewServer(Handler(dispatcher, store, results, func() (string, error) { return token, nil })) + defer server.Close() + for name, header := range map[string]string{"no token": "", "wrong token": "Bearer other"} { + request, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/results", nil) + if header != "" { + request.Header.Set("Authorization", header) + } + response, err := server.Client().Do(request) + if err != nil || response.StatusCode != http.StatusUnauthorized { + t.Fatalf("%s: %v, %v", name, response, err) + } + response.Body.Close() + } + if response, err := server.Client().Get(server.URL + "/readyz"); err != nil || response.StatusCode != http.StatusOK { + t.Fatalf("readiness = %v, %v", response, err) + } + remote, err := NewClient(server.URL, func() (string, error) { return token, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + a := assignment(t) + for range 3 { + if err := remote.Deliver(ctx, a); err != nil { + t.Fatal(err) + } + } + var held []site.Stored + deadline := time.Now().Add(10 * time.Second) + for len(held) == 0 { + if time.Now().After(deadline) { + t.Fatal("no result was stored") + } + time.Sleep(20 * time.Millisecond) + if held, err = remote.Results(ctx); err != nil { + t.Fatal(err) + } + } + dispatcher.Wait() + if kind.runs.Load() != 1 || len(held) != 1 || held[0].Result.Phase != ops.PhaseSucceeded || held[0].Result.Fence != 2 { + t.Fatalf("runs = %d, results = %+v", kind.runs.Load(), held) + } + if report, reported, err := remote.Fence(ctx, device); err != nil || !reported || report.Seen != 2 || report.Stopped != 2 { + t.Fatalf("fence = %+v, %v, %v", report, reported, err) + } + // A redelivery after the result is stored returns it and runs nothing. + if err := remote.Deliver(ctx, a); err != nil { + t.Fatal(err) + } + dispatcher.Wait() + if kind.runs.Load() != 1 { + t.Fatalf("a redelivered assignment ran again: %d", kind.runs.Load()) + } + if err := remote.Forget(ctx, held[0]); err != nil { + t.Fatal(err) + } + if held, err := remote.Results(ctx); err != nil || len(held) != 0 { + t.Fatalf("results after forget = %+v, %v", held, err) + } + // An invalid assignment is refused before anything runs. + bad := a + bad.Fence = 0 + if err := remote.Deliver(ctx, bad); err == nil { + t.Fatal("an invalid assignment was accepted") + } +} diff --git a/internal/site/siteapi/client.go b/internal/site/siteapi/client.go new file mode 100644 index 00000000..f9e3f53f --- /dev/null +++ b/internal/site/siteapi/client.go @@ -0,0 +1,98 @@ +package siteapi + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// Client is the coordinator's client for one site's API. It implements +// delivery.Site. +type Client struct { + Base *url.URL + Token func() (string, error) + HTTP *http.Client +} + +// NewClient parses the site's base URL. +func NewClient(base string, token func() (string, error), httpClient *http.Client) (*Client, error) { + parsed, err := url.Parse(strings.TrimRight(base, "/")) + if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { + return nil, errors.New("siteapi: the site URL must be http or https with a host") + } + if httpClient == nil { + httpClient = http.DefaultClient + } + return &Client{Base: parsed, Token: token, HTTP: httpClient}, nil +} + +func (c *Client) do(ctx context.Context, method, path string, body, into any) error { + var reader io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return err + } + reader = bytes.NewReader(data) + } + request, err := http.NewRequestWithContext(ctx, method, c.Base.String()+path, reader) + if err != nil { + return err + } + token, err := c.Token() + if err != nil { + return err + } + request.Header.Set("Authorization", "Bearer "+token) + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + response, err := c.HTTP.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode/100 != 2 { + return fmt.Errorf("siteapi: %s %s: %s", method, path, response.Status) + } + if into == nil { + return nil + } + decoder := json.NewDecoder(io.LimitReader(response.Body, 4<<20)) + decoder.DisallowUnknownFields() + return decoder.Decode(into) +} + +func (c *Client) Deliver(ctx context.Context, assignment site.Assignment) error { + return c.do(ctx, http.MethodPut, "/v1/assignments", assignment, nil) +} + +func (c *Client) Fence(ctx context.Context, device string) (custody.SiteFence, bool, error) { + namespace, name, ok := strings.Cut(device, "/") + if !ok { + return custody.SiteFence{}, false, errors.New("siteapi: a Device is namespace/name") + } + var report FenceReport + if err := c.do(ctx, http.MethodGet, "/v1/fences/"+url.PathEscape(namespace)+"/"+url.PathEscape(name), nil, &report); err != nil { + return custody.SiteFence{}, false, err + } + return custody.SiteFence{Seen: report.Seen, Stopped: report.Stopped}, true, nil +} + +func (c *Client) Results(ctx context.Context) ([]site.Stored, error) { + var held []site.Stored + return held, c.do(ctx, http.MethodGet, "/v1/results", nil, &held) +} + +func (c *Client) Forget(ctx context.Context, stored site.Stored) error { + return c.do(ctx, http.MethodDelete, "/v1/results", stored, nil) +} diff --git a/internal/site/siteapi/server.go b/internal/site/siteapi/server.go new file mode 100644 index 00000000..39393a30 --- /dev/null +++ b/internal/site/siteapi/server.go @@ -0,0 +1,174 @@ +// Package siteapi is a site's HTTP API for a coordinator that reaches it +// directly, as the simulator site does in the standalone smoke test and in +// synthetic staging. The coordinator delivers assignments and reads the +// site's fence reports and results. The site holds no credential that can +// change custody: it only answers. +package siteapi + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "strings" + "sync" + + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// Dispatcher runs each delivered assignment once at a time. A redelivery of +// an assignment that is running is ignored; one that finished returns its +// stored result through the runner. +type Dispatcher struct { + Runner *site.Runner + // Context ends every worker. A worker stopped this way stores no + // result, so the next site process resumes from the journal. + Context context.Context + Logger *slog.Logger + + mu sync.Mutex + running map[string]bool + wg sync.WaitGroup +} + +func key(assignment site.Assignment) string { + return assignment.Device + "/" + assignment.Key() +} + +func jsonInt(value int64) string { data, _ := json.Marshal(value); return string(data) } + +// Dispatch starts the assignment unless it runs already. +func (d *Dispatcher) Dispatch(assignment site.Assignment) error { + if err := assignment.Validate(); err != nil { + return err + } + d.mu.Lock() + defer d.mu.Unlock() + if d.running == nil { + d.running = map[string]bool{} + } + id := key(assignment) + if d.running[id] { + return nil + } + d.running[id] = true + d.wg.Add(1) + go func() { + defer d.wg.Done() + defer func() { + d.mu.Lock() + delete(d.running, id) + d.mu.Unlock() + }() + var err error + if assignment.Operation.Kind == "DeviceRecovery" { + // A recovery runs nothing: the site raises the fence and + // confirms the older worker stopped. + err = d.Runner.Fence(d.Context, assignment) + } else { + _, err = d.Runner.Run(d.Context, assignment) + } + if err != nil && !errors.Is(err, site.ErrAlreadyRunning) && d.Logger != nil { + d.Logger.Info("assignment stopped without a stored result", "device", assignment.Device, "operation", assignment.Operation.Name, "fence", assignment.Fence, "reason", err.Error()) + } + }() + return nil +} + +// Wait returns once every worker stopped. +func (d *Dispatcher) Wait() { d.wg.Wait() } + +// FenceReport is the site's fence report for one Device. +type FenceReport struct { + Seen int64 `json:"seen"` + Stopped int64 `json:"stopped"` +} + +// Handler serves the site API behind a bearer token. +func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, token func() (string, error)) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("PUT /v1/assignments", func(w http.ResponseWriter, r *http.Request) { + var assignment site.Assignment + if err := decode(r, &assignment); err != nil { + http.Error(w, "the assignment could not be decoded", http.StatusBadRequest) + return + } + if err := dispatcher.Dispatch(assignment); err != nil { + http.Error(w, "the assignment is invalid", http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusAccepted) + }) + mux.HandleFunc("GET /v1/fences/{namespace}/{name}", func(w http.ResponseWriter, r *http.Request) { + seen, stopped, err := store.Current(r.PathValue("namespace") + "/" + r.PathValue("name")) + if err != nil { + http.Error(w, "the fence is unreadable", http.StatusInternalServerError) + return + } + write(w, FenceReport{Seen: seen, Stopped: stopped}) + }) + mux.HandleFunc("GET /v1/results", func(w http.ResponseWriter, r *http.Request) { + held, err := results.Pending() + if err != nil { + http.Error(w, "the results are unreadable", http.StatusInternalServerError) + return + } + if held == nil { + held = []site.Stored{} + } + write(w, held) + }) + mux.HandleFunc("DELETE /v1/results", func(w http.ResponseWriter, r *http.Request) { + var stored site.Stored + if err := decode(r, &stored); err != nil || stored.Device == "" || stored.Result.Operation.Name == "" { + http.Error(w, "the result could not be decoded", http.StatusBadRequest) + return + } + if err := results.Forget(stored.Device, custody.SiteResult{Operation: stored.Result.Operation, Fence: stored.Result.Fence}); err != nil { + http.Error(w, "the result could not be deleted", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + return bearer(token, mux) +} + +func bearer(token func() (string, error), next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/readyz" { + next.ServeHTTP(w, r) + return + } + want, err := token() + got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if err != nil || want == "" || !ok || subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +const maxBody = 64 << 10 + +func decode(r *http.Request, into any) error { + decoder := json.NewDecoder(io.LimitReader(r.Body, maxBody)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(into); err != nil { + return err + } + if decoder.More() { + return errors.New("trailing data") + } + return nil +} + +func write(w http.ResponseWriter, value any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(value) +} diff --git a/internal/site/store.go b/internal/site/store.go index 4ae948ff..9cad0c07 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -201,6 +201,24 @@ func (s *Store) Current(device string) (fence, stopped int64, err error) { return fence, stopped, err } +// Peek reads a Device's fences without its lock, for readers on a read-only +// mount such as the boot server. Every write replaces the state file +// atomically, so a reader sees one complete state or none. +func (s *Store) Peek(device string) (fence, stopped int64, err error) { + data, err := os.ReadFile(filepath.Join(s.deviceDir(device), "state.json")) + if os.IsNotExist(err) { + return 0, 0, nil + } + if err != nil { + return 0, 0, err + } + var state deviceState + if err := json.Unmarshal(data, &state); err != nil || state.Device != device { + return 0, 0, errors.New("site: the Device's state is unreadable") + } + return state.Fence, state.Stopped, nil +} + // ConfirmStopped records that no worker below fence still runs for the // Device. It is refused if fence is no longer the stored fence. func (s *Store) ConfirmStopped(device string, fence int64) error { diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go new file mode 100644 index 00000000..7fa178f1 --- /dev/null +++ b/internal/site/vmwork/boot.go @@ -0,0 +1,254 @@ +package vmwork + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/site" +) + +// defaultBootOrigin is the provisioning bridge's address, used when the boot +// server shares the hypervisor's network namespace. +const defaultBootOrigin = "http://192.168.77.1:8080" + +func (c Config) origin() string { + if c.BootOrigin == "" { + return defaultBootOrigin + } + return c.BootOrigin +} + +// prepareNetwork is the only writer of the provisioning network. DHCP stays +// on a bridge in the runtime namespace; NAT forwarding lets the firmware +// reach a boot server outside it. +func (k Installation) prepareNetwork(ctx context.Context, work *site.Work, boot Boot) error { + if err := k.stopNetwork(ctx); err != nil { + return err + } + forward := "" + if k.origin() == defaultBootOrigin { + forward = "" + } + xml := fmt.Sprintf(`fleet-pxe%s`, forward, guestMAC, k.origin(), Key(work.Key()), boot.Token) + path := filepath.Join(k.directory(work.Device, work.Key()), "network-private.xml") + if err := os.WriteFile(path, []byte(xml), 0o600); err != nil { + return err + } + _, err := k.virsh(ctx, "net-create", path) + return err +} + +func (c Config) stopNetwork(ctx context.Context) error { + names, err := c.virsh(ctx, "net-list", "--name") + if err != nil { + return err + } + for _, name := range strings.Fields(names) { + if name == "fleet-pxe" { + _, err = c.virsh(ctx, "net-destroy", name) + return err + } + } + return nil +} + +// verifyNetworkBoot requires the boot server's completed deliveries and the +// firmware's DHCP lease. +func (k Installation) verifyNetworkBoot(ctx context.Context, work *site.Work) error { + data, err := os.ReadFile(filepath.Join(k.BootRoot, Key(work.Key()), "boot-delivery.log")) + if err != nil { + return err + } + completed := map[string]bool{} + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) != 4 || fields[1] != "write-complete" || !strings.HasPrefix(fields[3], "bytes=") { + continue + } + if n, err := strconv.Atoi(strings.TrimPrefix(fields[3], "bytes=")); err == nil && n > 0 { + completed[fields[2]] = true + } + } + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !completed[name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + leases, err := k.virsh(ctx, "net-dhcp-leases", "fleet-pxe") + if err != nil { + return err + } + if !strings.Contains(leases, guestMAC) || !strings.Contains(leases, "192.168.77.2") { + return fmt.Errorf("missing firmware DHCP lease") + } + return os.WriteFile(filepath.Join(k.directory(work.Device, work.Key()), "dhcp-leases.txt"), []byte(leases), 0o600) +} + +// admission returns the open admission under a boot key: open for the +// installer, unexpired, with the token, and at the Device's stored fence, so +// a superseded installation never boots the guest. +func admission(store *site.Store, key, token string, now time.Time) (Boot, bool) { + records, err := store.Records(bootRecords) + if err != nil { + return Boot{}, false + } + for _, record := range records { + var boot Boot + if record.Name != key || json.Unmarshal(record.Data, &boot) != nil || !boot.Open || boot.Closed || !now.Before(boot.Expires) || len(boot.Token) != 64 || subtle.ConstantTimeCompare([]byte(token), []byte(boot.Token)) != 1 { + continue + } + if fence, _, err := store.Peek(record.Device); err == nil && fence == boot.Fence { + return boot, true + } + } + return Boot{}, false +} + +// BootHandler serves an open admission's boot script and pinned artifacts. +// It never serves a caller-chosen path, and it records deliveries without +// URLs, headers or credentials. +func (c Config) BootHandler(store *site.Store) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(request.URL.Path, "/") + if request.Method != http.MethodGet || request.URL.RawQuery != "" || len(parts) != 4 { + deny() + return + } + boot, ok := admission(store, parts[1], parts[2], c.now()) + if !ok { + deny() + return + } + name := parts[3] + var data []byte + var artifact *os.File + var size int64 + 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)) + size = int64(len(data)) + case "kernel", "installer.gz": + // Hash the pinned artifact, then serve the same open file. + var err error + if artifact, err = os.Open(filepath.Join(c.Artifacts, name)); err != nil { + deny() + return + } + defer artifact.Close() + manifest, manifestErr := os.ReadFile(filepath.Join(c.Artifacts, "SHA256SUMS")) + sum := sha256.Sum256(manifest) + hash := sha256.New() + size, err = io.Copy(hash, artifact) + if manifestErr != nil || err != nil || c.Image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(hash.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + default: + deny() + return + } + dir := filepath.Join(c.BootRoot, parts[1]) + if err := appendEvidence(dir, fmt.Sprintf("%s admitted %s bytes=%d\n", c.now().Format(time.RFC3339), name, size)); err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var written int64 + var err error + if artifact != nil { + written, err = io.Copy(w, artifact) + } else { + var n int + n, err = w.Write(data) + written = int64(n) + } + // A completed write is not proof that the client received it. + if err == nil && written == size { + _ = appendEvidence(dir, fmt.Sprintf("%s write-complete %s bytes=%d\n", c.now().Format(time.RFC3339), name, written)) + } + }) +} + +func appendEvidence(dir, line string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + file, err := os.OpenFile(filepath.Join(dir, "boot-delivery.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + return err + } + _, err = file.WriteString(line) + if err == nil { + err = file.Sync() + } + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return syncDir(dir) +} + +// ServeBoot serves the boot handler. The write bound matches the boot +// window: emulated firmware takes minutes to fetch the installer. +func (c Config) ServeBoot(store *site.Store) error { + server := &http.Server{Addr: ":8080", Handler: c.BootHandler(store), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: c.window(), IdleTimeout: 5 * time.Second} + return server.ListenAndServe() +} + +// CheckClosedBoot probes a live boot server with every installation's +// closed admission, and with unknown names, and requires each to be denied. +// It prints no capability URL. +func (c Config) CheckClosedBoot(store *site.Store, origin string) (string, error) { + records, err := store.Records(bootRecords) + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + for _, record := range records { + var boot Boot + if err := json.Unmarshal(record.Data, &boot); err != nil { + return "", err + } + if !boot.Closed { + return "", fmt.Errorf("a boot admission is not closed") + } + base := origin + "/" + record.Name + "/" + boot.Token + for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { + response, err := client.Get(url) + if err != nil { + return "", fmt.Errorf("the boot denial probe is unavailable") + } + response.Body.Close() + if response.StatusCode != http.StatusForbidden { + return "", fmt.Errorf("a closed or unknown boot was served") + } + count++ + } + } + if count == 0 { + return "", fmt.Errorf("no boot admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed admissions' scripts and artifacts, an unsupported artifact, an unguarded artifact, an unknown identity", count), nil +} diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go new file mode 100644 index 00000000..7b2a4ede --- /dev/null +++ b/internal/site/vmwork/kinds.go @@ -0,0 +1,477 @@ +// Package vmwork is the local VM site's install and wipe workers. A libvirt +// domain stands in for a server: its disk, a one-time network boot from the +// site's boot server, and console receipts that prove which phase ran. Every +// effect goes through the site framework's fenced journal, so a newer fence +// stops a worker and a resumed worker continues from the journal. The site +// reaches its Devices through fixture.Access. It is a disposable acceptance +// executor, never a production one. +package vmwork + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "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" +) + +// DefaultBootWindow bounds one-time network boot admission. +const DefaultBootWindow = 10 * time.Minute + +// guestMAC is the provisioning NIC of the one local guest. +const guestMAC = "52:54:00:77:00:02" + +// Config is one local VM site. +type Config struct { + // Artifacts holds the installer kernel, initrd and their SHA256SUMS. + Artifacts string + // Image is the only image the site installs: the artifact manifest's + // identity, "fleet-local-linux@sha256:". + Image string + // Disks holds each installation's disk and console logs. + Disks string + // BootRoot holds the boot server's delivery evidence. + BootRoot string + // BootOrigin is the boot server's URL in the DHCP boot filename. Empty + // means the boot server shares the bridge. + BootOrigin string + // PXE boots the installer from the network; otherwise directly. + PXE bool + // Accelerator is kvm or tcg. + Accelerator string + URI string + BootWindow time.Duration + // Command runs libvirt's virsh. Tests replace it. + Command func(ctx context.Context, name string, args ...string) (string, error) + Now func() time.Time +} + +func (c Config) now() time.Time { + if c.Now != nil { + return c.Now().UTC() + } + return time.Now().UTC() +} + +func (c Config) window() time.Duration { + if c.BootWindow > 0 { + return c.BootWindow + } + return DefaultBootWindow +} + +func (c Config) virsh(ctx context.Context, args ...string) (string, error) { + run := c.Command + if run == nil { + run = func(ctx context.Context, name string, args ...string) (string, error) { + out, err := exec.CommandContext(ctx, name, args...).CombinedOutput() + if err != nil { + return "", fmt.Errorf("%s %s failed", name, args[0]) + } + return string(out), nil + } + } + if c.URI != "" { + args = append([]string{"-c", c.URI}, args...) + } + return run(ctx, "virsh", args...) +} + +// Key is an operation's 16-character key in boot URLs and directories. +func Key(operationUID string) string { + sum := sha256.Sum256([]byte(operationUID)) + return hex.EncodeToString(sum[:])[:16] +} + +func deviceKey(device string) string { + sum := sha256.Sum256([]byte(device)) + return hex.EncodeToString(sum[:])[:16] +} + +// directory is one installation's disk and console directory, under its +// Device so a wipe finds every disk of that Device. +func (c Config) directory(device, operationUID string) string { + return filepath.Join(c.Disks, deviceKey(device), Key(operationUID)) +} + +func domain(operationUID string) string { return "fleet-local-" + Key(operationUID) } + +// Installation is the local VM's DeviceInstallation worker. +type Installation struct{ Config } + +// Wipe is the local VM's DeviceWipe worker. +type Wipe struct{ Config } + +var ( + _ site.Kind = Installation{} + _ site.Kind = Wipe{} +) + +func enrolled(work *site.Work, disks []string) *custody.Refusal { + connection, _ := work.Connection.(*fixture.Connection) + if connection == nil { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site does not run local VMs"} + } + if len(disks) != 1 || len(connection.Target.Disks) != 1 || disks[0] != connection.Target.Disks[0] { + return &custody.Refusal{Reason: custody.ReasonTargetDisks, Message: "the site enrolls exactly one disk per Device"} + } + return nil +} + +func (k Installation) spec(work *site.Work) (ops.DeviceInstallationSpec, *custody.Refusal) { + var spec ops.DeviceInstallationSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceInstallation spec"} + } + return spec, nil +} + +func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { + spec, refusal := k.spec(work) + if refusal != nil { + return refusal + } + if spec.Bootstrap != nil { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} + } + if spec.Image.Name+"@"+spec.Image.Digest != k.Image { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site installs only its verified local image"} + } + return enrolled(work, spec.TargetDisks) +} + +// Boot is one installation's network boot admission. The boot server serves +// it only while it is open for the installer phase, unexpired, and at the +// Device's stored fence. +type Boot struct { + Operation string `json:"operation"` + Fence int64 `json:"fence"` + Receipt string `json:"receipt"` + Token string `json:"token"` + Expires time.Time `json:"expires"` + Open bool `json:"open,omitempty"` + Closed bool `json:"closed,omitempty"` +} + +const bootRecords = "vmboot" + +// boot reads the installation's boot admission, creating it once. The +// receipt is fixed before any boot, so a replay waits for the same receipt. +func (k Installation) boot(work *site.Work) (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())} + return boot, k.save(work, boot) +} + +func (k Installation) save(work *site.Work, boot Boot) error { + return work.Store().PutRecord(work.Device, work.Fence, bootRecords, Key(work.Key()), boot) +} + +func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { + if _, refusal := k.spec(work); refusal != nil { + return nil, refusal + } + boot, err := k.boot(work) + if err != nil { + return nil, err + } + dir := k.directory(work.Device, work.Key()) + var evidence ops.InstallationEvidence + record := func(step string) { + at, _ := work.JournaledAt(step) + evidence.Steps = append(evidence.Steps, ops.StepEvidence{Name: step, CompletedAt: metav1.NewTime(at.UTC())}) + } + disk := filepath.Join(dir, "disk.raw") + if err := work.Step(ctx, site.Step{ + Name: "prepare-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 nil, err + } + record("prepare-disk") + for _, stage := range []string{"installer", "disk"} { + if work.Journaled(stage + "-verified") { + record(stage) + continue + } + started := work.Journaled(stage + "-start") + if stage == "installer" && k.PXE && !started { + if boot.Closed || !k.now().Before(boot.Expires) { + return nil, errors.New("the boot admission expired or closed before the network boot") + } + if err := work.Step(ctx, site.Step{Name: "installer-network", Send: func(ctx context.Context) error { return k.prepareNetwork(ctx, work, boot) }, Idempotent: true}); err != nil { + return nil, err + } + boot.Open = true + if err := k.save(work, boot); err != nil { + return nil, err + } + } + if stage == "disk" && k.PXE { + if err := work.Step(ctx, site.Step{Name: "disk-network-off", Send: k.stopNetwork, Idempotent: true}); err != nil { + return nil, err + } + } + xml := k.domainXML(work, boot, stage) + if err := os.WriteFile(filepath.Join(dir, stage+".xml"), []byte(xml), 0o600); err != nil { + return nil, err + } + // A failed network boot closes its admission at once, so the boot + // server stops serving the installer. A worker stopped from outside + // leaves it open for its replacement to resume. + fail := func(err error) error { + if stage == "installer" && k.PXE && boot.Open && ctx.Err() == nil { + boot.Open, boot.Closed = false, true + _ = k.save(work, boot) + } + return err + } + // A boot is started once. After a crash it is observed: a running + // domain or this phase's console counts as started, and no sign of + // either leaves the outcome unknown rather than booting again. + if err := work.Step(ctx, site.Step{ + Name: stage + "-start", + Send: func(ctx context.Context) error { + _, err := k.virsh(ctx, "create", filepath.Join(dir, stage+".xml")) + return err + }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { + running, err := k.running(ctx, work.Key()) + if err != nil || running { + return running, err + } + _, err = os.Stat(filepath.Join(dir, stage+".log")) + return err == nil, nil + }, + }); err != nil { + return nil, fail(err) + } + if err := k.waitReceipt(ctx, work, boot, stage); err != nil { + return nil, fail(err) + } + if stage == "installer" && k.PXE { + if err := k.verifyNetworkBoot(ctx, work); err != nil { + return nil, fail(err) + } + boot.Open, boot.Closed = false, true + if err := k.save(work, boot); err != nil { + return nil, err + } + } + if err := work.Step(ctx, site.Step{Name: stage + "-verified", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { + return nil, err + } + record(stage) + } + return evidence, nil +} + +// createDisk creates the installation's disk exclusively, so an +// interrupted preparation never overwrites one. +func createDisk(dir, disk string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + file, err := os.OpenFile(disk, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600) + if err != nil { + return err + } + err = file.Truncate(2 << 30) + if err == nil { + err = file.Sync() + } + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return syncDir(dir) +} + +func syncDir(path string) error { + dir, err := os.Open(path) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + +func (k Installation) running(ctx context.Context, operationUID string) (bool, error) { + names, err := k.virsh(ctx, "list", "--all", "--name") + if err != nil { + return false, err + } + for _, name := range strings.Fields(names) { + if name == domain(operationUID) { + return true, nil + } + } + return false, nil +} + +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 k.PXE { + bootXML = "" + nic = "" + } + } + domainType := "kvm" + if k.Accelerator == "tcg" { + domainType = "qemu" + } + return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(work.Key()), bootXML, nic, dir, dir, stage) +} + +// 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:" + if stage == "disk" { + marker = "FLEET-DISK-BOOT:" + } + log := filepath.Join(k.directory(work.Device, work.Key()), stage+".log") + for { + running, err := k.running(ctx, work.Key()) + if err != nil { + return err + } + if !running { + data, err := os.ReadFile(log) + if err != nil { + return err + } + count := 0 + for _, line := range strings.Split(string(data), "\n") { + if strings.TrimSpace(line) == marker+boot.Receipt { + count++ + } + } + if count != 1 { + return errors.New("the guest stopped without exactly one boot receipt") + } + file, err := os.OpenFile(log, os.O_RDWR, 0) + if err != nil { + return err + } + err = file.Sync() + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return syncDir(filepath.Dir(log)) + } + select { + case <-ctx.Done(): + return context.Cause(ctx) + case <-time.After(time.Second): + } + } +} + +func (k Installation) wipeSpec(work *site.Work) (ops.DeviceWipeSpec, *custody.Refusal) { + var spec ops.DeviceWipeSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.CleaningPolicyDigest == "" { + return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceWipe spec"} + } + return spec, nil +} + +func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { + spec, refusal := Installation(k).wipeSpec(work) + if refusal != nil { + return refusal + } + return enrolled(work, spec.TargetDisks) +} + +// Run deletes every installation disk of the Device. A disk whose domain +// still runs stays, and the wipe's outcome is unknown. +func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := Installation(k).wipeSpec(work) + if refusal != nil { + return nil, refusal + } + root := filepath.Join(k.Disks, deviceKey(work.Device)) + remaining := func() ([]string, error) { + paths, err := filepath.Glob(filepath.Join(root, "*", "disk.raw")) + return paths, err + } + step := site.Step{ + Name: "wipe", + Send: func(ctx context.Context) error { + names, err := k.virsh(ctx, "list", "--all", "--name") + if err != nil { + return err + } + for _, name := range strings.Fields(names) { + if strings.HasPrefix(name, "fleet-local-") { + return errors.New("a local domain still runs; the wipe cannot prove the disks are unused") + } + } + paths, err := remaining() + if err != nil { + return err + } + for _, path := range paths { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + if err := syncDir(filepath.Dir(path)); err != nil { + return err + } + } + return nil + }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + paths, err := remaining() + return err == nil && len(paths) == 0, err + }, + // Deleting a deleted disk changes nothing. + Idempotent: true, + } + if err := work.Step(ctx, step); err != nil { + return nil, err + } + if paths, err := remaining(); err != nil || len(paths) != 0 { + return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "a disk remained after the wipe"} + } + at, _ := work.JournaledAt(step.Name) + return ops.WipeEvidence{Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: spec.TargetDisks, PolicyDigest: spec.CleaningPolicyDigest}, nil +} diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go new file mode 100644 index 00000000..ce683991 --- /dev/null +++ b/internal/site/vmwork/kinds_test.go @@ -0,0 +1,279 @@ +package vmwork + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + 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" +) + +const ( + device = "fleet-provider/server-example-001" + image = "fleet-local-linux@sha256:" + "abababababababababababababababababababababababababababababababab" + key = "1111111111111111111111111111111111111111111111111111111111111111" +) + +// hypervisor is a fake virsh: a created domain runs until the test lets it +// print its receipt and stop. +type hypervisor struct { + mu sync.Mutex + running map[string]string // domain -> console log + creates int + // hold keeps created domains running. + hold bool + // noReceipt makes the guest print no receipt. + noReceipt bool +} + +var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) + +func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, error) { + h.mu.Lock() + defer h.mu.Unlock() + switch args[0] { + case "create": + h.creates++ + data, err := os.ReadFile(args[1]) + if err != nil { + return "", err + } + xml := string(data) + name := regexp.MustCompile(`([^<]+)`).FindStringSubmatch(xml)[1] + log := regexp.MustCompile(``).FindStringSubmatch(xml)[1] + marker := "FLEET-DISK-BOOT:" + receipt := "" + if match := receiptArg.FindStringSubmatch(xml); match != nil { + marker, receipt = "FLEET-INSTALLED:", match[1] + } else { + // The disk boot prints the receipt the installer wrote. + installed, _ := os.ReadFile(filepath.Join(filepath.Dir(log), "installer.log")) + if match := regexp.MustCompile(`FLEET-INSTALLED:([0-9a-f]{64})`).FindStringSubmatch(string(installed)); match != nil { + receipt = match[1] + } + } + console := "booting\n" + marker + receipt + "\n" + if h.noReceipt { + console = "booting\n" + } + if err := os.WriteFile(log, []byte(console), 0o600); err != nil { + return "", err + } + h.running[name] = log + if !h.hold { + delete(h.running, name) + } + case "list": + var names []string + for name := range h.running { + names = append(names, name) + } + return strings.Join(names, "\n"), nil + } + return "", nil +} + +type rig struct { + t *testing.T + store *site.Store + runner *site.Runner + config Config + vm *hypervisor +} + +func newRig(t *testing.T) *rig { + root := t.TempDir() + for _, dir := range []string{"store", "disks", "boot", "artifacts"} { + if err := os.Mkdir(filepath.Join(root, dir), 0o700); err != nil { + t.Fatal(err) + } + } + store, err := site.OpenStore(filepath.Join(root, "store"), nil) + if err != nil { + t.Fatal(err) + } + vm := &hypervisor{running: map[string]string{}} + config := Config{Artifacts: filepath.Join(root, "artifacts"), Image: image, Disks: filepath.Join(root, "disks"), BootRoot: filepath.Join(root, "boot"), Command: vm.run} + enrollment := fixture.Enrollment{device: {BMCEndpoint: "https://[2001:db8::1]", SystemUUID: "00000000-0000-4000-8000-000000000001", BootMACAddress: "02:00:00:00:00:01", BMCPublicKeySHA256: key, Disks: []string{"disk-0"}}} + runner := &site.Runner{Site: "site-example-a", Store: store, Results: site.NewResults(store), Access: fixture.Access{Enrollment: enrollment}, + Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}, "DeviceWipe": Wipe{config}}, Poll: 10 * time.Millisecond} + return &rig{t: t, store: store, runner: runner, config: config, vm: vm} +} + +func (r *rig) assignment(kind, uid string, fence int64, spec any) site.Assignment { + inputs, _ := json.Marshal(spec) + digest, _ := custody.SpecDigest(spec) + now := time.Now().UTC() + return site.Assignment{Device: device, Operation: ops.OperationReference{Kind: kind, Name: "op-" + uid[len(uid)-3:]}, Fence: fence, AdmittedAt: now, Deadline: now.Add(30 * time.Second), + Snapshot: ops.DeviceSnapshot{BMCEndpoint: "https://[2001:db8::1]", SystemUUID: "00000000-0000-4000-8000-000000000001", BootMACAddress: "02:00:00:00:00:01", BMCPublicKeySHA256: key}, InputDigest: digest, Inputs: inputs} +} + +func envelope() ops.OperationEnvelope { + return ops.OperationEnvelope{Creator: ops.Creator{Username: "provider", UID: "u"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}} +} + +func installSpec() ops.DeviceInstallationSpec { + name, digest, _ := strings.Cut(image, "@") + return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} +} + +func wipeSpec() ops.DeviceWipeSpec { + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}} +} + +// TestInstallThenWipe installs directly, proves each phase by its receipt, +// and wipes every disk of the Device. +func TestInstallThenWipe(t *testing.T) { + r := newRig(t) + result, err := r.runner.Run(context.Background(), r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000201", 2, installSpec())) + if err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("install = %+v, %v", result, err) + } + var evidence ops.InstallationEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil || len(evidence.Steps) != 3 { + t.Fatalf("evidence = %s, %v", result.Evidence, err) + } + if r.vm.creates != 2 { + t.Fatalf("boots = %d, want the installer and the disk once each", r.vm.creates) + } + disks, _ := filepath.Glob(filepath.Join(r.config.Disks, "*", "*", "disk.raw")) + if len(disks) != 1 { + t.Fatalf("disks = %v", disks) + } + // A redelivery returns the stored result and boots nothing. + if again, err := r.runner.Run(context.Background(), r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000201", 2, installSpec())); err != nil || again.Phase != ops.PhaseSucceeded || r.vm.creates != 2 { + t.Fatalf("redelivery = %+v, %v, boots %d", again, err, r.vm.creates) + } + wiped, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000202", 3, wipeSpec())) + if err != nil || wiped.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe = %+v, %v", wiped, err) + } + if disks, _ := filepath.Glob(filepath.Join(r.config.Disks, "*", "*", "disk.raw")); len(disks) != 0 { + t.Fatalf("disks after the wipe = %v", disks) + } +} + +// TestAWipeWithARunningDomainIsNotProven keeps a disk in use from counting +// as wiped. +func TestAWipeWithARunningDomainIsNotProven(t *testing.T) { + r := newRig(t) + r.vm.running["fleet-local-0000000000000000"] = "console" + result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000203", 2, wipeSpec())) + if err != nil || result.Phase == ops.PhaseSucceeded { + t.Fatalf("wipe with a running domain = %+v, %v", result, err) + } +} + +// TestAResumedBootIsObservedNotRepeated crashes a worker after it started +// the installer; the next worker sees the domain and never boots it again. +func TestAResumedBootIsObservedNotRepeated(t *testing.T) { + r := newRig(t) + r.vm.hold = true + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000204", 2, installSpec()) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = r.runner.Run(ctx, assignment) + }() + deadline := time.Now().Add(5 * time.Second) + for { + r.vm.mu.Lock() + creates := r.vm.creates + r.vm.mu.Unlock() + if creates == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("the installer never started") + } + time.Sleep(10 * time.Millisecond) + } + cancel() + <-done + // The guest finishes while no worker runs. + r.vm.mu.Lock() + r.vm.hold = false + for name := range r.vm.running { + delete(r.vm.running, name) + } + r.vm.mu.Unlock() + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("resumed install = %+v, %v", result, err) + } + if r.vm.creates != 2 { + t.Fatalf("boots = %d, want the installer once and the disk once", r.vm.creates) + } +} + +// TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence denies a +// closed admission, a wrong token and a superseded fence. +func TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence(t *testing.T) { + r := newRig(t) + if err := r.store.Raise(device, 4); err != nil { + t.Fatal(err) + } + token := strings.Repeat("c", 64) + boot := Boot{Operation: "00000000-0000-4000-8000-000000000205", Fence: 4, Receipt: strings.Repeat("d", 64), Token: token, Expires: time.Now().Add(time.Minute), Open: true} + if err := r.store.PutRecord(device, 4, bootRecords, Key(boot.Operation), boot); err != nil { + t.Fatal(err) + } + server := httptest.NewServer(r.config.BootHandler(r.store)) + defer server.Close() + get := func(path string) int { + response, err := http.Get(server.URL + path) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + return response.StatusCode + } + script := "/" + Key(boot.Operation) + "/" + token + "/boot.ipxe" + if code := get(script); code != http.StatusOK { + t.Fatalf("open admission = %d", code) + } + if code := get("/" + Key(boot.Operation) + "/" + strings.Repeat("e", 64) + "/boot.ipxe"); code != http.StatusForbidden { + t.Fatalf("wrong token = %d", code) + } + if code := get("/" + Key(boot.Operation) + "/" + token + "/disk.raw"); code != http.StatusForbidden { + t.Fatalf("unsupported artifact = %d", code) + } + // A newer operation's fence closes this admission at once. + if err := r.store.Raise(device, 5); err != nil { + t.Fatal(err) + } + if code := get(script); code != http.StatusForbidden { + t.Fatalf("superseded admission = %d", code) + } +} + +// TestAFailedNetworkBootClosesItsAdmission stops serving the installer as +// soon as a network-boot installation fails. +func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { + r := newRig(t) + r.config.PXE = true + r.runner.Kinds["DeviceInstallation"] = Installation{r.config} + // The guest prints no receipt, so the installer phase fails. + r.vm.noReceipt = true + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000206", 2, installSpec()) + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase == ops.PhaseSucceeded { + t.Fatalf("install without a receipt = %+v, %v", result, err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Open || !boot.Closed { + t.Fatalf("admission after the failure = %+v, %v, %v", boot, found, err) + } +} diff --git a/internal/staging/handler.go b/internal/staging/handler.go index 17677062..82685548 100644 --- a/internal/staging/handler.go +++ b/internal/staging/handler.go @@ -6,8 +6,6 @@ package staging import ( "context" - "crypto/sha256" - "encoding/hex" "errors" "fmt" "reflect" @@ -21,9 +19,11 @@ import ( "k8s.io/client-go/util/retry" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/allocation" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/tenancy" ) // Handler is an event-driven synthetic provider and claim coordinator. It uses @@ -31,9 +31,10 @@ import ( // decision and provider observation. It accepts only powered-off, networkless // claims in one configured location. type Handler struct { - Public client.Client - Provider client.Client - Coordinator *controller.Coordinator + Public client.Client + Provider client.Client + // Allocator allocates and releases in the provider project, on custody. + Allocator *allocation.Allocator Project controller.ProjectIdentity ProviderProject controller.ProjectIdentity Location string @@ -41,7 +42,7 @@ type Handler struct { } func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequest) manager.Outcome { - if h.Public == nil || h.Coordinator == nil || !h.Project.Valid() || h.Location == "" || !request.Valid() || !request.SameProject(h.Project.AuthorityID, h.Project.UID) { + if h.Public == nil || h.Allocator == nil || !h.Project.Valid() || h.Location == "" || !request.Valid() || !request.SameProject(h.Project.AuthorityID, h.Project.UID) { return manager.Outcome{RetryError: manager.ErrEventWiringUnavailable} } crossProject := h.Provider != nil || h.ProviderProject.Valid() @@ -82,11 +83,17 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ sourceClass, sourceProfile := &class, &profile machineClient := h.Public if crossProject { - if class.Spec.Source == nil || class.Spec.Source.Project != h.ProviderProject.RouteName || !sourceResolved(&class) || !profilePublished(&profile) || !publishedFor(&class, h.ProviderProject) || !publishedFor(&profile, h.ProviderProject) { + if class.Spec.Source == nil || !sourceResolved(&class) || !profilePublished(&profile) || !publishedFor(&class, h.ProviderProject) || !publishedFor(&profile, h.ProviderProject) { return h.rejected(ctx, &claim, "UnresolvedPublication", "Synthetic cross-project allocation requires a publisher-owned class and profile with a current resolved source.") } + // The class's publisher must be the provider incarnation that + // published it. + publisher, err := tenancy.Incarnation(ctx, tenancy.Fixed(manager.ProjectConsumer(h.ProviderProject, h.Provider)), class.Spec.Source.PublisherRef, h.ProviderProject.UID) + if err != nil { + return h.rejected(ctx, &claim, "UnresolvedPublication", "The class's publisher is not the configured provider project.") + } sourceClass = &fleetv1.MachineClass{} - if err := h.Provider.Get(ctx, client.ObjectKey{Name: class.Spec.Source.Name}, sourceClass); err != nil { + if err := publisher.Client.Get(ctx, client.ObjectKey{Name: class.Spec.Source.Name}, sourceClass); err != nil { return h.dependency(ctx, &claim, "SourceMachineClassPending", err) } sourceProfile = &fleetv1.MachineProfile{} @@ -94,7 +101,7 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ if sourceProfileName == "" { return h.rejected(ctx, &claim, "UnresolvedPublication", "Published MachineProfile provenance is incomplete.") } - if err := h.Provider.Get(ctx, client.ObjectKey{Name: sourceProfileName}, sourceProfile); err != nil { + if err := publisher.Client.Get(ctx, client.ObjectKey{Name: sourceProfileName}, sourceProfile); err != nil { return h.dependency(ctx, &claim, "SourceMachineProfilePending", err) } revision, revisionErr := publicationRevision(sourceClass, h.ProviderProject) @@ -102,7 +109,7 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ if revisionErr != nil || class.Status.EvaluatedRevision != revision || !reflect.DeepEqual(class.Status.ResolvedClass, resolved) || class.Annotations[publicationSourceUIDAnnotation] != string(sourceClass.UID) || profile.Annotations[publicationSourceUIDAnnotation] != string(sourceProfile.UID) || !reflect.DeepEqual(profile.Spec, sourceProfile.Spec) || !profileAllowed(sourceClass.Spec.ProfilePolicy, sourceProfile.Name) { return h.rejected(ctx, &claim, "PublicationDrift", "Published inputs no longer match the exact provider source lifetimes.") } - machineClient = h.Provider + machineClient = publisher.Client } else if class.Spec.Source != nil { return h.rejected(ctx, &claim, "UnsupportedMachineClass", "Synthetic same-project staging requires a local capacity definition.") } @@ -134,48 +141,29 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ machines = append(machines, *machine) evidence[machine.UID] = now } - admission := controller.AdmissionAuthority{PrincipalUID: "synthetic-staging:" + string(h.Project.UID), DecisionID: "synthetic-staging:" + string(claim.UID)} - if crossProject { - if err := h.Coordinator.EnsureClaimCustody(ctx, &claim, namespace.UID, admission, h.Project); err != nil { - return h.lifecycleError(ctx, &claim, err) - } - authority, hold := syntheticCrossProjectAuthority(claim.UID, claim.Namespace, h.Project, h.ProviderProject) - if err := h.Coordinator.RetainClaimAuthority(ctx, claim.UID, h.Project, h.ProviderProject, authority); err != nil { - return h.lifecycleError(ctx, &claim, err) - } - if err := h.Coordinator.RetainAllocationAuthority(ctx, claim.UID, h.Project, h.ProviderProject, authority, hold); err != nil { - return h.lifecycleError(ctx, &claim, err) - } - } else if err := h.Coordinator.EnsureClaimCustody(ctx, &claim, namespace.UID, admission); err != nil { - return h.lifecycleError(ctx, &claim, err) - } - if !contains(claim.Finalizers, controller.MachineFinalizer) { + if !contains(claim.Finalizers, allocation.MachineFinalizer) { updated := claim.DeepCopyObject().(*fleetv1.Machine) - updated.Finalizers = append(updated.Finalizers, controller.MachineFinalizer) + updated.Finalizers = append(updated.Finalizers, allocation.MachineFinalizer) if err := h.Public.Update(ctx, updated); err != nil { return manager.Outcome{RetryError: err} } return manager.Outcome{} } - allocation := controller.AllocationRequest{ - Claim: &claim, Class: sourceClass, Profile: sourceProfile, MachineCapacities: machines, - EvidenceObservedAt: evidence, NamespaceUID: namespace.UID, Admission: admission, - LocalClassName: class.Name, LocalClassUID: class.UID, - LocalProfileName: profile.Name, LocalProfileUID: profile.UID, - } - if crossProject { - allocation.ConsumerProject, allocation.ProviderProject = h.Project, h.ProviderProject - allocation.Authority, allocation.ExternalHold = syntheticCrossProjectAuthority(claim.UID, claim.Namespace, h.Project, h.ProviderProject) - } - record, err := h.Coordinator.Allocate(ctx, allocation) - if errors.Is(err, controller.ErrInsufficientCapacity) { + record, err := h.Allocator.Allocate(ctx, allocation.Request{ + Machine: h.machine(&claim), Class: sourceClass, Profile: sourceProfile, + Authority: fleetv1.AllocationAuthority{Principal: "synthetic-staging:" + h.Project.RouteName, Decision: "synthetic-staging:" + claim.Namespace + "/" + claim.Name}, + }) + if errors.Is(err, allocation.ErrInsufficientCapacity) { return h.pending(ctx, &claim, "InsufficientCapacity", "No matching synthetic machine is currently available.", nil) } + if errors.Is(err, allocation.ErrCustodyLost) { + return h.pending(ctx, &claim, "CustodyLost", "Device custody no longer names this Machine's allocation; an operator must resolve it.", nil) + } if err != nil { - return h.lifecycleError(ctx, &claim, err) + return manager.Outcome{RetryError: err} } for i := range list.Items { - if list.Items[i].UID == record.MachineUID { + 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} } @@ -188,11 +176,10 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ status := fleetv1.MachineStatus{ Phase: "Ready", Placement: &fleetv1.Placement{LocationRef: fleetv1.LocalReference{Name: h.Location}}, AcceptedProfileRef: &fleetv1.LocalReference{Name: profile.Name}, - AllocatedHardware: &fleetv1.AllocatedHardwareStatus{ObservedAt: &observed, Hardware: record.Hardware}, - Power: &fleetv1.PowerStatus{State: "Off"}, + AllocatedHardware: &fleetv1.AllocatedHardwareStatus{ObservedAt: &observed, Hardware: record.Spec.Hardware}, Conditions: []metav1.Condition{ condition("Accepted", metav1.ConditionTrue, claim.Generation, admissionReason(crossProject), admissionMessage(crossProject)), - condition("Bound", metav1.ConditionTrue, claim.Generation, "ExclusiveBinding", "Private custody contains the exclusive binding."), + condition("Bound", metav1.ConditionTrue, claim.Generation, "MachineAllocationActive", "Device custody names this Machine's allocation."), condition("NetworkReady", metav1.ConditionTrue, claim.Generation, "NoAttachmentsRequired", "No network interfaces were requested."), condition("Ready", metav1.ConditionTrue, claim.Generation, "PoweredOffHandoff", "The synthetic powered-off handoff is ready."), }, @@ -208,18 +195,11 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ return manager.Outcome{} } -// lifecycleError reports a private record of this Machine that cannot be -// decoded as not bound and not ready, without retrying: retrying cannot make -// the record readable. Every other error is retried. -func (h Handler) lifecycleError(ctx context.Context, claim *fleetv1.Machine, err error) manager.Outcome { - if errors.Is(err, controller.ErrRecordUnreadable) { - return h.pending(ctx, claim, controller.ReasonUnreadablePrivateRecord, unreadableRecordMessage, nil) - } - return manager.Outcome{RetryError: err} +// machine is the claim's exact identity in its consumer project. +func (h Handler) machine(claim *fleetv1.Machine) allocation.Machine { + return allocation.MachineOf(manager.ProjectConsumer(h.Project, h.Public), claim) } -const unreadableRecordMessage = "A private lifecycle record for this Machine cannot be decoded. Fleet will not allocate, install, or release through it; an operator must remove the record." - func (h Handler) dependency(ctx context.Context, claim *fleetv1.Machine, reason string, err error) manager.Outcome { if apierrors.IsNotFound(err) { return h.pending(ctx, claim, reason, err.Error(), nil) @@ -260,57 +240,44 @@ func (h Handler) rejected(ctx context.Context, claim *fleetv1.Machine, reason, m return manager.Outcome{} } +// errReleasing means the release has not finished; the event is retried. +var errReleasing = errors.New("synthetic release is in progress") + func (h Handler) release(ctx context.Context, namespace string, uid types.UID, claim *fleetv1.Machine) manager.Outcome { - crossProject := h.Provider != nil && h.ProviderProject.Valid() && !h.ProviderProject.SameLifetime(h.Project) - var result controller.ReleaseResult - var err error - if crossProject { - result, err = h.Coordinator.ReleaseScoped(ctx, h.Project, uid) - } else { - result, err = h.Coordinator.Release(ctx, uid) + if claim == nil || !contains(claim.Finalizers, allocation.MachineFinalizer) { + // A claim that never reached allocation needs no release. + return manager.Outcome{} } + machine := h.machine(claim) + current, err := h.Allocator.Get(ctx, machine) if err != nil { - // A claim that never reached custody needs no synthetic cleanup. - if errors.Is(err, controller.ErrRecordInvalid) && (claim == nil || !contains(claim.Finalizers, controller.MachineFinalizer)) { - return manager.Outcome{} - } - // The finalizer stays until an operator removes the record; see - // docs/development/README.md. - if errors.Is(err, controller.ErrRecordUnreadable) { - return h.pending(ctx, claim, controller.ReasonUnreadablePrivateRecord, unreadableRecordMessage, nil) - } return manager.Outcome{RetryError: err} } - if crossProject && result.ExternalSettlementRequired { - authority, hold := syntheticCrossProjectAuthority(uid, namespace, h.Project, h.ProviderProject) - result, err = h.Coordinator.CompleteExternalRelease(ctx, uid, authority, hold, h.Project) - if err != nil { - return manager.Outcome{RetryError: err} - } + // Release also covers a Machine deleted before its allocation existed, + // which may hold a quota claim. + released, err := h.Allocator.ReleaseMachine(ctx, machine) + if err != nil { + return manager.Outcome{RetryError: err} } - if !result.SafeToRemoveFinalizer { - return manager.Outcome{RetryError: fmt.Errorf("synthetic cleanup is not settled")} + if !released { + return manager.Outcome{RetryError: errReleasing} } - if claim != nil && contains(claim.Finalizers, controller.MachineFinalizer) { - if err := h.removeFinalizer(ctx, client.ObjectKeyFromObject(claim), uid); err != nil { - return manager.Outcome{RetryError: err} - } + if err := h.removeFinalizer(ctx, client.ObjectKeyFromObject(claim), uid); err != nil { + return manager.Outcome{RetryError: err} } - // A Machine event wakes all claims routed through its class. Private - // custody remains the authority if more than one synthetic machine exists. - var machines fleetv1.MachineCapacityList - machineClient := h.Public - if crossProject { - machineClient = h.Provider + if current == nil { + return manager.Outcome{} } - if err := machineClient.List(ctx, &machines); err != nil { + // 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} } - for i := range machines.Items { - machine := &machines.Items[i] - if err := h.ensureObservation(ctx, machineClient, machine, true); err != nil { - return manager.Outcome{RetryError: err} - } + if err := h.ensureObservation(ctx, h.Allocator.Provider, capacity, true); err != nil { + return manager.Outcome{RetryError: err} } return manager.Outcome{} } @@ -346,15 +313,6 @@ func profilePublished(profile *fleetv1.MachineProfile) bool { return condition != nil && condition.Status == metav1.ConditionTrue && condition.ObservedGeneration == profile.Generation } -func syntheticCrossProjectAuthority(claimUID types.UID, namespace string, consumer, provider controller.ProjectIdentity) (controller.AuthorityRef, controller.ExternalHoldRef) { - value := "synthetic-cross-project-v1/" + consumer.AuthorityID + "/" + string(consumer.UID) + "/" + string(provider.UID) + "/" + string(claimUID) - sum := sha256.Sum256([]byte(value)) - digest := hex.EncodeToString(sum[:]) - authority := controller.AuthorityRef{Provider: "synthetic-staging", RecordName: "synthetic-publication-" + digest[:24], RecordID: digest[:32], ContractDigest: digest} - hold := controller.ExternalHoldRef{Provider: "synthetic-staging", Namespace: namespace, Name: "machine-" + digest[:24], UID: types.UID("synthetic-" + string(claimUID))} - return authority, hold -} - func admissionReason(crossProject bool) string { if crossProject { return "SyntheticCrossProjectAdmission" @@ -385,11 +343,11 @@ func (h Handler) removeFinalizer(ctx context.Context, key client.ObjectKey, uid return err } if current.UID != uid { - return controller.ErrRecordInvalid + return errors.New("the claim name was recreated before finalizer removal") } out := current.Finalizers[:0] for _, value := range current.Finalizers { - if value != controller.MachineFinalizer { + if value != allocation.MachineFinalizer { out = append(out, value) } } @@ -411,11 +369,13 @@ func condition(kind string, status metav1.ConditionStatus, generation int64, rea return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, LastTransitionTime: metav1.Now(), Reason: reason, Message: message} } -// preserveRequest carries forward the fields owned by the requested-hardware -// projector. This handler replaces Machine status wholesale and must never -// drop or rewrite the pinned snapshot or its RequestResolved condition. +// preserveRequest carries forward the fields owned by the projectors: the +// requested-hardware snapshot with its RequestResolved condition, and power. +// This handler replaces Machine status wholesale and must never drop or +// rewrite them. func preserveRequest(current, next fleetv1.MachineStatus) fleetv1.MachineStatus { next.RequestedHardware = current.RequestedHardware + next.Power = current.Power if resolved := apiMeta.FindStatusCondition(current.Conditions, controller.ConditionRequestResolved); resolved != nil { next.Conditions = append(next.Conditions, *resolved) } @@ -449,12 +409,18 @@ func ConsumerHandlers(base manager.HandlerFactory, consumer controller.ProjectId if err != nil || string(binding.ClusterName) != consumer.RouteName { return handlers, err } + if template.Allocator == nil { + return manager.Handlers{}, fmt.Errorf("%w: synthetic staging has no allocator", manager.ErrEventWiringUnavailable) + } if !binding.Project.SameLifetime(consumer) { return manager.Handlers{}, fmt.Errorf("%w: synthetic consumer %q is engaged as a different project lifetime", manager.ErrProjectIdentityUnavailable, binding.ClusterName) } handler := template handler.Public, handler.Project = binding.Client, binding.Project handlers.Machine = handler + // The power projector reads the custody of the Machine's allocation + // in the provider project. + handlers.MachineProjector = manager.Chain(handlers.MachineProjector, manager.PowerProjector{Client: binding.Client, Project: binding.Project, Provider: template.Allocator.Provider, Namespace: template.Allocator.Namespace}) return handlers, nil } } diff --git a/internal/staging/handler_test.go b/internal/staging/handler_test.go index dc6a6131..aa4420ff 100644 --- a/internal/staging/handler_test.go +++ b/internal/staging/handler_test.go @@ -1,249 +1,285 @@ package staging import ( - "context" + "reflect" + "strings" "testing" "time" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + 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/custody" "go.datum.net/fleet/internal/manager" - "go.datum.net/fleet/internal/simulator" + "go.datum.net/fleet/internal/tenancy" ) -type executor struct { - results map[string]simulator.OperationResult -} - -func (e *executor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - now := time.Now().UTC() - digest, err := simulator.RequestDigest(request) - if err != nil { - return simulator.OperationResult{}, err +func assertPhase(t *testing.T, claim *fleetv1.Machine, phase string) { + t.Helper() + if claim.Status.Phase != phase { + t.Fatalf("phase = %q, want %q", claim.Status.Phase, phase) } - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CreatedAt: now, CompletedAt: &now} - e.results[request.ID] = result - return result, nil } -func (e *executor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { - result, found := e.results[id] - return result, found, nil +func assertCondition(t *testing.T, claim *fleetv1.Machine, kind string, status metav1.ConditionStatus, reason string) { + t.Helper() + got := apiMeta.FindStatusCondition(claim.Status.Conditions, kind) + if got == nil || got.Status != status || (reason != "" && got.Reason != reason) { + t.Fatalf("%s condition = %#v, want %s %q", kind, got, status, reason) + } } func TestOneMachineAllocatesExclusivelyThenReusesAfterRelease(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) + s := startStack(t) + device := s.server(1) + handler := s.handler() + first, second := s.claim("first"), s.claim("second") + + // The first event adds the finalizer; the second allocates. + drive(t, s.ctx, handler, consumerProject, first, 2) + got := s.get(first) + assertPhase(t, got, "Ready") + assertCondition(t, got, "Bound", metav1.ConditionTrue, "MachineAllocationActive") + assertCondition(t, got, "Ready", metav1.ConditionTrue, "") + firstAllocation, err := s.allocator.Get(s.ctx, machineIdentity(consumerProject, first)) + if err != nil || firstAllocation == nil { + t.Fatalf("first allocation = %v, %v", firstAllocation, err) + } + if firstAllocation.Spec.DeviceRef.Name != device.Name || firstAllocation.Status.Phase != fleetv1.AllocationActive { + t.Fatalf("first allocation = %s %+v", firstAllocation.Status.Phase, firstAllocation.Spec.DeviceRef) + } + // Allocated hardware is the allocation's, and status.power belongs to + // the power projector alone. + if got.Status.AllocatedHardware == nil || !reflect.DeepEqual(got.Status.AllocatedHardware.Hardware, firstAllocation.Spec.Hardware) || got.Status.AllocatedHardware.Hardware.CPU.Cores != 24 { + t.Fatalf("allocated hardware = %#v, allocation %#v", got.Status.AllocatedHardware, firstAllocation.Spec.Hardware) + } + if got.Status.Power != nil { + t.Fatalf("handler wrote status.power = %#v", got.Status.Power) + } + if holder := s.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef == nil || holder.AllocationRef.Name != firstAllocation.Name { + t.Fatalf("holder = %+v", holder) } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) + + drive(t, s.ctx, handler, consumerProject, second, 2) + got = s.get(second) + assertPhase(t, got, "Pending") + assertCondition(t, got, "Bound", metav1.ConditionFalse, "InsufficientCapacity") + if found, err := s.allocator.Get(s.ctx, machineIdentity(consumerProject, second)); err != nil || found != nil { + t.Fatalf("second allocation = %v, %v", found, err) } - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default", Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}}}}} - cores := int64(24) - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: cores}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - machine := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "central-metal-01", UID: "machine-uid", Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "central-metal-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} - claim := func(name, uid string) *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(uid)}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: profile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} - } - first, second := claim("first", "first-uid"), claim("second", "second-uid") - public := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}).WithObjects(namespace, class, profile, machine, first, second).Build() - private := fake.NewClientBuilder().WithScheme(scheme).Build() - provider := &executor{results: map[string]simulator.OperationResult{}} - coordinator, err := controller.NewCoordinator(private, "fleet-system-private", provider, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { + + if err := s.admin.Delete(s.ctx, s.get(first)); err != nil { t.Fatal(err) } - project := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "project-uid"} - handler := Handler{Public: public, Coordinator: coordinator, Project: project, Location: "us-central-1", Now: time.Now} - reconcile := func(object *fleetv1.Machine) manager.Outcome { - return handler.ReconcileEvent(ctx, manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: object.Namespace, Name: object.Name, UID: object.UID}) - } - - for i := 0; i < 2; i++ { - if out := reconcile(first); out.RetryError != nil { - t.Fatal(out.RetryError) + // The release is repeated while the coordinator wipes the Device, and + // the finalizer stays until the allocation is Released. + s.until("the first Machine is released", func() bool { + if out := handler.ReconcileEvent(s.ctx, projectRequest(consumerProject, first)); out.RetryError != nil { + t.Logf("release: %v", out.RetryError) } + err := s.admin.Get(s.ctx, client.ObjectKeyFromObject(first), &fleetv1.Machine{}) + return apierrors.IsNotFound(err) + }) + wipe := &ops.DeviceWipe{} + if err := s.admin.Get(s.ctx, client.ObjectKey{Namespace: providerNamespace, Name: custody.WipeName(firstAllocation.Name, 1)}, wipe); err != nil || wipe.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe = %+v, %v", wipe.Status, err) } - assertPhase(t, ctx, public, client.ObjectKeyFromObject(first), "Ready") - for i := 0; i < 2; i++ { - if out := reconcile(second); out.RetryError != nil { - t.Fatal(out.RetryError) - } + if err := s.admin.Get(s.ctx, client.ObjectKeyFromObject(firstAllocation), firstAllocation); err != nil || firstAllocation.Status.Phase != fleetv1.AllocationReleased { + t.Fatalf("released allocation = %v, %v", firstAllocation.Status.Phase, err) } - assertPhase(t, ctx, public, client.ObjectKeyFromObject(second), "Pending") - var deleting fleetv1.Machine - if err := public.Get(ctx, client.ObjectKeyFromObject(first), &deleting); err != nil { - t.Fatal(err) + drive(t, s.ctx, handler, consumerProject, second, 1) + got = s.get(second) + assertPhase(t, got, "Ready") + secondAllocation, err := s.allocator.Get(s.ctx, machineIdentity(consumerProject, second)) + if err != nil || secondAllocation == nil || secondAllocation.Spec.DeviceRef.Name != device.Name { + t.Fatalf("second allocation = %v, %v", secondAllocation, err) } - if err := public.Delete(ctx, &deleting); err != nil { +} + +// The claim never releases a Machine whose allocation custody no longer +// names: it stays Pending with its own reason for an operator to resolve. +func TestLostCustodyKeepsTheMachinePendingWithItsOwnReason(t *testing.T) { + s := startStack(t) + device := s.server(1) + handler := s.handler() + claim := s.claim("lost") + drive(t, s.ctx, handler, consumerProject, claim, 2) + assertPhase(t, s.get(claim), "Ready") + active, err := s.allocator.Get(s.ctx, machineIdentity(consumerProject, claim)) + if err != nil || active == nil { + t.Fatalf("allocation = %v, %v", active, err) + } + // Custody moves to Release behind the Machine's back, so the active + // allocation can no longer claim the Device. + if err := s.allocator.Custody.BeginRelease(s.ctx, device.Name, active.Name); err != nil { t.Fatal(err) } - if err := public.Get(ctx, client.ObjectKeyFromObject(first), &deleting); err != nil { - t.Fatal(err) + + drive(t, s.ctx, handler, consumerProject, claim, 1) + got := s.get(claim) + assertPhase(t, got, "Pending") + assertCondition(t, got, "Bound", metav1.ConditionFalse, "CustodyLost") + assertCondition(t, got, "Ready", metav1.ConditionFalse, "CustodyLost") +} + +// Every status the handler writes replaces Machine status wholesale, so each +// path must carry the power projector's field forward. +func TestHandlerStatusWritesPreserveStatusPower(t *testing.T) { + s := startStack(t) + s.server(1) + handler := s.handler() + setPower := func(claim *fleetv1.Machine) { + t.Helper() + current := s.get(claim) + current.Status.Power = &fleetv1.PowerStatus{State: "On"} + if err := s.admin.Status().Update(s.ctx, current); err != nil { + t.Fatal(err) + } } - if out := reconcile(&deleting); out.RetryError != nil { - t.Fatal(out.RetryError) + unsupported := func(claim *fleetv1.Machine) { + t.Helper() + current := s.get(claim) + current.Spec.PowerState = "On" + if err := s.admin.Update(s.ctx, current); err != nil { + t.Fatal(err) + } } - if out := reconcile(second); out.RetryError != nil { - t.Fatal(out.RetryError) + tests := []struct { + name string + claim string + prepare func(*fleetv1.Machine) + phase string + condition string + reason string + status metav1.ConditionStatus + }{ + {"allocated", "power-allocated", nil, "Ready", "Ready", "PoweredOffHandoff", metav1.ConditionTrue}, + {"pending for capacity", "power-pending", nil, "Pending", "Bound", "InsufficientCapacity", metav1.ConditionFalse}, + {"rejected", "power-rejected", unsupported, "Pending", "Accepted", "UnsupportedSyntheticRequest", metav1.ConditionFalse}, + } + for _, tt := range tests { + claim := s.claim(tt.claim) + if tt.prepare != nil { + tt.prepare(claim) + } + setPower(claim) + drive(t, s.ctx, handler, consumerProject, claim, 2) + got := s.get(claim) + assertPhase(t, got, tt.phase) + assertCondition(t, got, tt.condition, tt.status, tt.reason) + if got.Status.Power == nil || got.Status.Power.State != "On" { + t.Fatalf("%s: status.power = %#v, want On preserved", tt.name, got.Status.Power) + } } - assertPhase(t, ctx, public, client.ObjectKeyFromObject(second), "Ready") } func TestPublishedConsumerClaimAllocatesProviderMachine(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - consumerProject := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "project-consumer", UID: "consumer-project-uid"} - providerProject := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "provider-project-uid"} - cores := int64(24) - sourceProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "source-profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: cores}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - sourceClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "central-metal", UID: "source-class-uid", Generation: 1}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: sourceProfile.Name}}}, Access: &fleetv1.AccessPolicy{}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default", Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}}}}} - machine := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "central-metal-01", UID: "machine-uid", Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "central-metal-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} - revision, err := publicationRevision(sourceClass, providerProject) - if err != nil { - t.Fatal(err) - } - localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: sourceClass.Name, UID: "local-class-uid", Generation: 1, Annotations: map[string]string{publicationManagedByAnnotation: publicationManager, publicationProviderUIDAnnotation: string(providerProject.UID), publicationSourceUIDAnnotation: string(sourceClass.UID), publicationSourceNameAnnotation: sourceClass.Name}}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{Project: providerProject.RouteName, Name: sourceClass.Name}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: revision, ResolvedClass: &fleetv1.ResolvedClass{ProfilePolicy: *sourceClass.Spec.ProfilePolicy}, Conditions: []metav1.Condition{publicationCondition("SourceResolved", metav1.ConditionTrue, 1, "AuthorizedSource", "resolved")}}} - localProfile := sourceProfile.DeepCopyObject().(*fleetv1.MachineProfile) - localProfile.UID = "local-profile-uid" - localProfile.Annotations = map[string]string{publicationManagedByAnnotation: publicationManager, publicationProviderUIDAnnotation: string(providerProject.UID), publicationSourceUIDAnnotation: string(sourceProfile.UID), publicationSourceNameAnnotation: sourceProfile.Name} - localProfile.Status.Conditions = []metav1.Condition{publicationCondition("Published", metav1.ConditionTrue, localProfile.Generation, "SourceCopied", "copied")} - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: "claim-uid"}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} - consumer := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.Machine{}).WithObjects(namespace, localClass, localProfile, claim).Build() - providerKube := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}).WithObjects(sourceClass, sourceProfile, machine).Build() - private := fake.NewClientBuilder().WithScheme(scheme).Build() - providerExecutor := &executor{results: map[string]simulator.OperationResult{}} - coordinator, err := controller.NewCoordinator(private, "fleet-system-private", providerExecutor, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) + s := startStack(t) + device := s.server(1) + consumer := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "project-consumer", UID: types.UID(uid(12))} + provider := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: types.UID(uid(13))} + + // The consumer sees the publisher's copies of the provider's class and + // profile, each naming the exact source lifetime. + sourceClass, sourceProfile := s.class, s.profile + revision, err := publicationRevision(sourceClass, provider) if err != nil { t.Fatal(err) } - h := Handler{Public: consumer, Provider: providerKube, Coordinator: coordinator, Project: consumerProject, ProviderProject: providerProject, Location: "us-central-1", Now: time.Now} - request := manager.ProjectRequest{AuthorityID: consumerProject.AuthorityID, ProjectUID: consumerProject.UID, Namespace: claim.Namespace, Name: claim.Name, UID: claim.UID} - for i := 0; i < 2; i++ { - if out := h.ReconcileEvent(ctx, request); out.RetryError != nil { - t.Fatal(out.RetryError) - } + provenance := func(source client.Object) map[string]string { + return map[string]string{publicationManagedByAnnotation: publicationManager, publicationProviderUIDAnnotation: string(provider.UID), publicationSourceUIDAnnotation: string(source.GetUID()), publicationSourceNameAnnotation: source.GetName()} } - assertPhase(t, ctx, consumer, client.ObjectKeyFromObject(claim), "Ready") - var allocated fleetv1.MachineCapacity - if err := providerKube.Get(ctx, client.ObjectKeyFromObject(machine), &allocated); err != nil { + localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: sourceClass.Name, UID: "local-class-uid", Generation: 1, Annotations: provenance(sourceClass)}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project(provider.RouteName), Name: sourceClass.Name}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: revision, ResolvedClass: &fleetv1.ResolvedClass{ProfilePolicy: *sourceClass.Spec.ProfilePolicy}, Conditions: []metav1.Condition{publicationCondition("SourceResolved", metav1.ConditionTrue, 1, "AuthorizedSource", "resolved")}}} + localProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: sourceProfile.Name, UID: "local-profile-uid", Generation: 1, Annotations: provenance(sourceProfile)}, Spec: sourceProfile.Spec} + localProfile.Status.Conditions = []metav1.Condition{publicationCondition("Published", metav1.ConditionTrue, 1, "SourceCopied", "copied")} + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(901))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + consumerKube := fake.NewClientBuilder().WithScheme(stackScheme(t)).WithStatusSubresource(&fleetv1.Machine{}).WithObjects(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}}, localClass, localProfile, claim).Build() + handler := Handler{Public: consumerKube, Provider: s.admin, Allocator: s.allocator, Project: consumer, ProviderProject: provider, Location: locationName, Now: time.Now} + + drive(t, s.ctx, handler, consumer, claim, 2) + var got fleetv1.Machine + if err := consumerKube.Get(s.ctx, client.ObjectKeyFromObject(claim), &got); err != nil { t.Fatal(err) } - available := false - for _, condition := range allocated.Status.Conditions { - if condition.Type == "Available" && condition.Status == metav1.ConditionFalse { - available = true - } - } - if !available { - t.Fatal("provider Machine was not marked allocated") + assertPhase(t, &got, "Ready") + assertCondition(t, &got, "Accepted", metav1.ConditionTrue, "SyntheticCrossProjectAdmission") + // The allocation lives in the provider project and names the consumer's + // exact Machine; the provider's Device is held for it. + machine := machineIdentity(consumer, claim) + allocated, err := s.allocator.Get(s.ctx, machine) + if err != nil || allocated == nil { + t.Fatalf("allocation = %v, %v", allocated, err) } - var deleting fleetv1.Machine - if err := consumer.Get(ctx, client.ObjectKeyFromObject(claim), &deleting); err != nil { - t.Fatal(err) + if allocated.Spec.ConsumerRef != tenancy.Project(consumer.RouteName) || allocated.Labels[fleetv1.LabelConsumerUID] != string(consumer.UID) || allocated.Spec.DeviceRef.Name != device.Name || got.Status.AllocatedHardware == nil || !reflect.DeepEqual(got.Status.AllocatedHardware.Hardware, allocated.Spec.Hardware) { + t.Fatalf("allocation = %+v, allocated hardware %#v", allocated.Spec, got.Status.AllocatedHardware) } - if err := consumer.Delete(ctx, &deleting); err != nil { - t.Fatal(err) - } - if err := consumer.Get(ctx, client.ObjectKeyFromObject(claim), &deleting); err != nil { - t.Fatal(err) + if holder := s.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != allocated.Name { + t.Fatalf("holder = %+v", holder) } - if out := h.ReconcileEvent(ctx, request); out.RetryError != nil { - t.Fatal(out.RetryError) + 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) } - if err := providerKube.Get(ctx, client.ObjectKeyFromObject(machine), &allocated); err != nil { + + if err := consumerKube.Delete(s.ctx, &got); err != nil { t.Fatal(err) } - reusable := false - for _, condition := range allocated.Status.Conditions { - if condition.Type == "Available" && condition.Status == metav1.ConditionTrue { - reusable = true + s.until("the cross-project Machine is released", func() bool { + if out := handler.ReconcileEvent(s.ctx, projectRequest(consumer, claim)); out.RetryError != nil { + t.Logf("release: %v", out.RetryError) } + return apierrors.IsNotFound(consumerKube.Get(s.ctx, client.ObjectKeyFromObject(claim), &fleetv1.Machine{})) + }) + if holder := s.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("holder after release = %+v", holder) } - if !reusable { - t.Fatal("provider Machine did not become reusable after cross-project release") + 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) } } -func assertPhase(t *testing.T, ctx context.Context, kube client.Client, key client.ObjectKey, phase string) { - t.Helper() - var claim fleetv1.Machine - if err := kube.Get(ctx, key, &claim); err != nil { - t.Fatal(err) - } - if claim.Status.Phase != phase { - t.Fatalf("phase = %q, want %q", claim.Status.Phase, phase) +func (s *stack) capacity(device string) *fleetv1.MachineCapacity { + s.t.Helper() + capacity := &fleetv1.MachineCapacity{} + if err := s.admin.Get(s.ctx, client.ObjectKey{Namespace: providerNamespace, Name: "capacity-" + device}, capacity); err != nil { + s.t.Fatal(err) } + return capacity } func TestStagingPreservesPinnedRequestAndRejectsConflictingProfile(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default"}}}} - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "profile-uid", Generation: 1}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "central-metal-01", UID: "capacity-uid"}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "central-metal-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} - machine := func(name, uid string) *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(uid), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: profile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} - } - ready := machine("ready", "ready-uid") + s := startStack(t) + s.server(1) + owner := manager.NewLifecycleOwner(s.handler(), manager.RequestedHardwareProjector{Client: s.admin, Project: consumerProject}, nil) + ready := s.claim("ready") // This Machine was accepted against an earlier same-name profile that // requested 8 cores; the current profile requests 24. - conflicting := machine("conflicting", "conflicting-uid") - conflicting.Status.RequestedHardware = &fleetv1.RequestedHardwareStatus{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 8}, Memory: fleetv1.MemoryRequirement{Capacity: "32Gi"}, Source: fleetv1.RequestedHardwareSource{MachineGeneration: 1, ProfileRef: fleetv1.LocalReference{Name: profile.Name}, ProfileGeneration: 1, ProfileDigest: "sha256:earlier"}} - public := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}).WithObjects(namespace, class, profile, capacity, ready, conflicting).Build() - coordinator, err := controller.NewCoordinator(fake.NewClientBuilder().WithScheme(scheme).Build(), "fleet-system-private", &executor{results: map[string]simulator.OperationResult{}}, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { + conflicting := s.claim("conflicting") + pinned := s.get(conflicting) + pinned.Status.RequestedHardware = &fleetv1.RequestedHardwareStatus{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 8}, Memory: fleetv1.MemoryRequirement{Capacity: "32Gi"}, Source: fleetv1.RequestedHardwareSource{MachineGeneration: pinned.Generation, ProfileRef: fleetv1.LocalReference{Name: profileName}, ProfileGeneration: 1, ProfileDigest: "sha256:" + strings.Repeat("0", 64)}} + if err := s.admin.Status().Update(s.ctx, pinned); err != nil { t.Fatal(err) } - project := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "project-uid"} - owner := manager.NewLifecycleOwner(Handler{Public: public, Coordinator: coordinator, Project: project, Location: "us-central-1", Now: time.Now}, manager.RequestedHardwareProjector{Client: public, Project: project}, nil) - reconcile := func(object *fleetv1.Machine) fleetv1.Machine { - t.Helper() - for i := 0; i < 3; i++ { - if out := owner.ReconcileEvent(ctx, manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: object.Namespace, Name: object.Name, UID: object.UID}); out.RetryError != nil { - t.Fatal(out.RetryError) - } - } - var current fleetv1.Machine - if err := public.Get(ctx, client.ObjectKeyFromObject(object), ¤t); err != nil { - t.Fatal(err) - } - return current - } - got := reconcile(ready) + drive(t, s.ctx, owner, consumerProject, ready, 3) + got := s.get(ready) resolved := apiMeta.FindStatusCondition(got.Status.Conditions, controller.ConditionRequestResolved) if got.Status.Phase != "Ready" || got.Status.RequestedHardware == nil || got.Status.RequestedHardware.CPU.Cores != 24 || got.Status.AllocatedHardware == nil || resolved == nil || resolved.Status != metav1.ConditionTrue { t.Fatalf("ready status = %#v", got.Status) } - got = reconcile(conflicting) + drive(t, s.ctx, owner, consumerProject, conflicting, 3) + got = s.get(conflicting) accepted := apiMeta.FindStatusCondition(got.Status.Conditions, "Accepted") if accepted == nil || accepted.Status != metav1.ConditionFalse || accepted.Reason != "RequestedHardwareConflict" || got.Status.AllocatedHardware != nil { t.Fatalf("conflicting status = %#v", got.Status) @@ -251,4 +287,42 @@ func TestStagingPreservesPinnedRequestAndRejectsConflictingProfile(t *testing.T) if got.Status.RequestedHardware == nil || got.Status.RequestedHardware.CPU.Cores != 8 || got.Status.RequestedHardware.Memory.Capacity != "32Gi" { t.Fatalf("pinned snapshot rewritten: %#v", got.Status.RequestedHardware) } + if found, err := s.allocator.Get(s.ctx, machineIdentity(consumerProject, conflicting)); err != nil || found != nil { + t.Fatalf("conflicting Machine was allocated: %v, %v", found, err) + } +} + +// TestAClassFromAnotherPublisherIsRejected never allocates through a +// published class whose publisherRef names anything but the provider +// project that published it. +func TestAClassFromAnotherPublisherIsRejected(t *testing.T) { + s := startStack(t) + s.server(1) + consumer := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "project-consumer", UID: types.UID(uid(12))} + provider := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: types.UID(uid(13))} + sourceClass, sourceProfile := s.class, s.profile + revision, err := publicationRevision(sourceClass, provider) + if err != nil { + t.Fatal(err) + } + provenance := func(source client.Object) map[string]string { + return map[string]string{publicationManagedByAnnotation: publicationManager, publicationProviderUIDAnnotation: string(provider.UID), publicationSourceUIDAnnotation: string(source.GetUID()), publicationSourceNameAnnotation: source.GetName()} + } + for i, publisher := range []fleetv1.TypedReference{tenancy.Project("another-provider"), tenancy.Namespace(provider.RouteName)} { + localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: sourceClass.Name, UID: "local-class-uid", Generation: 1, Annotations: provenance(sourceClass)}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{PublisherRef: publisher, Name: sourceClass.Name}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: revision, ResolvedClass: &fleetv1.ResolvedClass{ProfilePolicy: *sourceClass.Spec.ProfilePolicy}, Conditions: []metav1.Condition{publicationCondition("SourceResolved", metav1.ConditionTrue, 1, "AuthorizedSource", "resolved")}}} + localProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: sourceProfile.Name, UID: "local-profile-uid", Generation: 1, Annotations: provenance(sourceProfile)}, Spec: sourceProfile.Spec} + localProfile.Status.Conditions = []metav1.Condition{publicationCondition("Published", metav1.ConditionTrue, 1, "SourceCopied", "copied")} + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(910 + i))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + consumerKube := fake.NewClientBuilder().WithScheme(stackScheme(t)).WithStatusSubresource(&fleetv1.Machine{}).WithObjects(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}}, localClass, localProfile, claim).Build() + handler := Handler{Public: consumerKube, Provider: s.admin, Allocator: s.allocator, Project: consumer, ProviderProject: provider, Location: locationName, Now: time.Now} + handler.ReconcileEvent(s.ctx, projectRequest(consumer, claim)) + var got fleetv1.Machine + if err := consumerKube.Get(s.ctx, client.ObjectKeyFromObject(claim), &got); err != nil { + t.Fatal(err) + } + assertCondition(t, &got, "Accepted", metav1.ConditionFalse, "UnresolvedPublication") + if allocated, err := s.allocator.Get(s.ctx, machineIdentity(consumer, claim)); err != nil || allocated != nil { + t.Fatalf("publisher %+v: allocation = %v, %v", publisher, allocated, err) + } + } } diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go new file mode 100644 index 00000000..63816c5b --- /dev/null +++ b/internal/staging/harness_test.go @@ -0,0 +1,254 @@ +package staging + +import ( + "context" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" + 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/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + + "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" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/simwork" + "go.datum.net/fleet/internal/site/siteapi" +) + +const ( + providerNamespace = "fleet-provider" + providerUser = "system:serviceaccount:fleet-system:metal-provider" + releaseUser = "system:serviceaccount:fleet-system:release-controller" + siteName = "site-example-a" + siteToken = "synthetic-site-token" + policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" + locationName = "us-central-1" + className = "central-metal" + profileName = "general-purpose-24c-128g" +) + +func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } + +// stack is a real API server holding the provider project: the metal, +// inventory and custody CRDs, simulator Devices behind one site's HTTP API, +// and the custody coordinator loop. The tests' same-project consumer lives in +// it too; cross-project consumers are separate clients. +type stack struct { + t *testing.T + ctx context.Context + admin client.Client + allocator *allocation.Allocator + loop *delivery.Loop + servers fixture.Enrollment + sites *delivery.Sites + class *fleetv1.MachineClass + profile *fleetv1.MachineProfile +} + +func stackScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, fleetv1.AddToScheme, ops.AddToScheme} { + if err := add(s); err != nil { + t.Fatal(err) + } + } + return s +} + +func startStack(t *testing.T) *stack { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{ + filepath.Join(root, "config", "base", "crd"), + filepath.Join(root, "config", "components", "inventory", "crds"), + filepath.Join(root, "config", "components", "device-operations", "crds"), + }, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + admin, err := client.New(config, client.Options{Scheme: stackScheme(t)}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + s := &stack{t: t, ctx: ctx, admin: admin} + s.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: providerNamespace}}) + + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + 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} + 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() }) + remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + registry, err := custody.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: providerNamespace, Principals: custody.Principals{ + custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, + }}} + s.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: providerNamespace, + 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 }, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + } + 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"}}}}}} + s.create(s.class) + s.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profileName}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} + s.create(s.profile) + return s +} + +func (s *stack) create(object client.Object) { + s.t.Helper() + if err := s.admin.Create(s.ctx, object); err != nil { + s.t.Fatal(err) + } +} + +// server adds a synthetic Device, its enrollment at the site, its capacity +// and fixture discovery, and waits until custody is Verified. The capacity +// is named capacity-. +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{ + 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"}} + 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) + } + s.until("custody is Verified", func() bool { + state := s.custody(name) + return state != nil && state.Spec.State == ops.CustodyVerified + }) + return device +} + +// until runs coordinator passes until done holds. +func (s *stack) until(what string, done func() bool) { + s.t.Helper() + deadline := time.Now().Add(30 * time.Second) + for !done() { + if time.Now().After(deadline) { + s.t.Fatalf("timed out waiting until %s", what) + } + if err := s.loop.Pass(s.ctx); err != nil { + s.t.Logf("pass: %v", err) + } + time.Sleep(20 * time.Millisecond) + } +} + +func (s *stack) custody(name string) *ops.DeviceCustody { + state := &ops.DeviceCustody{} + if err := s.admin.Get(s.ctx, client.ObjectKey{Namespace: providerNamespace, Name: name}, state); err != nil { + return nil + } + return state +} + +var consumerProject = controller.ProjectIdentity{AuthorityID: "staging", RouteName: "consumer-example", UID: types.UID(uid(11))} + +// handler is the staging handler for same-project claims: the consumer shares +// the provider's API server. +func (s *stack) handler() Handler { + return Handler{Public: s.admin, Allocator: s.allocator, Project: consumerProject, Location: locationName, Now: time.Now} +} + +// claim creates a powered-off Machine in the default namespace. +func (s *stack) claim(name string) *fleetv1.Machine { + s.t.Helper() + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + s.create(claim) + return claim +} + +func (s *stack) get(claim *fleetv1.Machine) *fleetv1.Machine { + s.t.Helper() + var current fleetv1.Machine + if err := s.admin.Get(s.ctx, client.ObjectKeyFromObject(claim), ¤t); err != nil { + s.t.Fatal(err) + } + return ¤t +} + +func projectRequest(project controller.ProjectIdentity, claim *fleetv1.Machine) manager.ProjectRequest { + return manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: claim.Namespace, Name: claim.Name, UID: claim.UID} +} + +// drive handles n events for the claim and fails on any retry error. +func drive(t *testing.T, ctx context.Context, handler manager.Handler, project controller.ProjectIdentity, claim *fleetv1.Machine, n int) { + t.Helper() + for range n { + if out := handler.ReconcileEvent(ctx, projectRequest(project, claim)); out.RetryError != nil { + t.Fatal(out.RetryError) + } + } +} + +func machineIdentity(project controller.ProjectIdentity, claim *fleetv1.Machine) allocation.Machine { + return allocation.MachineOf(manager.ProjectConsumer(project, nil), claim) +} diff --git a/internal/staging/multicluster_test.go b/internal/staging/multicluster_test.go index 7725ddd1..22963c51 100644 --- a/internal/staging/multicluster_test.go +++ b/internal/staging/multicluster_test.go @@ -2,7 +2,6 @@ package staging import ( "context" - "sync" "sync/atomic" "testing" "time" @@ -28,7 +27,6 @@ import ( "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/multiclustertest" "go.datum.net/fleet/internal/projectdiscovery" - "go.datum.net/fleet/internal/simulator" networkingv1 "go.datum.net/network-services-operator/api/v1alpha" locationsv1alpha1 "go.miloapis.com/locations/api/v1alpha1" quotav1alpha1 "go.miloapis.com/milo/pkg/apis/quota/v1alpha1" @@ -36,27 +34,6 @@ import ( servicesv1alpha1 "go.miloapis.com/service-catalog/api/v1alpha1" ) -type safeExecutor struct { - mu sync.Mutex - results map[string]simulator.OperationResult -} - -func (e *safeExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - e.mu.Lock() - defer e.mu.Unlock() - now := time.Now().UTC() - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", CreatedAt: now, CompletedAt: &now} - e.results[request.ID] = result - return result, nil -} - -func (e *safeExecutor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { - e.mu.Lock() - defer e.mu.Unlock() - result, found := e.results[id] - return result, found, nil -} - func stagingScheme(t *testing.T) *runtime.Scheme { t.Helper() scheme := runtime.NewScheme() @@ -91,19 +68,23 @@ func stagingProject(t *testing.T, name string, objects ...client.Object) *multic // cross-project staging through the multi-project manager: discovery engages // the publication consumer and another project with identically named // Machines. The publisher writes only into the consumer, only the consumer's -// Machine is allocated, and the other project gets requested-hardware -// resolution and nothing else. +// Machine is allocated on custody, and the other project gets +// requested-hardware resolution and nothing else. func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { + // Custody and allocations live on a real API server; the provider + // project's fake cluster carries the source class, profile and the + // capacity the handler observes. + s := startStack(t) + device := s.server(1) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) scheme := stagingScheme(t) const authority = "staging" - profileName, className := "general-purpose-24c-128g", "central-metal" - sourceProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profileName, UID: "source-profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - sourceClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: className, UID: "source-class-uid", Generation: 1}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: profileName}}}, Access: &fleetv1.AccessPolicy{}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default", Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}}}}} - capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "central-metal-01", UID: "capacity-uid", Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "central-metal-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} + sourceProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profileName, UID: "source-profile-uid", Generation: 1}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} + sourceClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: className, UID: "source-class-uid", Generation: 1}, 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"}}}}}} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: providerNamespace, Name: "capacity-" + device.Name, UID: "capacity-uid", 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"}} claim := func() *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "m", UID: "shared-claim-uid", Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} + return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "m", UID: types.UID(uid(901)), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} } // The provider project is also an Active metal consumer with its own // Machine of the same name; it must engage with requested hardware only. @@ -134,13 +115,10 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { // resolves, but nothing publishes the class there and staging is not // installed for it. other := stagingProject(t, "other", &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "other-ns"}}, claim(), sourceProfile.DeepCopyObject().(*fleetv1.MachineProfile)) - private := multiclustertest.NewProject(t, "host", multiclustertest.ProjectOptions{Scheme: scheme, Indexes: indexes(t, func(ctx context.Context, indexer client.FieldIndexer) error { - return manager.RegisterPrivateIndexes(ctx, indexer, "fleet-system-private") - })}) root := fake.NewClientBuilder().WithScheme(scheme).WithObjects( - &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "datum-cloud", UID: "provider-project"}}, - &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "consumer", UID: "consumer-project"}}, - &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "other", UID: "other-project"}}, + &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "datum-cloud", UID: "00000000-0000-4000-8000-000000000021"}}, + &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "consumer", UID: "00000000-0000-4000-8000-000000000022"}}, + &resourcemanagerv1alpha1.Project{ObjectMeta: metav1.ObjectMeta{Name: "other", UID: "00000000-0000-4000-8000-000000000023"}}, ).Build() identity := func(name string) controller.ProjectIdentity { project, err := manager.ResolveProjectIdentity(ctx, root, authority, name) @@ -159,11 +137,6 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { } consumerProject, providerProject := identity("consumer"), identity("datum-cloud") - executor := &safeExecutor{results: map[string]simulator.OperationResult{}} - coordinator, err := controller.NewCoordinator(private.Client, "fleet-system-private", executor, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { - t.Fatal(err) - } discovery := multiclustertest.NewProvider() projects := manager.NewProjects(func(ctx context.Context, name multicluster.ClusterName) (controller.ProjectIdentity, error) { return manager.ResolveProjectIdentity(ctx, root, authority, string(name)) @@ -176,13 +149,11 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { t.Fatal(err) } providerCluster := provider.NewCluster() - template := Handler{Coordinator: coordinator, Location: "us-central-1", Provider: providerCluster.GetClient(), ProviderProject: providerProject, Now: time.Now} + template := Handler{Allocator: s.allocator, Location: locationName, Provider: providerCluster.GetClient(), ProviderProject: providerProject, Now: time.Now} if err := SetupPublisher(mgr, projects, providerCluster, PublisherOptions{ConsumerProject: consumerProject, ProviderProject: providerProject, ClassName: className, ProfileName: profileName}); err != nil { t.Fatal(err) } if err := manager.Setup(ctx, mgr, projects, manager.SetupOptions{ - PrivateNamespace: "fleet-system-private", - PrivateCluster: private.NewCluster(), HandlersFor: ConsumerHandlers(manager.DefaultHandlers, consumerProject, template), ProviderProject: providerProject, ProviderCluster: providerCluster, @@ -246,21 +217,20 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { 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" }) - // Every private record belongs to the consumer project. - var secrets corev1.SecretList - if err := private.Client.List(ctx, &secrets, client.InNamespace("fleet-system-private")); err != nil { + // Only the consumer's Machine holds provider capacity, on custody, and + // the power projector reports for it alone. + var allocations fleetv1.MachineAllocationList + if err := s.admin.List(ctx, &allocations, client.InNamespace(providerNamespace)); err != nil { t.Fatal(err) } - if len(secrets.Items) == 0 { - t.Fatal("staging retained no private custody") + if len(allocations.Items) != 1 || allocations.Items[0].Labels[fleetv1.LabelConsumerUID] != string(consumerProject.UID) || allocations.Items[0].Spec.DeviceRef.Name != device.Name { + t.Fatalf("allocations = %#v, want one for the consumer on %s", allocations.Items, device.Name) } - for i := range secrets.Items { - route, err := controller.DecodePrivateLifecycleRoute(&secrets.Items[i]) - if err != nil { - continue - } - if route.ConsumerProject.UID != "" && route.ConsumerProject.UID != types.UID("consumer-project") { - t.Fatalf("private record %s belongs to %q", secrets.Items[i].Name, route.ConsumerProject.UID) - } + if holder := s.custody(device.Name).Spec.Holder; holder.AllocationRef == nil || holder.AllocationRef.Name != allocations.Items[0].Name { + t.Fatalf("holder = %+v", holder) + } + multiclustertest.Eventually(t, "the consumer's power is projected from custody", func() bool { return get(consumer).Status.Power != nil }) + if get(other).Status.Power != nil || get(provider).Status.Power != nil { + t.Fatal("power was projected for a project without a custody-backed Machine") } } diff --git a/internal/staging/publication_scope_test.go b/internal/staging/publication_scope_test.go index a3723d35..4f583e75 100644 --- a/internal/staging/publication_scope_test.go +++ b/internal/staging/publication_scope_test.go @@ -14,6 +14,7 @@ import ( "sigs.k8s.io/multicluster-runtime/pkg/multicluster" mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" + "go.datum.net/fleet/internal/allocation" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/manager" @@ -142,8 +143,9 @@ func TestEngagedPublisherRefusesAReplacedConsumerLifetime(t *testing.T) { // The staging handler is installed only for the consumer's exact lifetime. func TestConsumerHandlersScopeStagingToTheConsumerLifetime(t *testing.T) { isStaging := func(h manager.Handlers) bool { _, ok := h.Machine.(Handler); return ok } - factory := ConsumerHandlers(manager.DefaultHandlers, scopeConsumer, Handler{Location: "us-central-1"}) c := fake.NewClientBuilder().WithScheme(scopeScheme(t)).Build() + // The factory wires the power projector from the allocator's provider. + factory := ConsumerHandlers(manager.DefaultHandlers, scopeConsumer, Handler{Allocator: &allocation.Allocator{Provider: c, Namespace: providerNamespace}, Location: "us-central-1"}) consumer, err := factory(manager.ProjectBinding{ClusterName: "consumer", Project: scopeConsumer, Client: c}) if err != nil || !isStaging(consumer) { t.Fatalf("consumer handlers = %#v, %v", consumer.Machine, err) diff --git a/internal/staging/publisher.go b/internal/staging/publisher.go index 62ea7862..0166dd18 100644 --- a/internal/staging/publisher.go +++ b/internal/staging/publisher.go @@ -27,6 +27,7 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/tenancy" ) const ( @@ -241,7 +242,7 @@ func (p *Publisher) ensureProfile(ctx context.Context, sourceProfile *fleetv1.Ma func (p *Publisher) ensureClass(ctx context.Context, sourceClass *fleetv1.MachineClass) error { var local fleetv1.MachineClass err := p.Consumer.Get(ctx, client.ObjectKey{Name: p.Options.ClassName}, &local) - wantSpec := fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{Project: p.Options.ProviderProject.RouteName, Name: sourceClass.Name}} + wantSpec := fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project(p.Options.ProviderProject.RouteName), Name: sourceClass.Name}} if apierrors.IsNotFound(err) { local = fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: p.Options.ClassName, Annotations: p.annotations(sourceClass)}, Spec: wantSpec} if err := p.Consumer.Create(ctx, &local); err != nil { diff --git a/internal/staging/publisher_test.go b/internal/staging/publisher_test.go index bf7c1060..83f6c663 100644 --- a/internal/staging/publisher_test.go +++ b/internal/staging/publisher_test.go @@ -12,6 +12,7 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/tenancy" ) func TestPublisherCreatesProtectedReferenceAndExactProfileCopy(t *testing.T) { @@ -35,7 +36,7 @@ func TestPublisherCreatesProtectedReferenceAndExactProfileCopy(t *testing.T) { if err := consumer.Get(ctx, client.ObjectKey{Name: class.Name}, &publishedClass); err != nil { t.Fatal(err) } - if publishedClass.Spec.Source == nil || publishedClass.Spec.Source.Project != providerProject.RouteName || publishedClass.Spec.Source.Name != class.Name || !sourceResolved(&publishedClass) { + if publishedClass.Spec.Source == nil || publishedClass.Spec.Source.PublisherRef != tenancy.Project(providerProject.RouteName) || publishedClass.Spec.Source.Name != class.Name || !sourceResolved(&publishedClass) { t.Fatalf("published class = %#v", publishedClass) } if publishedClass.Status.ResolvedClass.ProfilePolicy.AllowedProfiles[0].Name != profile.Name || publishedClass.Annotations[publicationSourceUIDAnnotation] != string(class.UID) { diff --git a/internal/staging/unreadable_test.go b/internal/staging/unreadable_test.go deleted file mode 100644 index 99db2465..00000000 --- a/internal/staging/unreadable_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package staging - -import ( - "context" - "encoding/json" - "testing" - "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" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/manager" - "go.datum.net/fleet/internal/simulator" -) - -// An asset record in the older CPU and memory shape is reported on its own -// Machine only. Other Machines still allocate and release, and the affected -// Machine keeps its finalizer until an operator removes the record. -func TestUnreadablePrivateRecordIsReportedOnlyOnItsMachine(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default", Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}}}}} - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - capacity := func(name string) *fleetv1.MachineCapacity { - return &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(name + "-uid"), Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} - } - claim := func(name string) *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(name + "-uid")}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: profile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} - } - stale, other := claim("stale"), claim("other") - public := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}).WithObjects(namespace, class, profile, capacity("central-metal-01"), capacity("central-metal-02"), stale, other).Build() - private := fake.NewClientBuilder().WithScheme(scheme).Build() - coordinator, err := controller.NewCoordinator(private, "fleet-system-private", &executor{results: map[string]simulator.OperationResult{}}, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { - t.Fatal(err) - } - project := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "project-uid"} - handler := Handler{Public: public, Coordinator: coordinator, Project: project, Location: "us-central-1", Now: time.Now} - reconcile := func(key client.ObjectKey) manager.Outcome { - var current fleetv1.Machine - if err := public.Get(ctx, key, ¤t); err != nil { - t.Fatal(err) - } - return handler.ReconcileEvent(ctx, manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: current.Namespace, Name: current.Name, UID: current.UID}) - } - staleKey, otherKey := client.ObjectKeyFromObject(stale), client.ObjectKeyFromObject(other) - - for i := 0; i < 2; i++ { - if out := reconcile(staleKey); out.RetryError != nil { - t.Fatal(out.RetryError) - } - } - assertPhase(t, ctx, public, staleKey, "Ready") - writeOlderAssetShape(t, ctx, private, stale.UID) - - assertUnreadable := func() { - t.Helper() - if out := reconcile(staleKey); out.RetryError != nil { - t.Fatalf("unreadable record was requeued: %v", out.RetryError) - } - var current fleetv1.Machine - if err := public.Get(ctx, staleKey, ¤t); err != nil { - t.Fatal(err) - } - ready := apiMeta.FindStatusCondition(current.Status.Conditions, "Ready") - if current.Status.Phase != "Pending" || ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != controller.ReasonUnreadablePrivateRecord { - t.Fatalf("stale status = %#v", current.Status) - } - } - assertUnreadable() - - for i := 0; i < 2; i++ { - if out := reconcile(otherKey); out.RetryError != nil { - t.Fatal(out.RetryError) - } - } - assertPhase(t, ctx, public, otherKey, "Ready") - - for _, key := range []client.ObjectKey{staleKey, otherKey} { - var current fleetv1.Machine - if err := public.Get(ctx, key, ¤t); err != nil { - t.Fatal(err) - } - if err := public.Delete(ctx, ¤t); err != nil { - t.Fatal(err) - } - } - if out := reconcile(otherKey); out.RetryError != nil { - t.Fatal(out.RetryError) - } - var released fleetv1.Machine - if err := public.Get(ctx, otherKey, &released); err == nil { - t.Fatalf("other Machine kept its finalizer: %#v", released.Finalizers) - } - assertUnreadable() - var kept fleetv1.Machine - if err := public.Get(ctx, staleKey, &kept); err != nil || !contains(kept.Finalizers, controller.MachineFinalizer) { - t.Fatalf("stale Machine lost its finalizer: %#v, %v", kept.Finalizers, err) - } -} - -func writeOlderAssetShape(t *testing.T, ctx context.Context, private client.Client, claimUID types.UID) { - t.Helper() - var secrets corev1.SecretList - if err := private.List(ctx, &secrets, client.MatchingLabels{"fleet.datumapis.com/private-record": "asset", "fleet.datumapis.com/claim-uid": string(claimUID)}); err != nil { - t.Fatal(err) - } - if len(secrets.Items) != 1 { - t.Fatalf("asset records for %s = %d, want 1", claimUID, len(secrets.Items)) - } - secret := &secrets.Items[0] - var fields map[string]json.RawMessage - if err := json.Unmarshal(secret.Data["record.json"], &fields); err != nil { - t.Fatal(err) - } - fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) - data, err := json.Marshal(fields) - if err != nil { - t.Fatal(err) - } - secret.Data["record.json"] = data - if err := private.Update(ctx, secret); err != nil { - t.Fatal(err) - } -} diff --git a/internal/standalone/reinstall_test.go b/internal/standalone/reinstall_test.go deleted file mode 100644 index 28d442f5..00000000 --- a/internal/standalone/reinstall_test.go +++ /dev/null @@ -1,347 +0,0 @@ -package standalone - -import ( - "context" - "encoding/json" - "errors" - "reflect" - "sync" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - apiMeta "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" - "go.datum.net/fleet/internal/simulator" -) - -type unavailableResultExecutor struct { - storeExecutor - beforeEffect func(simulator.Request) -} - -type changedHistoryExecutor struct { - storeExecutor - change func(simulator.OperationResult) (simulator.OperationResult, bool, error) -} - -func (e changedHistoryExecutor) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { - result, _, err := e.storeExecutor.Lookup(ctx, operationID) - if err != nil { - return result, false, err - } - return e.change(result) -} - -func TestCompletedInstallationRequiresSimulatorHistory(t *testing.T) { - for _, phase := range []string{PhaseInstall, PhaseReinstall} { - for _, corruption := range []string{"missing", "unavailable", "identity", "inputs", "kind", "phase", "result", "completion"} { - t.Run(phase+"/"+corruption, func(t *testing.T) { - runner, store, _ := reinstallFixture(t) - ctx := context.Background() - if err := runner.Run(ctx, phase); err != nil { - t.Fatal(err) - } - before := store.Snapshot() - runner.Executor = changedHistoryExecutor{storeExecutor{store}, func(result simulator.OperationResult) (simulator.OperationResult, bool, error) { - switch corruption { - case "missing": - return simulator.OperationResult{}, false, nil - case "unavailable": - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown - case "identity": - result.ID = "different-operation" - case "inputs": - result.InputDigest = "different-retained-request" - case "kind": - result.Kind = "cleanup" - case "phase": - result.Phase = "Pending" - case "result": - result.Result = "clean" - case "completion": - result.CompletedAt = nil - } - return result, true, nil - }} - if err := runner.Run(ctx, phase); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("unverified replay = %v", err) - } - claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) - if err != nil { - t.Fatal(err) - } - if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) { - t.Fatal("unverified history left machine ready") - } - if !reflect.DeepEqual(before, store.Snapshot()) { - t.Fatal("history verification executed a new effect") - } - assertWaitingConsumerBlocked(t, runner) - }) - } - } -} - -func (e unavailableResultExecutor) Execute(ctx context.Context, request simulator.Request) (simulator.OperationResult, error) { - if e.beforeEffect != nil { - e.beforeEffect(request) - } - if _, err := e.storeExecutor.Execute(ctx, request); err != nil { - return simulator.OperationResult{}, err - } - return simulator.OperationResult{}, executor.ErrOutcomeUnknown -} - -func (e unavailableResultExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { - return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown -} - -func reinstallFixture(t *testing.T) (Runner, *simulator.Store, string) { - t.Helper() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - options := DefaultOptions() - objects := append(fixtureObjects(options), &fleetv1.Installation{ - ObjectMeta: metav1.ObjectMeta{Namespace: options.FirstNamespace, Name: options.ReinstallationName, UID: "reinstallation-uid", Generation: 1}, - Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: options.ImageName}}, - }) - kube := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}, &fleetv1.Installation{}).Build() - path := t.TempDir() + "/state.json" - store, err := simulator.Open(path) - if err != nil { - t.Fatal(err) - } - runner := Runner{Client: kube, Executor: storeExecutor{store}, Options: options, Now: time.Now} - for _, phase := range []string{PhaseAllocate, PhaseInstall} { - if err := runner.Run(context.Background(), phase); err != nil { - t.Fatal(err) - } - } - return runner, store, path -} - -func retainedAsset(t *testing.T, runner Runner) controller.AssetRecord { - t.Helper() - var secrets corev1.SecretList - if err := runner.Client.List(context.Background(), &secrets, client.InNamespace(runner.Options.PrivateNamespace), client.MatchingLabels{"fleet.datumapis.com/private-record": "asset"}); err != nil { - t.Fatal(err) - } - if len(secrets.Items) != 1 { - t.Fatalf("retained assets = %d, want 1", len(secrets.Items)) - } - var record controller.AssetRecord - if err := json.Unmarshal(secrets.Items[0].Data["record.json"], &record); err != nil { - t.Fatal(err) - } - return record -} - -func assertWaitingConsumerBlocked(t *testing.T, runner Runner) { - t.Helper() - ctx := context.Background() - coordinator, err := controller.NewCoordinator(runner.Client, runner.Options.PrivateNamespace, runner.Executor, controller.LocalDigestImageResolver{}, nil, runner.Options.EvidenceAge) - if err != nil { - t.Fatal(err) - } - claim, namespace, admission, err := runner.claim(ctx, runner.Options.SecondNamespace) - if err != nil { - t.Fatal(err) - } - var class fleetv1.MachineClass - var profile fleetv1.MachineProfile - var machine fleetv1.MachineCapacity - for _, object := range []client.Object{&class, &profile, &machine} { - key := client.ObjectKey{} - switch object.(type) { - case *fleetv1.MachineClass: - key.Name = runner.Options.ClassName - case *fleetv1.MachineProfile: - key.Name = runner.Options.ProfileName - default: - key = client.ObjectKey{Namespace: runner.Options.ProviderNamespace, Name: runner.Options.MachineName} - } - if err := runner.Client.Get(ctx, key, object); err != nil { - t.Fatal(err) - } - } - if apiMeta.IsStatusConditionTrue(machine.Status.Conditions, "Available") { - t.Fatal("reinstall exposed occupied capacity as available") - } - apiMeta.SetStatusCondition(&machine.Status.Conditions, condition("Available", metav1.ConditionTrue, machine.Generation, "SyntheticStaleAvailability", "Synthetic stale projection cannot override custody.")) - if _, err := coordinator.Allocate(ctx, allocationRequest(claim, namespace, admission, &class, &profile, &machine, time.Now())); !errors.Is(err, controller.ErrInsufficientCapacity) { - t.Fatalf("waiting allocation with stale Available=True: %v", err) - } -} - -func TestReinstallRecoversExactOperationAndRejectsStalePredecessor(t *testing.T) { - ctx := context.Background() - runner, store, path := reinstallFixture(t) - before := retainedAsset(t, runner) - var operationID string - runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}, beforeEffect: func(request simulator.Request) { - asset := retainedAsset(t, runner) - if asset.ActiveOperationID != request.ID || asset.CurrentInstallationName != runner.Options.InstallationName || asset.BindingID != before.BindingID || asset.Epoch != before.Epoch { - t.Fatalf("effect lacks retained predecessor/authority: %#v", asset) - } - var secrets corev1.SecretList - if err := runner.Client.List(ctx, &secrets, client.InNamespace(runner.Options.PrivateNamespace)); err != nil { - t.Fatal(err) - } - found := false - for _, secret := range secrets.Items { - var operation controller.InstallationRecord - if json.Unmarshal(secret.Data["record.json"], &operation) == nil && operation.OperationID == request.ID { - found = operation.InstallationUID == "reinstallation-uid" && operation.Predecessor == runner.Options.InstallationName && operation.BindingID == before.BindingID && operation.ImageName == runner.Options.ImageName && operation.Admission.DecisionID == "standalone-install-reinstallation-uid" - } - } - if !found { - t.Fatal("exact reinstall inputs not retained before effect") - } - operationID = request.ID - }} - if err := runner.Run(ctx, PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("lost result = %v", err) - } - claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) - if err != nil { - t.Fatal(err) - } - if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) || claim.Status.CurrentInstallationRef.Name != runner.Options.InstallationName { - t.Fatalf("unknown reinstall advanced readiness: %#v", claim.Status) - } - assertWaitingConsumerBlocked(t, runner) - reopened, err := simulator.Open(path) - if err != nil { - t.Fatal(err) - } - restarted := Runner{Client: runner.Client, Executor: storeExecutor{reopened}, Options: runner.Options, Now: time.Now} - for range 2 { - if err := restarted.Run(ctx, PhaseReinstall); err != nil { - t.Fatal(err) - } - } - after := retainedAsset(t, restarted) - if after.BindingID != before.BindingID || after.Epoch != before.Epoch || after.ClaimUID != before.ClaimUID || after.CurrentInstallationName != runner.Options.ReinstallationName || after.ActiveOperationID != "" { - t.Fatalf("reinstall changed custody or failed completion: %#v", after) - } - snapshot := reopened.Snapshot() - if len(snapshot.Operations) != 2 || snapshot.Operations[operationID] == nil || !reflect.DeepEqual(snapshot.Operations[operationID], store.Snapshot().Operations[operationID]) { - t.Fatal("retry/restart changed the retained effect") - } - assertWaitingConsumerBlocked(t, restarted) - claim, _, _, err = restarted.claim(ctx, runner.Options.FirstNamespace) - if err != nil { - t.Fatal(err) - } - var installed fleetv1.Installation - if err := runner.Client.Get(ctx, client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installed); err != nil { - t.Fatal(err) - } - if !apiMeta.IsStatusConditionTrue(claim.Status.Conditions, "Ready") || claim.Status.CurrentInstallationRef.Name != installed.Name || installed.Status.Phase != "Ready" || installed.Status.CompletedAt == nil { - t.Fatal("verified reinstall did not project synthetic completion") - } - stale := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: runner.Options.FirstNamespace, Name: "stale-reinstall", UID: "stale-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: runner.Options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: runner.Options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: runner.Options.ImageName}}} - if err := runner.Client.Create(ctx, stale); err != nil { - t.Fatal(err) - } - staleRunner := restarted - staleRunner.Options.InstallationName = stale.Name - if err := staleRunner.Run(ctx, PhaseInstall); !errors.Is(err, controller.ErrPredecessorConflict) { - t.Fatalf("stale predecessor accepted: %v", err) - } - if !reflect.DeepEqual(snapshot, reopened.Snapshot()) { - t.Fatal("stale predecessor produced a simulator effect") - } - if err := restarted.Run(ctx, PhaseReinstall); err != nil { - t.Fatal(err) - } - if err := restarted.Run(ctx, PhaseRelease); err != nil { - t.Fatal(err) - } - if len(reopened.Snapshot().Operations) != 3 { - t.Fatal("release did not retain exactly two installs and one cleanup") - } - assertRetainedOwner(t, runner.Client, runner.Options, "claim-b-uid", 2) -} - -func TestUnknownReinstallBlocksReleaseAndCapacityReuse(t *testing.T) { - runner, store, _ := reinstallFixture(t) - runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}} - if err := runner.Run(context.Background(), PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatal(err) - } - if err := runner.Run(context.Background(), PhaseRelease); !errors.Is(err, executor.ErrOutcomeUnknown) { - t.Fatalf("release with unresolved reinstall = %v", err) - } - assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) - assertWaitingConsumerBlocked(t, runner) - if len(store.Snapshot().Operations) != 2 { - t.Fatal("unknown reinstall allowed premature cleanup") - } -} - -func TestConcurrentReinstallConvergesWithoutDuplicateEffects(t *testing.T) { - runner, store, _ := reinstallFixture(t) - var workers sync.WaitGroup - results := make(chan error, 4) - for range cap(results) { - workers.Go(func() { results <- runner.Run(context.Background(), PhaseReinstall) }) - } - workers.Wait() - close(results) - for err := range results { - if err != nil && !apierrors.IsConflict(err) && !errors.Is(err, controller.ErrPredecessorConflict) { - t.Fatalf("unexpected concurrent outcome: %v", err) - } - } - if err := runner.Run(context.Background(), PhaseReinstall); err != nil { - t.Fatal(err) - } - if len(store.Snapshot().Operations) != 2 { - t.Fatal("concurrent retries duplicated installation effects") - } - assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) -} - -func TestReinstallRequiresBoundedSuccessorFixture(t *testing.T) { - for _, variant := range []string{"missing", "same-name", "wrong-predecessor"} { - t.Run(variant, func(t *testing.T) { - runner, store, _ := reinstallFixture(t) - switch variant { - case "missing": - runner.Options.ReinstallationName = "" - case "same-name": - runner.Options.ReinstallationName = runner.Options.InstallationName - case "wrong-predecessor": - var installation fleetv1.Installation - if err := runner.Client.Get(context.Background(), client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installation); err != nil { - t.Fatal(err) - } - installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "None"} - if err := runner.Client.Update(context.Background(), &installation); err != nil { - t.Fatal(err) - } - } - if err := runner.Run(context.Background(), PhaseReinstall); err == nil { - t.Fatal("invalid successor fixture accepted") - } - if len(store.Snapshot().Operations) != 1 { - t.Fatal("invalid successor produced an effect") - } - }) - } -} diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index db3ad686..20dbb4fa 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -1,15 +1,15 @@ +// Package standalone runs the standalone smoke test's phases on Device +// custody. Each phase is the Metal provider and, for release, the release +// controller, acting on fixed fixtures in one kind cluster. The coordinator +// runs as its own process and the simulator is the site. package standalone import ( "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" "errors" "fmt" "time" - corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -17,9 +17,13 @@ import ( "k8s.io/client-go/util/retry" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/allocation" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/tenancy" ) const ( @@ -30,7 +34,6 @@ const ( ) type Options struct { - PrivateNamespace string ProviderNamespace string FirstNamespace string SecondNamespace string @@ -40,301 +43,375 @@ type Options struct { ClaimName string InstallationName string ReinstallationName string - ImageName string LocationName string - EvidenceAge time.Duration + // Wait bounds how long a phase waits for the coordinator and the site. + Wait time.Duration } func DefaultOptions() Options { return Options{ - PrivateNamespace: "fleet-system-private", ProviderNamespace: "fleet-provider", - FirstNamespace: "fleet-project-a", SecondNamespace: "fleet-project-b", + ProviderNamespace: "fleet-provider", + FirstNamespace: "fleet-project-a", SecondNamespace: "fleet-project-b", ClassName: "standard-metal", ProfileName: "general-purpose-24c-128g", MachineName: "central1-baremetal-01", ClaimName: "allocation", - ReinstallationName: "debian-12-reinstall", - InstallationName: "debian-12", ImageName: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb", - LocationName: "us-central-1", EvidenceAge: 5 * time.Minute, + ReinstallationName: "debian-12-reinstall", InstallationName: "debian-12", + LocationName: "us-central-1", Wait: 3 * time.Minute, } } +// Runner runs one phase. Client is the Metal provider's identity. The +// allocator carries the coordinator's and the release controller's clients. type Runner struct { - Client client.Client - Executor executor.Client - Options Options - Now func() time.Time -} - -type syntheticEvidence struct { - SchemaVersion int `json:"schemaVersion"` - MachineNamespace string `json:"machineNamespace"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - Location string `json:"location"` - ObservedAt time.Time `json:"observedAt"` - Hardware fleetv1.Hardware `json:"hardware"` + Client client.Client + Allocator *allocation.Allocator + Options Options + Now func() time.Time } func (r Runner) Run(ctx context.Context, phase string) error { - if r.Client == nil || r.Executor == nil { - return errors.New("Kubernetes and simulator clients are required") + if r.Client == nil || r.Allocator == nil { + return errors.New("standalone: a client and an allocator are required") } if r.Now == nil { r.Now = time.Now } - if r.Options.EvidenceAge <= 0 { - return errors.New("positive evidence age is required") - } - coordinator, err := controller.NewCoordinator(r.Client, r.Options.PrivateNamespace, r.Executor, controller.LocalDigestImageResolver{}, nil, r.Options.EvidenceAge) - if err != nil { - return err - } switch phase { case PhaseAllocate: - return r.allocate(ctx, coordinator) + return r.allocate(ctx) case PhaseInstall: - return r.install(ctx, coordinator, r.Options.InstallationName) + return r.install(ctx, r.Options.InstallationName) case PhaseReinstall: if r.Options.ReinstallationName == "" || r.Options.ReinstallationName == r.Options.InstallationName { return errors.New("reinstall requires a distinct installation name") } - return r.install(ctx, coordinator, r.Options.ReinstallationName) + return r.install(ctx, r.Options.ReinstallationName) case PhaseRelease: - return r.release(ctx, coordinator) + return r.release(ctx) default: return fmt.Errorf("unsupported smoke phase %q", phase) } } -func (r Runner) allocate(ctx context.Context, coordinator *controller.Coordinator) error { - class, profile, machine, observedAt, err := r.inputs(ctx, true) +func (r Runner) allocate(ctx context.Context) error { + class, profile, capacity, err := r.inputs(ctx) if err != nil { return err } - first, firstNS, firstAdmission, err := r.prepareClaim(ctx, coordinator, r.Options.FirstNamespace) - if err != nil { + 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.ObjectKey{Namespace: r.Options.ProviderNamespace, Name: capacity.Spec.DeviceRef.Name}, 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 } - second, secondNS, secondAdmission, err := r.prepareClaim(ctx, coordinator, r.Options.SecondNamespace) + first, err := r.prepareClaim(ctx, r.Options.FirstNamespace) if err != nil { return err } - firstRequest := allocationRequest(first, firstNS, firstAdmission, class, profile, machine, observedAt) - secondRequest := allocationRequest(second, secondNS, secondAdmission, class, profile, machine, observedAt) - if err := coordinator.CheckCapacity(firstRequest); err != nil { - return fmt.Errorf("first consumer capacity preflight: %w", err) - } - if err := coordinator.CheckCapacity(secondRequest); err != nil { - return fmt.Errorf("second consumer capacity preflight: %w", err) + second, err := r.prepareClaim(ctx, r.Options.SecondNamespace) + if err != nil { + return err } - firstRecord, err := coordinator.Allocate(ctx, firstRequest) + won, err := r.Allocator.Allocate(ctx, r.request(first, class, profile)) if err != nil { return fmt.Errorf("allocate first consumer: %w", err) } - if err := r.projectBoundMachine(ctx, first, profile, firstRecord, observedAt); err != nil { + if err := r.projectBound(ctx, first, profile, won); err != nil { return err } - // Both contenders use the same retained Available=True evidence. Private - // custody, not a status projection racing the second request, decides the winner. - _, err = coordinator.Allocate(ctx, secondRequest) - if !errors.Is(err, controller.ErrInsufficientCapacity) { + // Both contenders see the same Available capacity. Custody, not a + // status projection, decides the winner. + if _, err := r.Allocator.Allocate(ctx, r.request(second, class, profile)); !errors.Is(err, allocation.ErrInsufficientCapacity) { return fmt.Errorf("second consumer must wait for capacity: %w", err) } - if firstRecord.ClaimUID != first.UID || firstRecord.ClaimNamespace != first.Namespace || firstRecord.ClaimName != first.Name || firstRecord.BindingID == "" { - return fmt.Errorf("%w: retained exclusive owner does not match the winning claim", controller.ErrRecordInvalid) + 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.projectMachineOccupied(ctx, machine); err != nil { + if err := r.projectOccupied(ctx, capacity); err != nil { return err } - return r.projectPendingClaim(ctx, second, profile, "InsufficientCapacity", "The only synthetic machine is allocated to another consumer.") + return r.projectPending(ctx, second, profile, "InsufficientCapacity", "The only synthetic machine is allocated to another consumer.") } -func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator, installationName string) error { - claim, namespace, admission, err := r.claim(ctx, r.Options.FirstNamespace) +func (r Runner) install(ctx context.Context, installationName string) error { + first, err := r.claim(ctx, r.Options.FirstNamespace) if err != nil { return err } + current, err := r.Allocator.Get(ctx, first.machine) + if err != nil { + return err + } + if current == nil || current.Status.Phase != fleetv1.AllocationActive { + return errors.New("the first consumer has no active allocation") + } var installation fleetv1.Installation - if err := r.Client.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: installationName}, &installation); err != nil { + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: first.claim.Namespace, Name: installationName}, &installation); err != nil { return err } if installationName == r.Options.ReinstallationName && installation.Spec.ExpectedPredecessor != (fleetv1.InstallationPredecessor{Type: "Installation", Name: r.Options.InstallationName}) { return errors.New("synthetic reinstall must name the configured initial installation as predecessor") } - apiMeta.SetStatusCondition(&claim.Status.Conditions, condition("Ready", metav1.ConditionUnknown, claim.Generation, "SyntheticInstallationUnverified", "The synthetic installation request has not yet returned verified completion.")) - if err := r.Client.Status().Update(ctx, claim); err != nil { + // A rerun after the site restarted finds the same operation by name and + // waits for its result; it never creates a second one. + operation := &ops.DeviceInstallation{} + name := custody.InstallationName(current.Name, string(installation.UID)) + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.Options.ProviderNamespace, Name: name}, operation); apierrors.IsNotFound(err) { + previous := "" + if ref := first.claim.Status.CurrentInstallationRef; ref != nil { + previous = ref.Name + } + apiMeta.SetStatusCondition(&first.claim.Status.Conditions, condition("Ready", metav1.ConditionUnknown, first.claim.Generation, "InstallationUnverified", "The installation has not yet returned a verified result.")) + if err := r.Client.Status().Update(ctx, first.claim); err != nil { + return err + } + if operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &installation, Current: previous}); err != nil { + return fmt.Errorf("install synthetic image: %w", err) + } + } else if err != nil { return err } - imageDecision := "local-test-" + imageDigest(r.Options.ImageName) - result, err := coordinator.Install(ctx, controller.InstallationRequest{Claim: claim, Installation: &installation, NamespaceUID: namespace.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: admission.PrincipalUID, DecisionID: "standalone-install-" + string(installation.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: imageDecision}}) - if err != nil { - return fmt.Errorf("install synthetic image: %w", err) - } - retained, found, err := r.Executor.Lookup(ctx, result.Record.OperationID) - if err != nil || !found || retained.ID != result.Record.OperationID || retained.Kind != "install" || retained.Phase != "Succeeded" || retained.Result != "installed" || retained.CompletedAt == nil || result.RequestDigest == "" || retained.InputDigest != result.RequestDigest { - return fmt.Errorf("%w: simulator installation history is missing or does not match retained authority and inputs", executor.ErrOutcomeUnknown) + if err := r.await(ctx, "the DeviceInstallation succeeds", func() (bool, error) { + if err := r.Client.Get(ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + return false, err + } + if phase := operation.Status.Phase; phase.Ended() && phase != ops.PhaseSucceeded { + return false, fmt.Errorf("the installation ended %s: %s", phase, operation.Status.Reason) + } + return operation.Status.Phase == ops.PhaseSucceeded, nil + }); err != nil { + return err } now := metav1.NewTime(r.Now().UTC()) - installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, Conditions: []metav1.Condition{condition("Accepted", metav1.ConditionTrue, installation.Generation, "SyntheticFixtureAccepted", "The standalone fixture admitted this request; this is not Milo authorization."), condition("Executing", metav1.ConditionFalse, installation.Generation, "Completed", "The persistent simulator returned a verified terminal result."), condition("Ready", metav1.ConditionTrue, installation.Generation, "Installed", "The synthetic provider verified installation completion.")}} + installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, Conditions: []metav1.Condition{ + condition("Accepted", metav1.ConditionTrue, installation.Generation, "SyntheticFixtureAccepted", "The standalone fixture admitted this request; this is not Milo authorization."), + condition("Executing", metav1.ConditionFalse, installation.Generation, "Completed", "The simulator site returned a verified result under the operation's fence."), + condition("Ready", metav1.ConditionTrue, installation.Generation, "Installed", "The simulator site verified the installation."), + }} if err := r.Client.Status().Update(ctx, &installation); err != nil { return err } - claim.Status.CurrentInstallationRef = &fleetv1.LocalReference{Name: installation.Name} - apiMeta.SetStatusCondition(&claim.Status.Conditions, condition("Ready", metav1.ConditionTrue, claim.Generation, "SyntheticHandoffReady", "Synthetic installation and powered-off handoff are verified.")) - return r.Client.Status().Update(ctx, claim) + if err := r.Client.Get(ctx, client.ObjectKeyFromObject(first.claim), first.claim); err != nil { + return err + } + first.claim.Status.CurrentInstallationRef = &fleetv1.LocalReference{Name: installation.Name} + apiMeta.SetStatusCondition(&first.claim.Status.Conditions, condition("Ready", metav1.ConditionTrue, first.claim.Generation, "SyntheticHandoffReady", "The installation is verified.")) + if err := r.Client.Status().Update(ctx, first.claim); err != nil { + return err + } + return r.projectPower(ctx, first.machine) } -func (r Runner) release(ctx context.Context, coordinator *controller.Coordinator) error { - claim, _, _, err := r.claim(ctx, r.Options.FirstNamespace) +func (r Runner) release(ctx context.Context) error { + first, err := r.claim(ctx, r.Options.FirstNamespace) if err != nil && !apierrors.IsNotFound(err) { return err } if err == nil { - claimUID, claimResourceVersion := claim.UID, claim.ResourceVersion - if claim.DeletionTimestamp == nil { - if err := r.requestExactDeletion(ctx, claim, claimUID, claimResourceVersion); err != nil { + if first.claim.DeletionTimestamp == nil { + uid, version := first.claim.UID, first.claim.ResourceVersion + if err := r.Client.Delete(ctx, first.claim, client.Preconditions{UID: &uid, ResourceVersion: &version}); err != nil && !apierrors.IsNotFound(err) { return err } } - result, releaseErr := coordinator.Release(ctx, claimUID) - if releaseErr != nil { - return fmt.Errorf("release first consumer: %w", releaseErr) + current, err := r.Allocator.Get(ctx, first.machine) + if err != nil { + return err } - if !result.SafeToRemoveFinalizer { - return errors.New("cleanup did not authorize finalizer removal") + if current != nil { + if err := r.await(ctx, "the first allocation is Released", func() (bool, error) { + if err := r.Client.Get(ctx, client.ObjectKeyFromObject(current), current); err != nil { + return false, err + } + released, err := r.Allocator.Release(ctx, current, first.machine) + if errors.Is(err, allocation.ErrWipeFailed) { + return false, err + } + return released, nil + }); err != nil { + return err + } } - if err := r.removeExactFinalizer(ctx, client.ObjectKey{Namespace: r.Options.FirstNamespace, Name: r.Options.ClaimName}, claimUID); err != nil { + if err := r.removeFinalizer(ctx, client.ObjectKeyFromObject(first.claim), first.claim.UID); err != nil { return err } } - class, profile, machine, observedAt, err := r.inputs(ctx, false) + class, profile, capacity, err := r.inputs(ctx) if err != nil { return err } - second, secondNS, admission, err := r.claim(ctx, r.Options.SecondNamespace) + second, err := r.claim(ctx, r.Options.SecondNamespace) if err != nil { return err } - record, err := coordinator.Allocate(ctx, allocationRequest(second, secondNS, admission, class, profile, machine, observedAt)) + reused, err := r.Allocator.Allocate(ctx, r.request(second, class, profile)) if err != nil { return fmt.Errorf("allocate waiting consumer: %w", err) } - if record.Epoch < 2 { - return fmt.Errorf("reused asset epoch = %d, want at least 2", record.Epoch) + if reused.Spec.DeviceRef.Name != capacity.Spec.DeviceRef.Name { + return errors.New("the waiting consumer did not reuse the released Device") } - if err := r.projectBoundMachine(ctx, second, profile, record, observedAt); err != nil { + if err := r.projectBound(ctx, second, profile, reused); err != nil { return err } - return r.projectMachineOccupied(ctx, machine) + return r.projectOccupied(ctx, capacity) +} + +// await polls until done, a failure, or the phase's wait bound. +func (r Runner) await(ctx context.Context, what string, done func() (bool, error)) error { + deadline := r.Now().Add(r.Options.Wait) + for { + ok, err := done() + if err != nil || ok { + return err + } + if r.Now().After(deadline) { + return fmt.Errorf("timed out waiting until %s", what) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } } -func (r Runner) inputs(ctx context.Context, createEvidence bool) (*fleetv1.MachineClass, *fleetv1.MachineProfile, *fleetv1.MachineCapacity, time.Time, 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. +func (r Runner) inputs(ctx context.Context) (*fleetv1.MachineClass, *fleetv1.MachineProfile, *fleetv1.MachineCapacity, error) { var class fleetv1.MachineClass var profile fleetv1.MachineProfile - var machine fleetv1.MachineCapacity + var capacity fleetv1.MachineCapacity if err := r.Client.Get(ctx, client.ObjectKey{Name: r.Options.ClassName}, &class); err != nil { - return nil, nil, nil, time.Time{}, err + return nil, nil, nil, err } if err := r.Client.Get(ctx, client.ObjectKey{Name: r.Options.ProfileName}, &profile); err != nil { - return nil, nil, nil, time.Time{}, err + return nil, nil, nil, err } - if err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.Options.ProviderNamespace, Name: r.Options.MachineName}, &machine); err != nil { - return nil, nil, nil, time.Time{}, err + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.Options.ProviderNamespace, Name: r.Options.MachineName}, &capacity); err != nil { + return nil, nil, nil, err } - if class.Spec.Capacity == nil || class.Spec.Capacity.MachineCapacities.Namespace != r.Options.ProviderNamespace || machine.Namespace != r.Options.ProviderNamespace { - return nil, nil, nil, time.Time{}, errors.New("synthetic provider scope does not match configuration") + 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") } - evidence, err := r.loadEvidence(ctx, &machine, createEvidence) - if err != nil { - return nil, nil, nil, time.Time{}, err + 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."), } - machine.Status.Hardware = evidence.Hardware - machine.Status.Conditions = []metav1.Condition{condition("Prepared", metav1.ConditionTrue, machine.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), condition("Healthy", metav1.ConditionTrue, machine.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), condition("Available", metav1.ConditionTrue, machine.Generation, "SyntheticEvidence", "Private custody remains authoritative for exclusivity.")} - if err := r.Client.Status().Update(ctx, &machine); err != nil { - return nil, nil, nil, time.Time{}, err + if err := r.Client.Status().Update(ctx, &capacity); err != nil { + return nil, nil, nil, err } - return &class, &profile, &machine, evidence.ObservedAt, nil + return &class, &profile, &capacity, nil } -func (r Runner) prepareClaim(ctx context.Context, coordinator *controller.Coordinator, namespaceName string) (*fleetv1.Machine, *corev1.Namespace, controller.AdmissionAuthority, error) { - claim, ns, admission, err := r.claim(ctx, namespaceName) - if err != nil { - return nil, nil, admission, err - } - if claim.Spec.LocationRef.Name != r.Options.LocationName || claim.Spec.MachineClassRef.Name != r.Options.ClassName || claim.Spec.MachineProfileRef.Name != r.Options.ProfileName || len(claim.Spec.NetworkInterfaces) != 0 || claim.Spec.PowerState != "Off" { - return nil, nil, admission, fmt.Errorf("%w: claim does not match the configured synthetic fixture", controller.ErrRecordInvalid) - } - if err := coordinator.EnsureClaimCustody(ctx, claim, ns.UID, admission); err != nil { - return nil, nil, admission, err +type claim struct { + claim *fleetv1.Machine + machine allocation.Machine +} + +func (r Runner) claim(ctx context.Context, namespaceName string) (claim, error) { + machine := &fleetv1.Machine{} + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: namespaceName, Name: r.Options.ClaimName}, machine); err != nil { + return claim{}, err } - if !contains(claim.Finalizers, controller.MachineFinalizer) { - claim.Finalizers = append(claim.Finalizers, controller.MachineFinalizer) - if err := r.Client.Update(ctx, claim); err != nil { - return nil, nil, admission, err - } + // Each consumer namespace stands in for a consumer project. + consumer, err := tenancy.Namespaces{Client: r.Client}.Resolve(ctx, tenancy.Namespace(namespaceName)) + if err != nil { + return claim{}, err } - return claim, ns, admission, nil + return claim{claim: machine, machine: allocation.MachineOf(consumer, machine)}, nil } -func (r Runner) claim(ctx context.Context, namespaceName string) (*fleetv1.Machine, *corev1.Namespace, controller.AdmissionAuthority, error) { - var claim fleetv1.Machine - if err := r.Client.Get(ctx, client.ObjectKey{Namespace: namespaceName, Name: r.Options.ClaimName}, &claim); err != nil { - return nil, nil, controller.AdmissionAuthority{}, err +func (r Runner) prepareClaim(ctx context.Context, namespaceName string) (claim, error) { + current, err := r.claim(ctx, namespaceName) + if err != nil { + return claim{}, err } - ns := &corev1.Namespace{} - if err := r.Client.Get(ctx, client.ObjectKey{Name: namespaceName}, ns); err != nil { - return nil, nil, controller.AdmissionAuthority{}, err + spec := current.claim.Spec + if spec.LocationRef.Name != r.Options.LocationName || spec.MachineClassRef.Name != r.Options.ClassName || spec.MachineProfileRef.Name != r.Options.ProfileName || len(spec.NetworkInterfaces) != 0 || spec.PowerState != "Off" { + return claim{}, errors.New("the claim does not match the configured synthetic fixture") } - a := controller.AdmissionAuthority{PrincipalUID: "standalone-fixture-" + string(ns.UID), DecisionID: "standalone-claim-" + string(claim.UID)} - return &claim, ns, a, nil + if !contains(current.claim.Finalizers, allocation.MachineFinalizer) { + current.claim.Finalizers = append(current.claim.Finalizers, allocation.MachineFinalizer) + if err := r.Client.Update(ctx, current.claim); err != nil { + return claim{}, err + } + } + return current, nil } -func allocationRequest(claim *fleetv1.Machine, ns *corev1.Namespace, admission controller.AdmissionAuthority, class *fleetv1.MachineClass, profile *fleetv1.MachineProfile, machine *fleetv1.MachineCapacity, observed time.Time) controller.AllocationRequest { - return controller.AllocationRequest{Claim: claim, Class: class, Profile: profile, MachineCapacities: []fleetv1.MachineCapacity{*machine}, EvidenceObservedAt: map[types.UID]time.Time{machine.UID: observed}, NamespaceUID: ns.UID, Admission: admission, LocalClassName: class.Name, LocalClassUID: class.UID, LocalProfileName: profile.Name, LocalProfileUID: profile.UID} +func (r Runner) request(c claim, class *fleetv1.MachineClass, profile *fleetv1.MachineProfile) allocation.Request { + return allocation.Request{Machine: c.machine, Class: class, Profile: profile, Authority: fleetv1.AllocationAuthority{Principal: "standalone-fixture", Decision: "standalone-claim:" + c.machine.Namespace + "/" + c.machine.Name}} } // withRequestedHardware applies the same resolve-once contract as the -// manager's requested-hardware projector: a pinned snapshot is carried forward -// unchanged, and an unresolvable fixture profile fails the phase rather than -// producing a guessed request. -func withRequestedHardware(claim *fleetv1.Machine, profile *fleetv1.MachineProfile, status fleetv1.MachineStatus) (fleetv1.MachineStatus, error) { - requested := claim.Status.RequestedHardware +// manager's requested-hardware projector. +func withRequestedHardware(machine *fleetv1.Machine, profile *fleetv1.MachineProfile, status fleetv1.MachineStatus) (fleetv1.MachineStatus, error) { + requested := machine.Status.RequestedHardware if requested == nil { var err error - if requested, err = controller.ResolveRequestedHardware(claim, profile); err != nil { + if requested, err = controller.ResolveRequestedHardware(machine, profile); err != nil { return status, fmt.Errorf("resolve requested hardware: %w", err) } } status.RequestedHardware = requested - status.Conditions = append(status.Conditions, condition(controller.ConditionRequestResolved, metav1.ConditionTrue, claim.Generation, controller.ReasonRequestResolved, "Requested hardware is pinned from the fixture MachineProfile.")) + status.Conditions = append(status.Conditions, condition(controller.ConditionRequestResolved, metav1.ConditionTrue, machine.Generation, controller.ReasonRequestResolved, "Requested hardware is pinned from the fixture MachineProfile.")) return status, nil } -func (r Runner) projectBoundMachine(ctx context.Context, claim *fleetv1.Machine, profile *fleetv1.MachineProfile, record *controller.AssetRecord, observedAt time.Time) error { - observed := metav1.NewTime(observedAt.UTC()) - status := fleetv1.MachineStatus{Phase: "Ready", Placement: &fleetv1.Placement{LocationRef: fleetv1.LocalReference{Name: r.Options.LocationName}}, AcceptedProfileRef: &fleetv1.LocalReference{Name: r.Options.ProfileName}, AllocatedHardware: &fleetv1.AllocatedHardwareStatus{ObservedAt: &observed, Hardware: record.Hardware}, Power: &fleetv1.PowerStatus{State: "Off"}, Conditions: []metav1.Condition{condition("Accepted", metav1.ConditionTrue, claim.Generation, "SyntheticFixtureAccepted", "This standalone fixture does not represent Milo admission."), condition("Bound", metav1.ConditionTrue, claim.Generation, "MachineAllocationCommitted", "Private custody contains the immutable allocation."), condition("NetworkReady", metav1.ConditionTrue, claim.Generation, "NoAttachmentsRequired", "No network interfaces were requested."), condition("Ready", metav1.ConditionTrue, claim.Generation, "PoweredOffHandoff", "Synthetic powered-off handoff is ready.")}} - return r.writeClaimStatus(ctx, claim, profile, status) +func (r Runner) projectBound(ctx context.Context, c claim, profile *fleetv1.MachineProfile, bound *fleetv1.MachineAllocation) error { + observed := metav1.NewTime(r.Now().UTC()) + status := fleetv1.MachineStatus{Phase: "Ready", Placement: &fleetv1.Placement{LocationRef: fleetv1.LocalReference{Name: r.Options.LocationName}}, AcceptedProfileRef: &fleetv1.LocalReference{Name: r.Options.ProfileName}, AllocatedHardware: &fleetv1.AllocatedHardwareStatus{ObservedAt: &observed, Hardware: bound.Spec.Hardware}, Conditions: []metav1.Condition{ + condition("Accepted", metav1.ConditionTrue, c.claim.Generation, "SyntheticFixtureAccepted", "This standalone fixture does not represent Milo admission."), + condition("Bound", metav1.ConditionTrue, c.claim.Generation, "MachineAllocationActive", "Device custody names this Machine's allocation."), + condition("NetworkReady", metav1.ConditionTrue, c.claim.Generation, "NoAttachmentsRequired", "No network interfaces were requested."), + condition("Ready", metav1.ConditionTrue, c.claim.Generation, "PoweredOffHandoff", "Synthetic powered-off handoff is ready."), + }} + if err := r.writeStatus(ctx, c.claim, profile, status); err != nil { + return err + } + return r.projectPower(ctx, c.machine) } -func (r Runner) projectPendingClaim(ctx context.Context, claim *fleetv1.Machine, profile *fleetv1.MachineProfile, reason, message string) error { - status := fleetv1.MachineStatus{Phase: "Pending", Placement: &fleetv1.Placement{LocationRef: fleetv1.LocalReference{Name: r.Options.LocationName}}, Conditions: []metav1.Condition{condition("Accepted", metav1.ConditionTrue, claim.Generation, "SyntheticFixtureAccepted", "This standalone fixture does not represent Milo admission."), condition("Bound", metav1.ConditionFalse, claim.Generation, reason, message), condition("Ready", metav1.ConditionFalse, claim.Generation, reason, message)}} - return r.writeClaimStatus(ctx, claim, profile, status) +func (r Runner) projectPending(ctx context.Context, c claim, profile *fleetv1.MachineProfile, reason, message string) error { + status := fleetv1.MachineStatus{Phase: "Pending", Placement: &fleetv1.Placement{LocationRef: fleetv1.LocalReference{Name: r.Options.LocationName}}, Conditions: []metav1.Condition{ + condition("Accepted", metav1.ConditionTrue, c.claim.Generation, "SyntheticFixtureAccepted", "This standalone fixture does not represent Milo admission."), + condition("Bound", metav1.ConditionFalse, c.claim.Generation, reason, message), + condition("Ready", metav1.ConditionFalse, c.claim.Generation, reason, message), + }} + return r.writeStatus(ctx, c.claim, profile, status) } -func (r Runner) writeClaimStatus(ctx context.Context, claim *fleetv1.Machine, profile *fleetv1.MachineProfile, status fleetv1.MachineStatus) error { - status, err := withRequestedHardware(claim, profile, status) +// writeStatus keeps status.power, which only the manager's power projector +// writes. +func (r Runner) writeStatus(ctx context.Context, machine *fleetv1.Machine, profile *fleetv1.MachineProfile, status fleetv1.MachineStatus) error { + status, err := withRequestedHardware(machine, profile, status) if err != nil { return err } - claim.Status = status - return r.Client.Status().Update(ctx, claim) + status.Power = machine.Status.Power + machine.Status = status + return r.Client.Status().Update(ctx, machine) } -func (r Runner) projectMachineOccupied(ctx context.Context, machine *fleetv1.MachineCapacity) error { - apiMeta.SetStatusCondition(&machine.Status.Conditions, condition("Available", metav1.ConditionFalse, machine.Generation, "Allocated", "Private custody records an active allocation.")) - return r.Client.Status().Update(ctx, machine) +// projectPower runs the manager's power projector for a fixture Machine. +func (r Runner) projectPower(ctx context.Context, machine allocation.Machine) error { + 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) removeExactFinalizer(ctx context.Context, key client.ObjectKey, uid types.UID) error { +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 if err := r.Client.Get(ctx, key, ¤t); apierrors.IsNotFound(err) { @@ -343,85 +420,20 @@ func (r Runner) removeExactFinalizer(ctx context.Context, key client.ObjectKey, return err } if current.UID != uid { - return fmt.Errorf("%w: claim name was recreated before finalizer removal", controller.ErrRecordInvalid) + return errors.New("the claim name was recreated before finalizer removal") } - if !contains(current.Finalizers, controller.MachineFinalizer) { + if !contains(current.Finalizers, allocation.MachineFinalizer) { return nil } - current.Finalizers = remove(current.Finalizers, controller.MachineFinalizer) + current.Finalizers = remove(current.Finalizers, allocation.MachineFinalizer) return r.Client.Update(ctx, ¤t) }) } -func (r Runner) requestExactDeletion(ctx context.Context, claim *fleetv1.Machine, uid types.UID, resourceVersion string) error { - if err := r.Client.Delete(ctx, claim, client.Preconditions{UID: &uid, ResourceVersion: &resourceVersion}); err != nil && !apierrors.IsNotFound(err) { - return err - } - var current fleetv1.Machine - if err := r.Client.Get(ctx, client.ObjectKeyFromObject(claim), ¤t); apierrors.IsNotFound(err) { - claim.UID = "" - return nil - } else if err != nil { - return err - } - if current.UID != uid { - return fmt.Errorf("%w: claim name was recreated during release", controller.ErrRecordInvalid) - } - *claim = current - return nil -} - -func (r Runner) loadEvidence(ctx context.Context, machine *fleetv1.MachineCapacity, create bool) (syntheticEvidence, error) { - name := evidenceName(machine.UID) - var secret corev1.Secret - err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.Options.PrivateNamespace, Name: name}, &secret) - if apierrors.IsNotFound(err) && create { - record := syntheticEvidence{ - SchemaVersion: 1, MachineNamespace: machine.Namespace, MachineName: machine.Name, - MachineUID: machine.UID, Location: r.Options.LocationName, ObservedAt: r.Now().UTC(), - Hardware: fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}}, - } - data, marshalErr := json.Marshal(record) - if marshalErr != nil { - return syntheticEvidence{}, marshalErr - } - secret = corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: r.Options.PrivateNamespace, Labels: map[string]string{"fleet.datumapis.com/private-record": "synthetic-evidence"}}, Data: map[string][]byte{"record.json": data}} - if createErr := r.Client.Create(ctx, &secret); apierrors.IsAlreadyExists(createErr) { - return r.loadEvidence(ctx, machine, false) - } else if createErr != nil { - return syntheticEvidence{}, createErr - } - return record, nil - } - if err != nil { - return syntheticEvidence{}, err - } - var record syntheticEvidence - if jsonErr := json.Unmarshal(secret.Data["record.json"], &record); jsonErr != nil { - return syntheticEvidence{}, fmt.Errorf("decode retained synthetic evidence: %w", jsonErr) - } - if record.SchemaVersion != 1 || record.MachineNamespace != machine.Namespace || record.MachineName != machine.Name || record.MachineUID != machine.UID || record.Location != r.Options.LocationName || record.ObservedAt.IsZero() || record.ObservedAt.After(r.Now()) || r.Now().Sub(record.ObservedAt) > r.Options.EvidenceAge || record.Hardware.CPU.Architecture != "amd64" || record.Hardware.CPU.Cores != 24 || record.Hardware.Memory.Capacity != "128Gi" { - return syntheticEvidence{}, fmt.Errorf("%w: retained synthetic evidence differs from configured fixture", controller.ErrRecordInvalid) - } - return record, nil -} - -func evidenceName(uid types.UID) string { - sum := sha256.Sum256([]byte(uid)) - return "fleet-evidence-" + hex.EncodeToString(sum[:8]) -} - func condition(t string, s metav1.ConditionStatus, g int64, reason, message string) metav1.Condition { return metav1.Condition{Type: t, Status: s, ObservedGeneration: g, LastTransitionTime: metav1.Now(), Reason: reason, Message: message} } -func imageDigest(value string) string { - for i := 0; i < len(value); i++ { - if value[i] == '@' { - return value[i+1:] - } - } - return "" -} + func contains(v []string, w string) bool { for _, x := range v { if x == w { @@ -430,6 +442,7 @@ func contains(v []string, w string) bool { } return false } + func remove(v []string, w string) []string { out := v[:0] for _, x := range v { diff --git a/internal/standalone/runner_test.go b/internal/standalone/runner_test.go deleted file mode 100644 index 9b6c39d5..00000000 --- a/internal/standalone/runner_test.go +++ /dev/null @@ -1,278 +0,0 @@ -package standalone - -import ( - "context" - "encoding/json" - "errors" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/simulator" -) - -type storeExecutor struct{ store *simulator.Store } - -type deleteCaptureClient struct { - client.Client - options *client.DeleteOptions -} - -type conflictOnceClient struct { - client.Client - remaining int -} - -type recreateOnDeleteClient struct{ client.Client } - -func (c *recreateOnDeleteClient) Delete(ctx context.Context, object client.Object, opts ...client.DeleteOption) error { - if err := c.Client.Delete(ctx, object, opts...); err != nil { - return err - } - replacement := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: object.GetNamespace(), Name: object.GetName(), UID: "replacement-uid"}} - return c.Client.Create(ctx, replacement) -} - -func (c *conflictOnceClient) Update(ctx context.Context, object client.Object, opts ...client.UpdateOption) error { - if c.remaining > 0 { - if _, ok := object.(*fleetv1.Machine); ok { - c.remaining-- - return apierrors.NewConflict(schema.GroupResource{Group: fleetv1.GroupVersion.Group, Resource: "machines"}, object.GetName(), errors.New("injected conflict")) - } - } - return c.Client.Update(ctx, object, opts...) -} - -func (c *deleteCaptureClient) Delete(ctx context.Context, object client.Object, opts ...client.DeleteOption) error { - c.options = (&client.DeleteOptions{}).ApplyOptions(opts) - return c.Client.Delete(ctx, object, opts...) -} - -func (e storeExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { - result, _, err := e.store.Submit(request) - return result.ResultView(), err -} -func (e storeExecutor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { - result, found := e.store.Get(id) - return result.ResultView(), found, nil -} - -func TestPhasesKeepExclusiveCustodyAndRecoverInstallation(t *testing.T) { - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - options := DefaultOptions() - objects := fixtureObjects(options) - base := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}, &fleetv1.Installation{}).Build() - kube := &deleteCaptureClient{Client: base} - statePath := t.TempDir() + "/state.json" - store, err := simulator.Open(statePath) - if err != nil { - t.Fatal(err) - } - now := time.Now().UTC().Truncate(time.Second) - runner := Runner{Client: kube, Executor: storeExecutor{store}, Options: options, Now: func() time.Time { return now }} - if err := runner.Run(context.Background(), PhaseAllocate); err != nil { - t.Fatal(err) - } - var first, second fleetv1.Machine - if err := kube.Get(context.Background(), types.NamespacedName{Namespace: options.FirstNamespace, Name: options.ClaimName}, &first); err != nil { - t.Fatal(err) - } - if err := kube.Get(context.Background(), types.NamespacedName{Namespace: options.SecondNamespace, Name: options.ClaimName}, &second); err != nil { - t.Fatal(err) - } - if first.Status.Phase != "Ready" || second.Status.Phase != "Pending" { - t.Fatalf("unexpected contention result: first=%s second=%s", first.Status.Phase, second.Status.Phase) - } - if first.Status.Placement == nil || first.Status.Placement.LocationRef.Name != options.LocationName || first.Status.AllocatedHardware == nil || first.Status.AllocatedHardware.ObservedAt == nil || !first.Status.AllocatedHardware.ObservedAt.Time.Equal(now) { - t.Fatalf("claim did not project exact retained location/evidence: %#v", first.Status) - } - for _, claim := range []fleetv1.Machine{first, second} { - if requested := claim.Status.RequestedHardware; requested == nil || requested.CPU.Cores != 24 || requested.Memory.Capacity != "128Gi" || requested.Source.ProfileRef.Name != options.ProfileName { - t.Fatalf("%s did not pin the exact requested hardware: %#v", claim.Namespace, requested) - } - } - waitingRequest := *second.Status.RequestedHardware - var evidenceSecret corev1.Secret - if err := kube.Get(context.Background(), client.ObjectKey{Namespace: options.PrivateNamespace, Name: evidenceName("machine-uid")}, &evidenceSecret); err != nil { - t.Fatal(err) - } - var evidence syntheticEvidence - if err := json.Unmarshal(evidenceSecret.Data["record.json"], &evidence); err != nil { - t.Fatal(err) - } - if evidence.Location != options.LocationName || evidence.MachineUID != "machine-uid" || !evidence.ObservedAt.Equal(now) { - t.Fatalf("unexpected retained evidence: %#v", evidence) - } - assertRetainedOwner(t, kube, options, "claim-a-uid", 1) - if err := runner.Run(context.Background(), PhaseInstall); err != nil { - t.Fatal(err) - } - var installed fleetv1.Installation - if err := kube.Get(context.Background(), types.NamespacedName{Namespace: options.FirstNamespace, Name: options.InstallationName}, &installed); err != nil { - t.Fatal(err) - } - if installed.Status.Phase != "Ready" || installed.Status.CompletedAt == nil { - t.Fatalf("installation was not projected: %#v", installed.Status) - } - beforeRestart := store.Snapshot() - if len(beforeRestart.Operations) != 1 { - t.Fatalf("got %d install operations, want 1", len(beforeRestart.Operations)) - } - var installID string - var installBinding string - for id, operation := range beforeRestart.Operations { - installID, installBinding = id, operation.BindingID - if operation.ID != id || operation.Kind != "install" || operation.Epoch != 1 || operation.Phase != "Succeeded" || operation.Result != "installed" || operation.BindingID == "" { - t.Fatalf("unexpected retained install: %#v", operation) - } - } - // Reopen the durable file, rather than reusing in-memory simulator state. - reopened, err := simulator.Open(statePath) - if err != nil { - t.Fatal(err) - } - restarted := Runner{Client: kube, Executor: storeExecutor{reopened}, Options: options, Now: func() time.Time { return now }} - if err := restarted.Run(context.Background(), PhaseInstall); err != nil { - t.Fatal(err) - } - if snapshot := reopened.Snapshot(); len(snapshot.Operations) != 1 || snapshot.Operations[installID] == nil || snapshot.Operations[installID].BindingID != installBinding { - t.Fatalf("restart created %d effects, want 1", len(snapshot.Operations)) - } - if err := restarted.Run(context.Background(), PhaseRelease); err != nil { - t.Fatal(err) - } - if err := kube.Get(context.Background(), types.NamespacedName{Namespace: options.FirstNamespace, Name: options.ClaimName}, &first); !apierrors.IsNotFound(err) { - t.Fatalf("released claim still exists or lookup failed: %v", err) - } - if err := kube.Get(context.Background(), types.NamespacedName{Namespace: options.SecondNamespace, Name: options.ClaimName}, &second); err != nil { - t.Fatal(err) - } - if second.Status.Phase != "Ready" || second.Status.AllocatedHardware == nil || second.Status.AllocatedHardware.Hardware.CPU.Cores != 24 { - t.Fatalf("waiting claim did not acquire released hardware: %#v", second.Status) - } - if second.Status.RequestedHardware == nil || *second.Status.RequestedHardware != waitingRequest { - t.Fatalf("allocation rewrote the pinned request: %#v", second.Status.RequestedHardware) - } - if kube.options == nil || kube.options.Preconditions == nil || kube.options.Preconditions.UID == nil || *kube.options.Preconditions.UID != "claim-a-uid" || kube.options.Preconditions.ResourceVersion == nil { - t.Fatalf("claim delete lacked exact UID/resourceVersion preconditions: %#v", kube.options) - } - if snapshot := reopened.Snapshot(); len(snapshot.Operations) != 2 { - t.Fatalf("release produced %d total effects, want install plus cleanup", len(snapshot.Operations)) - } else { - for id, operation := range snapshot.Operations { - if id == installID { - continue - } - if operation.ID != id || operation.Kind != "cleanup" || operation.BindingID != installBinding || operation.Epoch != 1 || operation.Phase != "Succeeded" || operation.Result != "clean" { - t.Fatalf("unexpected retained cleanup: %#v", operation) - } - } - } - assertRetainedOwner(t, kube, options, "claim-b-uid", 2) -} - -func assertRetainedOwner(t *testing.T, kube client.Client, options Options, claimUID types.UID, epoch int64) { - t.Helper() - var secrets corev1.SecretList - if err := kube.List(context.Background(), &secrets, client.InNamespace(options.PrivateNamespace), client.MatchingLabels{"fleet.datumapis.com/private-record": "asset"}); err != nil { - t.Fatal(err) - } - if len(secrets.Items) != 1 { - t.Fatalf("got %d retained assets, want 1", len(secrets.Items)) - } - var record controller.AssetRecord - if err := json.Unmarshal(secrets.Items[0].Data["record.json"], &record); err != nil { - t.Fatal(err) - } - if record.ClaimUID != claimUID || record.Epoch != int64(epoch) || record.BindingID == "" { - t.Fatalf("unexpected retained owner: %#v", record) - } -} - -func TestFinalizerRemovalRejectsRecreatedClaimAndRetriesConflict(t *testing.T) { - scheme := runtime.NewScheme() - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - key := client.ObjectKey{Namespace: "project", Name: "allocation"} - recreated := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: key.Namespace, Name: key.Name, UID: "new-uid", Finalizers: []string{controller.MachineFinalizer}}} - base := fake.NewClientBuilder().WithScheme(scheme).WithObjects(recreated).Build() - runner := Runner{Client: base} - if err := runner.removeExactFinalizer(context.Background(), key, "old-uid"); !errors.Is(err, controller.ErrRecordInvalid) { - t.Fatalf("recreated claim error = %v", err) - } - var current fleetv1.Machine - if err := base.Get(context.Background(), key, ¤t); err != nil { - t.Fatal(err) - } - if !contains(current.Finalizers, controller.MachineFinalizer) { - t.Fatal("recreated claim finalizer was removed") - } - - current.UID = "exact-uid" - if err := base.Update(context.Background(), ¤t); err != nil { - t.Fatal(err) - } - conflicting := &conflictOnceClient{Client: base, remaining: 1} - runner.Client = conflicting - if err := runner.removeExactFinalizer(context.Background(), key, "exact-uid"); err != nil { - t.Fatal(err) - } - if conflicting.remaining != 0 { - t.Fatal("conflict was not exercised") - } - if err := base.Get(context.Background(), key, ¤t); err != nil { - t.Fatal(err) - } - if contains(current.Finalizers, controller.MachineFinalizer) { - t.Fatal("exact claim finalizer remained after retry") - } -} - -func TestExactDeletionRejectsNameRecreation(t *testing.T) { - scheme := runtime.NewScheme() - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "project", Name: "allocation", UID: "original-uid", ResourceVersion: "1"}} - base := fake.NewClientBuilder().WithScheme(scheme).WithObjects(claim).Build() - runner := Runner{Client: &recreateOnDeleteClient{Client: base}} - if err := runner.requestExactDeletion(context.Background(), claim, "original-uid", claim.ResourceVersion); !errors.Is(err, controller.ErrRecordInvalid) { - t.Fatalf("recreation error = %v", err) - } - var current fleetv1.Machine - if err := base.Get(context.Background(), client.ObjectKeyFromObject(claim), ¤t); err != nil { - t.Fatal(err) - } - if current.UID != "replacement-uid" { - t.Fatalf("replacement UID = %q", current.UID) - } -} - -func fixtureObjects(o Options) []client.Object { - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: o.ClassName, UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: o.ProviderNamespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/pool": "central"}}}}}} - cores := int64(24) - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: o.ProfileName, UID: "profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: cores}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - machine := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: o.ProviderNamespace, Name: o.MachineName, UID: "machine-uid", Generation: 1, Labels: map[string]string{"fleet.datumapis.com/pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "asset-central-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-clean"}, ReclaimPolicy: "Retain"}} - claim := func(ns, uid string) *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: o.ClaimName, UID: types.UID(uid), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: o.ClassName}, MachineProfileRef: fleetv1.LocalReference{Name: o.ProfileName}, LocationRef: fleetv1.LocalReference{Name: o.LocationName}, PowerState: "Off"}} - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: o.FirstNamespace, Name: o.InstallationName, UID: "installation-uid", Generation: 1}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: o.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: o.ImageName}}} - return []client.Object{&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: o.PrivateNamespace, UID: "private-uid"}}, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: o.ProviderNamespace, UID: "provider-uid"}}, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: o.FirstNamespace, UID: "project-a-uid"}}, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: o.SecondNamespace, UID: "project-b-uid"}}, class, profile, machine, claim(o.FirstNamespace, "claim-a-uid"), claim(o.SecondNamespace, "claim-b-uid"), installation} -} diff --git a/internal/tenancy/tenancy.go b/internal/tenancy/tenancy.go new file mode 100644 index 00000000..96804576 --- /dev/null +++ b/internal/tenancy/tenancy.go @@ -0,0 +1,135 @@ +// Package tenancy resolves a Metal consumer from its typed reference. The +// allocator, release, quota, the Machine status projector, staging and the +// standalone mode reach a consumer only through a Resolver, so standalone +// and managed consumers share one allocation and installation contract. +package tenancy + +import ( + "context" + "errors" + "fmt" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +// The consumer kinds Fleet supports: a Milo Project, and a Namespace, which +// stands in for a project in the standalone mode. +const ( + ProjectGroup = "resourcemanager.miloapis.com" + ProjectKind = "Project" + NamespaceKind = "Namespace" +) + +// ErrUnsupportedConsumer means a reference names a consumer kind Fleet does +// not serve. +var ErrUnsupportedConsumer = errors.New("tenancy: unsupported consumer kind") + +// ErrConsumerUnavailable means the consumer cannot be reached now. +var ErrConsumerUnavailable = errors.New("tenancy: consumer unavailable") + +// ErrConsumerGone means the consumer no longer exists. +var ErrConsumerGone = errors.New("tenancy: consumer gone") + +// Incarnation resolves a reference and requires the incarnation it was +// recorded for. A consumer recreated under the same name is ErrConsumerGone +// for the earlier incarnation. +func Incarnation(ctx context.Context, resolver Resolver, ref fleetv1.TypedReference, uid types.UID) (Consumer, error) { + consumer, err := resolver.Resolve(ctx, ref) + if err != nil { + return Consumer{}, err + } + if consumer.UID != uid { + return Consumer{}, fmt.Errorf("%w: %s %s was recreated", ErrConsumerGone, ref.Kind, ref.Name) + } + return consumer, nil +} + +// Project is the reference to a Milo Project. +func Project(name string) fleetv1.TypedReference { + return fleetv1.TypedReference{APIGroup: ProjectGroup, Kind: ProjectKind, Name: name} +} + +// Namespace is the reference to a standalone consumer namespace. +func Namespace(name string) fleetv1.TypedReference { + return fleetv1.TypedReference{Kind: NamespaceKind, Name: name} +} + +// Supported refuses a reference to any kind Fleet does not serve, or one +// without a name. +func Supported(ref fleetv1.TypedReference) error { + switch { + case ref.Name == "": + return fmt.Errorf("%w: a consumer reference needs a name", ErrUnsupportedConsumer) + case ref.APIGroup == ProjectGroup && ref.Kind == ProjectKind, ref.APIGroup == "" && ref.Kind == NamespaceKind: + return nil + } + return fmt.Errorf("%w: %s/%s", ErrUnsupportedConsumer, ref.APIGroup, ref.Kind) +} + +// Consumer is one consumer's current incarnation and its API. +type Consumer struct { + // Ref names the consumer. It is the only part recorded in a spec. + Ref fleetv1.TypedReference + // UID is the consumer's incarnation. It goes into names and labels, + // never into a spec. + UID types.UID + // Client reaches the consumer's API, where its Machines live. + Client client.Client +} + +// Resolver resolves a consumer reference to the consumer's current +// incarnation and API. It returns ErrUnsupportedConsumer for a kind it does +// not serve and ErrConsumerUnavailable when it cannot reach the consumer. +type Resolver interface { + Resolve(ctx context.Context, ref fleetv1.TypedReference) (Consumer, error) +} + +// ResolverFunc adapts a function to a Resolver. +type ResolverFunc func(context.Context, fleetv1.TypedReference) (Consumer, error) + +func (f ResolverFunc) Resolve(ctx context.Context, ref fleetv1.TypedReference) (Consumer, error) { + return f(ctx, ref) +} + +// Namespaces resolves standalone consumers: each Namespace in one cluster +// stands in for a project, and its API is that cluster's. +type Namespaces struct { + Client client.Client +} + +func (n Namespaces) Resolve(ctx context.Context, ref fleetv1.TypedReference) (Consumer, error) { + if err := Supported(ref); err != nil { + return Consumer{}, err + } + if ref.Kind != NamespaceKind { + return Consumer{}, fmt.Errorf("%w: the standalone mode serves Namespaces only", ErrUnsupportedConsumer) + } + namespace := &corev1.Namespace{} + if err := n.Client.Get(ctx, client.ObjectKey{Name: ref.Name}, namespace); apierrors.IsNotFound(err) { + return Consumer{}, fmt.Errorf("%w: %v", ErrConsumerGone, err) + } else if err != nil { + return Consumer{}, fmt.Errorf("%w: %v", ErrConsumerUnavailable, err) + } + return Consumer{Ref: ref, UID: namespace.UID, Client: n.Client}, nil +} + +// Fixed resolves only the consumers it lists, each to its one incarnation. +// Any other reference is ErrConsumerGone. +func Fixed(consumers ...Consumer) Resolver { + return ResolverFunc(func(_ context.Context, ref fleetv1.TypedReference) (Consumer, error) { + if err := Supported(ref); err != nil { + return Consumer{}, err + } + for _, consumer := range consumers { + if consumer.Ref == ref { + return consumer, nil + } + } + return Consumer{}, fmt.Errorf("%w: %s %s", ErrConsumerGone, ref.Kind, ref.Name) + }) +} diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 17e913fd..7301d619 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -33,18 +33,22 @@ result reports every required phase `Passed`. These are the acceptance tests of [#174 at `d4d17f9`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server, and Increment B covers the -site side in unit tests. End-to-end coverage arrives in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). +site side in unit tests. Increment C runs allocation, installation, release and +reuse end to end in the standalone smoke. The multi-plane local VM and Redfish +runs use the same code, and verification of both is pending. The remaining +end-to-end failure scenarios arrive in Increment D. See [device +custody](../../docs/development/device-custody.md#tests). | #174 acceptance test | Executable evidence | Current state | | --- | --- | --- | -| Two allocators race for one server; one wins | `TestConcurrency` | Envtest verified; end to end proposed | -| An allocator retries after a lost response and claims no second server | `TestConcurrency` | Envtest verified for the custody claim; naming from the Machine UID arrives in C | +| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner` | Envtest verified; the standalone smoke verifies two consumers contending for one server | +| An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | | A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power | | A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | | A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | | A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | -| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart` | Unit verified; end to end proposed | -| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`, against TLS servers | Unit verified; the emulator lab has no TLS | +| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart` | Unit verified; the multi-plane `delivery-faults` phase replays an assignment below the stored fence, and its verification is pending | +| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`, against TLS servers | Unit verified. The Redfish run's lab BMC serves TLS with a per-run key and workers reach it only through the pin, so a mismatch is not injected there; verification of the run is pending | | Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild` | Envtest verified with a fake site; end to end proposed | | A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery` | Envtest verified; end to end proposed | | No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets` | Role definitions verified; bootstrap stays refused | @@ -52,4 +56,6 @@ site side in unit tests. End-to-end coverage arrives in Increments C and D. See The emulator lab cannot cover BMC TLS key rotation, vendor Redfish behavior, UEFI or real PXE firmware, real disks and wipe assurance, real power reset evidence, clock skew between coordinator and site, more than one site serving -a Device, or a permanently lost site. None of these tests qualifies hardware. +a Device, or a permanently lost site. The multi-plane Milo registers no creator +webhook, so the multi-plane runs do not prove it. None of these tests qualifies +hardware.