diff --git a/README.md b/README.md index 345fddbf..f20e6837 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,9 @@ services. Each subsystem owns its resources and controls changes to them. Fleet is under development. This repository contains the service design, alpha APIs, lifecycle libraries, and synthetic validation environments. Production -integration and real provider support are not complete; the production manager -rejects work that requires those integrations and makes no provider changes. See the +integration and real provider support are not complete. By default the manager +makes no provider changes. An explicitly enrolled [physical site route](docs/operations/site-execution.md#routing-a-providers-physical-devices) +can deliver admitted provider operations through Karmada without enabling customer allocation. See the [implementation status](docs/development/README.md) for the implemented subset and remaining gaps. diff --git a/cmd/fleet-manager/main.go b/cmd/fleet-manager/main.go index c56b3337..33742c2a 100644 --- a/cmd/fleet-manager/main.go +++ b/cmd/fleet-manager/main.go @@ -36,6 +36,7 @@ const leaseName = "fleet-manager.fleet.datumapis.com" type managerFlags struct { configPath, leaderElectionNamespace string + physicalConfig string syntheticStaging bool syntheticProviderURL, syntheticTokenFile, syntheticLocation string @@ -49,6 +50,7 @@ type managerFlags struct { func bindFlags(flags *flag.FlagSet) *managerFlags { f := &managerFlags{} + flags.StringVar(&f.physicalConfig, "physical-site-config", "", "provider custody route to a physical Karmada member") flags.StringVar(&f.configPath, "config", "", "path to the FleetManager configuration file (authority and project discovery)") flags.StringVar(&f.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") @@ -142,42 +144,54 @@ func main() { } 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 { - consumerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticConsumerProjectName) + var physical *physicalSite + if flags.physicalConfig != "" { + physical, err = readPhysicalSite(flags.physicalConfig) must(err) - // 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) - must(err) - if providerProject.SameLifetime(consumerProject) { - must(eventmanager.ErrEventWiringUnavailable) - } + } + if flags.syntheticStaging || physical != nil { + providerName := flags.syntheticProviderProjectName + if providerName == "" { + providerName = flags.syntheticConsumerProjectName + } + if physical != nil { + must(physical.checkScope(flags, providerName)) + providerName = physical.ProviderProject } + providerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, providerName) + must(err) providerConfig, err := projectdiscovery.ProjectRESTConfig(selection.ProjectConfig, providerProject.RouteName) must(err) - allocator, loop, discover, err := syntheticCustody(ctx, scheme, providerConfig, flags) + allocator, loop, discover, err := providerCustody(ctx, scheme, providerConfig, flags, physical) must(err) // Both need the leader lease: one coordinator writes custody. + if physical != nil { + loop.VerifyProvider = func(ctx context.Context) error { + return verifierFor(providerProject).VerifyProject(ctx, providerProject) + } + } must(mgr.GetLocalManager().Add(manager.RunnableFunc(loop.Run))) - 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() - }) + if flags.syntheticStaging { + consumerProject, err := eventmanager.ResolveProjectIdentity(ctx, rootMiloClient, cfg.AuthorityID, flags.syntheticConsumerProjectName) must(err) - template.Provider, template.ProviderProject = providerCluster.GetClient(), providerProject - setupOptions.ProviderProject, setupOptions.ProviderCluster, setupOptions.ProviderVerifier = providerProject, providerCluster, verifierFor(providerProject) - setupOptions.ProviderConsumer = multicluster.ClusterName(consumerProject.RouteName) - must(staging.SetupPublisher(mgr, projects, providerCluster, staging.PublisherOptions{ConsumerProject: consumerProject, ProviderProject: providerProject, ClassName: flags.syntheticPublishedClassName, ProfileName: flags.syntheticPublishedProfileName})) + if flags.syntheticProviderProjectName != "" && providerProject.SameLifetime(consumerProject) { + must(eventmanager.ErrEventWiringUnavailable) + } + must(mgr.GetLocalManager().Add(manager.RunnableFunc(discover))) + template := staging.Handler{Allocator: allocator, Location: flags.syntheticLocation} + if flags.syntheticProviderProjectName != "" { + providerCluster, err := ctrlcluster.New(providerConfig, func(options *ctrlcluster.Options) { + options.Scheme = scheme + options.Cache = eventmanager.ProjectCacheOptions() + }) + must(err) + template.Provider, template.ProviderProject = providerCluster.GetClient(), providerProject + setupOptions.ProviderProject, setupOptions.ProviderCluster, setupOptions.ProviderVerifier = providerProject, providerCluster, verifierFor(providerProject) + setupOptions.ProviderConsumer = multicluster.ClusterName(consumerProject.RouteName) + must(staging.SetupPublisher(mgr, projects, providerCluster, staging.PublisherOptions{ConsumerProject: consumerProject, ProviderProject: providerProject, ClassName: flags.syntheticPublishedClassName, ProfileName: flags.syntheticPublishedProfileName})) + } + setupOptions.HandlersFor = staging.ConsumerHandlers(eventmanager.DefaultHandlers, consumerProject, template) } - setupOptions.HandlersFor = staging.ConsumerHandlers(eventmanager.DefaultHandlers, consumerProject, template) } must(eventmanager.Setup(ctx, mgr, projects, setupOptions)) // Readiness reflects discovery and cache health only. It never depends on diff --git a/cmd/fleet-manager/physical.go b/cmd/fleet-manager/physical.go new file mode 100644 index 00000000..4a7b9cc2 --- /dev/null +++ b/cmd/fleet-manager/physical.go @@ -0,0 +1,93 @@ +package main + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/yaml" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/delivery" +) + +type physicalSite struct { + ProviderProject string `json:"providerProject"` + DeviceNamespace string `json:"deviceNamespace"` + Cell string `json:"cell"` + HubKubeconfig string `json:"hubKubeconfig"` + CoordinatorCertDir string `json:"coordinatorCertDir"` + ReleaseCertDir string `json:"releaseCertDir"` + ProjectorCertDir string `json:"projectorCertDir"` + Devices map[string]types.UID `json:"devices"` +} + +func readPhysicalSite(path string) (*physicalSite, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var config physicalSite + if err := yaml.UnmarshalStrict(data, &config); err != nil { + return nil, err + } + if len(validation.IsDNS1123Label(config.DeviceNamespace)) != 0 || len(validation.IsDNS1123Subdomain(config.ProviderProject)) != 0 || + len(validation.IsDNS1123Label(config.Cell)) != 0 || config.Cell == syntheticSite || len(config.Devices) == 0 { + return nil, errors.New("physical site needs an explicit provider project, namespace, member and nonempty Device enrollment") + } + for _, mount := range []string{config.HubKubeconfig, config.CoordinatorCertDir, config.ReleaseCertDir, config.ProjectorCertDir} { + if !filepath.IsAbs(mount) { + return nil, errors.New("physical site credential mounts must be absolute paths") + } + } + for name, uid := range config.Devices { + if len(validation.IsDNS1123Subdomain(name)) != 0 || strings.TrimSpace(string(uid)) == "" { + return nil, errors.New("physical site requires exact Device names and UIDs") + } + } + return &config, nil +} + +func (config *physicalSite) attach(sites *delivery.Sites, api dynamic.Interface) error { + for name := range config.Devices { + if _, exists := sites.Devices[name]; exists { + return fmt.Errorf("Device %s has overlapping physical and synthetic enrollments", name) + } + } + sites.Sites[config.Cell] = &coordination.Hub{API: api, Namespace: "fleet-coordination", Cell: config.Cell, MaxAge: time.Minute} + sites.DeviceUIDs = config.Devices + for name := range config.Devices { + sites.Devices[name] = []string{config.Cell} + } + return nil +} + +func (config *physicalSite) connect(sites *delivery.Sites) error { + hub, err := clientcmd.BuildConfigFromFlags("", config.HubKubeconfig) + if err != nil { + return err + } + if !strings.HasPrefix(hub.Host, "https://") || hub.Insecure { + return errors.New("physical hub kubeconfig requires verified HTTPS") + } + hub.Timeout = 30 * time.Second + api, err := dynamic.NewForConfig(hub) + if err != nil { + return err + } + return config.attach(sites, api) +} + +func (config *physicalSite) checkScope(flags *managerFlags, provider string) error { + if flags.syntheticStaging && (provider != config.ProviderProject || flags.syntheticDeviceNamespace != config.DeviceNamespace || flags.syntheticCoordinatorCertDir != config.CoordinatorCertDir || flags.syntheticProjectorCertDir != config.ProjectorCertDir || flags.syntheticReleaseCertDir != config.ReleaseCertDir) { + return errors.New("mixed routes require one provider project, Device namespace and set of coordinator, release and projector identities") + } + return nil +} diff --git a/cmd/fleet-manager/physical_test.go b/cmd/fleet-manager/physical_test.go new file mode 100644 index 00000000..22e03bfd --- /dev/null +++ b/cmd/fleet-manager/physical_test.go @@ -0,0 +1,99 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/delivery" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" +) + +const exampleRoute = `providerProject: provider-example +deviceNamespace: inventory +coordinatorCertDir: /credentials/coordinator +releaseCertDir: /credentials/release +projectorCertDir: /credentials/projector +hubKubeconfig: /credentials/hub/config +cell: cell-example +devices: + server-example: 00000000-0000-4000-8000-000000000001 +` + +func routeFile(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "route.yaml") + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + return path +} + +func TestPhysicalEnrollmentRoutesOnlyNamedDeviceLifetime(t *testing.T) { + route, err := readPhysicalSite(routeFile(t, exampleRoute)) + if err != nil { + t.Fatal(err) + } + api := fake.NewSimpleDynamicClient(runtime.NewScheme()) + sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: nil}, Devices: map[string][]string{"fixture": {syntheticSite}}} + if err := route.attach(sites, api); err != nil { + t.Fatal(err) + } + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example", Namespace: "inventory", UID: route.Devices["server-example"]}} + if !slices.Equal(sites.Serving(device), []string{"cell-example"}) { + t.Fatal("physical Device not routed exclusively to member") + } + if _, reported, err := sites.Fence(context.Background(), route.Cell, device); err != nil || reported { + t.Fatalf("missing member observation was not unknown: %v, %v", reported, err) + } + handoff, err := api.Resource(coordination.Resource).Namespace("fleet-coordination").Get(context.Background(), coordination.ReportName("inventory/server-example"), metav1.GetOptions{}) + if err != nil || handoff.GetLabels()[coordination.CellLabel] != route.Cell { + t.Fatalf("missing cell-targeted report intent: %v", err) + } + device.UID = "replacement" + if len(sites.Serving(device)) != 0 { + t.Fatal("replacement inherited route") + } + device.Name = "fixture" + if !slices.Equal(sites.Serving(device), []string{syntheticSite}) { + t.Fatal("synthetic route changed") + } + fixtureSites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: nil}, Devices: map[string][]string{"server-example": {syntheticSite}}} + if err := route.attach(fixtureSites, api); err == nil || len(fixtureSites.Sites) != 1 { + t.Fatal("overlapping enrollment accepted") + } +} + +func TestPhysicalConfigRejectsAmbiguousRoutes(t *testing.T) { + for _, bad := range []string{exampleRoute + "cel: elsewhere\n", exampleRoute + "cell: other\n", strings.Replace(exampleRoute, "cell-example", syntheticSite, 1), strings.Replace(exampleRoute, "server-example:", "inventory/server-example:", 1), strings.Replace(exampleRoute, "/credentials/hub/config", "''", 1)} { + if _, err := readPhysicalSite(routeFile(t, bad)); err == nil { + t.Fatal("accepted invalid config") + } + } + route, err := readPhysicalSite(routeFile(t, exampleRoute)) + if err != nil { + t.Fatal(err) + } + flags := &managerFlags{} + if err := route.checkScope(flags, ""); err != nil { + t.Fatal(err) + } + flags.syntheticStaging = true + if err := route.checkScope(flags, "other"); err == nil { + t.Fatal("mixed provider scopes accepted") + } + flags.syntheticDeviceNamespace = route.DeviceNamespace + flags.syntheticCoordinatorCertDir = route.CoordinatorCertDir + flags.syntheticProjectorCertDir = route.ProjectorCertDir + flags.syntheticReleaseCertDir = route.ReleaseCertDir + if err := route.checkScope(flags, route.ProviderProject); err != nil { + t.Fatal(err) + } +} diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index d6bb8cfe..33bc5eef 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -28,25 +28,20 @@ import ( // syntheticSite is the synthetic provider: the simulator site. const syntheticSite = "synthetic-provider" -// 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 +func providerCustody(ctx context.Context, scheme *runtime.Scheme, providerConfig *rest.Config, flags *managerFlags, physical *physicalSite) (*allocation.Allocator, *delivery.Loop, func(context.Context) error, error) { + namespace, coordinatorDir, releaseDir, projectorDir := flags.syntheticDeviceNamespace, flags.syntheticCoordinatorCertDir, flags.syntheticReleaseCertDir, flags.syntheticProjectorCertDir + if physical != nil { + namespace, coordinatorDir, releaseDir, projectorDir = physical.DeviceNamespace, physical.CoordinatorCertDir, physical.ReleaseCertDir, physical.ProjectorCertDir } - coordinatorConfig, err := withClientCert(providerConfig, flags.syntheticCoordinatorCertDir) + coordinatorConfig, err := withClientCert(providerConfig, coordinatorDir) if err != nil { return nil, nil, nil, fmt.Errorf("custody coordinator credential: %w", err) } - releaseConfig, err := withClientCert(providerConfig, flags.syntheticReleaseCertDir) + releaseConfig, err := withClientCert(providerConfig, releaseDir) if err != nil { return nil, nil, nil, fmt.Errorf("release controller credential: %w", err) } - projectorConfig, err := withClientCert(providerConfig, flags.syntheticProjectorCertDir) + projectorConfig, err := withClientCert(providerConfig, projectorDir) if err != nil { return nil, nil, nil, fmt.Errorf("capacity projector credential: %w", err) } @@ -70,18 +65,30 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi if err != nil { return nil, nil, nil, err } - remote, err := siteapi.NewClient(flags.syntheticProviderURL, func() (string, error) { return readToken(flags.syntheticTokenFile) }, &http.Client{Timeout: 30 * time.Second}) - if err != nil { - return nil, nil, nil, err + sites := &delivery.Sites{Sites: map[string]delivery.Site{}, Devices: map[string][]string{}} + var enrollment fixture.Enrollment + if flags.syntheticStaging { + enrollment, err = readEnrollment(flags.syntheticEnrollmentFile) + if err != nil { + return nil, nil, nil, err + } + remote, err := siteapi.NewClient(flags.syntheticProviderURL, func() (string, error) { return readToken(flags.syntheticTokenFile) }, &http.Client{Timeout: 30 * time.Second}) + if err != nil { + return nil, nil, nil, err + } + sites.Sites[syntheticSite] = remote + for device := range enrollment { + deviceNamespace, name, _ := strings.Cut(device, "/") + if deviceNamespace != namespace { + return nil, nil, nil, fmt.Errorf("enrolled Device %s is outside %s", device, namespace) + } + sites.Devices[name] = []string{syntheticSite} + } } - 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) + if physical != nil { + if err := physical.connect(sites); err != nil { + return nil, nil, nil, err } - sites.Devices[name] = []string{syntheticSite} } principals := custody.Principals{ custody.CreatorMetalProvider: {{Username: providerCreator.Username, UID: providerCreator.UID}}, @@ -97,8 +104,12 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: coordinatorClient, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, OnError: func(err error) { log.Info("coordinator pass incomplete", "error", err.Error()) }} + if !flags.syntheticStaging { + return nil, loop, nil, nil + } allocator := &allocation.Allocator{ - Provider: provider, ProviderCreator: providerCreator, + AllowsDevice: func(name string) bool { _, ok := enrollment[namespace+"/"+name]; return ok }, + Provider: provider, ProviderCreator: providerCreator, Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: coordinator, Namespace: namespace, Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: capacity.Policies(provider, namespace)}, diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index cb6e5ef9..dd134007 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -36,6 +36,54 @@ digest, and `flux-verify` checks the release history records that digest. See ## Topology on the selected cell +### Routing a provider's physical Devices + +`fleet-manager --physical-site-config=/etc/fleet/routes/physical.yaml` attaches one +Karmada member to the provider custody coordinator. The file is read at startup; +the route is off by default. Example (invented identifiers, no credentials): + +```yaml +providerProject: provider-example +deviceNamespace: inventory +cell: cell-example +hubKubeconfig: /credentials/hub/config +coordinatorCertDir: /credentials/coordinator +releaseCertDir: /credentials/release +projectorCertDir: /credentials/projector +devices: + server-example: 00000000-0000-4000-8000-000000000001 +``` + +`devices` maps Device names in `deviceNamespace` to their **Kubernetes UIDs**, +not Redfish System UUIDs. The provider supplies reviewed enrollment, not a +Facility selector. Mount the hub kubeconfig privately and the three separate +Milo client certificate directories (`tls.crt`, `tls.key`). The manager's Milo +project credential identifies the provider. Keep the normal discovery and +leader-lease flags. The provider project lifetime is checked before each pass. +This enables custody and capacity projection, not customer allocation or +fixture discovery. With synthetic staging enabled, use the same provider, +Device namespace and certificate paths: one coordinator serves both transports. +The enrollments must be disjoint; synthetic allocation and discovery use only +the fixture enrollment. Do not retarget a Device with outstanding work or +reuse its journal for another asset; changing configuration is not cancellation. + +Give this coordinator exclusive ownership of the member's handoffs and payloads +in `fleet-coordination`. Install the [coordination CRDs](../../config/multiplane/coordination) +on the hub and member, the [management role and status interpreter](../../config/multiplane/karmada-api) +on the hub, and a [member placement policy](../../config/multiplane/karmada-members/members.yaml) +selecting only `cell`. Use the existing site observer, retained journal and kro +dispatcher. Supply the physical site's own Redfish enrollment, project, trust, +credentials and storage; the [lab graph](../../config/site/redfish/graph) and +its emulator targets are not a physical deployment. No worker needs hub access. + +First verify a `fence-…` report handoff has reached the named member and its +observer's fresh `seen` and `stopped` values have been reflected back. A hub +object alone does not confirm a fence. An absent, foreign or stale report +does not verify custody; a prior failed recovery is not replayed by enabling +a route. Never write a fence, status or worker Job to stand in for this step. +Federated bootstrap payloads remain disabled. This path has not been qualified +on physical hardware. + ```text cell Flux (one source revision, scoped identity per layer) ┌──────────────────┬───────────────────────┬──────────────────────────┐ diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index fa78ec9e..8ff543d0 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -136,6 +136,7 @@ type Request struct { // Allocator allocates, installs and releases on custody. type Allocator struct { + AllowsDevice func(string) bool // Provider is the Metal provider's client to the provider project. It // must read through to the API server. It creates MachineAllocations // and DeviceInstallations. @@ -233,6 +234,9 @@ func (a *Allocator) Get(ctx context.Context, machine Machine) (*fleetv1.MachineA return nil, err } // A same-name Machine or consumer never inherits the allocation. + if a.AllowsDevice != nil && !a.AllowsDevice(allocation.Spec.DeviceRef.Name) { + return nil, ErrConflict + } 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 } @@ -423,6 +427,9 @@ func (a *Allocator) candidate(ctx context.Context, request Request, tried map[st var uncovered error for index := range capacities.Items { capacity := &capacities.Items[index] + if a.AllowsDevice != nil && !a.AllowsDevice(capacity.Spec.DeviceRef.Name) { + continue + } if tried[capacity.Name] || capacity.Spec.AllocationPolicy != "Enabled" || !capacity.DeletionTimestamp.IsZero() || !selector.Matches(labels.Set(capacity.Labels)) { continue } diff --git a/internal/allocation/candidate_test.go b/internal/allocation/candidate_test.go index 90ebacfd..b08c2add 100644 --- a/internal/allocation/candidate_test.go +++ b/internal/allocation/candidate_test.go @@ -23,6 +23,23 @@ type offersExcept struct { evaluated []string } +func TestCandidateExcludesDevicesOutsideAllocatorEnrollment(t *testing.T) { + provider, request := candidates(t) + allocator := &Allocator{Namespace: namespace, Provider: provider, Capacity: offersAll{}, AllowsDevice: func(name string) bool { return name == "server-b" }} + _, device, _, err := allocator.candidate(context.Background(), request, nil) + if err != nil || device.Name != "server-b" { + t.Fatalf("selected %v: %v", device, err) + } + record := &fleetv1.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: Name(machine(1))}, Spec: fleetv1.MachineAllocationSpec{DeviceRef: fleetv1.AllocatedDeviceReference{Name: "server-a"}, ConsumerRef: machine(1).Consumer, MachineRef: machine(1).reference()}} + record.Labels = map[string]string{fleetv1.LabelMachineUID: string(machine(1).UID), fleetv1.LabelConsumerUID: string(machine(1).ConsumerUID)} + if err := provider.Create(context.Background(), record); err != nil { + t.Fatal(err) + } + if _, err := allocator.Get(context.Background(), machine(1)); !errors.Is(err, ErrConflict) { + t.Fatalf("resumed allocation outside enrollment: %v", err) + } +} + func (o *offersExcept) Offer(ctx context.Context, capacity *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) { o.evaluated = append(o.evaluated, capacity.Name) if o.fail[capacity.Name] { diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index fc1427ec..01d79d1c 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -14,6 +14,7 @@ import ( "time" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" @@ -47,7 +48,8 @@ type Site interface { type Sites struct { Sites map[string]Site // Devices maps a Device name to the names of the sites serving it. - Devices map[string][]string + Devices map[string][]string + DeviceUIDs map[string]types.UID } // DeliveryMethods reads the site's own declaration, from its enrollment, as @@ -66,6 +68,9 @@ var ( ) func (s *Sites) Serving(device *inventory.Device) []string { + if uid, pinned := s.DeviceUIDs[device.Name]; pinned && uid != device.UID { + return nil + } var out []string for _, name := range s.Devices[device.Name] { if _, ok := s.Sites[name]; ok { @@ -198,6 +203,9 @@ func (c *Courier) Deliver(ctx context.Context, name string) error { if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, device); err != nil { return err } + if uid, pinned := c.Sites.DeviceUIDs[name]; pinned && (device.UID != uid || state.Labels[ops.LabelDeviceUID] != string(uid)) { + return errors.New("delivery: custody and Device must match the enrolled incarnation") + } var failed error for _, serving := range c.Sites.Serving(device) { if err := c.Sites.Sites[serving].Deliver(ctx, assignment, payload); err != nil { @@ -264,6 +272,21 @@ func (c *Courier) Collect(ctx context.Context) error { continue } for _, stored := range held { + if stored.Device != c.Namespace+"/"+stored.Result.Device || !slices.Contains(c.Sites.Devices[stored.Result.Device], name) { + failed = errors.Join(failed, fmt.Errorf("result from %s is outside its Device enrollment", name)) + continue + } + if _, pinned := c.Sites.DeviceUIDs[stored.Result.Device]; pinned { + device := &inventory.Device{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: stored.Result.Device}, device); err != nil { + failed = errors.Join(failed, err) + continue + } + if !slices.Contains(c.Sites.Serving(device), name) { + failed = errors.Join(failed, errors.New("result Device no longer matches enrollment")) + continue + } + } // The site names itself; the coordinator records the site it // asked. stored.Result.Site = name @@ -283,10 +306,11 @@ func (c *Courier) Collect(ctx context.Context) error { // delivers active operations, collects results, projects capacity status and // sweeps retention. type Loop struct { - Client client.Reader - Coordinator *custody.Coordinator - Courier *Courier - Namespace string + VerifyProvider func(context.Context) error + 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. @@ -305,6 +329,11 @@ const maxSteps = 32 // Pass reconciles each Device until it settles, delivers, and collects. func (l *Loop) Pass(ctx context.Context) error { + if l.VerifyProvider != nil { + if err := l.VerifyProvider(ctx); err != nil { + return err + } + } names := map[string]bool{} var devices inventory.DeviceList if err := l.Client.List(ctx, &devices, client.InNamespace(l.Namespace)); err != nil { diff --git a/internal/delivery/delivery_test.go b/internal/delivery/delivery_test.go index 18598c0c..3a442ef1 100644 --- a/internal/delivery/delivery_test.go +++ b/internal/delivery/delivery_test.go @@ -3,6 +3,7 @@ package delivery import ( "context" "encoding/json" + "errors" "fmt" "testing" @@ -78,6 +79,32 @@ type siteWith struct { carries bool } +type foreignResultSite struct { + Site + held site.Stored +} + +func (remote foreignResultSite) Results(context.Context) ([]site.Stored, error) { + return []site.Stored{remote.held}, nil +} + +func TestForeignResultsNeverReachCustodyOrGetAcknowledged(t *testing.T) { + for _, held := range []site.Stored{{Device: "default/physical", Result: custody.SiteResult{Device: "physical"}}, {Device: "elsewhere/fixture", Result: custody.SiteResult{Device: "fixture"}}, {Device: "default/fixture", Result: custody.SiteResult{Device: "physical"}}} { + courier := Courier{Namespace: "default", Sites: &Sites{Devices: map[string][]string{"physical": {"cell"}, "fixture": {"sim"}}, Sites: map[string]Site{"sim": foreignResultSite{held: held}}}} + if err := courier.Collect(context.Background()); err == nil { + t.Fatal("accepted foreign result") + } + } +} + +func TestProviderIdentityFailureStopsPassBeforeIO(t *testing.T) { + unavailable := errors.New("provider lifetime unavailable") + loop := Loop{VerifyProvider: func(context.Context) error { return unavailable }} + if err := loop.Pass(context.Background()); !errors.Is(err, unavailable) { + t.Fatal(err) + } +} + func (s siteWith) CarriesPayloads() bool { return s.carries } func TestADeviceCarriesPayloadsOnlyIfEverySiteServingItDoes(t *testing.T) {