From fb6525a6356f96961ff4c42d36d54753b96d83a2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 16:31:45 -0600 Subject: [PATCH 1/8] feat(inventory): add the physical inventory API in Milo Add the fleet.datumapis.com/v1alpha1 inventory kinds: Facility, Rack, DeviceClaim, Device, Cable and PowerFeed, the Manufacturer and DeviceType hardware catalog, and the observational Site. config/milo registers their CRDs, ProtectedResources and the viewer, editor, manager and importer roles; the management-cluster roots install none of them. The records are operator-written and observational. No controller reads them, and creating one provisions nothing, publishes no capacity and establishes no readiness. CEL keeps Device identity and claim binding immutable, rejects ambiguous MACs and credential-bearing BMC endpoints, and validates faceplate layouts within the per-call cost limit. config/inventory renders the CRDs alone for an environment that installed them on the management cluster before Milo became their home. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .../inventory/crds/fleet.datumapis.com.yaml | 1392 +++++++++++++++++ .../inventory/crds/kustomization.yaml | 3 + .../components/inventory/kustomization.yaml | 6 + .../inventory/protected-resources/cable.yaml | 21 + .../inventory/protected-resources/device.yaml | 14 + .../protected-resources/deviceclaim.yaml | 14 + .../protected-resources/devicetype.yaml | 21 + .../protected-resources/facility.yaml | 21 + .../protected-resources/kustomization.yaml | 12 + .../protected-resources/manufacturer.yaml | 21 + .../protected-resources/powerfeed.yaml | 21 + .../inventory/protected-resources/rack.yaml | 21 + .../inventory/protected-resources/site.yaml | 21 + config/components/inventory/roles/editor.yaml | 48 + .../components/inventory/roles/importer.yaml | 30 + .../inventory/roles/kustomization.yaml | 7 + .../components/inventory/roles/manager.yaml | 39 + config/components/inventory/roles/viewer.yaml | 37 + config/inventory/kustomization.yaml | 4 + config/milo/kustomization.yaml | 1 + hack/testdata/physical/manual.yaml | 70 + internal/api/inventory/v1alpha1/capacity.go | 30 + internal/api/inventory/v1alpha1/catalog.go | 155 ++ .../v1alpha1/catalog_envtest_test.go | 144 ++ .../api/inventory/v1alpha1/catalog_test.go | 192 +++ internal/api/inventory/v1alpha1/crd_test.go | 432 +++++ .../api/inventory/v1alpha1/depth_face_test.go | 72 + .../v1alpha1/faceplate_envtest_test.go | 128 ++ .../api/inventory/v1alpha1/faceplate_test.go | 295 ++++ internal/api/inventory/v1alpha1/iam_test.go | 178 +++ .../api/inventory/v1alpha1/lifecycle_test.go | 78 + internal/api/inventory/v1alpha1/physical.go | 219 +++ .../api/inventory/v1alpha1/physical_test.go | 170 ++ .../v1alpha1/reported_placement_test.go | 201 +++ .../v1alpha1/site_facility_name_test.go | 15 + .../api/inventory/v1alpha1/site_reader.go | 31 + internal/api/inventory/v1alpha1/site_test.go | 215 +++ internal/api/inventory/v1alpha1/types.go | 238 +++ .../inventory/v1alpha1/unidentified_test.go | 187 +++ 40 files changed, 4805 insertions(+) create mode 100644 config/components/inventory/crds/fleet.datumapis.com.yaml create mode 100644 config/components/inventory/crds/kustomization.yaml create mode 100644 config/components/inventory/kustomization.yaml create mode 100644 config/components/inventory/protected-resources/cable.yaml create mode 100644 config/components/inventory/protected-resources/device.yaml create mode 100644 config/components/inventory/protected-resources/deviceclaim.yaml create mode 100644 config/components/inventory/protected-resources/devicetype.yaml create mode 100644 config/components/inventory/protected-resources/facility.yaml create mode 100644 config/components/inventory/protected-resources/kustomization.yaml create mode 100644 config/components/inventory/protected-resources/manufacturer.yaml create mode 100644 config/components/inventory/protected-resources/powerfeed.yaml create mode 100644 config/components/inventory/protected-resources/rack.yaml create mode 100644 config/components/inventory/protected-resources/site.yaml create mode 100644 config/components/inventory/roles/editor.yaml create mode 100644 config/components/inventory/roles/importer.yaml create mode 100644 config/components/inventory/roles/kustomization.yaml create mode 100644 config/components/inventory/roles/manager.yaml create mode 100644 config/components/inventory/roles/viewer.yaml create mode 100644 config/inventory/kustomization.yaml create mode 100644 hack/testdata/physical/manual.yaml create mode 100644 internal/api/inventory/v1alpha1/capacity.go create mode 100644 internal/api/inventory/v1alpha1/catalog.go create mode 100644 internal/api/inventory/v1alpha1/catalog_envtest_test.go create mode 100644 internal/api/inventory/v1alpha1/catalog_test.go create mode 100644 internal/api/inventory/v1alpha1/crd_test.go create mode 100644 internal/api/inventory/v1alpha1/depth_face_test.go create mode 100644 internal/api/inventory/v1alpha1/faceplate_envtest_test.go create mode 100644 internal/api/inventory/v1alpha1/faceplate_test.go create mode 100644 internal/api/inventory/v1alpha1/iam_test.go create mode 100644 internal/api/inventory/v1alpha1/lifecycle_test.go create mode 100644 internal/api/inventory/v1alpha1/physical.go create mode 100644 internal/api/inventory/v1alpha1/physical_test.go create mode 100644 internal/api/inventory/v1alpha1/reported_placement_test.go create mode 100644 internal/api/inventory/v1alpha1/site_facility_name_test.go create mode 100644 internal/api/inventory/v1alpha1/site_reader.go create mode 100644 internal/api/inventory/v1alpha1/site_test.go create mode 100644 internal/api/inventory/v1alpha1/types.go create mode 100644 internal/api/inventory/v1alpha1/unidentified_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 848551a1..0258703b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: - run: kustomize build config/milo >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null + - run: kustomize build config/inventory >/dev/null - run: ./hack/validate-synthetic-staging-render.sh - run: ./hack/validate-overlay-isolation.sh - run: ./hack/test-overlay-isolation.sh diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml new file mode 100644 index 00000000..49936808 --- /dev/null +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -0,0 +1,1392 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceclaims.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceClaim + listKind: DeviceClaimList + plural: deviceclaims + singular: deviceclaim + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Facility + type: string + jsonPath: .spec.placement.facility + - name: Rack + type: string + jsonPath: .spec.placement.rack + - name: Position + type: integer + jsonPath: .spec.placement.position + - name: Model + type: string + jsonPath: .spec.expectedIdentity.model + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - expectedIdentity + - placement + x-kubernetes-validations: + - rule: has(self.lifecycle) == has(oldSelf.lifecycle) + message: legacy claims cannot be reinterpreted as installations + - rule: '!has(self.lifecycle) || self.placement == oldSelf.placement' + message: installation placement is immutable; migration requires an explicit handover + - rule: '!has(self.lifecycle) || !has(self.ports) || self.ports.all(p, !has(p.expectedPeer))' + message: Cable is the only expected topology authority for installations + - rule: has(self.lifecycle) == has(self.placement.scope) + message: typed placement requires an installation lifecycle; legacy slots keep their text placement + properties: + expectedIdentity: + type: object + required: + - model + properties: + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 + placement: + type: object + properties: + facility: + type: string + minLength: 1 + maxLength: 253 + rack: + type: string + minLength: 1 + maxLength: 253 + position: + type: integer + format: int32 + minimum: 1 + maximum: 100 + height: + type: integer + format: int32 + minimum: 1 + maximum: 100 + face: + type: string + enum: + - front + - rear + scope: + type: string + enum: + - Facility + - RackMembership + - RackUnits + - NonRackUnitMount + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + mount: + type: string + minLength: 1 + maxLength: 253 + x-kubernetes-validations: + - rule: 'has(self.scope) ? (!has(self.facility) && !has(self.rack)) : (has(self.facility) && has(self.rack) + && has(self.position) && has(self.face) && !has(self.facilityRef) && !has(self.rackRef) && !has(self.mount))' + message: choose legacy text placement or typed placement, never both + - rule: '!has(self.scope) || (self.scope == ''Facility'' ? (has(self.facilityRef) && !has(self.rackRef)) + : (has(self.rackRef) && !has(self.facilityRef)))' + message: typed placement requires exactly the reference appropriate to its scope + - rule: '!has(self.scope) || (self.scope == ''RackUnits'' ? (has(self.position) && has(self.height) + && has(self.face) && !has(self.mount)) : (!has(self.position) && !has(self.height) && !has(self.face) + && (self.scope == ''NonRackUnitMount'' ? has(self.mount) : !has(self.mount))))' + message: partial placement cannot assert rack units; non-unit mounts require a mount identifier + ports: + type: array + maxItems: 128 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 63 + type: + type: string + maxLength: 253 + speedMbps: + type: integer + format: int64 + minimum: 1 + expectedPeer: + type: object + required: + - device + - port + properties: + device: + type: string + minLength: 1 + maxLength: 253 + port: + type: string + minLength: 1 + maxLength: 253 + lifecycle: + type: string + enum: + - Installation + cableRefs: + type: array + maxItems: 256 + items: *id001 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + displayName: + type: string + minLength: 1 + maxLength: 253 + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devices.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Device + listKind: DeviceList + plural: devices + singular: device + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Claim + type: string + jsonPath: .spec.claimRef.name + - name: Model + type: string + jsonPath: .spec.identity.model + - name: Serial + type: string + jsonPath: .spec.identity.serial + - name: Lifecycle + type: string + jsonPath: .spec.lifecycle + - name: System UUID + type: string + priority: 1 + jsonPath: .spec.identity.systemUUID + - name: Unidentified + type: boolean + priority: 1 + jsonPath: .spec.identity.unidentified + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - claimRef + - identity + x-kubernetes-validations: + - rule: self.claimRef == oldSelf.claimRef + message: claimRef is immutable; bind replacement hardware as a new Device + - rule: self.identity == oldSelf.identity + message: identity is immutable; a hardware swap is a new Device + - rule: '!has(self.identity.unidentified) || !has(self.bmc)' + message: a device without hardware identity cannot record a BMC endpoint; it cannot be enrolled as machine capacity + - rule: '!has(oldSelf.deviceTypeRef) || (has(self.deviceTypeRef) && self.deviceTypeRef == oldSelf.deviceTypeRef)' + message: an assigned catalog reference cannot be removed or rebound + - rule: '!has(oldSelf.reportedPlacement) || has(self.reportedPlacement)' + message: retain a report; omit unknown location fields rather than removing the report + - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' + optionalOldSelf: true + message: first report revision must be 1; every changed report must increment revision exactly once + - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, + has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) + || !(a.macAddress in self.unmappedMACAddresses))))' + message: a MAC address may be recorded only once + - rule: '!has(self.topologyAuthority) || !has(self.interfaces) || self.interfaces.all(p, !has(p.peer))' + message: Cable topology excludes inline peers + - rule: '!has(self.components) || has(self.topologyAuthority)' + message: typed components require Cable topology + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, (m.from.componentID + != m.to.componentID || m.from.position != m.to.position) && self.components.exists(c, c.id == m.from.componentID + && m.from.position <= (has(c.positions) ? c.positions : 1)) && self.components.exists(c, c.id == + m.to.componentID && m.to.position <= (has(c.positions) ? c.positions : 1))))' + message: internal mappings must reference present component positions + - rule: '!has(self.internalMappings) || self.internalMappings.all(m, self.internalMappings.filter(n, + n.from == m.from).size() == 1)' + message: each internal source position maps once + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') ? self.components.exists(c, c.id == m.to.componentID + && c.type == ''RearPort'') : (self.components.exists(c, c.id == m.from.componentID && c.type == + ''PowerOutlet'') && self.components.exists(c, c.id == m.to.componentID && c.type == ''PowerInlet''))))' + message: internal paths must map front to rear or power outlet to inlet + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, !self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') || self.internalMappings.filter(n, n.to.componentID + == m.to.componentID && n.to.position == m.to.position).size() == 1))' + message: a pass-through rear position can be mapped only once + - rule: '!has(self.serviceAssociations) || (has(self.components) && self.serviceAssociations.all(a, + self.components.exists(c, c.id == a.componentID)))' + message: service associations must reference present components + - rule: '!has(oldSelf.lifecycle) || oldSelf.lifecycle != ''Retired'' || (has(self.lifecycle) && self.lifecycle + == ''Retired'')' + message: Retired is terminal; a Retired Device cannot change lifecycle + - rule: '!has(self.lifecycle) || self.lifecycle != ''Retired'' || (has(oldSelf.lifecycle) && oldSelf.lifecycle + in [''Decommissioning'', ''Retired''])' + message: move an Active Device to Decommissioning before Retired + properties: + lifecycle: + type: string + enum: [Active, Decommissioning, Retired] + default: Active + deviceTypeRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' + reportedPlacement: + type: object + required: [revision, observedAt, reason, reference] + x-kubernetes-validations: + - rule: '(!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth) && !has(self.mount)) || has(self.rackRef)' + message: rack geometry requires a reported rack + - rule: '!has(self.mount) || (!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth))' + message: non-unit mounts cannot also report unit geometry + - rule: '!has(self.position) || !has(self.height) || self.position + self.height <= 101.0' + message: reported geometry exceeds supported rack bounds + properties: + revision: + type: integer + minimum: 1 + maximum: 2147483647 + reason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + reference: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + observedAt: + type: string + format: date-time + facilityRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + rackRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + position: + type: number + minimum: 1 + maximum: 100 + height: + type: number + minimum: 0 + exclusiveMinimum: true + maximum: 100 + face: + type: string + enum: [front, rear] + fullDepth: + type: boolean + mount: + type: string + minLength: 1 + maxLength: 253 + claimRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + identity: + type: object + required: + - model + x-kubernetes-validations: + - rule: has(self.serial) || has(self.systemUUID) || has(self.unidentified) + message: a device needs a serial or system UUID, or unidentified set to true with a reason + - rule: '!has(self.unidentified) || self.unidentified' + message: unidentified may only be true; omit it when the device has a serial or system UUID + - rule: has(self.unidentified) == has(self.unidentifiedReason) + message: unidentified and unidentifiedReason must be set together + - rule: '!has(self.unidentified) || (!has(self.serial) && !has(self.systemUUID))' + message: an unidentified device cannot carry a serial or system UUID; record identified hardware as a new Device + properties: + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 + systemUUID: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + unidentified: + type: boolean + unidentifiedReason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + bmc: + type: object + required: + - endpoint + properties: + endpoint: + type: string + maxLength: 2048 + x-kubernetes-validations: + - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() + != '' + message: bmc.endpoint must be an https URL without credentials + interfaces: + type: array + maxItems: 32 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 63 + macAddress: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + peer: + type: object + required: + - device + - port + properties: + device: + type: string + minLength: 1 + maxLength: 253 + port: + type: string + minLength: 1 + maxLength: 253 + unmappedMACAddresses: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + assetTag: + type: string + minLength: 1 + maxLength: 253 + providerHostRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + components: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + internalMappings: + type: array + maxItems: 256 + items: + type: object + properties: + from: &id002 + type: object + properties: + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + to: *id002 + required: + - from + - to + serviceAssociations: + type: array + maxItems: 128 + items: + type: object + properties: + serviceRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + componentID: + type: string + minLength: 1 + maxLength: 63 + required: + - serviceRef + - componentID + topologyAuthority: + type: string + enum: + - Cable + displayName: + type: string + minLength: 1 + maxLength: 253 + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + width: + type: string + enum: + - Full + - Half + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: facilities.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Facility + listKind: FacilityList + plural: facilities + singular: facility + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + identifiers: + type: array + maxItems: 64 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [provider, type, value] + items: + type: object + required: [provider, type, value] + properties: + provider: + type: string + minLength: 1 + maxLength: 253 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: + type: string + enum: [PremisesCode, PremisesAlias, PremisesID] + value: + type: string + minLength: 1 + maxLength: 253 + locationRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + required: + - displayName + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: sites.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Site + listKind: SiteList + plural: sites + singular: site + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + code: + type: string + minLength: 1 + maxLength: 64 + facilityRefs: + type: array + maxItems: 64 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name] + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + required: + - displayName + - code + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: racks.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Rack + listKind: RackList + plural: racks + singular: rack + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + facilityRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + heightUnits: + type: integer + minimum: 1 + maximum: 100 + required: + - displayName + - facilityRef + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cables.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Cable + listKind: CableList + plural: cables + singular: cable + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + medium: + type: string + enum: + - Copper + - Fiber + - Power + - Console + - Unknown + lanes: + type: array + maxItems: 64 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + a: &id002 + type: object + properties: + deviceRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + powerFeedRef: *id001 + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + x-kubernetes-validations: + - rule: has(self.deviceRef) != has(self.powerFeedRef) + message: exactly one local endpoint owner is required + b: *id002 + required: + - id + - a + - b + x-kubernetes-validations: + - rule: '!(self.a.componentID == self.b.componentID && self.a.position == self.b.position && ((has(self.a.deviceRef) + && has(self.b.deviceRef) && self.a.deviceRef.name == self.b.deviceRef.name) || (has(self.a.powerFeedRef) + && has(self.b.powerFeedRef) && self.a.powerFeedRef.name == self.b.powerFeedRef.name)))' + message: a cable lane must have different endpoints + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + required: + - displayName + - medium + - lanes + x-kubernetes-validations: + - rule: self.lanes.all(l, self.lanes.filter(m, (m.a.componentID == l.a.componentID && m.a.position == + l.a.position && ((has(m.a.deviceRef) && has(l.a.deviceRef) && m.a.deviceRef.name == l.a.deviceRef.name) + || (has(m.a.powerFeedRef) && has(l.a.powerFeedRef) && m.a.powerFeedRef.name == l.a.powerFeedRef.name))) + || (m.b.componentID == l.a.componentID && m.b.position == l.a.position && ((has(m.b.deviceRef) && + has(l.a.deviceRef) && m.b.deviceRef.name == l.a.deviceRef.name) || (has(m.b.powerFeedRef) && has(l.a.powerFeedRef) + && m.b.powerFeedRef.name == l.a.powerFeedRef.name)))).size() == 1 && self.lanes.filter(m, (m.a.componentID + == l.b.componentID && m.a.position == l.b.position && ((has(m.a.deviceRef) && has(l.b.deviceRef) + && m.a.deviceRef.name == l.b.deviceRef.name) || (has(m.a.powerFeedRef) && has(l.b.powerFeedRef) + && m.a.powerFeedRef.name == l.b.powerFeedRef.name))) || (m.b.componentID == l.b.componentID && m.b.position + == l.b.position && ((has(m.b.deviceRef) && has(l.b.deviceRef) && m.b.deviceRef.name == l.b.deviceRef.name) + || (has(m.b.powerFeedRef) && has(l.b.powerFeedRef) && m.b.powerFeedRef.name == l.b.powerFeedRef.name)))).size() + == 1) + message: each termination position can occur only once in a cable + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: powerfeeds.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: PowerFeed + listKind: PowerFeedList + plural: powerfeeds + singular: powerfeed + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + supply: + type: object + properties: + type: + type: string + enum: + - AC + - DC + - Unknown + voltageV: + type: integer + minimum: 1 + maximum: 100000 + currentA: + type: integer + minimum: 1 + maximum: 100000 + phase: + type: string + enum: + - single-phase + - three-phase + - Unknown + required: + - type + terminations: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + upstreamSources: + type: array + maxItems: 64 + items: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + required: + - displayName + - facilityRef + - terminations + x-kubernetes-validations: + - rule: self.terminations.all(t, t.type == 'PowerOutlet') + message: feed terminations must be power outlets + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: manufacturers.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Manufacturer + listKind: ManufacturerList + plural: manufacturers + singular: manufacturer + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - canonicalName + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + canonicalName: &id001 + type: string + minLength: 1 + maxLength: 253 + pattern: '^[A-Za-z0-9]([ -~]*[!-~])?$' + aliases: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: *id001 + x-kubernetes-validations: + - rule: '!has(self.aliases) || self.aliases.all(a, a.lowerAscii() != self.canonicalName.lowerAscii() + && self.aliases.filter(b, a.lowerAscii() == b.lowerAscii()).size() + == 1)' + message: aliases must be distinct ignoring ASCII case and cannot repeat + the canonical name + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicetypes.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceType + listKind: DeviceTypeList + plural: devicetypes + singular: devicetype + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - manufacturerRef + - model + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + manufacturerRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' + model: + type: string + minLength: 1 + maxLength: 253 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + width: + type: string + enum: + - Full + - Half + faceplate: + type: object + required: + - banks + properties: + banks: + type: array + minItems: 1 + maxItems: 32 + items: + type: object + required: + - id + - face + - rows + - columns + properties: + id: + type: string + minLength: 1 + maxLength: 63 + face: + type: string + enum: + - Front + - Rear + rows: + type: integer + minimum: 1 + maximum: 8 + columns: + type: integer + minimum: 1 + maximum: 64 + offset: + type: number + minimum: 0 + maximum: 1 + cellMM: + type: object + required: + - width + - height + properties: + width: + type: number + minimum: 1 + maximum: 450 + height: + type: number + minimum: 1 + maximum: 400 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + x-kubernetes-validations: + - rule: "['Front', 'Rear'].all(f, self.banks.all(b, b.face != f || has(b.offset)) + || self.banks.all(b, b.face != f || !has(b.offset)))" + message: bank offsets must be set on every bank of a face or on none + componentTemplates: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + face: + type: string + enum: + - Front + - Rear + layout: + type: object + required: + - bank + - row + - column + properties: + bank: + type: string + minLength: 1 + maxLength: 63 + row: + type: integer + minimum: 1 + maximum: 8 + column: + type: integer + minimum: 1 + maximum: 64 + span: + type: integer + minimum: 1 + maximum: 64 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + x-kubernetes-validations: + # The overlap rule below compares every pair of templates. This + # cap keeps its worst runtime cost near 60% of the per-call CEL + # limit; 256 laid-out templates can exceed it. Evaluated first so + # an over-cap object reports the cap, not a cost error. + - rule: self.filter(t, has(t.layout)).size() <= 128 + message: at most 128 templates may carry a layout; leave the rest without + one + - rule: 'self.all(t, !has(t.layout) || self.exists_one(u, has(u.layout) + && u.layout.row == t.layout.row && u.layout.column < t.layout.column + + (has(t.layout.span) ? t.layout.span : 1) && t.layout.column < u.layout.column + + (has(u.layout.span) ? u.layout.span : 1) && u.layout.bank == t.layout.bank))' + message: two templates overlap in one bank row; each cell, including a + span, holds one template + x-kubernetes-validations: + - rule: '!has(self.componentTemplates) || self.componentTemplates.all(t, !has(t.layout) + || has(t.face) && has(self.faceplate) && self.faceplate.banks.exists(b, + b.id == t.layout.bank && b.face == t.face))' + message: a template layout must name a faceplate bank on the template's own + face + - rule: '!has(self.componentTemplates) || !has(self.faceplate) || self.componentTemplates.all(t, + !has(t.layout) || self.faceplate.banks.all(b, b.id != t.layout.bank || + t.layout.row <= b.rows && t.layout.column + (has(t.layout.span) ? t.layout.span + : 1) - 1 <= b.columns))' + message: a template layout, including its span, must fall inside its bank's + rows and columns + - rule: self.manufacturerRef == oldSelf.manufacturerRef && self.model + == oldSelf.model + message: manufacturer and normalized model identity are immutable; displayName + is mutable + status: + type: object diff --git a/config/components/inventory/crds/kustomization.yaml b/config/components/inventory/crds/kustomization.yaml new file mode 100644 index 00000000..1f890b4c --- /dev/null +++ b/config/components/inventory/crds/kustomization.yaml @@ -0,0 +1,3 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [fleet.datumapis.com.yaml] diff --git a/config/components/inventory/kustomization.yaml b/config/components/inventory/kustomization.yaml new file mode 100644 index 00000000..cc727f1c --- /dev/null +++ b/config/components/inventory/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crds + - protected-resources + - roles diff --git a/config/components/inventory/protected-resources/cable.yaml b/config/components/inventory/protected-resources/cable.yaml new file mode 100644 index 00000000..f92364db --- /dev/null +++ b/config/components/inventory/protected-resources/cable.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-cable +spec: + serviceRef: + name: fleet.datumapis.com + kind: Cable + plural: cables + singular: cable + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/device.yaml b/config/components/inventory/protected-resources/device.yaml new file mode 100644 index 00000000..78bdacfa --- /dev/null +++ b/config/components/inventory/protected-resources/device.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-device +spec: + serviceRef: + name: fleet.datumapis.com + kind: Device + plural: devices + singular: device + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/deviceclaim.yaml b/config/components/inventory/protected-resources/deviceclaim.yaml new file mode 100644 index 00000000..2d4cad48 --- /dev/null +++ b/config/components/inventory/protected-resources/deviceclaim.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-deviceclaim +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceClaim + plural: deviceclaims + singular: deviceclaim + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/devicetype.yaml b/config/components/inventory/protected-resources/devicetype.yaml new file mode 100644 index 00000000..8a268545 --- /dev/null +++ b/config/components/inventory/protected-resources/devicetype.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicetype +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceType + plural: devicetypes + singular: devicetype + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/facility.yaml b/config/components/inventory/protected-resources/facility.yaml new file mode 100644 index 00000000..5a84110a --- /dev/null +++ b/config/components/inventory/protected-resources/facility.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-facility +spec: + serviceRef: + name: fleet.datumapis.com + kind: Facility + plural: facilities + singular: facility + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/kustomization.yaml b/config/components/inventory/protected-resources/kustomization.yaml new file mode 100644 index 00000000..b107ad0e --- /dev/null +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - manufacturer.yaml + - devicetype.yaml + - deviceclaim.yaml + - device.yaml + - facility.yaml + - site.yaml + - rack.yaml + - cable.yaml + - powerfeed.yaml diff --git a/config/components/inventory/protected-resources/manufacturer.yaml b/config/components/inventory/protected-resources/manufacturer.yaml new file mode 100644 index 00000000..e5e1f632 --- /dev/null +++ b/config/components/inventory/protected-resources/manufacturer.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-manufacturer +spec: + serviceRef: + name: fleet.datumapis.com + kind: Manufacturer + plural: manufacturers + singular: manufacturer + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/powerfeed.yaml b/config/components/inventory/protected-resources/powerfeed.yaml new file mode 100644 index 00000000..f731d7df --- /dev/null +++ b/config/components/inventory/protected-resources/powerfeed.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-powerfeed +spec: + serviceRef: + name: fleet.datumapis.com + kind: PowerFeed + plural: powerfeeds + singular: powerfeed + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/rack.yaml b/config/components/inventory/protected-resources/rack.yaml new file mode 100644 index 00000000..b1f974aa --- /dev/null +++ b/config/components/inventory/protected-resources/rack.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-rack +spec: + serviceRef: + name: fleet.datumapis.com + kind: Rack + plural: racks + singular: rack + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/site.yaml b/config/components/inventory/protected-resources/site.yaml new file mode 100644 index 00000000..618a9d5f --- /dev/null +++ b/config/components/inventory/protected-resources/site.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-site +spec: + serviceRef: + name: fleet.datumapis.com + kind: Site + plural: sites + singular: site + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/roles/editor.yaml b/config/components/inventory/roles/editor.yaml new file mode 100644 index 00000000..a951878d --- /dev/null +++ b/config/components/inventory/roles/editor.yaml @@ -0,0 +1,48 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-editor + annotations: + kubernetes.io/display-name: Fleet Inventory Editor + kubernetes.io/description: Plan slots and register devices in provider inventory +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/manufacturers.delete + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/devicetypes.delete + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.update + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/sites.delete + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.update + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/deviceclaims.delete + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/devices.delete + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/facilities.delete + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/racks.delete + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/cables.delete + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch + - fleet.datumapis.com/powerfeeds.delete diff --git a/config/components/inventory/roles/importer.yaml b/config/components/inventory/roles/importer.yaml new file mode 100644 index 00000000..54f5e258 --- /dev/null +++ b/config/components/inventory/roles/importer.yaml @@ -0,0 +1,30 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-importer + annotations: + kubernetes.io/display-name: Fleet Inventory Importer + kubernetes.io/description: Create and server-side apply physical inventory records from an external source without deleting them or writing status +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.patch diff --git a/config/components/inventory/roles/kustomization.yaml b/config/components/inventory/roles/kustomization.yaml new file mode 100644 index 00000000..81e649bf --- /dev/null +++ b/config/components/inventory/roles/kustomization.yaml @@ -0,0 +1,7 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - viewer.yaml + - editor.yaml + - manager.yaml + - importer.yaml diff --git a/config/components/inventory/roles/manager.yaml b/config/components/inventory/roles/manager.yaml new file mode 100644 index 00000000..f9f79f74 --- /dev/null +++ b/config/components/inventory/roles/manager.yaml @@ -0,0 +1,39 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-manager + annotations: + kubernetes.io/display-name: Fleet Inventory Manager + kubernetes.io/description: Create and maintain physical inventory records without deletion or operational control +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/sites.create + - fleet.datumapis.com/sites.update + - fleet.datumapis.com/sites.patch + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.update + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch diff --git a/config/components/inventory/roles/viewer.yaml b/config/components/inventory/roles/viewer.yaml new file mode 100644 index 00000000..72e63237 --- /dev/null +++ b/config/components/inventory/roles/viewer.yaml @@ -0,0 +1,37 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-viewer + annotations: + kubernetes.io/display-name: Fleet Inventory Viewer + kubernetes.io/description: View the provider's planned slots and registered devices +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/manufacturers.get + - fleet.datumapis.com/manufacturers.list + - fleet.datumapis.com/manufacturers.watch + - fleet.datumapis.com/devicetypes.get + - fleet.datumapis.com/devicetypes.list + - fleet.datumapis.com/devicetypes.watch + - fleet.datumapis.com/sites.get + - fleet.datumapis.com/sites.list + - fleet.datumapis.com/sites.watch + - fleet.datumapis.com/deviceclaims.list + - fleet.datumapis.com/deviceclaims.get + - fleet.datumapis.com/deviceclaims.watch + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/facilities.get + - fleet.datumapis.com/facilities.list + - fleet.datumapis.com/facilities.watch + - fleet.datumapis.com/racks.get + - fleet.datumapis.com/racks.list + - fleet.datumapis.com/racks.watch + - fleet.datumapis.com/cables.get + - fleet.datumapis.com/cables.list + - fleet.datumapis.com/cables.watch + - fleet.datumapis.com/powerfeeds.get + - fleet.datumapis.com/powerfeeds.list + - fleet.datumapis.com/powerfeeds.watch diff --git a/config/inventory/kustomization.yaml b/config/inventory/kustomization.yaml new file mode 100644 index 00000000..a44f7dd6 --- /dev/null +++ b/config/inventory/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../components/inventory/crds diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index baa07462..0f5a7f84 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -4,3 +4,4 @@ resources: - ../base/crd - ../components/iam - ../components/service-catalog + - ../components/inventory diff --git a/hack/testdata/physical/manual.yaml b/hack/testdata/physical/manual.yaml new file mode 100644 index 00000000..003a7bbf --- /dev/null +++ b/hack/testdata/physical/manual.yaml @@ -0,0 +1,70 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Facility +metadata: + name: example-facility + namespace: default +spec: + displayName: Example premises +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Rack +metadata: + name: example-rack + namespace: default +spec: + displayName: Example rack + facilityRef: {name: example-facility} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: example-installation + namespace: default +spec: + lifecycle: Installation + expectedIdentity: {manufacturer: Example Vendor, model: Example server} + placement: + scope: RackMembership + rackRef: {name: example-rack} + cableRefs: [{name: example-power-cable}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: example-server + namespace: default +spec: + claimRef: {name: example-installation} + identity: + manufacturer: Example Vendor + model: Example server + serial: SYNTHETIC-MANUAL-0001 + topologyAuthority: Cable + components: + - {id: psu-a, name: PSU A input, type: PowerInlet} + - {id: eth0, name: Ethernet 0, type: NetworkPort} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: PowerFeed +metadata: + name: example-feed + namespace: default +spec: + displayName: Example feed + facilityRef: {name: example-facility} + rackRef: {name: example-rack} + terminations: + - {id: outlet-a, name: Outlet A, type: PowerOutlet} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: example-power-cable + namespace: default +spec: + displayName: Example power cable + medium: Power + lanes: + - id: power + a: {powerFeedRef: {name: example-feed}, componentID: outlet-a, position: 1} + b: {deviceRef: {name: example-server}, componentID: psu-a, position: 1} diff --git a/internal/api/inventory/v1alpha1/capacity.go b/internal/api/inventory/v1alpha1/capacity.go new file mode 100644 index 00000000..866e7e15 --- /dev/null +++ b/internal/api/inventory/v1alpha1/capacity.go @@ -0,0 +1,30 @@ +package v1alpha1 + +import "errors" + +var ( + // ErrUnidentifiedDevice means a Device was recorded without hardware + // identity and cannot back MachineCapacity. + ErrUnidentifiedDevice = errors.New("device has no recorded hardware identity and cannot back machine capacity") + // ErrDeviceIdentityMissing means a Device carries neither a serial nor a + // system UUID, for example a legacy record whose only identity was pruned. + ErrDeviceIdentityMissing = errors.New("device has no serial or system UUID and cannot back machine capacity") +) + +// CapacityBackingError reports why a Device cannot back a MachineCapacity, or +// nil when this basic identity check passes. Registration applies additional +// paired-identity, alias, incarnation and authorization checks. Recorded identity +// is matching evidence: a nil result is not verification or allocator eligibility. +func CapacityBackingError(device *Device) error { + if device == nil { + return ErrDeviceIdentityMissing + } + identity := device.Spec.Identity + if identity.Unidentified || identity.UnidentifiedReason != "" { + return ErrUnidentifiedDevice + } + if identity.Serial == "" && identity.SystemUUID == "" { + return ErrDeviceIdentityMissing + } + return nil +} diff --git a/internal/api/inventory/v1alpha1/catalog.go b/internal/api/inventory/v1alpha1/catalog.go new file mode 100644 index 00000000..c2f32d7c --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog.go @@ -0,0 +1,155 @@ +package v1alpha1 + +import ( + "context" + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type ManufacturerSpec struct { + PhysicalMetadata `json:",inline"` + CanonicalName string `json:"canonicalName"` + Aliases []string `json:"aliases,omitempty"` +} + +type ComponentTemplate struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Connector string `json:"connector,omitempty"` + Positions int32 `json:"positions,omitempty"` + // Face is the chassis face the component sits on, relative to the + // chassis and never to the rack. Unset means unknown. A Device component + // inherits it from the template whose ID equals the component ID; there + // is no Device-level override. + Face ChassisFace `json:"face,omitempty"` + // Layout places the template in cells of one faceplate bank on its own + // face. It needs Face and a DeviceType faceplate. Unset means the + // template's position on the face is not recorded; it is never guessed. + Layout *TemplateLayout `json:"layout,omitempty"` +} + +// TemplateLayout is a nominal bank-grid position, never a millimetre +// coordinate. Row and Column are 1-based. Span covers that many columns from +// Column to the right; unset means 1. +type TemplateLayout struct { + Bank string `json:"bank"` + Row int32 `json:"row"` + Column int32 `json:"column"` + Span int32 `json:"span,omitempty"` +} + +// Faceplate is the nominal physical layout of a model's faces as clusters of +// identical cells, such as a 2x12 RJ45 block or a PSU bay. It is catalog data +// only: a Device inherits it through its DeviceType and cannot override it. +// It carries no state. Whether a port is cabled comes from Cable records. +type Faceplate struct { + Banks []FaceplateBank `json:"banks"` +} + +// FaceplateBank is one grid of cells on one chassis face. Offset is the +// bank's left edge as a fraction of the usable face width. On each face it is +// set on every bank or on none; with none, banks flow left to right in list +// order. CellMM sizes module cells, such as PSUs, drive bays and fans; unset +// means readers use the nominal size of the cell's connector. +type FaceplateBank struct { + ID string `json:"id"` + Face ChassisFace `json:"face"` + Rows int32 `json:"rows"` + Columns int32 `json:"columns"` + Offset *float64 `json:"offset,omitempty"` + CellMM *CellSize `json:"cellMM,omitempty"` +} + +// CellSize is a nominal cell size in millimetres. +type CellSize struct { + Width float64 `json:"width"` + Height float64 `json:"height"` +} + +// ChassisFace names a side of the chassis itself. The front is whatever the +// manufacturer calls the front; for many switches that is the port side. +type ChassisFace string + +const ( + ChassisFront ChassisFace = "Front" + ChassisRear ChassisFace = "Rear" +) + +type DeviceTypeSpec struct { + PhysicalMetadata `json:",inline"` + ManufacturerRef LocalReference `json:"manufacturerRef"` + Model string `json:"model"` + ModelShape *ModelShape `json:"modelShape,omitempty"` + ComponentTemplates []ComponentTemplate `json:"componentTemplates,omitempty"` + // Faceplate is optional. Unset means the layout is not recorded, and + // readers show grouped components instead of a drawing. + Faceplate *Faceplate `json:"faceplate,omitempty"` +} + +type Manufacturer struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ManufacturerSpec `json:"spec"` +} + +type ManufacturerList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Manufacturer `json:"items"` +} + +type DeviceType struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceTypeSpec `json:"spec"` +} + +type DeviceTypeList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceType `json:"items"` +} + +func (in *Manufacturer) DeepCopyObject() runtime.Object { + out := new(Manufacturer) + deepCopy(in, out) + return out +} + +func (in *ManufacturerList) DeepCopyObject() runtime.Object { + out := new(ManufacturerList) + deepCopy(in, out) + return out +} + +func (in *DeviceType) DeepCopyObject() runtime.Object { + out := new(DeviceType) + deepCopy(in, out) + return out +} + +func (in *DeviceTypeList) DeepCopyObject() runtime.Object { + out := new(DeviceTypeList) + deepCopy(in, out) + return out +} + +func ReadDeviceCatalog(ctx context.Context, reader client.Reader, device *Device) (*DeviceType, *Manufacturer, error) { + unavailable := fmt.Errorf("hardware catalog unavailable") + if reader == nil || device == nil || device.Namespace == "" || !device.DeletionTimestamp.IsZero() || device.Spec.DeviceTypeRef == nil || device.Spec.DeviceTypeRef.Name == "" { + return nil, nil, unavailable + } + var model DeviceType + if err := reader.Get(ctx, client.ObjectKey{Namespace: device.Namespace, Name: device.Spec.DeviceTypeRef.Name}, &model); err != nil || !model.DeletionTimestamp.IsZero() || model.Spec.ManufacturerRef.Name == "" { + return nil, nil, unavailable + } + var manufacturer Manufacturer + if err := reader.Get(ctx, client.ObjectKey{Namespace: device.Namespace, Name: model.Spec.ManufacturerRef.Name}, &manufacturer); err != nil || !manufacturer.DeletionTimestamp.IsZero() { + return nil, nil, unavailable + } + return &model, &manufacturer, nil +} diff --git a/internal/api/inventory/v1alpha1/catalog_envtest_test.go b/internal/api/inventory/v1alpha1/catalog_envtest_test.go new file mode 100644 index 00000000..70db1888 --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog_envtest_test.go @@ -0,0 +1,144 @@ +package v1alpha1 + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + 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/client-go/kubernetes" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +func TestCatalogAPIConcurrencyAndStrictFields(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable catalog API validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system"}}); err != nil { + t.Fatal(err) + } + manufacturer, model := catalogRecords() + device := syntheticDevice() + for _, record := range []client.Object{manufacturer, model, &device} { + if err := api.Create(ctx, record); err != nil { + t.Fatal(err) + } + } + var stored DeviceType + if err := api.Get(ctx, client.ObjectKeyFromObject(model), &stored); err != nil { + t.Fatal(err) + } + if stored.Spec.ModelShape != nil { + t.Fatalf("API server invented a DeviceType shape; unset depth must stay unknown: %+v", stored.Spec.ModelShape) + } + stale := device.DeepCopyObject().(*Device) + device.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + if err := api.Update(ctx, &device); err != nil { + t.Fatal(err) + } + stale.Spec.DeviceTypeRef = &LocalReference{Name: "different"} + if err := api.Update(ctx, stale); !apierrors.IsConflict(err) { + t.Fatalf("stale writer did not conflict: %v", err) + } + device.Spec.DeviceTypeRef = nil + if err := api.Update(ctx, &device); !apierrors.IsInvalid(err) { + t.Fatalf("reference removal accepted: %v", err) + } + model.Spec.DisplayName = "Edited catalog only" + if err := api.Update(ctx, model); err != nil { + t.Fatal(err) + } + var unchanged Device + if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &unchanged); err != nil { + t.Fatal(err) + } + if unchanged.Spec.Identity != syntheticDevice().Spec.Identity || unchanged.Spec.DeviceTypeRef.Name != model.Name || len(unchanged.Spec.Components) != 0 { + t.Fatal("catalog edit changed physical instance") + } + core, err := kubernetes.NewForConfig(config) + if err != nil { + t.Fatal(err) + } + for face, valid := range map[string]bool{"Front": true, "Rear": true, "front": false, "Side": false} { + faced := object(t, model) + faced["apiVersion"], faced["kind"] = GroupVersion.String(), "DeviceType" + faced["metadata"] = map[string]any{"name": "faced-" + strings.ToLower(face), "namespace": "fleet-system"} + faced["spec"].(map[string]any)["componentTemplates"] = []any{map[string]any{"id": "port-1", "name": "Port 1", "type": "NetworkPort", "face": face}} + body, err := json.Marshal(faced) + if err != nil { + t.Fatal(err) + } + err = core.RESTClient().Post().AbsPath("/apis/fleet.datumapis.com/v1alpha1/namespaces/fleet-system/devicetypes").Param("fieldValidation", "Strict").Body(body).Do(ctx).Error() + if valid && err != nil || !valid && !apierrors.IsInvalid(err) { + t.Fatalf("template face %q: valid=%v, got %v", face, valid, err) + } + } + invalid := object(t, syntheticDevice()) + invalid["metadata"].(map[string]any)["name"] = "invalid-reference" + invalid["spec"].(map[string]any)["deviceTypeRef"] = map[string]any{"name": model.Name, "uid": "not-a-spec-field", "namespace": "other"} + body, err := json.Marshal(invalid) + if err != nil { + t.Fatal(err) + } + err = core.RESTClient().Post().AbsPath("/apis/fleet.datumapis.com/v1alpha1/namespaces/fleet-system/devices").Param("fieldValidation", "Strict").Body(body).Do(ctx).Error() + if !apierrors.IsBadRequest(err) { + t.Fatalf("strict API did not reject unknown reference fields: %v", err) + } + for _, entry := range []struct { + resource string + record any + }{ + {"manufacturers", manufacturer}, + {"devicetypes", model}, + {"devices", syntheticDevice()}, + } { + for _, retired := range []string{"provenance", "sourceIdentity"} { + t.Run(entry.resource+"/"+retired, func(t *testing.T) { + candidate := object(t, entry.record) + candidate["metadata"] = map[string]any{"name": "retired-field", "namespace": "fleet-system"} + spec := candidate["spec"].(map[string]any) + if entry.resource == "devices" && retired == "sourceIdentity" { + spec = spec["identity"].(map[string]any) + } + spec[retired] = map[string]any{"system": "synthetic", "id": "1"} + body, err := json.Marshal(candidate) + if err != nil { + t.Fatal(err) + } + err = core.RESTClient().Post().AbsPath("/apis/fleet.datumapis.com/v1alpha1/namespaces/fleet-system/"+entry.resource).Param("fieldValidation", "Strict").Body(body).Do(ctx).Error() + if !apierrors.IsBadRequest(err) { + t.Fatalf("strict API accepted retired field: %v", err) + } + }) + } + } +} diff --git a/internal/api/inventory/v1alpha1/catalog_test.go b/internal/api/inventory/v1alpha1/catalog_test.go new file mode 100644 index 00000000..adb828db --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog_test.go @@ -0,0 +1,192 @@ +package v1alpha1 + +import ( + "context" + "fmt" + "reflect" + "strings" + "testing" + + metavalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestCatalogNamespaceBoundaries(t *testing.T) { + for _, namespace := range []string{"a", strings.Repeat("a", 63), "has.dot", strings.Repeat("a", 64)} { + t.Run(namespace, func(t *testing.T) { + manufacturer, model := catalogRecords() + for _, record := range []client.Object{manufacturer, model} { + record.SetNamespace(namespace) + metadata := metav1.ObjectMeta{Name: record.GetName(), Namespace: namespace} + errors := metavalidation.ValidateObjectMeta(&metadata, true, metavalidation.NameIsDNSSubdomain, field.NewPath("metadata")) + valid := namespace == "a" || namespace == strings.Repeat("a", 63) + if (len(errors) == 0) != valid { + t.Fatalf("unexpected metadata validation: %v", errors) + } + if valid { + candidate := object(t, record) + if errors := admit(t, candidate["kind"].(string), candidate, nil); len(errors) != 0 { + t.Fatal(errors) + } + } + } + }) + } +} + +func catalogRecords() (*Manufacturer, *DeviceType) { + metadata := PhysicalMetadata{DisplayName: "Example"} + manufacturer := &Manufacturer{TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Manufacturer"}, ObjectMeta: metav1.ObjectMeta{Name: "vendor-stable", Namespace: "fleet-system"}, Spec: ManufacturerSpec{PhysicalMetadata: metadata, CanonicalName: "Example Vendor", Aliases: []string{"Old Vendor"}}} + model := &DeviceType{TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceType"}, ObjectMeta: metav1.ObjectMeta{Name: "model-stable", Namespace: "fleet-system"}, Spec: DeviceTypeSpec{PhysicalMetadata: metadata, ManufacturerRef: LocalReference{Name: manufacturer.Name}, Model: "example-1u", ComponentTemplates: []ComponentTemplate{{ID: "port-1", Name: "Port 1", Type: "NetworkPort"}}}} + return manufacturer, model +} + +func TestCatalogAdmission(t *testing.T) { + manufacturer, model := catalogRecords() + manufacturer.Spec.CanonicalName = "Example Vendor, Inc." + manufacturer.Spec.Aliases = []string{"Old Vendor", "Example Vendor"} + for _, record := range []any{manufacturer, model} { + candidate := object(t, record) + if errs := admit(t, candidate["kind"].(string), candidate, nil); len(errs) != 0 { + t.Fatal(errs) + } + } + manufacturer, _ = catalogRecords() + for _, aliases := range [][]string{{"Old Vendor", "old vendor"}, {"Example Vendor"}, {" leading"}, {"trailing "}, {""}} { + candidate := manufacturer.DeepCopyObject().(*Manufacturer) + candidate.Spec.Aliases = aliases + if errs := admit(t, "Manufacturer", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted aliases %v", aliases) + } + } + for _, key := range []string{"Example-1u", "example 1u", "example--1u", "", "example_1u"} { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.Model = key + if errs := admit(t, "DeviceType", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted non-normalized key %q", key) + } + } + for _, name := range []string{"", "Upper", "vendor..one", "vendor/one", "vendor.-one"} { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.ManufacturerRef.Name = name + if errs := admit(t, "DeviceType", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted invalid reference %q", name) + } + } + duplicate := model.DeepCopyObject().(*DeviceType) + duplicate.Spec.ComponentTemplates = append(duplicate.Spec.ComponentTemplates, duplicate.Spec.ComponentTemplates[0]) + if errs := admit(t, "DeviceType", object(t, duplicate), nil); len(errs) == 0 { + t.Fatal("accepted duplicate template ID") + } + duplicate = model.DeepCopyObject().(*DeviceType) + duplicate.Name = "different-resource-name" + if errs := admit(t, "DeviceType", object(t, duplicate), nil); len(errs) != 0 { + t.Fatal("local admission must not claim cross-object uniqueness", errs) + } +} + +func TestCatalogScheme(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"Manufacturer", "ManufacturerList", "DeviceType", "DeviceTypeList"} { + if _, err := scheme.New(GroupVersion.WithKind(kind)); err != nil { + t.Fatal(err) + } + } +} + +func TestCatalogUpdatesAndDeviceCompatibility(t *testing.T) { + _, model := catalogRecords() + changed := model.DeepCopyObject().(*DeviceType) + changed.Spec.DisplayName = "New human label" + changed.Spec.ComponentTemplates[0].Name = "Renamed template only" + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) != 0 { + t.Fatal(errs) + } + changed.Spec.Model = "different-model" + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) == 0 { + t.Fatal("accepted model identity mutation") + } + changed = model.DeepCopyObject().(*DeviceType) + changed.Spec.ManufacturerRef.Name = "different-manufacturer" + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) == 0 { + t.Fatal("accepted manufacturer reference mutation") + } + for _, baseline := range []Device{syntheticDevice(), reportedDevice()} { + attached := baseline.DeepCopyObject().(*Device) + attached.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + if errs := admit(t, "Device", object(t, attached), object(t, baseline)); len(errs) != 0 { + t.Fatal(errs) + } + for _, reference := range []*LocalReference{nil, {Name: "another-model"}} { + rebound := attached.DeepCopyObject().(*Device) + rebound.Spec.DeviceTypeRef = reference + if errs := admit(t, "Device", object(t, rebound), object(t, attached)); len(errs) == 0 { + t.Fatal("accepted catalog removal or rebind") + } + } + attached.Spec.DeviceTypeRef = nil + if !reflect.DeepEqual(object(t, attached.Spec), object(t, baseline.Spec)) { + t.Fatal("catalog attachment changed an observation or physical identity") + } + } +} + +type deniedCatalogReader struct{ client.Reader } + +func (deniedCatalogReader) Get(context.Context, client.ObjectKey, client.Object, ...client.GetOption) error { + return fmt.Errorf("denied secret manufacturer and model") +} + +func TestCatalogResolutionAndDeepCopy(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + manufacturer, model := catalogRecords() + device := syntheticDevice() + device.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + before := object(t, device) + reader := fake.NewClientBuilder().WithScheme(scheme).WithObjects(manufacturer, model).Build() + resolved, vendor, err := ReadDeviceCatalog(context.Background(), reader, &device) + if err != nil || vendor.Name != manufacturer.Name || resolved.Name != model.Name { + t.Fatal("same-namespace reference failed", err) + } + resolved.Spec.ComponentTemplates[0].Name = "mutated copy" + if model.Spec.ComponentTemplates[0].Name != "Port 1" || !reflect.DeepEqual(before, object(t, device)) { + t.Fatal("resolution mutated source or device") + } + for _, namespace := range []string{"", "another-namespace"} { + other := device.DeepCopyObject().(*Device) + other.Namespace = namespace + if model, vendor, err := ReadDeviceCatalog(context.Background(), reader, other); err == nil || model != nil || vendor != nil { + t.Fatal("resolved across namespace boundary") + } + } + if model, vendor, err := ReadDeviceCatalog(context.Background(), deniedCatalogReader{}, &device); err == nil || err.Error() != "hardware catalog unavailable" || model != nil || vendor != nil { + t.Fatal("denied reference disclosed details") + } + if err := reader.Delete(context.Background(), manufacturer); err != nil { + t.Fatal(err) + } + if model, vendor, err := ReadDeviceCatalog(context.Background(), reader, &device); err == nil || model != nil || vendor != nil { + t.Fatal("dangling reference returned partial catalog") + } + replacement := manufacturer.DeepCopyObject().(*Manufacturer) + replacement.ResourceVersion = "" + replacement.UID = "replacement" + replacement.Spec.CanonicalName = "Replacement Vendor" + if err := reader.Create(context.Background(), replacement); err != nil { + t.Fatal(err) + } + _, vendor, err = ReadDeviceCatalog(context.Background(), reader, &device) + if err != nil || vendor.UID != "replacement" || !reflect.DeepEqual(before, object(t, device)) { + t.Fatal("name reuse must resolve without rewriting device", err) + } +} diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go new file mode 100644 index 00000000..41303ce0 --- /dev/null +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -0,0 +1,432 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning" + "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utiljson "k8s.io/apimachinery/pkg/util/json" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apimachinery/pkg/util/yaml" + celconfig "k8s.io/apiserver/pkg/apis/cel" +) + +var ( + configRoot = filepath.Join("..", "..", "..", "..", "config") + inventoryRoot = filepath.Join(configRoot, "components", "inventory") +) + +func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { + t.Helper() + data, err := os.ReadFile(filepath.Join(inventoryRoot, "crds", "fleet.datumapis.com.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + out := map[string]*extensionsv1.CustomResourceDefinition{} + for { + var crd extensionsv1.CustomResourceDefinition + if err := decoder.Decode(&crd); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if crd.Name != "" { + copied := crd + out[crd.Spec.Names.Kind] = &copied + } + } +} + +func TestInventoryCRDContract(t *testing.T) { + crds := loadCRDs(t) + if len(crds) != 9 || crds["Manufacturer"] == nil || crds["DeviceType"] == nil || crds["Site"] == nil || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got %d CRDs, want six physical kinds, Site and two catalog kinds", len(crds)) + } + for kind, crd := range crds { + if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { + t.Fatalf("%s identity = %s %s", kind, crd.Name, crd.Spec.Scope) + } + version := crd.Spec.Versions[0] + if len(crd.Spec.Versions) != 1 || version.Name != GroupVersion.Version || !version.Served || !version.Storage { + t.Fatalf("%s must serve and store exactly v1alpha1", kind) + } + if version.Subresources == nil || version.Subresources.Status == nil { + t.Fatalf("%s must reserve status as a separate subresource", kind) + } + if status := version.Schema.OpenAPIV3Schema.Properties["status"]; len(status.Properties) != 0 || status.XPreserveUnknownFields != nil { + t.Fatalf("%s status must stay empty until a collector or verifier owns it", kind) + } + if crd.Annotations["discovery.miloapis.com/parent-contexts"] != "Project" { + t.Fatalf("%s must be served in Milo project control planes", kind) + } + defaulted := crd.DeepCopy() + extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) + defaulted.Status.StoredVersions = []string{GroupVersion.Version} + var internal apiextensions.CustomResourceDefinition + if err := extensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(defaulted, &internal, nil); err != nil { + t.Fatal(err) + } + if errs := crdvalidation.ValidateCustomResourceDefinition(context.Background(), &internal); len(errs) > 0 { + t.Fatalf("%s: %v", kind, errs.ToAggregate()) + } + } +} + +// admit applies schema defaults to both objects, as stored objects already +// carry them, then the OpenAPI, list-type, and CEL +// validation the API server runs on create (old == nil) or update. Objects are +// decoded with integer-preserving JSON, as the API server decodes them. +func admit(t *testing.T, kind string, object, old map[string]any) field.ErrorList { + t.Helper() + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)[kind].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + structuraldefaulting.Default(object, structural) + validator, _, err := validation.NewSchemaValidator(&schema) + if err != nil { + t.Fatal(err) + } + errs := validation.ValidateCustomResource(nil, object, validator) + errs = append(errs, listtype.ValidateListSetsAndMaps(nil, structural, object)...) + var oldObject any + if old != nil { + structuraldefaulting.Default(old, structural) + oldObject = old + } + celErrs, _ := cel.NewValidator(structural, true, celconfig.PerCallLimit).Validate(context.Background(), nil, structural, object, oldObject, celconfig.RuntimeCELCostBudget) + return append(errs, celErrs...) +} + +func object(t *testing.T, value any) map[string]any { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + var out map[string]any + if err := utiljson.Unmarshal(data, &out); err != nil { + t.Fatal(err) + } + return out +} + +var baseTime = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + +func syntheticClaim() DeviceClaim { + return DeviceClaim{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceClaim"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12", Namespace: "fleet-system"}, + Spec: DeviceClaimSpec{ + ExpectedIdentity: ExpectedIdentity{Manufacturer: "Example Vendor", Model: "Example 1U"}, + Placement: Placement{Facility: "example-facility", Rack: "rack-01", Position: 12, Face: "front"}, + Ports: []ExpectedPort{ + {Name: "eth0", Type: "25gbase-x-sfp28", SpeedMbps: 25000, ExpectedPeer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", Type: "1000base-t", SpeedMbps: 1000, ExpectedPeer: &PortPeer{Device: "mgmt-switch-01", Port: "Ethernet5"}}, + }, + }, + } +} + +func syntheticDevice() Device { + return Device{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Device"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12-synthetic-0001", Namespace: "fleet-system"}, + Spec: DeviceSpec{ + ClaimRef: LocalReference{Name: "rack-01-u12"}, + Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, + BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, + Interfaces: []Interface{ + {Name: "eth0", MACAddress: "00:00:5e:00:53:01", Peer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", MACAddress: "00:00:5e:00:53:02"}, + }, + UnmappedMACAddresses: []string{"00:00:5e:00:53:03"}, + }, + } +} + +func later(d time.Duration) metav1.Time { return metav1.NewTime(baseTime.Add(d)) } + +func TestValidRecordsAreAccepted(t *testing.T) { + if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), nil); len(errs) > 0 { + t.Fatalf("claim rejected: %v", errs) + } + if errs := admit(t, "Device", object(t, syntheticDevice()), nil); len(errs) > 0 { + t.Fatalf("device rejected: %v", errs) + } + minimal := syntheticDevice() + minimal.Spec.Identity.Serial = "" + minimal.Spec.BMC, minimal.Spec.Interfaces = nil, nil + if errs := admit(t, "Device", object(t, minimal), nil); len(errs) > 0 { + t.Fatalf("device with only a system UUID rejected: %v", errs) + } +} + +func TestClaimDoesNotRequireSerialOrInventHeight(t *testing.T) { + claim := object(t, syntheticClaim()) + if errs := admit(t, "DeviceClaim", claim, nil); len(errs) > 0 { + t.Fatal(errs) + } + if height := claim["spec"].(map[string]any)["placement"].(map[string]any)["height"]; height != nil { + t.Fatalf("height must not invent a partial-placement footprint: %v", height) + } +} + +func TestInvalidClaimsAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*DeviceClaim){ + "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, + "missing facility": func(c *DeviceClaim) { c.Spec.Placement.Facility = "" }, + "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, + "unknown face": func(c *DeviceClaim) { c.Spec.Placement.Face = "side" }, + "duplicate port": func(c *DeviceClaim) { c.Spec.Ports[1].Name = c.Spec.Ports[0].Name }, + "peer without port": func(c *DeviceClaim) { + c.Spec.Ports[0].ExpectedPeer = &PortPeer{Device: "switch-01"} + }, + } { + claim := syntheticClaim() + mutate(&claim) + if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } +} + +func TestInvalidDevicesAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*Device){ + "missing claim": func(d *Device) { d.Spec.ClaimRef.Name = "" }, + "no identity key": func(d *Device) { d.Spec.Identity.Serial, d.Spec.Identity.SystemUUID = "", "" }, + "uppercase system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-00000000000A" }, + "malformed system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "not-a-uuid" }, + "uppercase MAC": func(d *Device) { d.Spec.Interfaces[0].MACAddress = "00:00:5E:00:53:01" }, + "malformed MAC": func(d *Device) { d.Spec.UnmappedMACAddresses = []string{"not-a-mac"} }, + "duplicate interface": func(d *Device) { d.Spec.Interfaces[1].Name = d.Spec.Interfaces[0].Name }, + "MAC on two interfaces": func(d *Device) { d.Spec.Interfaces[1].MACAddress = d.Spec.Interfaces[0].MACAddress }, + "MAC mapped and unmapped": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{d.Spec.Interfaces[0].MACAddress} + }, + "duplicate unmapped MAC": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{"00:00:5e:00:53:03", "00:00:5e:00:53:03"} + }, + "plain-http BMC": func(d *Device) { d.Spec.BMC.Endpoint = "http://192.0.2.100" }, + "BMC with credentials": func(d *Device) { d.Spec.BMC.Endpoint = "https://admin:secret@192.0.2.100" }, + "BMC not a URL": func(d *Device) { d.Spec.BMC.Endpoint = "192.0.2.100" }, + } { + device := syntheticDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + withoutClaim := object(t, syntheticDevice()) + delete(withoutClaim["spec"].(map[string]any), "claimRef") + if errs := admit(t, "Device", withoutClaim, nil); len(errs) == 0 { + t.Error("device without a claim reference accepted") + } +} + +func TestDeviceIdentityNeedsSerialOrSystemUUID(t *testing.T) { + serialOnly := syntheticDevice() + serialOnly.Spec.Identity.SystemUUID = "" + serialOnly.Spec.BMC, serialOnly.Spec.Interfaces, serialOnly.Spec.UnmappedMACAddresses = nil, nil, nil + record := object(t, serialOnly) + if _, ok := record["spec"].(map[string]any)["provenance"]; ok { + t.Fatal("device fixture must not carry provenance") + } + if errs := admit(t, "Device", record, nil); len(errs) > 0 { + t.Fatalf("device with only a serial rejected: %v", errs) + } + neither := serialOnly + neither.Spec.Identity.Serial = "" + if errs := admit(t, "Device", object(t, neither), nil); len(errs) == 0 { + t.Fatal("device with neither serial nor system UUID accepted") + } +} + +// TestEditsDoNotNeedARecordingTimestamp pins that spec changes carry no +// attribution field; audit logs record who changed a record. +func TestEditsDoNotNeedARecordingTimestamp(t *testing.T) { + claim := syntheticClaim() + claim.Spec.Placement.Position = 14 + if errs := admit(t, "DeviceClaim", object(t, claim), object(t, syntheticClaim())); len(errs) > 0 { + t.Fatalf("claim edit rejected: %v", errs) + } + device := syntheticDevice() + device.Spec.BMC.Endpoint = "https://192.0.2.101" + if errs := admit(t, "Device", object(t, device), object(t, syntheticDevice())); len(errs) > 0 { + t.Fatalf("device edit rejected: %v", errs) + } +} + +// TestRetiredFieldsArePruned shows that objects stored with the retired +// provenance, source identity, component source and report import fields +// lose them when read or written through the structural schema, and that +// what remains is admitted when it still has a serial or system UUID. +func TestRetiredFieldsArePruned(t *testing.T) { + legacy := object(t, reportedDevice()) + spec := legacy["spec"].(map[string]any) + spec["provenance"] = map[string]any{"method": "Manual", "recordedBy": "operator@example.com", "recordedAt": "2026-01-02T03:04:05Z", "reference": "rack plan 1234"} + spec["identity"].(map[string]any)["sourceIdentity"] = map[string]any{"system": "example", "type": "device", "id": "1"} + report := spec["reportedPlacement"].(map[string]any) + report["method"] = "Manual" + report["snapshotDigest"] = "sha256:" + strings.Repeat("a", 64) + spec["topologyAuthority"] = "Cable" + delete(spec, "interfaces") + spec["components"] = []any{map[string]any{"id": "front", "name": "front", "type": "FrontPort", "sourceRef": map[string]any{"system": "example", "type": "port", "id": "1"}}} + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + pruning.Prune(legacy, structural, true) + spec = legacy["spec"].(map[string]any) + if _, ok := spec["provenance"]; ok { + t.Fatal("provenance survived pruning") + } + if _, ok := spec["identity"].(map[string]any)["sourceIdentity"]; ok { + t.Fatal("sourceIdentity survived pruning") + } + if _, ok := spec["components"].([]any)[0].(map[string]any)["sourceRef"]; ok { + t.Fatal("component sourceRef survived pruning") + } + report = spec["reportedPlacement"].(map[string]any) + if _, ok := report["method"]; ok { + t.Fatal("report method survived pruning") + } + if _, ok := report["snapshotDigest"]; ok { + t.Fatal("report snapshotDigest survived pruning") + } + if errs := admit(t, "Device", legacy, nil); len(errs) > 0 { + t.Fatalf("pruned legacy device rejected: %v", errs) + } + for _, kind := range []string{"DeviceClaim", "Facility", "Site", "Rack", "Cable", "PowerFeed", "Manufacturer", "DeviceType"} { + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)[kind].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + if _, ok := structural.Properties["spec"].Properties["provenance"]; ok || structural.Properties["spec"].XPreserveUnknownFields { + t.Fatalf("%s spec must not declare or preserve provenance", kind) + } + } +} + +// TestSourceOnlyIdentityDoesNotSurvivePruning pins the case that does need +// action: a Device whose only identity was sourceIdentity prunes to an +// identity without a serial or system UUID, which is no longer valid. Because +// identity is immutable, such a Device has to be deleted and recreated. +func TestSourceOnlyIdentityDoesNotSurvivePruning(t *testing.T) { + legacy := object(t, syntheticDevice()) + spec := legacy["spec"].(map[string]any) + identity := spec["identity"].(map[string]any) + delete(identity, "serial") + delete(identity, "systemUUID") + identity["sourceIdentity"] = map[string]any{"system": "example", "type": "device", "id": "1"} + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + pruning.Prune(legacy, structural, true) + if errs := admit(t, "Device", legacy, nil); len(errs) == 0 { + t.Fatal("a Device with only a pruned source identity was admitted") + } +} + +func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { + old := object(t, syntheticDevice()) + for name, mutate := range map[string]func(*Device){ + "retarget claim": func(d *Device) { d.Spec.ClaimRef.Name = "rack-01-u14" }, + "change serial": func(d *Device) { d.Spec.Identity.Serial = "SYNTHETIC-0002" }, + "remove serial": func(d *Device) { d.Spec.Identity.Serial = "" }, + "change system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" }, + "change model": func(d *Device) { d.Spec.Identity.Model = "Example 2U" }, + } { + device := syntheticDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), old); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + unserialed := syntheticDevice() + unserialed.Spec.Identity.Serial = "" + added := syntheticDevice() + if errs := admit(t, "Device", object(t, added), object(t, unserialed)); len(errs) == 0 { + t.Error("adding a serial to a registered device accepted; a new identity needs a new Device") + } +} + +func TestReplacementBindsANewDeviceToTheSameClaim(t *testing.T) { + replacement := syntheticDevice() + replacement.Name = "rack-01-u12-synthetic-0002" + replacement.Spec.Identity.Serial = "SYNTHETIC-0002" + replacement.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" + if errs := admit(t, "Device", object(t, replacement), nil); len(errs) > 0 { + t.Fatalf("replacement device for the same claim rejected: %v", errs) + } +} + +func TestStatusAcceptsNoFieldsYet(t *testing.T) { + device := object(t, syntheticDevice()) + device["status"] = map[string]any{"identity": map[string]any{"serial": "SYNTHETIC-0009"}} + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + if structural.Properties["status"].Properties != nil { + t.Fatal("status declares fields") + } +} + +func TestSchemeRegistersBothKinds(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + claim, device := syntheticClaim(), syntheticDevice() + for _, obj := range []runtime.Object{claim.DeepCopyObject(), device.DeepCopyObject(), &DeviceClaimList{}, &DeviceList{}} { + if _, _, err := scheme.ObjectKinds(obj); err != nil { + t.Fatal(err) + } + } + if copied := device.DeepCopyObject().(*Device); copied.Spec.Identity != device.Spec.Identity || &copied.Spec.Interfaces[0] == &device.Spec.Interfaces[0] { + t.Fatal("deep copy did not copy the device") + } +} diff --git a/internal/api/inventory/v1alpha1/depth_face_test.go b/internal/api/inventory/v1alpha1/depth_face_test.go new file mode 100644 index 00000000..f1cada23 --- /dev/null +++ b/internal/api/inventory/v1alpha1/depth_face_test.go @@ -0,0 +1,72 @@ +package v1alpha1 + +import "testing" + +// Unset depth stays unset on both kinds: a default would hide "depth +// unknown" and make conflict checks overconfident. +func TestModelShapeDepthIsNeverDefaulted(t *testing.T) { + _, model := catalogRecords() + half, height := false, 1.0 + for _, test := range []struct { + name string + shape *ModelShape + want any + }{ + {"no model shape", nil, nil}, + {"shape without depth", &ModelShape{HeightUnits: &height}, nil}, + {"explicit half depth", &ModelShape{FullDepth: &half}, false}, + } { + t.Run(test.name, func(t *testing.T) { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.ModelShape = test.shape + device := syntheticDevice() + device.Spec.ModelShape = test.shape + for kind, admitted := range map[string]map[string]any{"DeviceType": object(t, candidate), "Device": object(t, device)} { + if errs := admit(t, kind, admitted, nil); len(errs) > 0 { + t.Fatal(kind, errs) + } + shape, ok := admitted["spec"].(map[string]any)["modelShape"].(map[string]any) + if test.shape == nil { + if ok { + t.Fatalf("%s modelShape was defaulted: %v", kind, shape) + } + continue + } + if got := shape["fullDepth"]; got != test.want { + t.Fatalf("%s admitted fullDepth = %v, want %v", kind, got, test.want) + } + } + }) + } +} + +func TestComponentTemplateFaceIsChassisRelativeEnum(t *testing.T) { + _, model := catalogRecords() + for _, face := range []ChassisFace{ChassisFront, ChassisRear, ""} { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.ComponentTemplates[0].Face = face + if errs := admit(t, "DeviceType", object(t, candidate), nil); len(errs) > 0 { + t.Fatalf("face %q rejected: %v", face, errs) + } + } + for _, face := range []string{"front", "rear", "Left", "Unknown", ""} { + candidate := object(t, model) + templates := candidate["spec"].(map[string]any)["componentTemplates"].([]any) + templates[0].(map[string]any)["face"] = face + if errs := admit(t, "DeviceType", candidate, nil); len(errs) == 0 { + t.Fatalf("face %q accepted; template faces are Front or Rear, and unknown is omitted", face) + } + } +} + +// The mounted rack face keeps its lowercase vocabulary. The chassis face +// vocabulary is not accepted there, so the two cannot be confused. +func TestMountedRackFaceRejectsChassisVocabulary(t *testing.T) { + for face, valid := range map[string]bool{"front": true, "rear": true, "Front": false, "Rear": false} { + device := reportedDevice() + device.Spec.ReportedPlacement.Face = face + if errs := admit(t, "Device", object(t, device), nil); (len(errs) == 0) != valid { + t.Fatalf("reported placement face %q: valid=%v, errors %v", face, valid, errs) + } + } +} diff --git a/internal/api/inventory/v1alpha1/faceplate_envtest_test.go b/internal/api/inventory/v1alpha1/faceplate_envtest_test.go new file mode 100644 index 00000000..8b8e448e --- /dev/null +++ b/internal/api/inventory/v1alpha1/faceplate_envtest_test.go @@ -0,0 +1,128 @@ +package v1alpha1 + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + 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" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// TestFaceplateLayoutOnTheAPIServer installs the CRDs into a disposable API +// server, which proves it accepts the rules' estimated cost, then checks each +// layout rule and the worst-case runtime cost against the real server. +func TestFaceplateLayoutOnTheAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable faceplate layout validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system"}}); err != nil { + t.Fatal(err) + } + serial := 0 + create := func(model *DeviceType) error { + serial++ + model.ResourceVersion = "" + model.Name = fmt.Sprintf("layout-%d", serial) + return api.Create(ctx, model) + } + + valid := layoutSwitch() + if err := create(valid); err != nil { + t.Fatal(err) + } + var stored DeviceType + if err := api.Get(ctx, client.ObjectKeyFromObject(valid), &stored); err != nil { + t.Fatal(err) + } + if stored.Spec.Faceplate == nil || len(stored.Spec.Faceplate.Banks) != 5 || stored.Spec.ComponentTemplates[0].Layout == nil || stored.Spec.ComponentTemplates[0].Layout.Span != 0 || stored.Spec.ModelShape.Width != ChassisFullWidth { + t.Fatalf("layout did not round-trip unchanged: %+v", stored.Spec) + } + if stored.Spec.Faceplate.Banks[0].Offset != nil { + t.Fatal("the server invented an offset for a flowed bank") + } + // Removing the layout is an ordinary catalog edit. + stored.Spec.Faceplate = nil + for i := range stored.Spec.ComponentTemplates { + stored.Spec.ComponentTemplates[i].Layout = nil + } + if err := api.Update(ctx, &stored); err != nil { + t.Fatalf("clearing the layout rejected: %v", err) + } + + if err := create(worstCaseLayout(128)); err != nil { + t.Fatalf("worst-case layout within the cap rejected: %v", err) + } + + for name, test := range map[string]struct { + mutate func(*DeviceType) + message string + }{ + "bank on the other face": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Face = ChassisRear }, "own face"}, + "layout without a face": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Face = "" }, "own face"}, + "unknown bank": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Bank = "missing" }, "own face"}, + "row outside the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Row = 3 }, "inside its bank"}, + "column outside the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Column = 13 }, "inside its bank"}, + "span outside the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[56].Layout.Span = 2 }, "inside its bank"}, + "two templates in a cell": {func(m *DeviceType) { m.Spec.ComponentTemplates[1].Layout = m.Spec.ComponentTemplates[0].Layout }, "overlap"}, + "span over a neighbour": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Span = 2 }, "overlap"}, + "offsets on part of face": {func(m *DeviceType) { m.Spec.Faceplate.Banks[1].Offset = ptr(0.5) }, "offsets"}, + "offset missing on a bank": {func(m *DeviceType) { m.Spec.Faceplate.Banks[3].Offset = nil }, "offsets"}, + "over the layout cap": {func(m *DeviceType) { + *m = *worstCaseLayout(129) + }, "at most 128 templates"}, + } { + t.Run(name, func(t *testing.T) { + model := layoutSwitch() + test.mutate(model) + err := create(model) + if !apierrors.IsInvalid(err) || !strings.Contains(err.Error(), test.message) { + t.Fatalf("want an invalid error containing %q, got %v", test.message, err) + } + if strings.Contains(err.Error(), "cost") { + t.Fatalf("rejected by CEL cost, not by the rule: %v", err) + } + }) + } + + device := syntheticDevice() + device.Spec.ModelShape = &ModelShape{Width: ChassisHalfWidth} + if err := api.Create(ctx, &device); err != nil { + t.Fatalf("half-width Device rejected: %v", err) + } + wide := syntheticDevice() + wide.Name, wide.Spec.Identity.Serial, wide.Spec.Identity.SystemUUID = "wide", "SYNTHETIC-0002", "00000000-0000-4000-8000-000000000002" + wide.Spec.ModelShape = &ModelShape{Width: "Double"} + if err := api.Create(ctx, &wide); !apierrors.IsInvalid(err) { + t.Fatalf("unknown width accepted: %v", err) + } +} diff --git a/internal/api/inventory/v1alpha1/faceplate_test.go b/internal/api/inventory/v1alpha1/faceplate_test.go new file mode 100644 index 00000000..293db66b --- /dev/null +++ b/internal/api/inventory/v1alpha1/faceplate_test.go @@ -0,0 +1,295 @@ +package v1alpha1 + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model" + "k8s.io/apimachinery/pkg/util/validation/field" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "k8s.io/apiserver/pkg/cel/environment" + "sigs.k8s.io/yaml" +) + +func ptr[T any](value T) *T { return &value } + +// layoutSwitch is a synthetic 48 RJ45 plus 8 QSFP28 switch: two RJ45 banks +// numbered odd-top, even-bottom, a QSFP28 bank with one double-wide cage, and +// rear PSUs placed by offset. +func layoutSwitch() *DeviceType { + _, model := catalogRecords() + model.Spec.ModelShape = &ModelShape{HeightUnits: ptr(1.0), FullDepth: ptr(true), Width: ChassisFullWidth} + model.Spec.Faceplate = &Faceplate{Banks: []FaceplateBank{ + {ID: "rj45-a", Face: ChassisFront, Rows: 2, Columns: 12}, + {ID: "rj45-b", Face: ChassisFront, Rows: 2, Columns: 12}, + {ID: "qsfp", Face: ChassisFront, Rows: 2, Columns: 5}, + {ID: "psu-1", Face: ChassisRear, Rows: 1, Columns: 1, Offset: ptr(0.0), CellMM: &CellSize{Width: 40, Height: 38}}, + {ID: "psu-2", Face: ChassisRear, Rows: 1, Columns: 1, Offset: ptr(0.89), CellMM: &CellSize{Width: 40, Height: 38}}, + }} + model.Spec.ComponentTemplates = nil + for port := int32(1); port <= 48; port++ { + bank, index := "rj45-a", port + if port > 24 { + bank, index = "rj45-b", port-24 + } + model.Spec.ComponentTemplates = append(model.Spec.ComponentTemplates, ComponentTemplate{ + ID: fmt.Sprintf("ge%d", port), Name: fmt.Sprintf("Ethernet %d", port), Type: "NetworkPort", Connector: "RJ45", Face: ChassisFront, + Layout: &TemplateLayout{Bank: bank, Row: 2 - index%2, Column: (index + 1) / 2}, + }) + } + for port := int32(1); port <= 8; port++ { + layout := &TemplateLayout{Bank: "qsfp", Row: 2 - port%2, Column: (port + 1) / 2} + model.Spec.ComponentTemplates = append(model.Spec.ComponentTemplates, ComponentTemplate{ID: fmt.Sprintf("q%d", port), Name: fmt.Sprintf("QSFP %d", port), Type: "NetworkPort", Connector: "QSFP28", Face: ChassisFront, Layout: layout}) + } + // A double-wide cage in the last column pair of the top row. + model.Spec.ComponentTemplates = append(model.Spec.ComponentTemplates, + ComponentTemplate{ID: "dd1", Name: "QSFP-DD 1", Type: "NetworkPort", Connector: "QSFP-DD", Face: ChassisFront, Layout: &TemplateLayout{Bank: "qsfp", Row: 2, Column: 5}}, + ComponentTemplate{ID: "psu1", Name: "PSU 1", Type: "PowerInlet", Connector: "IEC C14", Face: ChassisRear, Layout: &TemplateLayout{Bank: "psu-1", Row: 1, Column: 1}}, + ComponentTemplate{ID: "psu2", Name: "PSU 2", Type: "PowerInlet", Connector: "IEC C14", Face: ChassisRear, Layout: &TemplateLayout{Bank: "psu-2", Row: 1, Column: 1}}, + // Recorded but not laid out: the readers put it in a tray. + ComponentTemplate{ID: "console", Name: "Console", Type: "ConsolePort", Connector: "RJ45", Face: ChassisRear}, + ) + return model +} + +func TestFaceplateLayoutIsAccepted(t *testing.T) { + model := layoutSwitch() + if errs := admit(t, "DeviceType", object(t, model), nil); len(errs) > 0 { + t.Fatal(errs) + } + // Span: one module across two columns beside a single-width one. + model.Spec.Faceplate.Banks[2].Columns = 6 + model.Spec.ComponentTemplates[56].Layout = &TemplateLayout{Bank: "qsfp", Row: 2, Column: 5, Span: 2} + if errs := admit(t, "DeviceType", object(t, model), nil); len(errs) > 0 { + t.Fatalf("span inside the grid rejected: %v", errs) + } + // Offsets are per face: the fixture flows its front and places its + // rear. Placing every front bank too is also valid. + for i, offset := range []float64{0, 0.36, 0.72} { + model.Spec.Faceplate.Banks[i].Offset = ptr(offset) + } + if errs := admit(t, "DeviceType", object(t, model), nil); len(errs) > 0 { + t.Fatalf("placed front and rear rejected: %v", errs) + } + // A layout is optional on every template and on the model. + _, plain := catalogRecords() + if errs := admit(t, "DeviceType", object(t, plain), nil); len(errs) > 0 { + t.Fatal(errs) + } + stored := object(t, model) + if errs := admit(t, "DeviceType", stored, nil); len(errs) > 0 { + t.Fatal(errs) + } + for _, template := range stored["spec"].(map[string]any)["componentTemplates"].([]any) { + if layout, ok := template.(map[string]any)["layout"].(map[string]any); ok { + if _, defaulted := layout["span"]; defaulted && template.(map[string]any)["id"] != "dd1" { + t.Fatalf("span was defaulted on %v", template) + } + } + } +} + +func TestFaceplateLayoutRules(t *testing.T) { + for name, test := range map[string]struct { + mutate func(*DeviceType) + message string + }{ + "layout without a faceplate": {func(m *DeviceType) { m.Spec.Faceplate = nil }, "own face"}, + "layout without a face": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Face = "" }, "own face"}, + "unknown bank": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Bank = "missing" }, "own face"}, + "bank on the other face": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Face = ChassisRear }, "own face"}, + "row below the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Row = 3 }, "inside its bank"}, + "column past the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[0].Layout.Column = 13 }, "inside its bank"}, + "span past the grid": {func(m *DeviceType) { m.Spec.ComponentTemplates[56].Layout.Span = 2 }, "inside its bank"}, + "two templates in one cell": {func(m *DeviceType) { m.Spec.ComponentTemplates[1].Layout = m.Spec.ComponentTemplates[0].Layout }, "overlap"}, + "span over a neighbour": {func(m *DeviceType) { + m.Spec.ComponentTemplates[0].Layout = &TemplateLayout{Bank: "rj45-a", Row: 1, Column: 1, Span: 2} + }, "overlap"}, + "offset on some banks of a face": {func(m *DeviceType) { m.Spec.Faceplate.Banks[0].Offset = ptr(0.0) }, "offsets"}, + "offset missing on one rear bank": {func(m *DeviceType) { m.Spec.Faceplate.Banks[4].Offset = nil }, "offsets"}, + "offset past the face": {func(m *DeviceType) { m.Spec.Faceplate.Banks[3].Offset = ptr(1.5) }, ""}, + "duplicate bank id": {func(m *DeviceType) { m.Spec.Faceplate.Banks[1].ID = "rj45-a" }, ""}, + "bank without a face": {func(m *DeviceType) { m.Spec.Faceplate.Banks[0].Face = "" }, ""}, + "too many rows": {func(m *DeviceType) { m.Spec.Faceplate.Banks[0].Rows = 9 }, ""}, + "zero columns": {func(m *DeviceType) { m.Spec.Faceplate.Banks[0].Columns = 0 }, ""}, + "negative span": {func(m *DeviceType) { m.Spec.ComponentTemplates[56].Layout.Span = -1 }, ""}, + "empty faceplate": {func(m *DeviceType) { m.Spec.Faceplate.Banks = nil }, ""}, + "unknown width": {func(m *DeviceType) { m.Spec.ModelShape.Width = "Quarter" }, ""}, + "zero-size module cell": {func(m *DeviceType) { m.Spec.Faceplate.Banks[3].CellMM.Width = 0 }, ""}, + } { + t.Run(name, func(t *testing.T) { + model := layoutSwitch() + test.mutate(model) + errs := admit(t, "DeviceType", object(t, model), nil) + if len(errs) == 0 { + t.Fatal("accepted") + } + if test.message != "" && !strings.Contains(errs.ToAggregate().Error(), test.message) { + t.Fatalf("rejected for another reason: %v", errs) + } + }) + } +} + +// Width is shape, not layout: it sits on ModelShape on both kinds, as depth +// does, and is never defaulted. +func TestModelShapeWidthIsOptionalOnBothKinds(t *testing.T) { + _, model := catalogRecords() + for _, width := range []ChassisWidth{"", ChassisFullWidth, ChassisHalfWidth} { + model.Spec.ModelShape = &ModelShape{Width: width} + device := syntheticDevice() + device.Spec.ModelShape = &ModelShape{Width: width} + for kind, record := range map[string]map[string]any{"DeviceType": object(t, model), "Device": object(t, device)} { + if errs := admit(t, kind, record, nil); len(errs) > 0 { + t.Fatalf("%s width %q: %v", kind, width, errs) + } + if got, ok := record["spec"].(map[string]any)["modelShape"].(map[string]any)["width"]; width == "" && ok { + t.Fatalf("%s width defaulted to %v", kind, got) + } + } + } +} + +// worstCaseLayout is the costliest valid layout found for the overlap rule: +// 32 banks of one row with maximum-length IDs, and every laid-out template in +// that one row, so every pair passes the row check and pairs with the same +// column range also reach the bank comparison. A single 4x64 bank, or full +// spans across 8 rows, cost less. The other templates carry no layout. +func worstCaseLayout(laidOut int) *DeviceType { + _, model := catalogRecords() + id := func(n int) string { return fmt.Sprintf("%s%02d", strings.Repeat("b", 61), n) } + model.Spec.Faceplate = &Faceplate{} + for n := range 32 { + model.Spec.Faceplate.Banks = append(model.Spec.Faceplate.Banks, FaceplateBank{ID: id(n), Face: ChassisFront, Rows: 1, Columns: 64}) + } + model.Spec.ComponentTemplates = nil + for n := range 256 { + template := ComponentTemplate{ID: fmt.Sprintf("%s%03d", strings.Repeat("t", 60), n), Name: fmt.Sprintf("Port %d", n), Type: "NetworkPort", Face: ChassisFront} + if n < laidOut { + template.Layout = &TemplateLayout{Bank: id(n % 32), Row: 1, Column: int32(n/32)*8 + 1, Span: 8} + } + model.Spec.ComponentTemplates = append(model.Spec.ComponentTemplates, template) + } + return model +} + +// runtimeCost is the CEL cost the API server charges an object on create. +func runtimeCost(t *testing.T, record *DeviceType) (int64, field.ErrorList) { + t.Helper() + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["DeviceType"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + errs, remaining := cel.NewValidator(structural, true, celconfig.PerCallLimit).Validate(context.Background(), nil, structural, object(t, record), nil, celconfig.RuntimeCELCostBudget) + return celconfig.RuntimeCELCostBudget - remaining, errs +} + +// TestFaceplateRulesFitTheCELBudget records the estimated cost of each +// layout rule against the static per-expression and per-CRD limits, and +// admits the worst-case object under the runtime per-call limit and +// per-object budget the API server uses. +func TestFaceplateRulesFitTheCELBudget(t *testing.T) { + crd := loadCRDs(t)["DeviceType"] + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(crd.Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + spec := structural.Properties["spec"] + envSet := environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion()) + // None of these nodes sits inside a list, so each rule runs once per + // object and its estimated cost is also its share of the CRD total. + var total uint64 + for _, node := range []struct { + path string + schema *structuralschema.Structural + }{ + {"spec", &spec}, + {"spec.faceplate", ptr(spec.Properties["faceplate"])}, + {"spec.componentTemplates", ptr(spec.Properties["componentTemplates"])}, + } { + results, err := cel.Compile(node.schema, model.SchemaDeclType(node.schema, false), celconfig.PerCallLimit, envSet, cel.NewExpressionsEnvLoader()) + if err != nil { + t.Fatal(err) + } + for i, result := range results { + if result.Error != nil { + t.Fatalf("%s rule %d: %v", node.path, i, result.Error) + } + total += result.MaxCost + t.Logf("%s rule %d: estimated cost %d (per-expression limit %d)", node.path, i, result.MaxCost, crdvalidation.StaticEstimatedCostLimit) + if result.MaxCost > crdvalidation.StaticEstimatedCostLimit { + t.Fatalf("%s rule %d estimated cost %d exceeds %d", node.path, i, result.MaxCost, crdvalidation.StaticEstimatedCostLimit) + } + } + } + t.Logf("DeviceType layout rules total %d (CRD limit %d)", total, crdvalidation.StaticEstimatedCRDCostLimit) + if total > crdvalidation.StaticEstimatedCRDCostLimit { + t.Fatalf("DeviceType rules estimated %d, over the CRD limit %d", total, crdvalidation.StaticEstimatedCRDCostLimit) + } + // Static estimates assume all 256 templates are laid out; the runtime + // cap of 128 is what keeps the real cost inside the per-call limit. + worst := worstCaseLayout(128) + cost, errs := runtimeCost(t, worst) + t.Logf("worst-case 128 laid-out templates: runtime cost %d (per-call limit %d)", cost, celconfig.PerCallLimit) + if len(errs) > 0 { + t.Fatalf("worst-case layout rejected: %v", errs) + } + // Keep headroom: the whole object, every rule included, under 75% of + // what one rule may spend. + if cost > celconfig.PerCallLimit*3/4 { + t.Fatalf("worst-case runtime cost %d leaves too little headroom under %d", cost, celconfig.PerCallLimit) + } + // One overlap in the worst case is reported as an overlap, not a cost error. + worst.Spec.ComponentTemplates[127].Layout = worst.Spec.ComponentTemplates[0].Layout + if _, errs := runtimeCost(t, worst); len(errs) == 0 || !strings.Contains(errs.ToAggregate().Error(), "overlap") || strings.Contains(errs.ToAggregate().Error(), "cost") { + t.Fatalf("worst-case overlap: %v", errs) + } + // Past the cap the object is rejected and says why, even where the + // overlap rule would then run out of budget. + for _, laidOut := range []int{129, 256} { + if errs := admit(t, "DeviceType", object(t, worstCaseLayout(laidOut)), nil); len(errs) == 0 || !strings.Contains(errs.ToAggregate().Error(), "at most 128 templates") { + t.Fatalf("%d laid-out templates: %v", laidOut, errs) + } + } +} + +// The hardware catalog doc's synthetic example must stay admissible. +func TestHardwareCatalogDocExampleIsAdmitted(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "docs", "development", "hardware-catalog.md")) + if err != nil { + t.Fatal(err) + } + _, after, found := strings.Cut(string(data), "### Example (synthetic)\n\n```yaml\n") + example, _, closed := strings.Cut(after, "```") + if !found || !closed { + t.Fatal("hardware-catalog.md has no synthetic faceplate example") + } + var record map[string]any + if err := yaml.Unmarshal([]byte(example), &record); err != nil { + t.Fatal(err) + } + if errs := admit(t, "DeviceType", object(t, record), nil); len(errs) > 0 { + t.Fatalf("documented example rejected: %v", errs) + } + spec := record["spec"].(map[string]any) + if len(spec["faceplate"].(map[string]any)["banks"].([]any)) != 5 || len(spec["componentTemplates"].([]any)) != 7 { + t.Fatal("example changed shape; update this test with it") + } +} diff --git a/internal/api/inventory/v1alpha1/iam_test.go b/internal/api/inventory/v1alpha1/iam_test.go new file mode 100644 index 00000000..f43023da --- /dev/null +++ b/internal/api/inventory/v1alpha1/iam_test.go @@ -0,0 +1,178 @@ +package v1alpha1 + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/util/yaml" +) + +type protectedResource struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + ServiceRef struct{ Name string } `json:"serviceRef"` + Kind string `json:"kind"` + Plural string `json:"plural"` + Singular string `json:"singular"` + Permissions []string `json:"permissions"` + Parents []struct { + APIGroup string `json:"apiGroup"` + Kind string `json:"kind"` + } `json:"parentResources"` + } `json:"spec"` +} + +type role struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + Inherited []struct{ Name string } `json:"inheritedRoles"` + Included []string `json:"includedPermissions"` + } `json:"spec"` +} + +func decodeDir[T any](t *testing.T, dir string) []T { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "*.yaml")) + if err != nil { + t.Fatal(err) + } + var out []T + for _, file := range files { + if filepath.Base(file) == "kustomization.yaml" { + continue + } + data, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var item T + if err := decoder.Decode(&item); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + out = append(out, item) + } + } + return out +} + +func TestProtectedResourcesMatchTheCRDs(t *testing.T) { + crds := loadCRDs(t) + resources := decodeDir[protectedResource](t, filepath.Join(inventoryRoot, "protected-resources")) + if len(resources) != len(crds) { + t.Fatalf("got %d ProtectedResources for %d CRDs", len(resources), len(crds)) + } + for _, resource := range resources { + crd := crds[resource.Spec.Kind] + if crd == nil { + t.Fatalf("ProtectedResource %s names unknown kind %s", resource.Metadata.Name, resource.Spec.Kind) + } + // The authorization provider indexes ProtectedResources by + // "{apiGroup}/{plural}", so serviceRef must be the API group. + if resource.Spec.ServiceRef.Name != GroupVersion.Group || resource.Spec.Plural != crd.Spec.Names.Plural || resource.Spec.Singular != crd.Spec.Names.Singular { + t.Fatalf("ProtectedResource %s does not match %s", resource.Metadata.Name, crd.Name) + } + if resource.Metadata.Name != GroupVersion.Group+"-"+crd.Spec.Names.Singular { + t.Fatalf("ProtectedResource name %s", resource.Metadata.Name) + } + if len(resource.Spec.Parents) != 1 || resource.Spec.Parents[0].APIGroup != "resourcemanager.miloapis.com" || resource.Spec.Parents[0].Kind != "Project" { + t.Fatalf("%s must be project-scoped", resource.Metadata.Name) + } + if slices.Contains(resource.Spec.Permissions, "updateStatus") { + t.Fatalf("%s grants status writes; status has no writer yet", resource.Metadata.Name) + } + } +} + +func TestInventoryRolesSplitReadFromWrite(t *testing.T) { + declared := map[string]bool{} + for _, resource := range decodeDir[protectedResource](t, filepath.Join(inventoryRoot, "protected-resources")) { + for _, verb := range resource.Spec.Permissions { + declared[GroupVersion.Group+"/"+resource.Spec.Plural+"."+verb] = true + } + } + roles := map[string]role{} + for _, r := range decodeDir[role](t, filepath.Join(inventoryRoot, "roles")) { + roles[r.Metadata.Name] = r + } + wantVerbs := map[string][]string{ + "fleet.datumapis.com-inventory-viewer": {"get", "list", "watch"}, + "fleet.datumapis.com-inventory-editor": {"create", "update", "patch", "delete"}, + "fleet.datumapis.com-inventory-manager": {"create", "update", "patch"}, + "fleet.datumapis.com-inventory-importer": {"create", "patch"}, + } + if len(roles) != len(wantVerbs) { + t.Fatalf("want exactly viewer, editor, manager and importer roles, got %v", roles) + } + for name, verbs := range wantVerbs { + t.Run(name, func(t *testing.T) { + current, ok := roles[name] + if !ok { + t.Fatalf("missing role %s", name) + } + var expected []string + for _, resource := range []string{"manufacturers", "devicetypes", "sites", "deviceclaims", "devices", "facilities", "racks", "cables", "powerfeeds"} { + for _, verb := range verbs { + expected = append(expected, GroupVersion.Group+"/"+resource+"."+verb) + } + } + actual := slices.Clone(current.Spec.Included) + slices.Sort(expected) + slices.Sort(actual) + if !slices.Equal(actual, expected) { + t.Fatalf("%s permissions = %v, want %v", name, actual, expected) + } + for _, permission := range actual { + if !declared[permission] { + t.Fatalf("role permission %s has no ProtectedResource", permission) + } + } + if name == "fleet.datumapis.com-inventory-viewer" { + if len(current.Spec.Inherited) != 0 { + t.Fatal("viewer must not inherit additional permissions") + } + } else if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-inventory-viewer" { + t.Fatal("editor, manager and importer must inherit only the viewer role") + } + }) + } +} + +func TestOnlyMiloServesTheInventoryKinds(t *testing.T) { + read := func(path string) string { + data, err := os.ReadFile(filepath.Join(configRoot, path, "kustomization.yaml")) + if err != nil { + t.Fatal(err) + } + return string(data) + } + if !strings.Contains(read("milo"), "../components/inventory\n") { + t.Fatal("config/milo must register the inventory kinds") + } + for _, root := range []string{"base/crd", "overlays/management-plane", "overlays/synthetic-staging"} { + if strings.Contains(read(root), "inventory") { + t.Fatalf("config/%s must not install the inventory kinds on the management cluster", root) + } + } + // Metal roles reach consumers. None may grant inventory access. + for _, r := range decodeDir[role](t, filepath.Join(configRoot, "components", "iam", "roles")) { + for _, permission := range r.Spec.Included { + if strings.HasPrefix(permission, GroupVersion.Group+"/") { + t.Fatalf("metal role %s grants inventory permission %s", r.Metadata.Name, permission) + } + } + for _, inherited := range r.Spec.Inherited { + if strings.HasPrefix(inherited.Name, GroupVersion.Group+"-") { + t.Fatalf("metal role %s inherits inventory role %s", r.Metadata.Name, inherited.Name) + } + } + } +} diff --git a/internal/api/inventory/v1alpha1/lifecycle_test.go b/internal/api/inventory/v1alpha1/lifecycle_test.go new file mode 100644 index 00000000..c6413816 --- /dev/null +++ b/internal/api/inventory/v1alpha1/lifecycle_test.go @@ -0,0 +1,78 @@ +package v1alpha1 + +import "testing" + +func lifecycleDevice(t *testing.T, lifecycle DeviceLifecycle) map[string]any { + t.Helper() + device := syntheticDevice() + device.Spec.Lifecycle = lifecycle + return object(t, device) +} + +func TestDeviceLifecycleDefaultsToActive(t *testing.T) { + device := lifecycleDevice(t, "") + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + if got := device["spec"].(map[string]any)["lifecycle"]; got != string(DeviceActive) { + t.Fatalf("unset lifecycle defaulted to %v, want Active", got) + } + if got := LifecycleOf(&Device{}); got != DeviceActive { + t.Fatalf("LifecycleOf(unset) = %q, want Active", got) + } + if errs := admit(t, "Device", lifecycleDevice(t, "Unknown"), nil); len(errs) == 0 { + t.Fatal("an unknown lifecycle value was accepted") + } +} + +func TestDeviceLifecycleTransitions(t *testing.T) { + for _, test := range []struct { + from, to DeviceLifecycle + allowed bool + }{ + {DeviceActive, DeviceActive, true}, + {DeviceActive, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceActive, true}, + {DeviceDecommissioning, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceRetired, true}, + {DeviceRetired, DeviceRetired, true}, + // An unset value is Active, before and after. + {"", DeviceDecommissioning, true}, + {DeviceDecommissioning, "", true}, + {DeviceActive, DeviceRetired, false}, + {"", DeviceRetired, false}, + {DeviceRetired, DeviceActive, false}, + {DeviceRetired, DeviceDecommissioning, false}, + // Removing the field defaults it to Active, so it is not a way out. + {DeviceRetired, "", false}, + } { + errs := admit(t, "Device", lifecycleDevice(t, test.to), lifecycleDevice(t, test.from)) + if allowed := len(errs) == 0; allowed != test.allowed { + t.Errorf("%q -> %q: allowed = %v, want %v (%v)", test.from, test.to, allowed, test.allowed, errs) + } + } +} + +// TestRetiredDeviceStillAcceptsOtherEdits pins that the terminal rule only +// freezes lifecycle, so a Retired record can still be corrected. +func TestRetiredDeviceStillAcceptsOtherEdits(t *testing.T) { + old := syntheticDevice() + old.Spec.Lifecycle = DeviceRetired + edited := syntheticDevice() + edited.Spec.Lifecycle = DeviceRetired + edited.Spec.AssetTag = "asset-0001" + if errs := admit(t, "Device", object(t, edited), object(t, old)); len(errs) > 0 { + t.Fatalf("edit of a Retired Device rejected: %v", errs) + } +} + +// TestDeviceMayBeCreatedInAnyLifecycle pins that transition rules apply to +// updates only: a record of hardware already out of service may be created +// as such. +func TestDeviceMayBeCreatedInAnyLifecycle(t *testing.T) { + for _, lifecycle := range []DeviceLifecycle{DeviceActive, DeviceDecommissioning, DeviceRetired} { + if errs := admit(t, "Device", lifecycleDevice(t, lifecycle), nil); len(errs) > 0 { + t.Errorf("create as %s rejected: %v", lifecycle, errs) + } + } +} diff --git a/internal/api/inventory/v1alpha1/physical.go b/internal/api/inventory/v1alpha1/physical.go new file mode 100644 index 00000000..8c6875ec --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical.go @@ -0,0 +1,219 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +type ExternalReference struct { + System string `json:"system"` + Type string `json:"type"` + ID string `json:"id"` +} + +// ModelShape is a nominal shape, never a measurement. FullDepth means the +// chassis reaches both the front and rear rails. Unset means unknown and is +// never defaulted. Width is Full or Half; unset means unknown, and a reader +// that draws it assumes Full and says so. A Device value overrides its +// DeviceType's value. +type ModelShape struct { + HeightUnits *float64 `json:"heightUnits,omitempty"` + FullDepth *bool `json:"fullDepth,omitempty"` + Width ChassisWidth `json:"width,omitempty"` +} + +// ChassisWidth is the nominal chassis width: the full rack width, or half, +// for servers and switches that sit side by side in one unit. Which half a +// Device occupies is a placement fact and is not recorded here. +type ChassisWidth string + +const ( + ChassisFullWidth ChassisWidth = "Full" + ChassisHalfWidth ChassisWidth = "Half" +) + +type PhysicalMetadata struct { + DisplayName string `json:"displayName"` +} + +type FacilitySpec struct { + PhysicalMetadata `json:",inline"` + LocationRef *LocalReference `json:"locationRef,omitempty"` + Identifiers []FacilityIdentifier `json:"identifiers,omitempty"` +} + +type FacilityIdentifier struct { + Provider string `json:"provider"` + Type string `json:"type"` + Value string `json:"value"` +} + +type SiteSpec struct { + PhysicalMetadata `json:",inline"` + Code string `json:"code"` + FacilityRefs []LocalReference `json:"facilityRefs,omitempty"` +} + +type Site struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec SiteSpec `json:"spec"` +} + +type SiteList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Site `json:"items"` +} + +func (in *Site) DeepCopyObject() runtime.Object { + out := new(Site) + deepCopy(in, out) + return out +} + +func (in *SiteList) DeepCopyObject() runtime.Object { + out := new(SiteList) + deepCopy(in, out) + return out +} + +type RackSpec struct { + PhysicalMetadata `json:",inline"` + FacilityRef LocalReference `json:"facilityRef"` + HeightUnits int32 `json:"heightUnits,omitempty"` +} + +type Component struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Connector string `json:"connector,omitempty"` + Positions int32 `json:"positions,omitempty"` + Serial string `json:"serial,omitempty"` + AssetTag string `json:"assetTag,omitempty"` +} + +type ComponentPosition struct { + ComponentID string `json:"componentID"` + Position int32 `json:"position"` +} + +type InternalMapping struct { + From ComponentPosition `json:"from"` + To ComponentPosition `json:"to"` +} + +type ServiceAssociation struct { + ServiceRef ExternalReference `json:"serviceRef"` + ComponentID string `json:"componentID"` +} + +type CableEndpoint struct { + DeviceRef *LocalReference `json:"deviceRef,omitempty"` + PowerFeedRef *LocalReference `json:"powerFeedRef,omitempty"` + ComponentID string `json:"componentID"` + Position int32 `json:"position"` +} + +type CableLane struct { + ID string `json:"id"` + A CableEndpoint `json:"a"` + B CableEndpoint `json:"b"` +} + +type CableSpec struct { + PhysicalMetadata `json:",inline"` + Medium string `json:"medium"` + Lanes []CableLane `json:"lanes"` +} + +type PowerSupply struct { + Type string `json:"type"` + VoltageV int32 `json:"voltageV,omitempty"` + CurrentA int32 `json:"currentA,omitempty"` + Phase string `json:"phase,omitempty"` +} + +type PowerFeedSpec struct { + PhysicalMetadata `json:",inline"` + FacilityRef LocalReference `json:"facilityRef"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Supply *PowerSupply `json:"supply,omitempty"` + Terminations []Component `json:"terminations"` + UpstreamSources []ExternalReference `json:"upstreamSources,omitempty"` +} + +type Facility struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec FacilitySpec `json:"spec"` +} +type Rack struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec RackSpec `json:"spec"` +} +type Cable struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec CableSpec `json:"spec"` +} +type PowerFeed struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec PowerFeedSpec `json:"spec"` +} +type FacilityList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Facility `json:"items"` +} +type RackList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Rack `json:"items"` +} +type CableList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Cable `json:"items"` +} +type PowerFeedList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PowerFeed `json:"items"` +} + +func (in *Facility) DeepCopyObject() runtime.Object { + out := new(Facility) + deepCopy(in, out) + return out +} +func (in *Rack) DeepCopyObject() runtime.Object { out := new(Rack); deepCopy(in, out); return out } +func (in *Cable) DeepCopyObject() runtime.Object { out := new(Cable); deepCopy(in, out); return out } +func (in *PowerFeed) DeepCopyObject() runtime.Object { + out := new(PowerFeed) + deepCopy(in, out) + return out +} +func (in *FacilityList) DeepCopyObject() runtime.Object { + out := new(FacilityList) + deepCopy(in, out) + return out +} +func (in *RackList) DeepCopyObject() runtime.Object { + out := new(RackList) + deepCopy(in, out) + return out +} +func (in *CableList) DeepCopyObject() runtime.Object { + out := new(CableList) + deepCopy(in, out) + return out +} +func (in *PowerFeedList) DeepCopyObject() runtime.Object { + out := new(PowerFeedList) + deepCopy(in, out) + return out +} diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go new file mode 100644 index 00000000..ba337dc4 --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -0,0 +1,170 @@ +package v1alpha1 + +import ( + "bytes" + "flag" + "io" + "os" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/yaml" +) + +const manualInventoryExample = "../../../../hack/testdata/physical/manual.yaml" + +var inventoryRecords = flag.String("inventory-records", manualInventoryExample, "private YAML records to validate offline; never applies records") + +func TestManualInventoryRecordsPassAdmission(t *testing.T) { + data, err := os.ReadFile(*inventoryRecords) + if err != nil { + t.Fatal("cannot read inventory records") + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + crds := loadCRDs(t) + seen := map[string]bool{} + count := 0 + for { + var record map[string]any + if err := decoder.Decode(&record); err == io.EOF { + break + } else if err != nil { + t.Fatal("cannot decode inventory records") + } + if len(record) == 0 { + continue + } + kind, ok := record["kind"].(string) + if !ok || crds[kind] == nil { + t.Fatal("expected one of the six physical kinds") + } + seen[kind] = true + if *inventoryRecords == manualInventoryExample { + spec := record["spec"].(map[string]any) + if spec["provenance"] != nil || record["status"] != nil { + t.Fatal("manual example must carry no provenance or status assertion") + } + if kind == "DeviceClaim" && spec["lifecycle"] != "Installation" || kind == "Device" && spec["topologyAuthority"] != "Cable" { + t.Fatal("new manual records must use typed installation and Cable topology") + } + } + for _, previous := range []map[string]any{nil, object(t, record)} { + if errs := admit(t, kind, object(t, record), previous); len(errs) != 0 { + t.Fatalf("record %d (%s) failed admission with %d errors; inspect privately", count+1, kind, len(errs)) + } + } + count++ + } + if count == 0 { + t.Fatal("no inventory records validated") + } + if *inventoryRecords == manualInventoryExample && len(seen) != 6 { + t.Fatal("manual example must exercise all six physical kinds") + } + t.Logf("validated %d records for create and unchanged update; no API writes", count) +} + +func TestTypedPlacementAndLegacyBinding(t *testing.T) { + claim := syntheticClaim() + claim.Spec.Lifecycle = "Installation" + claim.Spec.Ports = nil + claim.Spec.Placement = Placement{Scope: "RackMembership", RackRef: &LocalReference{Name: "rack-a"}} + if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) != 0 { + t.Fatal(errs) + } + for _, placement := range []Placement{ + {Scope: "Facility", FacilityRef: &LocalReference{Name: "facility-a"}}, + {Scope: "RackUnits", RackRef: &LocalReference{Name: "rack-a"}, Position: 12, Height: 1, Face: "front"}, + {Scope: "NonRackUnitMount", RackRef: &LocalReference{Name: "rack-a"}, Mount: "side-a"}, + } { + candidate := claim + candidate.Spec.Placement = placement + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) != 0 { + t.Fatal(errs) + } + if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, claim)); len(errs) == 0 { + t.Fatal("moved an installation by editing placement") + } + } + candidate := claim + candidate.Spec.Placement.Position = 1 + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted synthetic units on rack membership") + } + candidate = claim + if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, syntheticClaim())); len(errs) == 0 { + t.Fatal("converted a legacy slot in place") + } + candidate.Spec.Ports = syntheticClaim().Spec.Ports + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted competing inline topology") + } +} + +func TestPhysicalKindsSchemeAndAdmission(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + common := PhysicalMetadata{DisplayName: "Example"} + metadata := metav1.ObjectMeta{Name: "example", Namespace: "inventory"} + records := []runtime.Object{ + &Facility{ObjectMeta: metadata, Spec: FacilitySpec{PhysicalMetadata: common}}, + &Rack{ObjectMeta: metadata, Spec: RackSpec{PhysicalMetadata: common, FacilityRef: LocalReference{Name: "example"}, HeightUnits: 42}}, + &PowerFeed{ObjectMeta: metadata, Spec: PowerFeedSpec{PhysicalMetadata: common, FacilityRef: LocalReference{Name: "example"}, Terminations: []Component{{ID: "output", Name: "output", Type: "PowerOutlet"}}}}, + &Cable{ObjectMeta: metadata, Spec: CableSpec{PhysicalMetadata: common, Medium: "Power", Lanes: []CableLane{{ID: "one", A: CableEndpoint{PowerFeedRef: &LocalReference{Name: "example"}, ComponentID: "output", Position: 1}, B: CableEndpoint{DeviceRef: &LocalReference{Name: "server"}, ComponentID: "inlet", Position: 1}}}}}, + } + for _, record := range records { + kinds, _, err := scheme.ObjectKinds(record) + if err != nil { + t.Fatal(err) + } + kind := kinds[0].Kind + if errs := admit(t, kind, object(t, record.DeepCopyObject()), nil); len(errs) != 0 { + t.Fatalf("%s: %v", kind, errs) + } + } + cable := records[3].(*Cable) + cable.Spec.Lanes[0].A.DeviceRef = &LocalReference{Name: "other"} + if errs := admit(t, "Cable", object(t, cable), nil); len(errs) == 0 { + t.Fatal("accepted ambiguous endpoint owner") + } + cable.Spec.Lanes[0].A.DeviceRef = nil + cable.Spec.Lanes = append(cable.Spec.Lanes, cable.Spec.Lanes[0]) + cable.Spec.Lanes[1].ID = "two" + if errs := admit(t, "Cable", object(t, cable), nil); len(errs) == 0 { + t.Fatal("accepted duplicate lane endpoint") + } +} + +func TestComponentSafety(t *testing.T) { + device := syntheticDevice() + device.Spec.Interfaces = nil + device.Spec.TopologyAuthority = "Cable" + device.Spec.Components = []Component{{ID: "front", Name: "front", Type: "FrontPort"}, {ID: "rear", Name: "rear", Type: "RearPort", Positions: 2}} + device.Spec.InternalMappings = []InternalMapping{{From: ComponentPosition{ComponentID: "front", Position: 1}, To: ComponentPosition{ComponentID: "rear", Position: 2}}} + if errs := admit(t, "Device", object(t, device), nil); len(errs) != 0 { + t.Fatal(errs) + } + candidate := device.DeepCopyObject().(*Device) + candidate.Spec.InternalMappings[0].To.Position = 3 + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted nonexistent panel position") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Components = append(candidate.Spec.Components, candidate.Spec.Components[0]) + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted duplicate component ID") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Components[1].Type = "NetworkPort" + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted incompatible pass-through component types") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Interfaces = syntheticDevice().Spec.Interfaces + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted Cable and inline topology writers") + } +} diff --git a/internal/api/inventory/v1alpha1/reported_placement_test.go b/internal/api/inventory/v1alpha1/reported_placement_test.go new file mode 100644 index 00000000..4ab655ca --- /dev/null +++ b/internal/api/inventory/v1alpha1/reported_placement_test.go @@ -0,0 +1,201 @@ +package v1alpha1 + +import ( + "bytes" + "encoding/json" + "reflect" + "testing" + "time" + + jsonpatch "github.com/evanphx/json-patch/v5" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestPlacementJSONPatchPreconditionsBeforeAdmission(t *testing.T) { + baseline := reportedDevice() + baseline.UID = "device-uid" + baseline.ResourceVersion = "7" + report := &ReportedPlacement{Revision: 2, ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example"} + request, err := json.Marshal([]map[string]any{ + {"op": "test", "path": "/metadata/uid", "value": string(baseline.UID)}, + {"op": "test", "path": "/metadata/resourceVersion", "value": baseline.ResourceVersion}, + {"op": "add", "path": "/spec/reportedPlacement", "value": report}, + }) + if err != nil { + t.Fatal(err) + } + patch, err := jsonpatch.DecodePatch(request) + if err != nil { + t.Fatal(err) + } + for _, conflict := range []string{"", "uid", "resourceVersion"} { + t.Run(conflict, func(t *testing.T) { + current := baseline.DeepCopyObject().(*Device) + if conflict == "uid" { + current.UID = "replacement" + } + if conflict == "resourceVersion" { + current.ResourceVersion = "8" + } + before, err := json.Marshal(current) + if err != nil { + t.Fatal(err) + } + retained := bytes.Clone(before) + candidate, err := patch.Apply(before) + if !bytes.Equal(before, retained) { + t.Fatal("mutated input before commit") + } + if conflict != "" { + if err == nil || candidate != nil { + t.Fatal("precondition did not reject before mutation") + } + return + } + if err != nil { + t.Fatal(err) + } + var changed Device + if err := json.Unmarshal(candidate, &changed); err != nil { + t.Fatal(err) + } + if errs := admit(t, "Device", object(t, changed), object(t, current)); len(errs) != 0 { + t.Fatal(errs) + } + beforeSpec := object(t, baseline)["spec"].(map[string]any) + afterSpec := object(t, changed)["spec"].(map[string]any) + if !reflect.DeepEqual(afterSpec["identity"], beforeSpec["identity"]) || changed.Spec.ClaimRef != baseline.Spec.ClaimRef { + t.Fatal("changed protected fields") + } + }) + } +} + +func reportedDevice() Device { + device := syntheticDevice() + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, ObservedAt: metav1.NewTime(baseTime), Reason: "Initial report", Reference: "ticket/initial", RackRef: &LocalReference{Name: "rack-a"}} + return device +} + +func TestReportedPlacementAdmission(t *testing.T) { + for _, device := range []Device{syntheticDevice(), reportedDevice()} { + for _, previous := range []map[string]any{nil, object(t, device)} { + if errs := admit(t, "Device", object(t, device), previous); len(errs) != 0 { + t.Fatal(errs) + } + } + } + for _, height := range []float64{0.5, 1, 4} { + device := reportedDevice() + position := 12.5 + device.Spec.ReportedPlacement.Height = &height + device.Spec.ReportedPlacement.Position = &position + if errs := admit(t, "Device", object(t, device), nil); len(errs) != 0 { + t.Fatal(errs) + } + } + for name, mutate := range map[string]func(*Device){ + "negative": func(device *Device) { value := -1.0; device.Spec.ReportedPlacement.Position = &value }, + "position range": func(device *Device) { value := 101.0; device.Spec.ReportedPlacement.Position = &value }, + "height range": func(device *Device) { value := 101.0; device.Spec.ReportedPlacement.Height = &value }, + "end range": func(device *Device) { + position, height := 100.0, 2.0 + device.Spec.ReportedPlacement.Position = &position + device.Spec.ReportedPlacement.Height = &height + }, + "zero height": func(device *Device) { value := 0.0; device.Spec.ReportedPlacement.Height = &value }, + "invalid face": func(device *Device) { device.Spec.ReportedPlacement.Face = "unknown" }, + "geometry without rack": func(device *Device) { + device.Spec.ReportedPlacement.RackRef = nil + device.Spec.ReportedPlacement.Face = "front" + }, + "mount and units": func(device *Device) { + device.Spec.ReportedPlacement.Mount = "side" + device.Spec.ReportedPlacement.Face = "front" + }, + "missing reason": func(device *Device) { device.Spec.ReportedPlacement.Reason = "" }, + "missing reference": func(device *Device) { device.Spec.ReportedPlacement.Reference = "" }, + "revision": func(device *Device) { device.Spec.ReportedPlacement.Revision = 2 }, + } { + t.Run(name, func(t *testing.T) { + device := reportedDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Fatal("accepted invalid report") + } + }) + } +} + +func TestPlacementCorrectionProtectsIdentityAndRevision(t *testing.T) { + for name, mutate := range map[string]func(*Device){ + "stale revision enrichment": func(device *Device) { value := 12.0; device.Spec.ReportedPlacement.Position = &value }, + "stale revision rack move": func(device *Device) { device.Spec.ReportedPlacement.RackRef.Name = "rack-b" }, + "removal": func(device *Device) { device.Spec.ReportedPlacement = nil }, + "rebinding": func(device *Device) { device.Spec.ClaimRef.Name = "other" }, + "identity": func(device *Device) { device.Spec.Identity.Serial = "other" }, + } { + t.Run(name, func(t *testing.T) { + old := reportedDevice() + device := old.DeepCopyObject().(*Device) + mutate(device) + device.Spec.DisplayName = "bundled edit" + device.Labels = map[string]string{"owner": "operator", "audit-approved": "true"} + device.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "fleet-staff-inventory-ui", Operation: metav1.ManagedFieldsOperationUpdate}} + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) == 0 { + t.Fatal("direct update bypassed gate") + } + }) + } + device := reportedDevice() + old := device.DeepCopyObject().(*Device) + old.Spec.ReportedPlacement = nil + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } + old = device.DeepCopyObject().(*Device) + device.Spec.DisplayName = "unrelated recordkeeping" + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } +} + +func TestPlacementCorrections(t *testing.T) { + for _, existing := range []bool{false, true} { + old := reportedDevice() + if !existing { + old.Spec.ReportedPlacement = nil + } + device := old.DeepCopyObject().(*Device) + revision := int32(1) + if old.Spec.ReportedPlacement != nil { + revision++ + } + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: revision, ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example", RackRef: &LocalReference{Name: "other-rack"}} + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } + for name, mutate := range map[string]func(*Device){ + "missing reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = "" }, + "blank reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = " " }, + "missing evidence": func(record *Device) { record.Spec.ReportedPlacement.Reference = "" }, + "skipped revision": func(record *Device) { record.Spec.ReportedPlacement.Revision += 2 }, + "claim binding": func(record *Device) { record.Spec.ClaimRef.Name = "other" }, + "identity": func(record *Device) { record.Spec.Identity.Serial = "other" }, + } { + t.Run(name, func(t *testing.T) { + invalid := device.DeepCopyObject().(*Device) + mutate(invalid) + if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { + t.Fatal("accepted invalid correction") + } + }) + } + unknown := device.DeepCopyObject().(*Device) + unknown.Spec.ReportedPlacement.RackRef = nil + unknown.Spec.ReportedPlacement.Revision++ + if errs := admit(t, "Device", object(t, unknown), object(t, device)); len(errs) != 0 { + t.Fatal(errs) + } + } +} diff --git a/internal/api/inventory/v1alpha1/site_facility_name_test.go b/internal/api/inventory/v1alpha1/site_facility_name_test.go new file mode 100644 index 00000000..16ff84d4 --- /dev/null +++ b/internal/api/inventory/v1alpha1/site_facility_name_test.go @@ -0,0 +1,15 @@ +package v1alpha1 + +import "testing" + +func TestIndependentSiteRejectsImpossibleFacilityNames(t *testing.T) { + for _, name := range []string{"premises..one", "premises.-one", "premises-.one"} { + t.Run(name, func(t *testing.T) { + candidate := syntheticSite() + candidate.Spec.FacilityRefs[0].Name = name + if errs := admit(t, "Site", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("admitted a reference that cannot name a Kubernetes Facility") + } + }) + } +} diff --git a/internal/api/inventory/v1alpha1/site_reader.go b/internal/api/inventory/v1alpha1/site_reader.go new file mode 100644 index 00000000..0a609519 --- /dev/null +++ b/internal/api/inventory/v1alpha1/site_reader.go @@ -0,0 +1,31 @@ +package v1alpha1 + +import ( + "context" + "fmt" + + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func ReadSiteFacilities(ctx context.Context, reader client.Reader, site *Site) ([]Facility, error) { + if reader == nil || site == nil || site.Namespace == "" || site.UID == "" || !site.DeletionTimestamp.IsZero() { + return nil, fmt.Errorf("site membership unavailable") + } + facilities := make([]Facility, 0, len(site.Spec.FacilityRefs)) + seenNames := map[string]bool{} + for _, reference := range site.Spec.FacilityRefs { + if reference.Name == "" || seenNames[reference.Name] { + return nil, fmt.Errorf("invalid facility membership reference") + } + seenNames[reference.Name] = true + var facility Facility + if err := reader.Get(ctx, client.ObjectKey{Namespace: site.Namespace, Name: reference.Name}, &facility); err != nil { + return nil, fmt.Errorf("facility membership unavailable") + } + if !facility.DeletionTimestamp.IsZero() { + return nil, fmt.Errorf("facility membership unavailable") + } + facilities = append(facilities, facility) + } + return facilities, nil +} diff --git a/internal/api/inventory/v1alpha1/site_test.go b/internal/api/inventory/v1alpha1/site_test.go new file mode 100644 index 00000000..b3f3d8f1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/site_test.go @@ -0,0 +1,215 @@ +package v1alpha1 + +import ( + "context" + "fmt" + "reflect" + "strings" + "testing" + + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + 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" +) + +func syntheticSite() *Site { + return &Site{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Site"}, + ObjectMeta: metav1.ObjectMeta{Name: "site-stable", Namespace: "inventory", UID: "site-uid"}, + Spec: SiteSpec{PhysicalMetadata: PhysicalMetadata{DisplayName: "Example operational site"}, Code: "EX3", FacilityRefs: []LocalReference{{Name: "facility-stable"}}}, + } +} + +func syntheticFacility() *Facility { + return &Facility{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Facility"}, + ObjectMeta: metav1.ObjectMeta{Name: "facility-stable", Namespace: "inventory", UID: "facility-uid"}, + Spec: FacilitySpec{PhysicalMetadata: syntheticSite().Spec.PhysicalMetadata, Identifiers: []FacilityIdentifier{{Provider: "example-a", Type: "PremisesCode", Value: "EX1"}, {Provider: "example-b", Type: "PremisesCode", Value: "EX1"}}}, + } +} + +func TestSiteAndFacilityAdmission(t *testing.T) { + site, facility := syntheticSite(), syntheticFacility() + for _, record := range []any{site, facility} { + kind := object(t, record)["kind"].(string) + if errs := admit(t, kind, object(t, record), nil); len(errs) != 0 { + t.Fatal(errs) + } + } + legacy := syntheticFacility() + legacy.Spec.Identifiers = nil + if errs := admit(t, "Facility", object(t, legacy), object(t, legacy)); len(errs) != 0 { + t.Fatal(errs) + } + renamed := site.DeepCopyObject().(*Site) + renamed.Spec.Code = "NEW-CODE" + renamed.Spec.DisplayName = "Renamed operational label" + if errs := admit(t, "Site", object(t, renamed), object(t, site)); len(errs) != 0 { + t.Fatal(errs) + } + for name, mutate := range map[string]func(*Site){ + "missing name": func(candidate *Site) { candidate.Spec.FacilityRefs[0].Name = "" }, + "missing code": func(candidate *Site) { candidate.Spec.Code = "" }, + "duplicate name": func(candidate *Site) { + candidate.Spec.FacilityRefs = append(candidate.Spec.FacilityRefs, LocalReference{Name: "facility-stable"}) + }, + } { + t.Run(name, func(t *testing.T) { + candidate := syntheticSite() + mutate(candidate) + if errs := admit(t, "Site", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted invalid Site relationship") + } + }) + } + for _, identifier := range []FacilityIdentifier{{Type: "PremisesCode", Value: "EX1"}, {Provider: "example", Type: "Metro", Value: "EX"}, {Provider: "example", Type: "Account", Value: "account"}, {Provider: "example", Type: "PremisesCode"}} { + candidate := syntheticFacility() + candidate.Spec.Identifiers = []FacilityIdentifier{identifier} + if errs := admit(t, "Facility", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted unqualified or non-premises identifier") + } + } + facility.Spec.Identifiers = append(facility.Spec.Identifiers, facility.Spec.Identifiers[0]) + if errs := admit(t, "Facility", object(t, facility), nil); len(errs) == 0 { + t.Fatal("accepted duplicate identifier") + } +} + +func TestSiteReferenceAndProviderDNSLabelBoundaries(t *testing.T) { + for _, name := range []string{"premises..one", "premises.-one", "premises-.one", "Upper", "_invalid"} { + facility := syntheticFacility() + facility.Spec.Identifiers[0].Provider = name + if errs := admit(t, "Facility", object(t, facility), nil); len(errs) == 0 { + t.Fatalf("accepted invalid provider namespace %q", name) + } + } + for _, name := range []string{"premises", "premises.one", "premises-one.provider-two"} { + site := syntheticSite() + site.Spec.FacilityRefs[0].Name = name + if errs := admit(t, "Site", object(t, site), nil); len(errs) != 0 { + t.Fatalf("rejected valid reference %q: %v", name, errs) + } + } +} + +type deniedFacilityReader struct{ client.Reader } + +func (deniedFacilityReader) Get(context.Context, client.ObjectKey, client.Object, ...client.GetOption) error { + return fmt.Errorf("forbidden secret-provider-code") +} + +func TestSiteReaderIsObservationalAndNamespaceScoped(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + facility, site := syntheticFacility(), syntheticSite() + store := fake.NewClientBuilder().WithScheme(scheme).WithObjects(facility, site).Build() + before := facility.DeepCopyObject() + resolved, err := ReadSiteFacilities(context.Background(), store, site) + if err != nil || len(resolved) != 1 { + t.Fatalf("membership: %v, %v", resolved, err) + } + site.Spec.Code = "RENAMED" + facility.Spec.Identifiers[0].Value = "RENAMED-PROVIDER-CODE" + if err := store.Update(context.Background(), facility); err != nil { + t.Fatal(err) + } + resolved, err = ReadSiteFacilities(context.Background(), store, site) + if err != nil || resolved[0].UID != before.(*Facility).UID { + t.Fatal("labels changed stable membership") + } + for _, candidate := range []*Site{ + {ObjectMeta: metav1.ObjectMeta{Namespace: "other", UID: site.UID}, Spec: site.Spec}, + {ObjectMeta: site.ObjectMeta, Spec: SiteSpec{FacilityRefs: []LocalReference{{Name: "missing"}}}}, + {ObjectMeta: site.ObjectMeta, Spec: SiteSpec{FacilityRefs: []LocalReference{{Name: facility.Name}, {Name: facility.Name}}}}, + } { + if records, err := ReadSiteFacilities(context.Background(), store, candidate); err == nil || records != nil { + t.Fatal("unresolved membership was treated as resolved") + } + } + if records, err := ReadSiteFacilities(context.Background(), deniedFacilityReader{}, site); err == nil || records != nil || strings.Contains(err.Error(), "secret-provider-code") { + t.Fatal("denied read leaked data or returned membership") + } + empty := syntheticSite() + empty.Spec.FacilityRefs = nil + if records, err := ReadSiteFacilities(context.Background(), store, empty); err != nil || len(records) != 0 { + t.Fatal("unmapped Site should resolve to no Facilities") + } + var storedSite Site + if err := store.Get(context.Background(), client.ObjectKeyFromObject(site), &storedSite); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(object(t, storedSite)["spec"], object(t, syntheticSite())["spec"]) { + t.Fatal("reader changed stored Site") + } +} + +func TestSiteNameReuseResolvesReplacementWithoutChangingDesiredState(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + site, facility := syntheticSite(), syntheticFacility() + store := fake.NewClientBuilder().WithScheme(scheme).WithObjects(site, facility).Build() + before := site.DeepCopyObject().(*Site) + if err := store.Delete(context.Background(), facility); err != nil { + t.Fatal(err) + } + if records, err := ReadSiteFacilities(context.Background(), store, site); err == nil || records != nil { + t.Fatal("missing name should remain unresolved") + } + replacement := syntheticFacility() + replacement.UID = "replacement-server-uid" + if err := store.Create(context.Background(), replacement); err != nil { + t.Fatal(err) + } + records, err := ReadSiteFacilities(context.Background(), store, site) + if err != nil || len(records) != 1 || records[0].UID != replacement.UID { + t.Fatalf("name reference must resolve the replacement: %v, %v", records, err) + } + if !reflect.DeepEqual(object(t, site)["spec"], object(t, before)["spec"]) { + t.Fatal("reader changed desired state") + } + replacement.DeletionTimestamp = &metav1.Time{Time: baseTime} + replacement.Finalizers = []string{"test.example/retain"} + deleting := fake.NewClientBuilder().WithScheme(scheme).WithObjects(replacement).Build() + if records, err := ReadSiteFacilities(context.Background(), deleting, site); err == nil || records != nil { + t.Fatal("deleting Facility should remain unavailable") + } +} + +func TestSiteAndFacilitySpecsContainNoUIDFields(t *testing.T) { + var inspect func(extensionsv1.JSONSchemaProps, string) + inspect = func(schema extensionsv1.JSONSchemaProps, path string) { + for name, property := range schema.Properties { + if strings.Contains(strings.ToLower(name), "uid") { + t.Fatalf("UID field in desired-state schema: %s.%s", path, name) + } + inspect(property, path+"."+name) + } + if schema.Items != nil && schema.Items.Schema != nil { + inspect(*schema.Items.Schema, path+"[]") + } + } + crds := loadCRDs(t) + for _, kind := range []string{"Site", "Facility"} { + inspect(crds[kind].Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"], kind+".spec") + } + site := syntheticSite() + encoded := object(t, site) + refs := encoded["spec"].(map[string]any)["facilityRefs"].([]any) + if !reflect.DeepEqual(refs[0], map[string]any{"name": "facility-stable"}) { + t.Fatal("serialized spec reference must contain only a name") + } + if encoded["metadata"].(map[string]any)["uid"] != "site-uid" { + t.Fatal("server metadata UID was lost") + } + copy := site.DeepCopyObject().(*Site) + copy.Spec.FacilityRefs[0].Name = "other" + if site.Spec.FacilityRefs[0].Name != "facility-stable" || copy.UID != site.UID { + t.Fatal("deep copy must isolate references and retain server identity") + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go new file mode 100644 index 00000000..cd8cd62c --- /dev/null +++ b/internal/api/inventory/v1alpha1/types.go @@ -0,0 +1,238 @@ +// Package v1alpha1 holds the six observational physical inventory kinds in +// fleet.datumapis.com. Legacy slot claims retain their historical bindings; +// new typed claims describe individual installations without accepting them. +// +// All are operator-written records. None has a controller. Registering a +// Device authorizes no hardware effect and creates or changes no +// MachineCapacity. Status is reserved for future collectors and verifiers and +// has no writer. +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +// DeviceClaim retains legacy slot plans and typed observational installations. +type DeviceClaim struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceClaimSpec `json:"spec"` + Status DeviceClaimStatus `json:"status,omitempty"` +} + +type DeviceClaimSpec struct { + DisplayName string `json:"displayName,omitempty"` + Lifecycle string `json:"lifecycle,omitempty"` + CableRefs []LocalReference `json:"cableRefs,omitempty"` + ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` + Placement Placement `json:"placement"` + Ports []ExpectedPort `json:"ports,omitempty"` +} + +// ExpectedIdentity is the planned equipment. Serial is usually unknown at plan +// time and is optional. +type ExpectedIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` +} + +// Placement retains legacy text placement or an explicit typed scope. +type Placement struct { + Scope string `json:"scope,omitempty"` + FacilityRef *LocalReference `json:"facilityRef,omitempty"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Mount string `json:"mount,omitempty"` + Facility string `json:"facility,omitempty"` + Rack string `json:"rack,omitempty"` + Position int32 `json:"position,omitempty"` + Height int32 `json:"height,omitempty"` + // Face is the mounted rack face: the rack face the chassis front points + // toward. See ReportedPlacement.Face. + Face string `json:"face,omitempty"` +} + +// ExpectedPort is a planned physical port and the cable peer it should reach. +// Logical LAGs and VLANs are not ports. +type ExpectedPort struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + SpeedMbps int64 `json:"speedMbps,omitempty"` + ExpectedPeer *PortPeer `json:"expectedPeer,omitempty"` +} + +// PortPeer names the far end of a cable by device name and port. +type PortPeer struct { + Device string `json:"device"` + Port string `json:"port"` +} + +// DeviceClaimStatus is reserved for verifiers. Nothing writes it yet. +type DeviceClaimStatus struct{} + +// Device is one actual asset, created by the registrar when detected hardware +// is bound to a claim. Its identity and claim binding are immutable: a hardware +// swap is a new Device. +type Device struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceSpec `json:"spec"` + Status DeviceStatus `json:"status,omitempty"` +} + +type DeviceSpec struct { + DeviceTypeRef *LocalReference `json:"deviceTypeRef,omitempty"` + ReportedPlacement *ReportedPlacement `json:"reportedPlacement,omitempty"` + DisplayName string `json:"displayName,omitempty"` + ModelShape *ModelShape `json:"modelShape,omitempty"` + AssetTag string `json:"assetTag,omitempty"` + ProviderHostRef *ExternalReference `json:"providerHostRef,omitempty"` + Components []Component `json:"components,omitempty"` + InternalMappings []InternalMapping `json:"internalMappings,omitempty"` + ServiceAssociations []ServiceAssociation `json:"serviceAssociations,omitempty"` + TopologyAuthority string `json:"topologyAuthority,omitempty"` + ClaimRef LocalReference `json:"claimRef"` + Identity DeviceIdentity `json:"identity"` + BMC *BMC `json:"bmc,omitempty"` + Interfaces []Interface `json:"interfaces,omitempty"` + // UnmappedMACAddresses are MACs detected on the asset that the registrar + // could not attribute to a named interface. + UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` + // Lifecycle is the asset's service state. The CRD defaults it to Active and + // allows Active and Decommissioning to move between each other and + // Decommissioning to move to Retired, which is terminal. Only an Active + // Device can back new capacity. + Lifecycle DeviceLifecycle `json:"lifecycle,omitempty"` +} + +// DeviceLifecycle is the service state of a Device. +type DeviceLifecycle string + +const ( + DeviceActive DeviceLifecycle = "Active" + DeviceDecommissioning DeviceLifecycle = "Decommissioning" + DeviceRetired DeviceLifecycle = "Retired" +) + +// LifecycleOf returns the Device's lifecycle, treating an unset value as +// Active, which is the CRD default. +func LifecycleOf(device *Device) DeviceLifecycle { + if device.Spec.Lifecycle == "" { + return DeviceActive + } + return device.Spec.Lifecycle +} + +type ReportedPlacement struct { + Revision int32 `json:"revision"` + ObservedAt metav1.Time `json:"observedAt"` + // Reason and Reference explain and evidence the report. Both are required. + Reason string `json:"reason"` + Reference string `json:"reference"` + FacilityRef *LocalReference `json:"facilityRef,omitempty"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Position *float64 `json:"position,omitempty"` + Height *float64 `json:"height,omitempty"` + // Face is the mounted rack face, front or rear: the rack face the + // chassis front points toward, as NetBox records it. A half-depth device + // sits on that face's rails and occupies only that face; a full-depth + // device occupies both faces. A switch mounted reversed, with its ports + // toward the rack rear, has face rear when its ports are on the chassis + // front. A chassis-relative component face maps to a rack face through + // this value: Front lands on Face, Rear on the opposite face. + Face string `json:"face,omitempty"` + // FullDepth is the reported depth for this installation. When unset, + // readers fall back to the Device's and then the DeviceType's model + // shape. A depth still unknown is counted as full depth for occupancy + // and conflicts only, and is labelled unknown; it is never defaulted. + FullDepth *bool `json:"fullDepth,omitempty"` + Mount string `json:"mount,omitempty"` +} + +type LocalReference struct { + Name string `json:"name"` +} + +// DeviceIdentity is the detected chassis identity. Serial and SystemUUID are +// matching evidence, not authenticators. A Device carries at least one of +// them, or sets Unidentified with neither. +type DeviceIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` + // SystemUUID is the SMBIOS system UUID in lowercase canonical form. + SystemUUID string `json:"systemUUID,omitempty"` + // Unidentified records deliberately that the equipment has no serial or + // system UUID on record, such as a patch panel. It may only be true, needs + // UnidentifiedReason, and excludes Serial and SystemUUID. Like the rest of + // identity it is immutable: recording a serial later is a new Device. An + // unidentified Device cannot back MachineCapacity. + Unidentified bool `json:"unidentified,omitempty"` + UnidentifiedReason string `json:"unidentifiedReason,omitempty"` +} + +// BMC records where the management controller was reached. Credentials never +// belong here. +type BMC struct { + Endpoint string `json:"endpoint"` +} + +type Interface struct { + Name string `json:"name"` + MACAddress string `json:"macAddress,omitempty"` + Peer *PortPeer `json:"peer,omitempty"` +} + +// DeviceStatus is reserved for collectors and verifiers to report drift and +// mismatch. It never carries identity. Nothing writes it yet. +type DeviceStatus struct{} + +type DeviceClaimList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceClaim `json:"items"` +} + +type DeviceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Device `json:"items"` +} + +func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &Manufacturer{}, &ManufacturerList{}, &DeviceType{}, &DeviceTypeList{}) + s.AddKnownTypes(GroupVersion, &Site{}, &SiteList{}, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}, &Facility{}, &FacilityList{}, &Rack{}, &RackList{}, &Cable{}, &CableList{}, &PowerFeed{}, &PowerFeedList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +var AddToScheme = addKnown + +func (in *DeviceClaim) DeepCopyObject() runtime.Object { + out := new(DeviceClaim) + deepCopy(in, out) + return out +} +func (in *DeviceClaimList) DeepCopyObject() runtime.Object { + out := new(DeviceClaimList) + deepCopy(in, out) + return out +} +func (in *Device) DeepCopyObject() runtime.Object { + out := new(Device) + deepCopy(in, out) + return out +} +func (in *DeviceList) DeepCopyObject() runtime.Object { + out := new(DeviceList) + deepCopy(in, out) + return out +} + +func deepCopy[T any](in *T, out *T) { b, _ := json.Marshal(in); _ = json.Unmarshal(b, out) } diff --git a/internal/api/inventory/v1alpha1/unidentified_test.go b/internal/api/inventory/v1alpha1/unidentified_test.go new file mode 100644 index 00000000..c940c5c1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/unidentified_test.go @@ -0,0 +1,187 @@ +package v1alpha1 + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/validation/field" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// syntheticPatchPanel is passive equipment with no serial or system UUID on +// record, registered with the explicit marker so Cables can reference it. +func syntheticPatchPanel() Device { + device := syntheticDevice() + device.Name = "rack-01-u40-patch-panel" + device.Spec.ClaimRef = LocalReference{Name: "rack-01-u40"} + device.Spec.Identity = DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 24-port panel", Unidentified: true, UnidentifiedReason: "passive patch panel; no serial on the chassis"} + device.Spec.BMC, device.Spec.Interfaces, device.Spec.UnmappedMACAddresses = nil, nil, nil + device.Spec.TopologyAuthority = "Cable" + device.Spec.Components = []Component{{ID: "front", Name: "Front ports", Type: "FrontPort", Positions: 24}, {ID: "rear", Name: "Rear ports", Type: "RearPort", Positions: 24}} + return device +} + +func rejectedWith(errs field.ErrorList, message string) bool { + for _, err := range errs { + if strings.Contains(err.Error(), message) { + return true + } + } + return false +} + +func TestUnidentifiedMarkerAdmitsDeviceWithoutSerial(t *testing.T) { + if errs := admit(t, "Device", object(t, syntheticPatchPanel()), nil); len(errs) > 0 { + t.Fatalf("unidentified device rejected: %v", errs) + } +} + +func TestUnidentifiedMarkerRules(t *testing.T) { + for name, tc := range map[string]struct { + mutate func(*DeviceIdentity) + message string + }{ + "marker with serial": {func(i *DeviceIdentity) { i.Serial = "SYNTHETIC-0040" }, "cannot carry a serial or system UUID"}, + "marker with system UUID": {func(i *DeviceIdentity) { i.SystemUUID = "00000000-0000-4000-8000-000000000040" }, "cannot carry a serial or system UUID"}, + "neither marker nor identity": {func(i *DeviceIdentity) { i.Unidentified, i.UnidentifiedReason = false, "" }, + "a device needs a serial or system UUID"}, + "marker without reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = "" }, "must be set together"}, + "blank reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = " \t " }, "unidentifiedReason"}, + "reason without marker": {func(i *DeviceIdentity) { i.Unidentified, i.Serial = false, "SYNTHETIC-0040" }, "must be set together"}, + "overlong reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = strings.Repeat("x", 1025) }, "unidentifiedReason"}, + } { + device := syntheticPatchPanel() + tc.mutate(&device.Spec.Identity) + if errs := admit(t, "Device", object(t, device), nil); !rejectedWith(errs, tc.message) { + t.Errorf("%s: want rejection containing %q, got %v", name, tc.message, errs) + } + } + explicitFalse := object(t, syntheticDevice()) + explicitFalse["spec"].(map[string]any)["identity"].(map[string]any)["unidentified"] = false + if errs := admit(t, "Device", explicitFalse, nil); !rejectedWith(errs, "unidentified may only be true") { + t.Errorf("unidentified: false accepted: %v", errs) + } +} + +func TestUnidentifiedIdentityIsImmutable(t *testing.T) { + old := object(t, syntheticPatchPanel()) + identified := syntheticPatchPanel() + identified.Spec.Identity.Unidentified, identified.Spec.Identity.UnidentifiedReason, identified.Spec.Identity.Serial = false, "", "SYNTHETIC-0040" + for name, mutate := range map[string]func(*DeviceIdentity){ + "add serial": func(i *DeviceIdentity) { *i = identified.Spec.Identity }, + "change reason": func(i *DeviceIdentity) { i.UnidentifiedReason = "cable manager" }, + } { + device := syntheticPatchPanel() + mutate(&device.Spec.Identity) + if errs := admit(t, "Device", object(t, device), old); !rejectedWith(errs, "identity is immutable") { + t.Errorf("%s: want immutability rejection, got %v", name, errs) + } + } + marked := syntheticDevice() + marked.Spec.BMC = nil + marked.Spec.Identity = syntheticPatchPanel().Spec.Identity + if errs := admit(t, "Device", object(t, marked), object(t, syntheticDevice())); !rejectedWith(errs, "identity is immutable") { + t.Errorf("marking an identified device unidentified: want immutability rejection, got %v", errs) + } + renamed := syntheticPatchPanel() + renamed.Spec.DisplayName = "Rack 01 patch panel" + if errs := admit(t, "Device", object(t, renamed), old); len(errs) > 0 { + t.Errorf("non-identity edit of an unidentified device rejected: %v", errs) + } +} + +// An unidentified Device cannot record a BMC, the management endpoint +// enrollment would use, and the capacity contract rejects it. +func TestUnidentifiedDeviceCannotBackCapacity(t *testing.T) { + withBMC := syntheticPatchPanel() + withBMC.Spec.BMC = &BMC{Endpoint: "https://192.0.2.140:443"} + if errs := admit(t, "Device", object(t, withBMC), nil); !rejectedWith(errs, "cannot record a BMC endpoint") { + t.Errorf("unidentified device with a BMC: want rejection, got %v", errs) + } + panel := syntheticPatchPanel() + if err := CapacityBackingError(&panel); !errors.Is(err, ErrUnidentifiedDevice) { + t.Errorf("unidentified device: got %v, want ErrUnidentifiedDevice", err) + } + reasonOnly := syntheticPatchPanel() + reasonOnly.Spec.Identity.Unidentified = false + if err := CapacityBackingError(&reasonOnly); !errors.Is(err, ErrUnidentifiedDevice) { + t.Errorf("device with only an unidentified reason: got %v, want ErrUnidentifiedDevice", err) + } + pruned := syntheticDevice() + pruned.Spec.Identity.Serial, pruned.Spec.Identity.SystemUUID = "", "" + if err := CapacityBackingError(&pruned); !errors.Is(err, ErrDeviceIdentityMissing) { + t.Errorf("device without identity: got %v, want ErrDeviceIdentityMissing", err) + } + if err := CapacityBackingError(nil); !errors.Is(err, ErrDeviceIdentityMissing) { + t.Errorf("missing device: got %v, want ErrDeviceIdentityMissing", err) + } + for _, mutate := range []func(*DeviceIdentity){ + func(i *DeviceIdentity) {}, + func(i *DeviceIdentity) { i.SystemUUID = "" }, + func(i *DeviceIdentity) { i.Serial = "" }, + } { + device := syntheticDevice() + mutate(&device.Spec.Identity) + if err := CapacityBackingError(&device); err != nil { + t.Errorf("identified device %+v rejected: %v", device.Spec.Identity, err) + } + } +} + +// TestUnidentifiedMarkerAgainstAPIServer checks the same rules in a real API +// server, including the update path. It needs envtest binaries +// (KUBEBUILDER_ASSETS) and is skipped without them. +func TestUnidentifiedMarkerAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS is not set; see docs/development/README.md") + } + env := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + c, err := client.New(cfg, client.Options{}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + toUnstructured := func(device Device) *unstructured.Unstructured { + device.Namespace = "default" + return &unstructured.Unstructured{Object: object(t, device)} + } + + panel := toUnstructured(syntheticPatchPanel()) + if err := c.Create(ctx, panel); err != nil { + t.Fatalf("create unidentified device: %v", err) + } + for name, mutate := range map[string]func(*Device){ + "marker with serial": func(d *Device) { d.Spec.Identity.Serial = "SYNTHETIC-0041" }, + "blank reason": func(d *Device) { d.Spec.Identity.UnidentifiedReason = " " }, + "neither": func(d *Device) { + d.Spec.Identity.Unidentified, d.Spec.Identity.UnidentifiedReason = false, "" + }, + "BMC": func(d *Device) { d.Spec.BMC = &BMC{Endpoint: "https://192.0.2.141:443"} }, + } { + device := syntheticPatchPanel() + device.Name = "rejected-" + strings.ReplaceAll(name, " ", "-") + mutate(&device) + if err := c.Create(ctx, toUnstructured(device)); err == nil { + t.Errorf("%s: create accepted", name) + } + } + + identity := panel.Object["spec"].(map[string]any)["identity"].(map[string]any) + delete(identity, "unidentified") + delete(identity, "unidentifiedReason") + identity["serial"] = "SYNTHETIC-0041" + if err := c.Update(ctx, panel); err == nil || !strings.Contains(err.Error(), "identity is immutable") { + t.Errorf("adding a serial to an unidentified device: got %v, want immutability rejection", err) + } +} From 80aa195420edf71ab654356cd632a92c980e05d6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 16:31:45 -0600 Subject: [PATCH 2/8] docs(inventory): describe the physical inventory API Add the operator guide for planning and registering devices, the hardware catalog contract, and the inventory proposal and reference appendix, and index them from the configuration, architecture, development and operations guides. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 11 +- docs/architecture/README.md | 2 +- docs/development/README.md | 27 + docs/development/hardware-catalog.md | 225 +++++ docs/operations/README.md | 1 + docs/operations/physical-inventory.md | 455 +++++++++ .../fleet-management/inventory-reference.md | 873 ++++++++++++++++++ docs/proposals/fleet-management/inventory.md | 740 ++++----------- 8 files changed, 1792 insertions(+), 542 deletions(-) create mode 100644 docs/development/hardware-catalog.md create mode 100644 docs/operations/physical-inventory.md create mode 100644 docs/proposals/fleet-management/inventory-reference.md diff --git a/config/README.md b/config/README.md index df6693e2..52cce1e4 100644 --- a/config/README.md +++ b/config/README.md @@ -14,7 +14,7 @@ API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs, IAM protected resources and roles, service registration, and machine quota registration | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service registration, and machine quota registration | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | @@ -27,6 +27,14 @@ contracts charge, as billing ServicePricings for `metal.datumapis.com`. Staging' on `config/milo`; production doesn't, so production has no Bare Metal prices. A price change is a new `-v2` pricing, since a ServicePricing can't be changed. +`config/components/inventory` registers the operator-written +`fleet.datumapis.com` inventory kinds in Milo: their CRDs, ProtectedResources, +and the inventory viewer, editor, manager and importer roles. `config/milo` +includes it, and the records live in the provider project. `config/inventory` +renders the CRDs alone, for an environment that installed them on the +management cluster before Milo became their home; new environments must not use +it. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. @@ -84,6 +92,7 @@ Render both production roots before publishing the Kustomize bundle: kustomize build config/milo >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null +kustomize build config/inventory >/dev/null ``` ## Published artifacts diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 510c6d48..51688d90 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -58,7 +58,7 @@ processes or service-catalog entries. | Group | Resources and responsibility | Status | | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | -| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | +| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs. An operator-written subset is implemented: these six kinds plus a Manufacturer/DeviceType catalog and an observational `Site`. Their alpha CRDs, ProtectedResources and roles are [registered in Milo](../operations/physical-inventory.md) by `config/milo`, and the records live in the provider project. No controller reads them, and no real provider executor is implemented here. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract diff --git a/docs/development/README.md b/docs/development/README.md index bd10d00b..4e964020 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -678,6 +678,33 @@ The persisted schema and HTTP endpoints are internal alpha interfaces. No compatibility promise exists yet. The process fails closed if retained state is corrupt or uses an unsupported schema version. +## Physical inventory subset + +`internal/api/inventory/v1alpha1` defines Facility, Rack, DeviceClaim, Device, +Cable and PowerFeed records, a Manufacturer and DeviceType +[hardware catalog](hardware-catalog.md), and an observational Site. Legacy slot +claims coexist with new installation claims; no move or replacement handover is +automated. Records live in the provider project in Milo. +`config/components/inventory` holds their CRDs, ProtectedResources, and the +inventory viewer, editor, manager and importer roles. Only `config/milo` +includes it. + +Records carry no attribution fields: resource audit logs record who changed a +record and `metadata.creationTimestamp` records when it was created. CEL requires +a Device serial or system UUID, or the explicit `identity.unidentified` marker +with a reason and neither, and keeps a Device's `claimRef` and identity immutable, +rejects duplicate or ambiguous MACs, and accepts only credential-free `https` +BMC endpoints. Status is a reserved subresource with no fields and no writer. +No metal role grants inventory access. + +No controller reads these records. The primary workflow is +[manual entry and review](../operations/physical-inventory.md#manually-record-a-small-installation). +Fleet reads no external inventory source; a separate writer that copies records +in uses the same API and validation. Unit tests run API-server validation +offline and check IAM; envtest tests run the CEL rules against a real API +server. No physical verification, reservation, deletion safety, adoption or +hardware-effect path is established. + ## Build, test, and run Run the implemented checks from the repository root: diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md new file mode 100644 index 00000000..5c97b629 --- /dev/null +++ b/docs/development/hardware-catalog.md @@ -0,0 +1,225 @@ +# Shared hardware catalog + +[Implementation status](README.md) · [Physical inventory](../operations/physical-inventory.md) + +The [inventory proposal](../proposals/fleet-management/inventory-reference.md#asset-identity-and-typed-components) +describes a reusable model and port shape, initially as a document rather than a +public kind. This implementation promotes that concept to Manufacturer and +DeviceType records. It does **not** implement the proposal's accepted-plan +shape pinning, physical qualification, reservations, or component reconciliation. + +## Implemented contracts + +- `fleet.datumapis.com/v1alpha1` Manufacturer and DeviceType are namespaced, + operator-written catalog records served in the provider's Milo Project. + There is no catalog controller, status writer, capacity publication, allocation, + installation, node, networking, provisioning, or IAM membership effect. +- Manufacturer has a mutable `canonicalName`, human `displayName`, and optional + descriptive `aliases`. ASCII labels are bounded and cannot have leading/trailing + spaces; case-insensitive aliases must be distinct within one object and cannot + repeat its canonical name. Aliases never merge identities or resolve references. +- DeviceType has an immutable `manufacturerRef: {name}` and normalized `model` + identity key (`[a-z0-9]+(-[a-z0-9]+)*`). `displayName` is its mutable human model + label. Stable metadata names are operator-selected, not regenerated from labels. + Distinct hardware variants need distinct reviewed model keys. +- Shared `modelShape` reuses the existing height-in-rack-units/full-depth shape. + Absent values mean unknown and are never defaulted; a Device's + `fullDepth` overrides its DeviceType's. It is **nominal**, never a measured + installation or observed occupancy, but rack elevations use `fullDepth` to + decide which faces a Device occupies. `componentTemplates` reuse the component type, connector, + position, name and stable local-ID vocabulary, but have no serial, asset tag or + source-instance identity. They do not create installed ports, topology or assets. + A template may set a chassis-relative `face` (`Front` or `Rear`; absent means + unknown), which a Device component with the same id inherits. See + [rack faces, depth and component faces](../operations/physical-inventory.md#rack-faces-depth-and-component-faces). + `modelShape.width` (`Full` or `Half`) is optional on both kinds and follows + the same rules; see [faceplate layout](#faceplate-layout-implemented). +- Both kinds use `metadata.creationTimestamp` and resource audit logs for + attribution. They carry no provenance or source-identity fields. + A catalog edit changes no Device, claim, installed component, recorded hardware + observation, or reported placement. +- Device has an optional `deviceTypeRef: {name}` outside immutable `identity`. + Once attached, the reference cannot be removed or rebound. Existing inline + manufacturer/model, serial, system UUID and claimRef remain unchanged and + immutable. Catalog edits never overwrite recorded observations. + +## Faceplate layout (implemented) + +These fields are implemented in the Go types and the CRD. Every field is +optional, none is defaulted, and absence means "not recorded". + +Layout is nominal catalog data on DeviceType only. A Device inherits it through +`deviceTypeRef` and the template-id convention, and cannot override it. It +carries no state: whether a port is cabled comes from Cable records, and there +is still no observed health. + +**Joining components to templates.** The template-id convention means a Device +component whose `id` equals a template's `id` takes that template's face and +cell. Writers that copy records from another system must keep it by recording +each component's template id, not an id local to the source system. Changing +component ids later is not a fix, because Cables reference component ids. + +Positions are cells of a **bank grid**, never millimetres. A bank is one +cluster of identical cells on one face, such as a 2×12 RJ45 block or a PSU +bay. Row and column inside a bank give the usual odd-top, even-bottom switch +numbering. + +| Field | Status | Meaning | +| --- | --- | --- | +| `spec.faceplate.banks[]` | Implemented (was proposal) | Up to 32 banks, a list map keyed by `id` (1 to 63 characters). | +| `banks[].face` | Implemented (was proposal) | `Front` or `Rear`, chassis-relative. Required. | +| `banks[].rows`, `banks[].columns` | Implemented (was proposal) | The grid, 1 to 8 rows and 1 to 64 columns. Required. | +| `banks[].offset` | Implemented (was proposal) | The bank's left edge as a fraction (0 to 1) of the usable face width. All or none per face. With none, banks flow left to right in list order. | +| `banks[].cellMM {width, height}` | Implemented (was proposal) | Nominal module cell size in millimetres (width 1 to 450, height 1 to 400), for PSUs, drive bays and fans. With none, readers use the nominal size of the cell's connector. | +| `componentTemplates[].layout {bank, row, column}` | Implemented (was proposal) | The template's cell. 1-based. Required together. | +| `componentTemplates[].layout.span` | Implemented (was proposal) | Columns covered to the right, 1 to 64. Unset means 1. There is no row span. | +| `modelShape.width` | Implemented (was proposal) | `Full` or `Half`, on DeviceType and Device, as for `fullDepth`. Unset is unknown; drawings assume full width and say so. Which half a Device occupies is a placement fact and is not recorded. | + +**Decorative marks are not implemented.** The design's optional `marks[]` +(power buttons, LEDs, vents, labels) were dropped to keep the schema to the +fields above. Drawings show only components, and empty space stays empty. + +### Admission rules + +The CRD's CEL rules reject: + +- a template `layout` without a template `face`, without a `faceplate`, or + naming a bank that is missing or on the other face; +- a row past the bank's rows, or a column plus span past its columns + (minimums are schema bounds); +- two templates whose cells overlap in one bank row, spans included; +- offsets set on some banks of a face but not all; +- more than 128 templates with a layout. + +Banks are per face, so a cell that is unique in its bank is unique on its face. +CEL cannot check physical fit, such as banks that together are wider than the +face or that overlap each other. A reader that draws such a layout should +scale it and warn, not reject it. + +**CEL cost outcome.** The overlap rule compares every pair of templates. Its +static estimate is about 4.4M against the 10M per-expression limit, so the CRD +installs, and the layout rules total about 5.2M against the 100M CRD limit. +At runtime, though, 256 laid-out templates can exceed the 1M per-call limit. +Measured on the costliest valid shape found (32 one-row banks with 63-character +IDs, every template in row 1), the cost passes 1M between 176 and 192 laid-out +templates. The smallest safe change was a cheap cap: at most 128 templates may +carry a layout. That keeps the worst case at about 627K. `componentTemplates` +keeps its 256-item limit. Templates past the cap have no layout and no +position on a drawing. + +The cap rule runs before the overlap rule, so an over-cap object reports the +cap rather than a cost error. `faceplate_test.go` pins the estimates and the +worst-case runtime cost with 25% headroom. `faceplate_envtest_test.go` checks +every rule and the worst case against a Kubernetes 1.37.0 API server. If real +hardware needs more than 128 laid-out templates, such as a 2U 96-port patch +panel with front and rear ports, move overlap detection to a reviewed +admission webhook rather than raising the cap. + +### Example (synthetic) + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceType +metadata: + name: example-1u-server + namespace: example-inventory +spec: + displayName: Example 1U server + manufacturerRef: {name: example-vendor} + model: example-1u + modelShape: {heightUnits: 1, fullDepth: true, width: Full} + faceplate: + banks: + - {id: bays, face: Front, rows: 1, columns: 8, cellMM: {width: 40, height: 18}} + - {id: psu-1, face: Rear, rows: 1, columns: 1, offset: 0, cellMM: {width: 40, height: 38}} + - {id: ocp, face: Rear, rows: 1, columns: 2, offset: 0.13} + - {id: mgmt, face: Rear, rows: 1, columns: 1, offset: 0.34} + - {id: psu-2, face: Rear, rows: 1, columns: 1, offset: 0.89, cellMM: {width: 40, height: 38}} + componentTemplates: + - {id: bay-1, name: Bay 1, type: Module, connector: 2.5in bay, face: Front, layout: {bank: bays, row: 1, column: 1}} + - {id: eth0, name: Ethernet 0, type: NetworkPort, connector: SFP28, face: Rear, layout: {bank: ocp, row: 1, column: 1}} + - {id: eth1, name: Ethernet 1, type: NetworkPort, connector: SFP28, face: Rear, layout: {bank: ocp, row: 1, column: 2}} + - {id: bmc, name: BMC, type: NetworkPort, connector: RJ45, face: Rear, layout: {bank: mgmt, row: 1, column: 1}} + - {id: psu-1, name: PSU 1, type: PowerInlet, connector: IEC C14, face: Rear, layout: {bank: psu-1, row: 1, column: 1}} + - {id: psu-2, name: PSU 2, type: PowerInlet, connector: IEC C14, face: Rear, layout: {bank: psu-2, row: 1, column: 1}} + # Recorded, not laid out: its position on the face is not recorded. + - {id: console, name: Console, type: ConsolePort, connector: RJ45, face: Rear} +``` + +The front bank flows because none of its face's banks sets `offset`. The rear +banks are placed because all of them do. + +## Scope, guarantees, and reader safety + +References always resolve in the referring object's namespace and provider +Project. No spec accepts a UID or an explicit cross-namespace reference. Ordinary +Kubernetes unknown-field pruning is **not** rejection: clients must use +`fieldValidation=Strict`. Disposable API tests exercise strict decoding of +references and removed fields as well as conflict handling. + +These are name references, not incarnation pins. Missing or deleting targets are +unavailable; recreating a name resolves to the replacement object. This never +proves physical continuity or triggers instance changes. Do not reuse names during +routine catalog maintenance. Preventing reuse requires a separately reviewed +retention/tombstone policy, not a UID added to the spec. + +CRD admission validates **one object's** syntax, alias uniqueness, immutable +fields. It cannot atomically enforce uniqueness of a normalized +model across objects within a manufacturer, canonical manufacturer names across +objects, or the existence/authorization of references. +Distinct resource names can still describe the same model. No webhook or global +uniqueness reservation is claimed. Writers must adjudicate collisions; reads of +existing records are not a transaction and races remain possible. + +The Go reader requires a caller-authorized `client.Reader`; do not substitute an +unrestricted controller credential for a staff caller. It reads both targets and +returns no partial catalog/error detail when either is unavailable. + +Inventory viewer gains catalog get/list/watch. Importer inherits those reads and +gains catalog create and patch, for server-side apply, without update or +delete. Manager gains create/update/patch; editor also has delete, as for the +other inventory kinds. The exact-role regression test checks these grants +alongside every inventory kind. No status, +wildcard, consumer, membership or operational permission is added. Deploying +these definitions does not bind anyone to these roles. + +## Deferred work + +No external catalog import, deduplication or recurring synchronization is +implemented. Authorized direct-API writers may create catalog records with +ordinary Kubernetes metadata and the model fields documented here. Any external +attribution belongs in writer-owned labels/annotations and audit logs; Fleet does +not interpret it or acquire ownership from it. Creating catalog records remains +observational, never a capacity or provisioning action. + +Creating catalog records does not attach existing or new Devices. An explicit +direct-API attachment must use the Device's current owner, require fresh +authorized reads of both same-namespace targets, retain exact inputs, and test +metadata UID and resourceVersion before adding the reference. UIDs are request +preconditions, never spec references. Use Strict field validation. A failed or +uncertain request requires readback, not a blind retry. Correcting an already +attached reference requires a reviewed compatibility contract; do not weaken +identity immutability, delete/recreate the Device, or transfer its claim to work +around it. + +## Validation and rollout + +```sh +go test ./... +go test -race ./... +go vet ./... +kustomize build config/milo >/dev/null +kustomize build config/inventory >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +Set `KUBEBUILDER_ASSETS` to the repository's pinned envtest assets to include the +API-server checks; without it those tests are skipped. These checks are not +proof of real Milo authorization. + +Roll out additive CRDs and least-privilege IAM definitions, then denial-aware +readers, **before any writer**. Never roll back by pruning CRDs or catalog or +occupied records, downgrading schemas to prune retained fields, deleting +Devices, or rebinding identity. Live migration and any ownership transition +remain separately approved operations. diff --git a/docs/operations/README.md b/docs/operations/README.md index 7ff2feb7..24f4d1aa 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -16,6 +16,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | +| Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written inventory records in the provider project in Milo, with immutable identity and binding; no capacity or hardware effect; unit tested | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | | Configure protected acceptance workflow access | [GitHub execution boundary](../../test/acceptance/milo/github-environment.md) | Required environment and runner-group controls | diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md new file mode 100644 index 00000000..5725abb5 --- /dev/null +++ b/docs/operations/physical-inventory.md @@ -0,0 +1,455 @@ +# Planning and registering physical devices + +[Operations guide](README.md) · [Architecture](../architecture/README.md) · +[Implementation status](../development/README.md) + +Before Fleet can enroll or offer real hardware, operators need to record two +things: where a server is meant to go, and which physical server is actually +there. Recording either must not provision the server, publish capacity, or +take ownership of it. + +This package implements a minimal subset of the +[inventory lifecycle and trust proposal (#63)](https://github.com/datum-cloud/fleet/pull/63). +It has nine kinds in `fleet.datumapis.com/v1alpha1`: six physical record +kinds, a Manufacturer and DeviceType hardware catalog, and the observational +operational `Site` kind. +The primary workflow is **manual entry, operator review, and explicit record +ownership**. Authorized direct API creation is supported for new records; +legacy Flux-owned records require a reviewed ownership transition before edits +by another writer. Fleet does not read or reconcile any external inventory +source. A separate writer may copy records in from another system; it writes +ordinary records through the same API and validation, and keeps any record of +where facts came from on its own labels and annotations. + +| Kind | What it is | Writer | +| --- | --- | --- | +| `DeviceClaim` | An observational installation plan with expected model and known placement. New records use typed placement and Cable references; existing long-lived slots retain their legacy representation. | Installation planner, through the record's explicitly assigned writer | +| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, or an explicit marker that neither is on record, the model, an optional BMC endpoint, and interfaces. | The registrar (an operator, for now) | +| `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | +| `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | +| `Manufacturer` / `DeviceType` | A shared hardware catalog: vendors and models, with nominal component templates and an optional faceplate layout. A Device names its DeviceType with `deviceTypeRef`. | Inventory operator | +| `Site` | An operational site, related to the physical Facility it occupies by name in the same namespace. Membership is observational. | Inventory operator | + +## Status + +| Aspect | State | +| --- | --- | +| CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | +| Home | Milo. `config/milo` registers nine CRDs, nine ProtectedResources and four IAM roles. Management and synthetic-staging overlays install none of them. | +| Tests | Unit tests run API-server schema, list-type and CEL validation offline for the inventory kinds, including pruning of retired fields. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. | +| Controllers | None for inventory. No reconciler accepts plans, verifies hardware, discovers or synchronizes external inventory, or publishes eligibility. Flux applies only operator-reviewed Git records. | +| Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | + +## What registration does and does not do + +Creating a Device is the explicit, manual binding step. It records that the +registrar saw this hardware in this planned slot. It does not: + +- authorize power, boot, wipe, BMC credential, or network changes; +- create, change, or enable any `MachineCapacity`, or make anything + allocatable; or +- verify identity, placement, cabling, or power. + +Detection is manual too. The registrar records what the BMC (for example +Redfish) and the rack showed them. MachineCapacity is unchanged by this +package. Its `spec.deviceRef` already names a Device by name, and the +allocator forms the asset key +`/fleet.datumapis.com/Device/`. Devices live in the +provider project next to its MachineCapacities, so a `deviceRef` in the same +namespace resolves by name. Nothing checks that reference yet. + +## Where the records live + +Milo is the single home. All nine kinds are namespaced objects in the +**provider project's** control plane, in the same namespace as the +MachineCapacities they will back. No copy exists on the Fleet management +cluster, and no controller syncs them anywhere. + +All nine CRDs carry `discovery.miloapis.com/parent-contexts: Project`, so every +project control plane serves the kinds. Access is what keeps consumers out: + +| Role | Grants | +| --- | --- | +| `fleet.datumapis.com-inventory-viewer` | `get`, `list`, `watch` on all nine kinds | +| `fleet.datumapis.com-inventory-editor` | The viewer role plus `create`, `update`, `patch`, `delete` | +| `fleet.datumapis.com-inventory-manager` | The viewer role plus `create`, `update`, `patch`; no deletion or status writes | +| `fleet.datumapis.com-inventory-importer` | The viewer role plus `create` and `patch`, for server-side apply; no `update`, deletion or status writes | + +No `metal.datumapis.com` role includes or inherits any inventory role. The consumer, +claimant, and viewer roles that reach customer projects therefore grant no +inventory access, and the provider role does not either. Bind the inventory +roles explicitly, scoped to the provider project. No role grants status +writes, because status has no writer yet. + +The manager is a separate least-privilege role for explicitly authorized inventory +staff; it does not change the existing editor or give staff viewers write access. +It grants only the nine inventory kinds, never hardware operations, allocation, +installation, Metal, networking, billing, or IAM administration. Fleet owns this +role and its tests; environment-specific groups and project bindings belong in +the infrastructure repository. The role ships through `config/milo`; shipping a +role does not bind it or add members in any environment. + +The importer is the role for an external importer's identity. It can read +every physical kind, to detect existing records and identity collisions, and +write records with server-side apply, which needs `create` and `patch`. It +cannot delete any record, replace one with `update`, or write status. + +The API server can't restrict `patch` to server-side apply, so the role alone +does not stop an importer from changing records another writer owns. Importers +must apply under their own field manager, never force ownership, and leave +records they did not create alone. That way the managed fields show which +writer owns each field. Which kinds an importer writes is the importer's +decision; Fleet does not encode any source system in the role. Binding it, +scoped to the provider project, is the explicit opt-in for that identity to +write. + +A Project resource selector is project-wide, not a namespace filter. These +ProtectedResources have Project parents, and a binding's `metadata.namespace` +locates the IAM object, not the inventory it authorizes. Choosing `default` in a +portal request is a convention, not isolation from other namespaces in that +project. Require a separately supported and tested authorization boundary before +promising namespace-only access. + +The manager contract is validated offline with +`go test ./internal/api/inventory/v1alpha1`. That checks manifests, not deployed +authorization. Before adding named members, an environment owner must validate +the deployed role and binding, and explicitly decide record-writer ownership. +IAM capability does not transfer ownership away from Flux or permit two writers +for the same records. Existing GitOps-owned records remain GitOps-owned until a +separate reviewed transition; this role does not perform that transition. + +The ProtectedResources use `serviceRef: fleet.datumapis.com`. The authorization +provider looks resources up by `{apiGroup}/{plural}`, so the service name must +equal the API group. No `fleet.datumapis.com` Service or ServiceConfiguration +is registered; the kinds are provider-internal, not a catalog offering. + +## Writers and validation + +| Rule | Kind | Why | +| --- | --- | --- | +| Records carry no attribution fields | All nine | Resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. A writer that needs to remember where facts came from uses its own labels and annotations. | +| `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | +| `identity` is immutable, including adding missing fields; requires a serial or system UUID, or `unidentified: true` with a reason and neither | Device | Neither proves chassis identity. Legacy bindings are preserved; hardware handover is not automated. See [Devices without hardware identity](#devices-without-hardware-identity). | +| An unidentified Device cannot record a `bmc` endpoint | Device | Equipment that cannot be matched to a chassis must not be enrolled as machine capacity. | +| Serial is optional | DeviceClaim | It is usually unknown at plan time. | +| Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | +| The system UUID is in lowercase canonical form | Device | One spelling per identity. | +| `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Nothing reads the lifecycle yet. | +| `status` is a separate subresource that declares no fields | All nine | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | + +The CRDs cannot check that `claimRef` names an existing DeviceClaim, because +CEL cannot read other objects. Until a registrar enforces it, the operator +creates the claim first. + +## Devices without hardware identity + +Some equipment has no serial or system UUID on record: passive gear such as +patch panels and cable managers, and active gear such as PDUs, switches, +routers or console servers whose serial was never recorded or does not exist. +Cables reference Devices, so this equipment still needs a Device record. +Record it with an explicit marker instead of inventing a serial: + +```yaml +spec: + claimRef: + name: rack-01-u40 + identity: + manufacturer: Example Vendor + model: Example 24-port panel + unidentified: true + unidentifiedReason: passive patch panel; no serial on the chassis +``` + +The rules: + +- `identity.unidentified` may only be `true`. Omit it for a Device with a + serial or system UUID; there is no `false` spelling. +- `identity.unidentifiedReason` is required with the marker and allowed only + with it: 1 to 1024 characters, not all whitespace. Say why no identity is + recorded, not where the record came from. +- A marked Device carries no `serial` and no `systemUUID`. Every Device has + exactly one of the two forms. +- The marker is part of `identity` and is immutable. If a serial is found or + recorded later, create a new Device with that identity against the same + claim, as for a hardware swap. Cables that name the old Device keep naming + it until they are updated. +- A marked Device cannot record `bmc`. + +Use the marker only when no serial or system UUID is known. Do not use it to +skip reading a serial that the equipment reports, and do not put an asset tag +or provider host ID in `serial` to avoid it. + +**What it prevents.** A Device without hardware identity cannot back a +MachineCapacity. Nothing can match it to a chassis, so enrollment, wiping and +allocation could reach the wrong machine. Two things enforce this today: + +- Admission rejects a `bmc` endpoint on a marked Device, so it has no + management endpoint to enroll through. +- `CapacityBackingError` in `internal/api/inventory/v1alpha1` is the + resolution contract for `MachineCapacity.spec.deviceRef`. It returns + `ErrUnidentifiedDevice` for a marked Device and `ErrDeviceIdentityMissing` + for one with no identity at all. Any resolver of `deviceRef` must call it + and treat a non-nil result as ineligible. + +Nothing resolves `deviceRef` yet: the allocator uses the name only to form the +asset key and never reads the Device. Admission cannot check the reference +either, because MachineCapacity is a separate API group and CEL cannot read +other objects. Until a resolver exists, operators must not create a +MachineCapacity whose `deviceRef` names a marked Device, just as they must not +name a Device that does not exist. + +A marked Device still binds to a DeviceClaim through `claimRef`. Do not bind it +to a claim whose `expectedIdentity.serial` is set; that claim expects +identified hardware. Admission cannot check this across objects. + +Use `unmappedMACAddresses` for MACs detected on the asset that cannot yet be +attributed to a named port. Do not guess a mapping; #63 requires an +authenticated, complete NIC mapping before any network path depends on it. + +## Manually record a small installation + +1. Choose the provider project and namespace, and inspect existing records and + their writers. Records that a Flux Kustomization already applies stay with + Flux until an explicit ownership transition. Do not run a competing apply + against them. New and separately created inventory can be direct + API/operator-managed; GitOps is not required. Establish the authorized writer + per record before making changes. +2. Enter the Facility and Rack facts you actually know. Leave unknown + dimensions absent. Rack + membership is not a reserved footprint or evidence of available space. +3. For a new installation, set `DeviceClaim.spec.lifecycle: Installation` and + typed placement. Use `Facility` when only the premises are known, + `RackMembership` when the rack is known, or explicitly reviewed `RackUnits` + with position, height and face. Never guess a rack position. Use a new record + only for a genuinely new installation, not to evade an existing immutable binding. +4. Register an actual Device against that claim only when its identity is known. + A manual Device requires a real serial or system UUID. If neither exists or + was recorded, use the explicit + [no-hardware-identity marker](#devices-without-hardware-identity); otherwise + keep the plan and defer registration. Provider host IDs and asset tags are + not serials. Use typed `components` and `topologyAuthority: Cable`; put expected + connections in Cable records, not `ports.expectedPeer` or `interfaces.peer`. + Add PowerFeed facts without inferring usable power or independent redundancy. +5. Review every reference in the same namespace, component type and position, + cable endpoint, and potential duplicate against existing records. API validation + cannot enforce cross-object existence or exclusive endpoints. Preserve existing + names, Device identities, claim bindings and MachineCapacity references. +6. Review the intended record changes with another operator. They must contain + no status, capacity publication, hardware action, deletion or implicit + ownership transfer. Submit individually approved new records through the + authorized API/operator workflow; use the established Flux source for records + still owned by Flux. Compare acknowledged writes with read-only API and staff + views. An interrupted or uncertain request is unknown, not failed or ready; + inspect the record before retrying. + +The [complete synthetic six-record example](../../hack/testdata/physical/manual.yaml) +shows this workflow without external sources or credentials. It includes a partial rack +placement, typed network and power components, and one Cable from a PowerFeed to +the Device. It is a test fixture, not an automatically installed overlay. Copy +its shape into private configuration and replace synthetic facts only after +review. No physical status is asserted. + +Validate the synthetic example locally: + +```sh +go test ./internal/api/inventory/v1alpha1 -run TestManualInventoryRecordsPassAdmission -v +``` + +The same offline check accepts a private multi-document YAML file of existing +records. It validates creation and unchanged updates against the proposed schemas; +it does not read a cluster, check cross-object relationships, or write records. +Keep the file outside Git. Diagnostics report only kind, ordinal and error count. + +```sh +go test ./internal/api/inventory/v1alpha1 -run TestManualInventoryRecordsPassAdmission \ + -count=1 -v -args -inventory-records /private/tmp/reviewed-inventory.yaml +``` + +## Rack faces, depth and component faces + +Three fields together describe where equipment sits in a rack and which way it +points. None is measured or verified; each is a record. + +**Mounted rack face.** `face` (`front` or `rear`) on +`Device.spec.reportedPlacement` and on `DeviceClaim.spec.placement` is the rack +face that the chassis front points toward. This is the meaning NetBox gives its +`face` field. It also fixes the rails: + +| Depth | Mounted face | Rails and occupancy | +| --- | --- | --- | +| Half depth | `front` | Front rails. Occupies its units on the front face only. | +| Half depth | `rear` | Rear rails. Occupies its units on the rear face only. | +| Full depth | either | Both rails. Occupies its units on both faces. `face` says which way the chassis points. | + +A switch mounted reversed, with its ports toward the rack rear, has +`face: rear` when its DeviceType puts the ports on the chassis front. A +half-depth device mounted on one face's rails but pointing into the rack is +not representable. That mount is rare, and adding a second field for it would +make every other record ambiguous until both fields were set. + +**Depth.** Depth uses the existing optional `modelShape.fullDepth` boolean on +both Device and DeviceType. It has no default on either kind: unset means +unknown. A Device value overrides its DeviceType. Readers resolve a Device's +depth in this order: + +1. `Device.spec.reportedPlacement.fullDepth`, the depth reported for this + installation; +2. `Device.spec.modelShape.fullDepth`; +3. the DeviceType's `modelShape.fullDepth`, read through `deviceTypeRef`; +4. otherwise unknown. This includes a Device with no DeviceType, and a + DeviceType or Manufacturer that is missing or unreadable. + +Unknown depth counts as full depth only when computing occupancy and +conflicts, so it never makes the far face look clear, and readers should +label it unknown. A default would hide that and make +conflict checks overconfident. NetBox's `is_full_depth` defaults to true; an +importer, of which none exists today, should copy an explicit NetBox value +directly but should not write a value NetBox only defaulted. A claim-derived +fallback uses the depth of its registered Devices only when all of them +agree. + +**Component faces.** A `DeviceType.spec.componentTemplates[]` entry may set +`face` to `Front` or `Rear`. This face is relative to the chassis, never to the +rack, and unset means unknown. A Device component inherits the face of the +template whose `id` equals the component `id`; the Device has no face field of +its own and no override. A component's rack face is derived: + +| Chassis face | Mounted `front` | Mounted `rear` | +| --- | --- | --- | +| `Front` | rack front | rack rear | +| `Rear` | rack rear | rack front | + +If either face is unknown, the rack face is unknown. + +**Faceplate layout.** A DeviceType may also record where each template sits on +its face, as cells of named port banks (`spec.faceplate.banks[]` and +`componentTemplates[].layout`), plus an optional `modelShape.width`. Layout +needs the template's `face`, is catalog data only, and has no Device override. +See [faceplate layout](../development/hardware-catalog.md#faceplate-layout-implemented). + +**Conflicts.** Two placements whose units overlap on the same rack face +disagree. Two half-depth devices on opposite faces of the +same units do not disagree. Admission never blocks an overlap, because +placement is reported and not verified. A Cable whose two ends land on +opposite rack faces is not an error: a pass-through panel or a reversed peer +can make that correct. + +## Historical legacy example + +The following representation remains supported for existing long-lived slots. +It is **not the template for new records**. Do not convert existing claims in +place or copy their inline topology into a second Cable authority. + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: rack-01-u12 + namespace: fleet-system +spec: + expectedIdentity: + manufacturer: Example Vendor + model: Example 1U + placement: + facility: example-facility + rack: rack-01 + position: 12 + face: front + ports: + - name: eth0 + type: 25gbase-x-sfp28 + speedMbps: 25000 + expectedPeer: {device: switch-01, port: Ethernet1/1} + - name: bmc0 + type: 1000base-t + speedMbps: 1000 + expectedPeer: {device: mgmt-switch-01, port: Ethernet5} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: rack-01-u12-synthetic-0001 + namespace: fleet-system +spec: + claimRef: + name: rack-01-u12 + identity: + manufacturer: Example Vendor + model: Example 1U + serial: SYNTHETIC-0001 + systemUUID: 00000000-0000-4000-8000-000000000001 + bmc: + endpoint: https://192.0.2.100:443 + unmappedMACAddresses: + - 00:00:5e:00:53:01 + - 00:00:5e:00:53:02 +``` + +To replace the hardware, create a new Device with its own name and identity +that names the same claim. Leave the old Device in place and move its +`spec.lifecycle` from `Active` to `Decommissioning`, then to `Retired`. +Retired is terminal. + +## Relationship to the inventory proposal + +The names and writers match #63: + +- DeviceClaim is a physical installation plan written by the installation + planner. +- Device is the canonical asset created only by the registrar. +- Collectors submit observations and never edit Device identity. +- Status is a protected projection. +- Serial and SMBIOS UUID are matching evidence, not authenticators. +- Logical LAGs and VLANs are not ports. + +Still deferred to #63: + +- Qualified geometry/reservations and automatic migration of legacy text + placement/inline peers. The four additional physical record kinds now exist; + typed records do not silently take over historical surfaces. +- Plan acceptance, revisions, and reservations; canonical-identity + adjudication and duplicate detection; and the protected ledger. +- Trust roots, qualification profiles, enrollment challenges, technician and + collector attestation, and evidence freshness. +- Component incarnations and lineage, maintenance, moves, a retirement + workflow beyond the recorded Device lifecycle, and adopted custody. +- The `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, + `NetworkPathVerified`, and `PowerPathVerified` predicates and any eligibility + publication. +- Separation of planner, approver, registrar, and verifier roles. One operator + can write both kinds today. + +**Deliberate divergence: Milo-resident provider inventory.** #63 treats +private inventory, including serials, cable paths, and BMC endpoints, as +material that never reaches consumer catalogs or status, and keeps the +authoritative records in a protected management-side ledger. This package +stores the operator records in the provider project's Milo control plane +instead. Two things keep them away from consumers: they never enter a consumer +project or a catalog, and only the inventory roles can read them. This is a +deliberate change of home, not an oversight. It trades the ledger's isolation +for one authoritative record that MachineCapacity can name and that staff can +read. #63's ledger, trust, and enrollment protocol would still sit behind these +records if adopted. + +**Compatibility decision:** legacy slots retain all historical bindings. New +typed records use a distinct `Installation` lifecycle, but no automatic move or +replacement handover exists. Device identity and its original claimRef remain +immutable. No writer may delete/recreate or relabel legacy records to bypass this. + +## Applying the records + +`config/milo` installs the CRDs, ProtectedResources, and roles into Milo. Apply +operator-reviewed records through their approved writer after those are established, +claims before the Devices that name them. New records may be created +directly through the provider API with authorization and ownership safeguards. +Existing Flux-owned records remain with Flux until a reviewed transition stops +reconciliation for those exact records. Do not overwrite or adopt them implicitly. +Keep records with real serials, +UUIDs, MACs, endpoints, or cabling in the environment's private configuration, +not in this repository. + +`config/inventory` still renders the inventory CRDs alone, for an environment that +applied them to the management cluster before Milo became their home. Once that +environment has moved its records into Milo and stopped reconciling the root, it +will be removed. New environments must not use it. diff --git a/docs/proposals/fleet-management/inventory-reference.md b/docs/proposals/fleet-management/inventory-reference.md new file mode 100644 index 00000000..52fc3dd3 --- /dev/null +++ b/docs/proposals/fleet-management/inventory-reference.md @@ -0,0 +1,873 @@ +--- +status: provisional +stage: alpha +latest-milestone: "v0.1" +--- + +# Fleet inventory reference appendix + +Technical detail supporting the [Fleet inventory product proposal](inventory.md). +Start there for operator needs, the proposed experience and open decisions. +This appendix keeps field definitions, synthetic examples, +migration steps and test requirements together for implementers and reviewers. +It is part of the same enhancement, not a separate design. + +All contracts and field names remain provisional. Examples are not implemented +CRDs or manifests to apply; illustrative identifiers and evidence do not establish +physical truth. Local object incarnations are retained privately rather than +used as authored cross-control-plane references. + +For the implemented local-only Site membership and provider-qualified premises +identifier subset, see [Physical inventory](../../operations/physical-inventory.md). +Its name-only references are scoped to the same project and namespace, not +authored cross-control-plane IDs or allocation policy. Reusing a Facility name +rebinds the relationship; observed resource UIDs do not belong in desired-state spec. + +- [Contract details](#contract-details) + - [Metadata and evidence](#shared-metadata-references-and-evidence) + - [Facility and Rack](#facility-and-rack-contracts) + - [Assets and components](#asset-identity-and-typed-components) + - [Installation examples](#plan-a-physical-installation) + - [Reservations](#reserve-physical-resources) + - [Registration](#register-and-bind-a-device) + - [Verification](#verify-the-installation) + - [Cabling and power](#cabling-power-and-network-configuration) + - [Circuit boundary](#circuit-demarcations-and-external-ownership) + - [Lifecycle transitions](#moves-replacements-and-retirement) +- [Existing records and migration](#existing-records-and-migration) +- [Validation and qualification matrix](#validation-and-qualification-matrix) + +## Contract details + +### Shared metadata, references, and evidence + +The following are proposed contract semantics, not an assertion that these fields +are available in the current API. Keep the initial six kinds; use structured +entries and protected transition records rather than a kind for each work order, +photo, model, approval, or verification run. + +| Surface | Authoritative writer | Contract | +| --- | --- | --- | +| Facility/Rack definitions, DeviceClaim intent, Cable topology, PowerFeed supply plans | Authorized inventory planner | Changes produce reviewed revisions; they cannot rewrite registered observations or prove physical work. | +| Accepted plans, reservations, active placement and historical bindings | Inventory coordinator/registrar | Conditional durable transitions retain approval, exact inputs, and predecessor identities. Planner and collector writes cannot bypass them. | +| Device identity, asset tags and canonical component inventory | Registrar | Adjudicates authenticated observations and corrections; collectors never directly replace canonical identity. | +| Observations and evaluated conditions | Authenticated evidence submission; inventory verifier owns the projection | Preserve source observations separately from approved intent; only the verifier writes verification results. | +| Management endpoints and access | Provider management authority | Restricted references/projections only; inventory does not allocate OOB addresses, issue credentials, or authorize BMC actions. | +| Provider host IDs, service/circuit identifiers and commercial facts | Respective provider/service authority | Inventory retains sourced identifiers and physical associations, not orders, invoices, pricing, or routing intent. | + +All kinds need a human-readable label, optional description, and restricted +external references. Names and labels are not durable asset identity. Records do +not carry their own attribution: resource audit logs record who changed a record +and `metadata.creationTimestamp` records when it was created. A writer that copies +facts from another system keeps any record of where they came from on its own +labels and annotations; Fleet does not interpret them. Absence, undisclosed +information, a mismatch, and policy-approved inapplicability are distinct states, +never encoded as invented values or zero. + +Typed references identify the allowed kind/group, administrative scope, and name. +A kind-specific field such as `rackRef` fixes kind/group; examples omit scope only +for same-scope references. Cross-scope references require explicit scope and +authorization; they never resolve by a global name search. Acceptance pins the +resolved local incarnation and relevant revision privately. Name reuse, dangling +references, unauthorized targets, and wrong-kind targets cannot inherit evidence. +Identifiers from other systems are not directly resolvable Fleet references. + +`documentRefs` refer to photos, as-built sheets, installation attestations, LOAs, +or contracts in their existing document system. Retain document ID, category, +revision/digest when available, capture time, and the exact asset/plan or path +being supported. Documents keep their own ACLs; a Fleet reference grants no +access and contains no document body, token, signed download URL, or credential. +A mutable URL alone cannot establish evidence for a prior evaluation. A contract +or LOA is not proof of installed cabling; a photo requires an attributed +interpretation and qualified check. Unavailable evidence leaves dependent checks +Unknown rather than copying protected material into public status. + +Audit history retains who requested, approved, and committed a change, its reason, +before/after revisions, supporting references, and affected identities. Retain +supersession, identity corrections, component removals, and retirement events; +do not rewrite history to match the present plan. Retention and deletion policy +must preserve evidence needed by active reservations and consumer obligations. + +### Facility and Rack contracts + +| Kind | Proposed minimum and optional physical metadata | Validation and lifecycle | +| --- | --- | --- | +| Facility | Stable identity, display name, geographic `locationRef`, and physical-premises description. Optional structured postal address, building/room labels, coordinates with source/precision, operator identity reference, external facility-code mappings and document references. Sensitive access instructions stay external. | A metro code alone is insufficient to establish premises. Operator approval establishes or corrects a premises mapping. Closing a Facility blocks new plans; it neither relocates equipment nor releases occupancy. Preserve historical references. | +| Rack | Immutable `facilityRef` after accepted use, local rack label, optional room/row, mounting geometry and capacity, supported faces, depth/width limits, optional load limit with units, 0U mounting locations, and document references. Unknown dimensions remain absent. | Rack labels are unique within an agreed Facility scope, not globally. Known rack-unit numbering has a documented origin/direction; position denotes the lowest occupied unit. Reject out-of-range footprints, face/depth conflicts, and incompatible mounts. Do not infer usable space from omitted geometry. | + +A Facility is not a provider account, provider metro grouping, or Fleet policy +Site. One physical premises may have several provider codes; one provider metro +grouping may refer to several premises. Mapping records retain both directions +and unresolved candidates without creating a false one-to-one relationship. +Site policy selects eligible Facilities as described in +[Site rules for choosing eligible facilities](cluster-lifecycle.md#site-and-cluster-resources). + +Rack geometry changes that affect reservations require revalidation under the +coordinator, not a metadata edit that evicts occupants. Correcting a mistaken +Facility association requires an audited migration of dependent references and +evidence; physically moving a rack requires coordinated placement transitions +for its occupants. Deletion is blocked while active claims, Devices, Cables, or +feeds depend on the object. An empty inventory list does not prove an empty rack. + +### Asset identity and typed components + +Device identity includes manufacturer/model, independently evidenced chassis +serial when available, and optional SMBIOS UUID. Asset tags are separate +operator-assigned identifiers with issuer/scope and assignment history; replacing +a tag is not replacing a chassis. Provider host IDs belong in namespaced external +identifiers, never `serialNumber`. Serial, UUID, MAC, model, label, or asset tag +alone is not authentication or universally unique. Missing serials on passive +equipment require qualified technician identity evidence, not a fabricated +serial. Duplicate or conflicting matches remain quarantined for adjudication. + +An expected serial or asset tag may be unknown when planning. The accepted claim +pins its matching constraints and qualified hardware shape; registration records +actual identity, records discrepancies, and does not silently relax constraints. +Device role describes physical use, not cluster membership or allocation state. + +Repeated models justify a reusable, versioned **model/port shape**, initially a +reviewed document or configuration artifact rather than a new public kind. It +describes manufacturer/model/variant, dimensions, component slots, labels, +connector capabilities and internal pass-through or power mappings. Claims pin +the shape revision/digest and explicit deviations; updating a template never +retrofits an accepted plan or invents observed components. Provider marketing +models and VM flavors cannot establish chassis geometry. Qualification must +compare the shape to actual hardware variants. + +Each canonical component entry has a Device-local stable ID, a discriminated +type, physical label, optional parent/slot, relevant capabilities, +and retained incarnation/revision evidence. The registrar owns the canonical +entry; mutable observations and OS aliases are separate. Reject duplicate IDs, +parent cycles, incompatible fields, and references to removed incarnations. + +| Component type | Physical contract | Explicit exclusion or restriction | +| --- | --- | --- | +| Network port | Connector/media family, supported rates with units, lane/position capabilities, optional MAC observations and replaceable transceiver association. Management/Data is a role, not a separate identity system. | No VLAN, bond, IP allocation, BGP peer, or switch configuration. An OS name is only an observed alias. | +| Power inlet/outlet | Input/output direction, connector and AC/DC compatibility, supported voltage/current limits with units; outlet-to-input dependency for a PDU. | No assumption that two inlets or outlets are independent. Unsupported transfer-switch mappings remain unknown. | +| Console port | Serial/USB/Ethernet connector and host/server direction, with physical compatibility parameters where required. | No session credentials or console access authorization. A networked console server's Ethernet port remains a network port. | +| Pass-through termination | Front/rear side, connector, numbered positions, and explicit internal position mappings for a passive panel. | Never infer a direct link through a panel from LLDP alone. | +| Replaceable NIC, optic, PSU or disk | Parent slot, actual component identity/serial where disclosed, model/capabilities and insertion/removal history. Disks may retain observed WWIDs and capacity with units. | A disk is not a Cable endpoint; installation pins exact disk targets separately. A slot reused after repair is not the same component incarnation. | + +Only fields relevant to a component type are allowed. Supported type/connector +vocabularies and required units must be fixed by the first qualified schema; +unknown vendor strings may be retained as observations but cannot pass typed +connection validation. Claim port IDs express intended attachment points and +resolve explicitly to canonical component IDs, never by a guessed array index. + +For example, a synthetic observed panel shape can contain: + +```yaml +# Proposed component excerpt, not a complete Device manifest. +components: + - id: panel-front-01 + type: PassThroughTermination + side: Front + connector: LC + positions: [1, 2] + - id: panel-rear-01 + type: PassThroughTermination + side: Rear + connector: LC + positions: [1, 2] +passThroughMappings: + - from: {componentID: panel-front-01, position: 1} + to: {componentID: panel-rear-01, position: 1} + - from: {componentID: panel-front-01, position: 2} + to: {componentID: panel-rear-01, position: 2} +``` + +These are internal device mappings, not a second expected-cable graph. Cables +remain the only declarations connecting different assets. + +### Plan a physical installation + +The DeviceClaim contract retains role, expected identity constraints, placement +scope, declared attachment points, required Cable references, verification +profile/checks and approval revision. Where power is reserved, the +plan also pins a maximum load budget with units and the required failure scenario +per supply path. Missing load assumptions block power-capacity acceptance; the +number of PSUs does not supply them. Model-shape references and predecessor/asset +references for moves or replacements are optional inputs that become immutable +within an accepted revision. They do not grant permission to evict a predecessor. + +The Facility describes physical premises. A Fleet `Site` can select eligible +Facilities as operational policy without moving their assets. Location remains +the geographic reference; neither Site nor Facility is a provider identifier. + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Facility +metadata: + name: iad1 + namespace: infra-ops +spec: + displayName: Ashburn Facility 1 + locationRef: + name: us-east-1 +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Rack +metadata: + name: iad1-r12 + namespace: infra-ops +spec: + facilityRef: {name: iad1} + heightUnits: 42 +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: iad1-r12-u20-server + namespace: infra-ops +spec: + role: Server + expectedIdentity: + manufacturer: Dell + model: PowerEdge-R650 + serialNumber: EXAMPLE-SERVER-001 + assetTag: {issuer: datum-infra, value: EXAMPLE-ASSET-001} + placement: + rackRef: {name: iad1-r12} + position: 20 + heightUnits: 1 + face: Front + fullDepth: true + verification: + requiredChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] + ports: + - {id: bmc, type: EthernetPort, role: Management, physicalLabel: BMC} + - {id: nic1-p1, type: EthernetPort, role: Data, physicalLabel: NIC1/P1} + - {id: psu1, type: PowerInlet, physicalLabel: PSU1} + - {id: psu2, type: PowerInlet, physicalLabel: PSU2} + cableRefs: + - {name: iad1-r12-srv01-management} + - {name: iad1-r12-srv01-data} + - {name: iad1-r12-srv01-power-a} + - {name: iad1-r12-srv01-power-b} +``` + +The example assumes an existing management switch `iad1-oob01`, data switch +`iad1-r12-leaf-a`, and PDUs `iad1-r12-pdu-a`/`iad1-r12-pdu-b`, each registered +through its own claim. Their referenced components and upstream power paths +must exist and be verified. These four Cable plans describe the server's +required connections before the server Device exists: + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-management + namespace: infra-ops +spec: + medium: CopperEthernet + a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: bmc}] + b: [{deviceRef: {name: iad1-oob01}, componentID: port12}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-data + namespace: infra-ops +spec: + medium: DirectAttachCopper + a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: nic1-p1}] + b: [{deviceRef: {name: iad1-r12-leaf-a}, componentID: ethernet20}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-power-a + namespace: infra-ops +spec: + medium: Power + a: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: outlet20}] + b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu1}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-power-b + namespace: infra-ops +spec: + medium: Power + a: [{deviceRef: {name: iad1-r12-pdu-b}, componentID: outlet20}] + b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu2}] +``` + +`cableRefs` identifies prerequisites; it does not repeat expected peers. Cable +owns the endpoint declarations. A planned endpoint references a DeviceClaim +and its declared port ID; a registered endpoint references a Device and stable +component ID. Names are convenient authoring references. Acceptance retains the +exact local object incarnations privately and records approved dependency +revisions. Recreating an object with the same name never inherits a reservation. + +Placement may instead name `placement.facilityRef` without a rack. This covers +unracked equipment and rented bare metal whose physical Facility is known but +whose rack/patching is not disclosed. The claim must state its verification +requirements explicitly; for example: + +```yaml +# Excerpt for an identified physical server with facility-level visibility. +spec: + placement: + facilityRef: {name: iad1} + verification: + requiredChecks: [Identity, FacilityPlacement] +``` + +Admission constrains required checks using operator policy and the intended +offering. Authors cannot weaken verification to make a failed installation +pass. Rack placement derives Facility through the Rack; if both references are +supplied they must agree. Undisclosed rack/cable facts remain unknown, not +invented or marked physically inapplicable. `Ready` for a facility-scoped claim +does not imply verified rack position, cabling, power redundancy, or eligibility +for an offering that requires those facts. Historical UUID/IP/disk lists are +migration inputs, not sufficient verification evidence. + +**Rack known, position undisclosed** is a separate supported placement scope, +not facility-only placement and not a fictitious 1U footprint: + +```yaml +# Proposed excerpt for identified rented hardware; all identifiers are synthetic. +spec: + placement: + rackRef: {name: iad1-provider-rack-7} + scope: RackMembership + verification: + requiredChecks: [Identity, RackMembership] +``` + +The proposed placement discriminant distinguishes `Facility`, `RackMembership`, +`RackUnits`, and `NonRackUnitMount`. Existing exact-position examples imply +`RackUnits`; facility-only examples imply `Facility`. The eventual schema must +make this choice unambiguous. RackMembership forbids position, face, height and +full-depth assertions unless a subsequent approved revision establishes an +exact mount. It permits known asset dimensions in the model, but dimensions +alone cannot establish occupied units. NonRackUnitMount requires a qualified +mounting-location identifier for 0U or other non-unit rack mounts. Facility +placement describes unracked or undisclosed-rack equipment without such a mount. + +Acceptance for RackMembership records the known occupancy and may reserve known +terminations/power, but makes **no rack-unit reservation**. An unresolved +footprint prevents declaring the rack's unaccounted space free: block new exact +unit reservations in that rack until occupancy is reconciled, unless a qualified +operator-approved exclusion boundary proves a disjoint area safe. Do not guess +the exclusion boundary. Facility-only records likewise cannot establish free +rack capacity. A plan requiring exact placement remains Pending until an exact +footprint is approved and reserved. `PlacementVerified` reports Facility, +RackMembership, or exact mount scope; RackMembership readiness cannot satisfy a +RackUnits prerequisite. Invented positions copied from another system never +satisfy any placement check. + +### Reserve physical resources + +Acceptance commits a retained plan covering the claim and its required Cable +inputs. Inventory must reserve the applicable declared rack footprint, physical +terminations, and power capacity without races. Rack checks include occupied units, +front/rear constraints, full-depth equipment, and pending installations. The +model also supports 0U mounting and equipment outside a rack; it must not assign +them fictitious rack-unit positions. + +Endpoint reservations belong to one exact Cable incarnation and identify one +exact Device or DeviceClaim incarnation plus termination/position. Local object +identity is retained as private same-API-server evidence. Two cables cannot reserve the same +exclusive termination. Resolving a claim endpoint to a registered component +must preserve that reservation, including conflicts with direct Device +references. A successor placement cannot reserve an occupied resource merely +because the previous object's readiness is False. + +Use durable conditional commits or an equivalent serialized reservation +protocol, not an admission-time list check or controller-local lock. Partial +acquisition stays Pending and is recovered or explicitly unwound. Report +`Accepted=True` only after the complete current plan is committed. Hold +reservations through controller restarts and uncertainty; timeouts and expired +worker leases do not prove that space, cabling, or power is physically free. + +Referenced Cable plans may target other unbound claims. Validate and reserve +the intended endpoints without requiring those Devices to be Ready. Otherwise +two devices awaiting a connection could never be commissioned. Editing an +unbound plan requires revalidation and a new committed plan revision; stale +acceptance or registration requests cannot use the previous revision. + +### Register and bind a device + +A registration request must authenticate its enrollment channel and identify +an existing accepted DeviceClaim and approved plan revision. Match expected +identity against independently trusted evidence. Serial numbers, MAC +addresses, and SMBIOS UUIDs are matching attributes, not authentication. +Passive devices register through an authorized technician or integration; +they do not need to run a host agent. + +The registrar commits one reciprocal DeviceClaim-to-Device relationship and +retains both local object incarnations as private same-API-server evidence. One +claim binds one Device for one installation incarnation. One physical asset +cannot acquire duplicate Device identities, +and one Device has at most one active placement authority. Recovery after a +lost response finds the committed registration instead of creating a second +asset. Ambiguous matches, unexpected identities, expired authorization, or +already-bound claims fail closed. Unknown equipment remains isolated discovery +evidence; it cannot manufacture an accepted claim or eligible capacity. + +Registration does not require all physical verification to have succeeded. A +Device can exist in commissioning with a placement or wiring discrepancy: + +```yaml +# Registrar-created snapshot, not an operator-authored apply input. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: server-example-001 + namespace: infra-ops +spec: + # Registry-owned. A raw reference edit cannot move the asset. + claimRef: + name: iad1-r12-u20-server + identity: + manufacturer: Dell + model: PowerEdge-R650 + serialNumber: EXAMPLE-SERVER-001 +status: + observedPlacement: + rackRef: + name: iad1-r12 + position: 20 + face: Front + evidenceRef: installation-scan-001 + components: + - {id: management-port-1, type: EthernetPort, physicalLabel: BMC} + - id: nic-slot2-port1 + type: EthernetPort + physicalLabel: NIC1/P1 + macAddress: "02:00:00:00:12:01" + - {id: power-supply-1, type: PowerInlet, physicalLabel: PSU1} + - {id: power-supply-2, type: PowerInlet, physicalLabel: PSU2} +``` + +Declared claim ports resolve using trusted chassis labels, qualified hardware +layout, and physical component identity. A controller cannot swap the mapping +of `nic1-p1` to a different NIC merely to make the observed neighbor match. +The Device records actual components; the claim records the approved mapping +from its intended ports to those components. + +### Verify the installation + +Commissioning has an ordered dependency graph: + +```text +Accepted plan and physical reservations + -> trusted registration and exclusive Device binding + -> claim-port mapping and Cable endpoint resolution + -> identity, placement, network, and power evidence evaluated + -> physical Ready +``` + +Cable resolution depends on binding, not Device Ready. Protected enrollment +connectivity must exist before complete production-path verification. Any +inspection that boots or modifies a device requires a separately authorized +hardware operation; inventory readiness cannot authorize its own evidence +collection effects. + +- **Hardware identity and capabilities:** Authenticated BMC/qualified agent observations + or trusted installation evidence matched to the enrolled asset. Claimed identifiers + alone are insufficient. +- **Switch and port adjacency:** Trusted switch-side observations corroborated with the + enrolled NIC mapping. MAC learning or agent-reported LLDP alone does not prove asset + identity. +- **Link capability:** Current port state, negotiated parameters, and relevant hardware + observations; link-up is not proof of a complete passive path. +- **Exact rack position/orientation:** Authorized installation scans/attestations or + qualified rack instrumentation. Management-network reachability does not establish a + rack unit. +- **Passive cable identity and patch path:** Verified endpoint/cable-label scans or + qualified instrumentation. LLDP does not identify each passive segment. +- **PSU, outlet, and upstream feed:** Verified physical mappings and suitable + observations/instrumentation. Two healthy PSUs do not establish independent supplies. + +Link discovery can supply switch/port observations through qualified collectors; +it does not establish every physical fact above. Redfish's rack/offset fields +are writable metadata, so copying the intended position into a BMC and reading +it back is not independent placement evidence. See the +[Redfish data model](https://redfish.dmtf.org/schemas/v1/DSP0268_2025.3.pdf). + +Conditions report `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, +`NetworkPathVerified`, `PowerPathVerified`, and `Ready` separately. Readiness +requires every admitted required check for the current approved plan and +records the evaluated verification scope. `PlacementVerified` identifies +whether it evaluated Facility, RackMembership, or exact mount placement. Missing +or stale required evidence is Unknown; a verified mismatch is False. Checks outside the +scope remain explicitly unevaluated. A policy may mark a check physically +inapplicable, such as power for a passive panel; absence of evidence must not +silently become an exemption. Downstream controllers require the specific +verified facts their operation or offering needs, not an unqualified Ready bit. + +Each evaluation privately retains the exact local claim, Cable, Rack, PowerFeed, +and Device incarnations and records their revisions, Device +identity/component/trust revision, evaluated input digest, +evidence provenance, and verification time. Standard condition fields include +`observedGeneration`, reason, message, and transition time. The owning object's +generation alone is insufficient: recabling, a NIC replacement, or new trust +material can invalidate evidence without changing that object's spec. + +Keep bounded summaries and protected evidence references in status. Retain the +evaluated plan and evidence needed to explain the result. Evidence freshness +is check-specific: a current adjacency observation and an installation scan +have different validity rules. Relevant topology or hardware changes invalidate +the applicable result; an old `Ready=True` is not blanket authorization. + +```yaml +# Abbreviated controller-written verification snapshot after successful checks. +# Routine condition timestamps/messages are omitted for readability. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: iad1-r12-u20-server + namespace: infra-ops +status: + observedGeneration: 1 + evaluatedPlanDigest: "sha256:" + evaluatedChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] + evidenceRef: commissioning-evaluation-001 + deviceRef: + name: server-example-001 + portBindings: + - {claimPortID: bmc, deviceComponentID: management-port-1} + - {claimPortID: nic1-p1, deviceComponentID: nic-slot2-port1} + - {claimPortID: psu1, deviceComponentID: power-supply-1} + - {claimPortID: psu2, deviceComponentID: power-supply-2} + conditions: + - {type: Accepted, status: "True", reason: PhysicalReservationsCommitted, observedGeneration: 1} + - {type: Bound, status: "True", reason: ExclusiveDeviceBindingCommitted, observedGeneration: 1} + - {type: IdentityVerified, status: "True", reason: TrustedEnrollmentMatched, observedGeneration: 1} + - {type: PlacementVerified, status: "True", reason: InstallationScanVerified, observedGeneration: 1} + - {type: NetworkPathVerified, status: "True", reason: TrustedPeerEvidenceMatched, observedGeneration: 1} + - {type: PowerPathVerified, status: "True", reason: PowerPathEvidenceVerified, observedGeneration: 1} + - {type: Ready, status: "True", reason: RequiredEvidenceCurrent, observedGeneration: 1} +``` + +Cable status similarly reports resolved Device names/component IDs; protected +evidence privately retains the exact local Device incarnations. It separately +reports evidence for endpoint adjacency, cable identity, and any pass-through +path. It never rewrites spec to agree with discovery. Physical drift blocks +new allocations and operations that require the invalidated fact and alerts +operators. It does not independently authorize eviction, power-off, wiping, or +release of an existing consumer reservation. + +### Cabling, power, and network configuration + +Cable metadata includes a stable record identity, physical label/asset tag where +present, medium, connector information, and optional measured length with units, +color and external evidence references. Distinguish a planned label from an +observed one. Reusing a cable label does not transfer the old cable's verification. +Replacing a physical cable creates a successor Cable identity; repatching the +same cable retains identity but creates an approved endpoint revision and +invalidates affected paths. Preserve disconnected endpoints in history. + +Every Cable endpoint is a discriminated reference to exactly one DeviceClaim +port, Device component, or PowerFeed termination, with lane/position where +needed. Validate type, connector, direction, multiplicity and exclusive +termination use. A simple cable has one endpoint at each end; a qualified +breakout has explicit one-to-many lane mappings, not an unconstrained list that +implies all-to-all connectivity. Reject repeated lanes, unmodeled adapters and +incompatible media. Derive occupied terminations from the retained Cable plan, +not an independently editable peer list on Devices. + +A Cable connects typed physical terminations. Pass-through components on patch +panels retain explicit internal front/rear mappings. Breakout cables require +explicit position/lane mappings. Trace the complete supporting path; reject an +unsupported mapping rather than assuming a direct connection. + +A PDU is a Device. Its component model maps each outlet to the input that +supplies it. Power cables connect feeds to PDU inputs and outlets to device +inlets; a feed termination uses a typed `powerFeedRef`, resolved by name with its +exact local incarnation retained privately. +PowerFeed records include rated/usable capacity and known upstream +sources; unknown dependencies remain explicit. Reservation calculations must +account for the declared redundancy/failure scenario, not assume that each of +two feeds supplies half the load. Two differently named PDUs can share the same +UPS or upstream circuit. + +PowerFeed is the physical supply boundary, not a utility bill or a substitute +for a PDU Device. Its proposed contract includes Facility reference, operator +label, optional panel/circuit label, typed termination IDs, AC/DC supply, +nominal voltage, phase count where applicable, rated current/capacity with +units, usable budget and the derating-policy revision that produced it. Unknown +ratings cannot become zero demand or unlimited capacity. Declared reservations +and measured draw remain separate; a low instantaneous draw cannot free a +reserved budget. + +Upstream dependencies identify other PowerFeeds or scoped external electrical +source identities. Equal external identities mean a shared +dependency; different labels without evidence do not prove independence. +Unresolved dependencies remain Unknown, and cycles are invalid. An electrical +panel/circuit label is distinct from a network service circuit identifier. +Inventory owns the approved dependency graph; qualified measurements and +technician attestations verify it without overwriting the plan. + +```yaml +# Synthetic proposed supply example, not a verified electrical design. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: PowerFeed +metadata: + name: iad1-r12-feed-a + namespace: infra-ops +spec: + facilityRef: {name: iad1} + label: EXAMPLE-PANEL-A-12 + supply: {type: AC, nominalVoltageV: 208, phases: 1, ratedCurrentA: 30} + budget: {usableCurrentA: 24, policyRevision: example-derating-v1} + terminations: + - {id: output-1, type: PowerOutlet, connector: IEC60309} + upstreamSources: + - externalRef: {system: example-facilities, type: UPS, id: EXAMPLE-UPS-1} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-pdu-a-supply + namespace: infra-ops +spec: + medium: Power + a: [{powerFeedRef: {name: iad1-r12-feed-a}, terminationID: output-1}] + b: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: inlet-1}] +``` + +This example assumes a compatible, separately registered PDU inlet. It proves +neither usable capacity nor redundancy. If feeds A and B both depend on +`EXAMPLE-UPS-1`, two working cables do not qualify as UPS-independent supply. +Qualification pins voltage/phase/connector compatibility, load units and a +supported derating/failure model. Converting watts to amperes requires the +necessary electrical assumptions, not implicit arithmetic across unlike units. +Reserve the full admitted failover load on each surviving path required by that +model; reject insufficient headroom or report Unknown for undisclosed inputs. + +Feed decommissioning blocks new dependent plans. Changing a breaker rating, +upstream source or usable budget re-evaluates all affected reservations and +conditions; it never silently sheds load, releases occupied capacity, or powers +off equipment. Retire a feed only after dependent paths are safely removed and +their physical release is evidenced. + +Rack, switch, and power failure domains are derived from verified dependency +information, including shared upstream resources. Labels can expose validated +domains for selection; different labels do not establish physical independence. + +Physical connectivity does not select the VLAN, VRF, IP address, routing +adjacency, or tenant network carried over a link. Network management resources +reference registered Devices/components and own those behaviors. The +bare-metal provider requests attachment or isolation through the networking +authority, which remains the sole writer of the relevant switch configuration. +This physical/logical separation is consistent with +[RFC 8348's hardware model](https://www.rfc-editor.org/rfc/rfc8348.html) and +[RFC 8345's layered topology model](https://www.rfc-editor.org/rfc/rfc8345.html). + +### Circuit demarcations and external ownership + +Transit, transport/interconnection, and OOB circuits need durable identifiers and +physical demarcation records. A Cable alone does not identify the service, and a +BGP session does not prove its cross-connect. **Proposed decision:** keep the six +inventory kinds initially and reference the owning network/provider service +record; do not assume approval for a seventh `Circuit` kind. Selecting that +record's API/owner, or approving a dedicated physical Circuit kind later, remains +an explicit design decision before circuit-dependent commissioning is automated. + +The proposed minimum association is an owner-qualified external circuit ID, +use category (transit, transport or OOB), and named A/Z demarcations as disclosed. +Each physical demarcation records a resolved Facility reference, room/panel label, +and a typed Device/component/position reference when known, with source and +evidence references. A local cross-connect is a Cable or traced Cable path to +the registered demarcation termination. Do not create a fake far-end Device or +Facility for an undisclosed carrier endpoint. Store a reported label as evidence +until the termination is resolved; it cannot satisfy Cable endpoint reservations. + +For example, a synthetic proposed association on a panel termination is: + +```yaml +externalCircuitRef: + system: example-network-services + type: Circuit + id: EXAMPLE-OOB-0042 +demarcation: A +facilityRef: {name: iad1} +termination: {deviceRef: {name: iad1-demarc-panel}, componentID: rear-07, position: 1} +documentRefs: + - {system: example-drive, id: EXAMPLE-LOA-42, revision: "3", category: LOA} +``` + +This is an association excerpt, not a new resource or an implemented Circuit +API. Circuit identifiers are unique only within their provider/service scope. +The service owner owns identifier and delivery facts; inventory owns their +approved association to physical terminations and the local Cable topology. +Network services consume that association rather than authoring another +expected-peer graph. Prices, commitments, billing, orders and contract state +stay with provider/commercial owners. Addresses, VLANs, BGP, routing, service +bandwidth policy and activation stay with networking/IPAM/Galactic. + +Commissioning evaluates physical demarcation/path verification independently +from provider delivery and routing/service readiness. Missing external contract +support is an explicit unresolved prerequisite, not success or an exemption. +Circuit cancellation does not prove a cross-connect removed; removal of a cable +does not cancel the service. Retain retired associations, circuit IDs and LOA/ +as-built evidence without releasing terminations until physical disconnection +is established. + +### Moves, replacements, and retirement + +- **Move the same asset:** create a successor DeviceClaim naming the existing + Device and reserve the destination. A coordinated maintenance transition + transfers active placement authority with exact predecessor/binding + preconditions. The successor cannot become a second active placement claim. + Preserve the Device and MachineCapacity identities; verify the new placement and + paths before restoring eligibility. Release old physical reservations only + after the affected space/terminations are confirmed free. +- **Replace the whole server:** create a new DeviceClaim, Device, and MachineCapacity. + Do not transfer an existing customer Machine or inherit identity from a reused + name, BMC address, serial field, or rack position. Managed-node replacement + uses the separate NodeClaim/fencing contract. +- **Repair a component:** retain Device identity where the asset remains the + same, but record the replacement component identity and inventory/trust + revision. Revalidate affected port, disk, power, and management bindings. + Reusing a slot ID must not make old component evidence current. +- **Retire or remove equipment:** coordinate physical removal, active consumer + obligations, and reference cleanup explicitly. Deleting an inventory object + does not destroy equipment, release a customer Machine, or prove a rack is empty. + +Bound claims retain their committed Device name and private incarnation evidence +as history. A placement handover +changes the registry-owned active relationship, not the historical binding. +Required Cable plans must be explicitly changed or replaced during a move; +they do not silently follow a Device into another rack. Retain fulfilled claims +while Cable references rely on them, or transfer those references through the +placement-change protocol. Protect active references and reservations during +deletion, including recovery from partial transitions. + +The proposed lifecycle distinguishes Draft, Accepted, Bound, Superseded, +Cancelled and Retired intent/history without requiring one overloaded status +enum. Verification conditions remain independent: a Bound asset can have Unknown +placement evidence. Cancelling an unbound plan releases only reservations proven +unused; uncertain installation work keeps a hold. Superseded/retired records +remain referenceable history and cannot be rebound. Marking an asset retired +does not prove physical removal, secure disposal, tenant cleanup, or provider +release. Each obligation retains its owner and evidence. + +For replacement in an occupied rack slot, a successor plan may be retained as +pending contingent on the predecessor; it cannot obtain a second exclusive +reservation of that footprint. The transition must prove removal/fencing and +conditionally transfer the physical reservation, or use a separately reserved +destination. A crash between steps preserves the old hold or an explicit +transition hold. It never makes the slot free merely because readiness is False. + +## Existing records and migration + +### Manual Fleet records: implemented subset versus target + +The comparison below is pinned to Fleet PR #90, branch +`feat/manual-inventory-records`, commit +`08d6dde8563b7c999ecf839565db2bd37b4dda7e`: its [actual types][manual-types] +and [operations guide][manual-guide]. It is not a claim about merge status or +what is deployed. That revision implements operator-written DeviceClaim/Device +CRDs and access controls, not reservation, enrollment, verification, retirement, +or capacity-publication controllers. Its empty status types do not establish +any of the conditions proposed here. + +| Reviewed implementation | Proposed target and migration constraint | +| --- | --- | +| DeviceClaim describes a long-lived slot; a replacement Device names the same claim. Device identity and `claimRef` are immutable. | Retain this proposal's per-installation claim identity: each move/replacement has a successor claim. Keep a stable slot label for operator navigation, not a second binding authority or new Slot kind. This is a proposed resolution, not a schema change already approved in #90. | +| Placement requires string `facility`/`rack`, numeric position, height and face. | Resolve approved Facility/Rack references. Convert to explicit placement scope; do not treat strings as global IDs or retain fabricated positions as authoritative. | +| Claimed ports have name/type/speed and embedded `expectedPeer`; Device interfaces may contain `peer`. | Convert approved expected connections into Cable plans once; preserve actual peer reports as sourced observations. Reconcile reciprocal/contradictory entries before creating a single Cable authority. Keep old inline fields read-only during cutover, then remove/deprecate through a versioned migration. | +| Device carries model, serial/system UUID, interfaces and unmapped MACs. | Preserve original values; adjudicate canonical physical identity and component mappings. Do not coerce provider IDs into chassis serials, or turn interface names/MAC lists into trusted component identity. | +| Optional BMC endpoint lives on restricted provider-project objects in Milo. | Preserve access restrictions. Endpoint discovery does not authorize access. Transfer endpoint configuration authority explicitly to the provider management surface before exposing only references/read projections; never run two writable copies. | +| No controller checks binding exclusivity, evidence or `MachineCapacity.deviceRef` resolution. | Resolve duplicate/multiple bindings and protect existing occupancy before enabling automation. Do not infer Accepted, Bound, Ready or allocator eligibility from schema admission. | + +**Claim-lifetime decision gate.** The target remains one committed Device binding +per installation claim, with one active placement authority per Device. A +long-lived slot is useful for naming and history but must not replace an +installation incarnation: otherwise a serial swap can inherit old cabling, +acceptance or verification. Before implementation, approve the successor-claim +protocol and versioned conversion of the manual API, or explicitly amend this +proposal to provide equivalent immutable incarnation semantics. Do not automate +the long-lived-slot convention while presenting it as the target contract. + +For a legacy slot with several Devices, retain the original claim and all Device +records, their immutable bindings, and available registration/retirement history. +Adjudicate the active asset and create explicit installation-history mappings; +unknown order or occupancy remains unresolved. Do not choose the newest timestamp +as proof of physical replacement. The migration must select a versioned storage/ +conversion mechanism that preserves original bindings while representing the +registry-owned active relationship. A raw patch of immutable `claimRef`, deleting +and recreating Devices, or renaming them to fit a successor claim is not a safe +conversion. Existing MachineCapacity/asset-key references must continue to resolve +to the same asset; a move is not grounds to manufacture a new capacity identity. + +**Home and authority decision gate.** The reviewed manual API deliberately stores +records in the provider project's Milo control plane, protected by inventory +roles. This proposal does not move them into a second management-cluster copy. +Choose the scopes for shared Facility/Rack/Cable/PowerFeed references and the +private coordinator ledger before implementation. Internal ledgers retain exact +bindings/evidence; they are not independently writable asset catalogs. Qualify +cross-project reads, status writers, reference authorization and consumer redaction +before broadening access or adding cross-scope relationships. + +### Moving records from another inventory system + +A writer that copies records from another system into Fleet writes ordinary +records through the same API and admission as any other writer, and is +observational until an explicit ownership transition. Fleet does not model +where those records came from. Never copy local provider tokens, BMC password +fields, kubeconfigs or secret-bearing generated configuration. + +Use a staged, reversible handoff rather than destructive in-place normalization: + +1. Snapshot protected records and audit references; classify physical versus + virtual supply, identifier semantics, known occupancy and placement certainty. + Produce a read-only mapping/conflict report with no hardware effects. +2. Approve Facility mappings, model/component shapes and per-installation history. + Create proposed plans without treating copied occupancy as free. Preserve + current allocator reservations and consumer obligations under their owners. +3. Reconcile expected peer pairs into Cable plans and electrical dependencies into + PowerFeeds. Resolve contradictions and unsupported paths explicitly. Validate + partial placement and scoped external circuit associations without inventing + absent endpoints or upstream sources. +4. Shadow-read and compare authorized provisioning inputs (identity, model, + restricted OOB endpoint and network-owned joins). Establish parity for + the selected cohort, not an assertion of exhaustive equivalence. +5. Transfer one writable surface at a time with an explicit cutover revision and + predecessor preconditions. Disable its previous writer before enabling the + replacement. Keep compatibility projections read-only. +6. Qualify current evidence and separately authorize custody/adoption and consumer + integrations. Never seed Ready from an old active flag. Recovery/rollback uses + retained cutover state; it cannot reactivate a stale writer, erase new history, + or release a reservation whose physical state is uncertain. + +The [infrastructure provider responsibilities](bare-metal-hardware.md#infrastructure-providers), +[capacity readiness reporting](bare-metal-hardware.md#status), and +[ownership of records replaced by Fleet](bare-metal-hardware.md#replaced-artifacts) retain provider +host IDs and commercial observations with provider authorities and logical +networking with its owners. This amendment does not complete those separate APIs. + +## Validation and qualification matrix + +These are required future admission, concurrency, authorization and hardware +qualification tests, **not tests implemented or passed by this documentation +change**. Offline schema tests cannot establish physical truth. + +| Area | Cases to qualify | Required outcome | +| --- | --- | --- | +| References and scope | Wrong kind, missing scope, cross-project denial, dangling reference, name recreation, stale revision | Reject unauthorized/ambiguous resolution; no inherited binding or evidence. | +| Facility and Rack | Multi-premises provider Site, unknown dimensions, conflicting faces/depth, 0U mount, known rack/unknown position | Preserve uncertainty; no invented geometry or false free-space assertion; exact reservations require accounted occupancy. | +| Identity and components | Duplicate serials, provider ID in serial, VM in DCIM, swapped asset tag, OS rename, replaced NIC/PSU/disk in the same slot | Adjudicate identity; retain history; invalidate affected mappings without changing asset identity on ordinary repairs. | +| Binding and reservations | Concurrent claims, claim versus direct-Device cable endpoints, lost registration response, crash during handover, restored reservation database | One active placement and exclusive termination/footprint ownership; recover exact committed inputs; uncertainty keeps holds. | +| Cable topology | Copper/optical mismatch, console direction, unresolved demarcation, patch-panel polarity, breakout lane collision, repatch/replacement | Reject unsupported paths; verify each required segment and invalidate changed dependencies, not just end-to-end link state. | +| Power | Shared UPS behind distinct PDUs, unknown rating, mixed units, feed cycles, failover overbudget, stale upstream evidence | No false redundancy or capacity; independent sources and full failover budget proven under a qualified electrical model. | +| Evidence and authority | Forged submitter, copied BMC location, stale scan, inaccessible document, unknown external circuit owner, attempted collector spec write | Fail closed for required checks; no self-attestation from copied intent, no status forgery or automatic exemption. | +| Lifecycle | Occupied-slot replacement, move with active allocation, component removal, retirement with active references, cancelled partially installed plan | Retain history and consumer obligations; no premature physical release, destructive side effect or second active claim. | +| Migration/cutover | Duplicate batch, conflicting inline peers, invented rack positions, disappearing records, rollback after new writes | Idempotent mapping, single writer, no Ready backfill or free-capacity window; keep unresolved facts unknown. | +| Access/projections | Inventory roles versus consumer roles, OOB/console endpoint reads, document ACLs, secret-bearing source fields | Restricted management details remain restricted; credentials never enter inventory projections or repository fixtures. | + +Before a facility cohort becomes eligible, record the qualified model variants, +supported connector/patch/breakout/electrical layouts, evidence issuers and +freshness policy, verified failure scenarios and recovery results. Exercise the +actual consumer projection against its retained input revisions. Unsupported +hardware or topology stays unavailable for offerings requiring those checks; +registration alone does not satisfy this gate. + +[manual-types]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/internal/api/inventory/v1alpha1/types.go +[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index a96068e9..7122fe9f 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -7,556 +7,216 @@ latest-milestone: "v0.1" # Fleet inventory -Part of the [Fleet infrastructure management service](README.md). Inventory owns -physical installation intent, registered assets, and verified physical -topology. [Machine allocation](bare-metal-hardware.md) consumes those records; -[bare-metal provisioning](bare-metal-provisioning.md) executes authorized work -on the hardware. Separate controllers and permissions preserve these -responsibilities within Fleet. +Part of the [Fleet infrastructure management service](README.md). Fleet inventory +should give infrastructure operators a reliable answer to four questions: what +equipment do we have, where is it, how is it connected, and is it ready for use? + +**Status:** This is a proposal. The existing manual records cover only part of +this experience; the verification and safety requirements below have not yet +been implemented or tested on hardware. Implementation details belong in the +[physical inventory contracts, examples, and migration notes](inventory-reference.md). - [Summary](#summary) -- [Goals](#goals) -- [Non-goals](#non-goals) +- [Goals and boundaries](#goals-and-boundaries) - [Proposal](#proposal) - - [Resources and authority](#resources-and-authority) - - [Plan a physical installation](#plan-a-physical-installation) - - [Reserve physical resources](#reserve-physical-resources) - - [Register and bind a device](#register-and-bind-a-device) - - [Verify the installation](#verify-the-installation) - - [Cabling, power, and network configuration](#cabling-power-and-network-configuration) + - [Resources and responsibilities](#resources-and-responsibilities) + - [From installation plan to ready equipment](#from-installation-plan-to-ready-equipment) + - [Location and equipment identity](#location-and-equipment-identity) + - [Connections and power](#connections-and-power) - [Moves, replacements, and retirement](#moves-replacements-and-retirement) -- [Implementation](#implementation) -- [Rollout plan](#rollout-plan) -- [Open qualification questions](#open-qualification-questions) +- [Bringing existing records into Fleet](#bringing-existing-records-into-fleet) +- [First release and success criteria](#first-release-and-success-criteria) +- [Decisions still needed](#decisions-still-needed) ## Summary -Operators declare a `DeviceClaim` before equipment is registered. It expresses -the expected hardware, approved rack placement, declared ports, and required -cables. Acceptance reserves the physical resources. A trusted registrar matches -the equipment to that accepted plan and creates an exclusively bound `Device`. -Controllers compare physical evidence with the plan before reporting readiness. - -A `DeviceClaim` is a physical installation expectation. A customer `Machine` is -the consumer lifecycle resource whose private MachineAllocation reserves provider -compute capacity. They have independent lifetimes. -Neither registering a Device nor making its DeviceClaim Ready authorizes power -changes, boot-based inspection, installation, cleaning, or consumer allocation. - -This is the target Fleet inventory model, independent of the existing inventory -service's schema. The proposed group is `fleet.datumapis.com/v1alpha1`; -the API group, fields, and scopes remain provisional. Examples show operator -resources in `infra-ops`, not implemented CRDs or manifests to apply. Hardware -identifiers and evidence handles are illustrative; Kubernetes UIDs remain private -same-API-server recreation evidence rather than authored references. - -## Goals - -- Record physical identity, placement, cabling, and power dependencies once. -- Reserve nonconflicting installations before hardware arrives. -- Admit equipment only through trusted registration against an accepted claim. -- Preserve expected and observed state separately, including incomplete work. -- Provide current, attributable evidence for allocation and operation gates. -- Support servers, network devices, power equipment, and passive infrastructure. -- Preserve asset history through repairs, moves, and changes of consumer. - -## Non-goals - -- Allocating compute to consumers, configuring an OS, or managing clusters. -- Storing BMC/switch credentials in broadly readable inventory objects. -- Owning VLANs, VRFs, IP allocations, routing, or workload network attachments. -- Treating discovery as authorization to adopt or modify hardware. -- Inferring physical completion from a YAML declaration or link reachability. -- Automating procurement, warehouse management, or every field-work process in - the first implementation. +Operators need to plan new installations without double-booking rack space, +confirm that delivered equipment matches the plan, and identify missing or +incorrect connections before making it available. They also need to move, repair +and replace equipment without losing its history or disrupting customers by +accident. + +Fleet should keep the installation plan separate from what technicians and +trusted tools actually find. Operators should be able to see what has been +checked, what is wrong, and what is still unknown, with supporting records for +each result. A missing measurement must not look like a successful check. + +Inventory readiness is one input to [machine allocation](bare-metal-hardware.md), +not permission to use or change equipment. Recording a device or marking it ready +must never start it, erase it, install software, assign it to a customer, or end +an existing customer reservation. Those actions require separate approval through +[hardware provisioning and operations](bare-metal-provisioning.md). + +## Goals and boundaries + +- Give operators one reliable record of equipment, placement, cables and power. +- Prevent conflicting installation plans and show what remains to be completed. +- Preserve equipment history through imports, moves, repairs and retirement. +- Support servers, network and power equipment, and passive devices such as patch + panels, including equipment that cannot report its own state. + +Fleet inventory does not replace purchasing, billing, work scheduling, network +address management, routing, or cluster management. It links to those services +rather than keeping competing records. Passwords and other credentials never +belong in public inventory or repository examples. ## Proposal -### Resources and authority - -- **`Facility`:** Provider-neutral physical premises, associated with geographic Location. - Provider codes do not define its identity. -- **`Rack`:** Facility membership, mounting capacity, and physical constraints. -- **`DeviceClaim`:** Operator's expected installation, physical reservations, and one - committed Device binding. -- **`Device`:** Canonical registered physical asset: server, switch, router, PDU, console - server, or patch panel. -- **`Cable`:** Sole authority for expected physical connections and their termination - mappings. -- **`PowerFeed`:** Electrical supply connection, capacity, and upstream dependency - information. - -Ports and components are typed entries with stable IDs within a Device. They do -not require a separate public kind initially. Network interfaces, power -inlets/outlets, console ports, and pass-through terminations have different -connection rules. Component identity must remain distinct from mutable OS names -such as `eth0` and from logical interfaces such as a VLAN or bond. - -For owned servers, `MachineCapacity` has an immutable `deviceRef` to the -registered Device. It is provider capacity with allocation and reclamation -policy; it does not independently edit the asset's serial number, rack placement, -or cabling. A switch or patch panel can be a Device without being -MachineCapacity. Inventory owns -physical observations; the provider owns management configuration and hardware -operations; networking owns network configuration. An inventory relationship -is not a Kubernetes garbage-collection ownership relationship. - -A Device represents identifiable physical equipment. Do not fabricate a Device, -rack, or physical port for a provider VM or an offering that discloses no -physical asset identity. Such providers still participate through the generic -MachineCapacity contract and their own observed capabilities. - -Operator authorization controls claims, physical plans, and manual evidence. -Only the trusted registration service creates registered Devices and writes -identity/placement bindings. Collectors write observations through validated -interfaces; they cannot change the approved plan. References crossing an -administrative scope require explicit authorization on both sides. A namespace -or matching label alone does not grant that authority. - -### Plan a physical installation - -The Facility describes physical premises. A Fleet `Site` can select eligible -Facilities as operational policy without moving their assets. Location remains -the geographic reference; neither Site nor Facility is a provider identifier. - -```yaml -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Facility -metadata: - name: iad1 - namespace: infra-ops -spec: - displayName: Ashburn Facility 1 - locationRef: - name: us-east-1 ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Rack -metadata: - name: iad1-r12 - namespace: infra-ops -spec: - facilityRef: {name: iad1} - heightUnits: 42 ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: DeviceClaim -metadata: - name: iad1-r12-u20-server - namespace: infra-ops -spec: - role: Server - expectedIdentity: - manufacturer: Dell - model: PowerEdge-R650 - serialNumber: EXAMPLE-SERVER-001 - placement: - rackRef: {name: iad1-r12} - position: 20 - heightUnits: 1 - face: Front - fullDepth: true - verification: - requiredChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] - ports: - - {id: bmc, type: EthernetPort, role: Management, physicalLabel: BMC} - - {id: nic1-p1, type: EthernetPort, role: Data, physicalLabel: NIC1/P1} - - {id: psu1, type: PowerInlet, physicalLabel: PSU1} - - {id: psu2, type: PowerInlet, physicalLabel: PSU2} - cableRefs: - - {name: iad1-r12-srv01-management} - - {name: iad1-r12-srv01-data} - - {name: iad1-r12-srv01-power-a} - - {name: iad1-r12-srv01-power-b} -``` - -The example assumes an existing management switch `iad1-oob01`, data switch -`iad1-r12-leaf-a`, and PDUs `iad1-r12-pdu-a`/`iad1-r12-pdu-b`, each registered -through its own claim. Their referenced components and upstream power paths -must exist and be verified. These four Cable plans describe the server's -required connections before the server Device exists: - -```yaml -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-management - namespace: infra-ops -spec: - medium: CopperEthernet - a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: bmc}] - b: [{deviceRef: {name: iad1-oob01}, componentID: port12}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-data - namespace: infra-ops -spec: - medium: DirectAttachCopper - a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: nic1-p1}] - b: [{deviceRef: {name: iad1-r12-leaf-a}, componentID: ethernet20}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-power-a - namespace: infra-ops -spec: - medium: Power - a: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: outlet20}] - b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu1}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-power-b - namespace: infra-ops -spec: - medium: Power - a: [{deviceRef: {name: iad1-r12-pdu-b}, componentID: outlet20}] - b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu2}] -``` - -`cableRefs` identifies prerequisites; it does not repeat expected peers. Cable -owns the endpoint declarations. A planned endpoint references a DeviceClaim -and its declared port ID; a registered endpoint references a Device and stable -component ID. Names are convenient authoring references. Acceptance retains the -exact local object incarnations privately and records approved dependency -revisions. Recreating an object with the same name never inherits a reservation. - -Placement may instead name `placement.facilityRef` without a rack. This covers -unracked equipment and rented bare metal whose physical Facility is known but -whose rack/patching is not disclosed. The claim must state its verification -requirements explicitly; for example: - -```yaml -# Excerpt for an identified physical server with facility-level visibility. -spec: - placement: - facilityRef: {name: iad1} - verification: - requiredChecks: [Identity, FacilityPlacement] -``` - -Admission constrains required checks using operator policy and the intended -offering. Authors cannot weaken verification to make a failed installation -pass. Rack placement derives Facility through the Rack; if both references are -supplied they must agree. Undisclosed rack/cable facts remain unknown, not -invented or marked physically inapplicable. `Ready` for a facility-scoped claim -does not imply verified rack position, cabling, power redundancy, or eligibility -for an offering that requires those facts. Historical UUID/IP/disk lists are -migration inputs, not sufficient verification evidence. - -### Reserve physical resources - -Acceptance commits a retained plan covering the claim and its required Cable -inputs. Inventory must reserve the applicable declared rack footprint, physical -terminations, and power capacity without races. Rack checks include occupied units, -front/rear constraints, full-depth equipment, and pending installations. The -model also supports 0U mounting and equipment outside a rack; it must not assign -them fictitious rack-unit positions. - -Endpoint reservations belong to one exact Cable incarnation and identify one -exact Device or DeviceClaim incarnation plus termination/position. Local object -identity is retained as private same-API-server evidence. Two cables cannot reserve the same -exclusive termination. Resolving a claim endpoint to a registered component -must preserve that reservation, including conflicts with direct Device -references. A successor placement cannot reserve an occupied resource merely -because the previous object's readiness is False. - -Use durable conditional commits or an equivalent serialized reservation -protocol, not an admission-time list check or controller-local lock. Partial -acquisition stays Pending and is recovered or explicitly unwound. Report -`Accepted=True` only after the complete current plan is committed. Hold -reservations through controller restarts and uncertainty; timeouts and expired -worker leases do not prove that space, cabling, or power is physically free. - -Referenced Cable plans may target other unbound claims. Validate and reserve -the intended endpoints without requiring those Devices to be Ready. Otherwise -two devices awaiting a connection could never be commissioned. Editing an -unbound plan requires revalidation and a new committed plan revision; stale -acceptance or registration requests cannot use the previous revision. - -### Register and bind a device - -A registration request must authenticate its enrollment channel and identify -an existing accepted DeviceClaim and approved plan revision. Match expected -identity against independently trusted evidence. Serial numbers, MAC -addresses, and SMBIOS UUIDs are matching attributes, not authentication. -Passive devices register through an authorized technician or integration; -they do not need to run a host agent. - -The registrar commits one reciprocal DeviceClaim-to-Device relationship and -retains both local object incarnations as private same-API-server evidence. One -claim binds one Device for one installation incarnation. One physical asset -cannot acquire duplicate Device identities, -and one Device has at most one active placement authority. Recovery after a -lost response finds the committed registration instead of creating a second -asset. Ambiguous matches, unexpected identities, expired authorization, or -already-bound claims fail closed. Unknown equipment remains isolated discovery -evidence; it cannot manufacture an accepted claim or eligible capacity. - -Registration does not require all physical verification to have succeeded. A -Device can exist in commissioning with a placement or wiring discrepancy: - -```yaml -# Registrar-created snapshot, not an operator-authored apply input. -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Device -metadata: - name: server-example-001 - namespace: infra-ops -spec: - # Registry-owned. A raw reference edit cannot move the asset. - claimRef: - name: iad1-r12-u20-server - identity: - manufacturer: Dell - model: PowerEdge-R650 - serialNumber: EXAMPLE-SERVER-001 -status: - observedPlacement: - rackRef: - name: iad1-r12 - position: 20 - face: Front - evidenceRef: installation-scan-001 - components: - - {id: management-port-1, type: EthernetPort, physicalLabel: BMC} - - id: nic-slot2-port1 - type: EthernetPort - physicalLabel: NIC1/P1 - macAddress: "02:00:00:00:12:01" - - {id: power-supply-1, type: PowerInlet, physicalLabel: PSU1} - - {id: power-supply-2, type: PowerInlet, physicalLabel: PSU2} -``` - -Declared claim ports resolve using trusted chassis labels, qualified hardware -layout, and physical component identity. A controller cannot swap the mapping -of `nic1-p1` to a different NIC merely to make the observed neighbor match. -The Device records actual components; the claim records the approved mapping -from its intended ports to those components. - -### Verify the installation - -Commissioning has an ordered dependency graph: - -```text -Accepted plan and physical reservations - -> trusted registration and exclusive Device binding - -> claim-port mapping and Cable endpoint resolution - -> identity, placement, network, and power evidence evaluated - -> physical Ready -``` - -Cable resolution depends on binding, not Device Ready. Protected enrollment -connectivity must exist before complete production-path verification. Any -inspection that boots or modifies a device requires a separately authorized -hardware operation; inventory readiness cannot authorize its own evidence -collection effects. - -- **Hardware identity and capabilities:** Authenticated BMC/qualified agent observations - or trusted installation evidence matched to the enrolled asset. Claimed identifiers - alone are insufficient. -- **Switch and port adjacency:** Trusted switch-side observations corroborated with the - enrolled NIC mapping. MAC learning or agent-reported LLDP alone does not prove asset - identity. -- **Link capability:** Current port state, negotiated parameters, and relevant hardware - observations; link-up is not proof of a complete passive path. -- **Exact rack position/orientation:** Authorized installation scans/attestations or - qualified rack instrumentation. Management-network reachability does not establish a - rack unit. -- **Passive cable identity and patch path:** Verified endpoint/cable-label scans or - qualified instrumentation. LLDP does not identify each passive segment. -- **PSU, outlet, and upstream feed:** Verified physical mappings and suitable - observations/instrumentation. Two healthy PSUs do not establish independent supplies. - -Link discovery can supply switch/port observations through qualified collectors; -it does not establish every physical fact above. Redfish's rack/offset fields -are writable metadata, so copying the intended position into a BMC and reading -it back is not independent placement evidence. See the -[Redfish data model](https://redfish.dmtf.org/schemas/v1/DSP0268_2025.3.pdf). - -Conditions report `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, -`NetworkPathVerified`, `PowerPathVerified`, and `Ready` separately. Readiness -requires every admitted required check for the current approved plan and -records the evaluated verification scope. `PlacementVerified` identifies -whether it evaluated Facility or exact Rack placement. Missing or stale -required evidence is Unknown; a verified mismatch is False. Checks outside the -scope remain explicitly unevaluated. A policy may mark a check physically -inapplicable, such as power for a passive panel; absence of evidence must not -silently become an exemption. Downstream controllers require the specific -verified facts their operation or offering needs, not an unqualified Ready bit. - -Each evaluation privately retains the exact local claim, Cable, Rack, PowerFeed, -and Device incarnations and records their revisions, Device -identity/component/trust revision, evaluated input digest, -evidence provenance, and verification time. Standard condition fields include -`observedGeneration`, reason, message, and transition time. The owning object's -generation alone is insufficient: recabling, a NIC replacement, or new trust -material can invalidate evidence without changing that object's spec. - -Keep bounded summaries and protected evidence references in status. Retain the -evaluated plan and evidence needed to explain the result. Evidence freshness -is check-specific: a current adjacency observation and an installation scan -have different validity rules. Relevant topology or hardware changes invalidate -the applicable result; an old `Ready=True` is not blanket authorization. - -```yaml -# Abbreviated controller-written verification snapshot after successful checks. -# Routine condition timestamps/messages are omitted for readability. -apiVersion: fleet.datumapis.com/v1alpha1 -kind: DeviceClaim -metadata: - name: iad1-r12-u20-server - namespace: infra-ops -status: - observedGeneration: 1 - evaluatedPlanDigest: "sha256:" - evaluatedChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] - evidenceRef: commissioning-evaluation-001 - deviceRef: - name: server-example-001 - portBindings: - - {claimPortID: bmc, deviceComponentID: management-port-1} - - {claimPortID: nic1-p1, deviceComponentID: nic-slot2-port1} - - {claimPortID: psu1, deviceComponentID: power-supply-1} - - {claimPortID: psu2, deviceComponentID: power-supply-2} - conditions: - - {type: Accepted, status: "True", reason: PhysicalReservationsCommitted, observedGeneration: 1} - - {type: Bound, status: "True", reason: ExclusiveDeviceBindingCommitted, observedGeneration: 1} - - {type: IdentityVerified, status: "True", reason: TrustedEnrollmentMatched, observedGeneration: 1} - - {type: PlacementVerified, status: "True", reason: InstallationScanVerified, observedGeneration: 1} - - {type: NetworkPathVerified, status: "True", reason: TrustedPeerEvidenceMatched, observedGeneration: 1} - - {type: PowerPathVerified, status: "True", reason: PowerPathEvidenceVerified, observedGeneration: 1} - - {type: Ready, status: "True", reason: RequiredEvidenceCurrent, observedGeneration: 1} -``` - -Cable status similarly reports resolved Device names/component IDs; protected -evidence privately retains the exact local Device incarnations. It separately -reports evidence for endpoint adjacency, cable identity, and any pass-through -path. It never rewrites spec to agree with discovery. Physical drift blocks -new allocations and operations that require the invalidated fact and alerts -operators. It does not independently authorize eviction, power-off, wiping, or -release of an existing consumer reservation. - -### Cabling, power, and network configuration - -A Cable connects typed physical terminations. Pass-through components on patch -panels retain explicit internal front/rear mappings. Breakout cables require -explicit position/lane mappings. Trace the complete supporting path; reject an -unsupported mapping rather than assuming a direct connection. NetBox's -[cable model](https://netboxlabs.com/docs/netbox/models/dcim/cable/) provides an -established physical-path precedent. It is not a requirement to use NetBox's -schema or implementation. - -A PDU is a Device. Its component model maps each outlet to the input that -supplies it. Power cables connect feeds to PDU inputs and outlets to device -inlets; a feed termination uses a typed `powerFeedRef`, resolved by name with its -exact local incarnation retained privately. -PowerFeed records include rated/usable capacity and known upstream -sources; unknown dependencies remain explicit. Reservation calculations must -account for the declared redundancy/failure scenario, not assume that each of -two feeds supplies half the load. Two differently named PDUs can share the same -UPS or upstream circuit. See the -[power-feed](https://netboxlabs.com/docs/netbox/models/dcim/powerfeed/) and -[outlet](https://netboxlabs.com/docs/netbox/models/dcim/poweroutlet/) precedents. - -Rack, switch, and power failure domains are derived from verified dependency -information, including shared upstream resources. Labels can expose validated -domains for selection; different labels do not establish physical independence. - -Physical connectivity does not select the VLAN, VRF, IP address, routing -adjacency, or tenant network carried over a link. Network management resources -reference registered Devices/components and own those behaviors. The -bare-metal provider requests attachment or isolation through the networking -authority, which remains the sole writer of the relevant switch configuration. -This physical/logical separation is consistent with -[RFC 8348's hardware model](https://www.rfc-editor.org/rfc/rfc8348.html) and -[RFC 8345's layered topology model](https://www.rfc-editor.org/rfc/rfc8345.html). +### Resources and responsibilities + +The proposed experience uses six records: + +| Record | What it tells an operator | +| --- | --- | +| Facility | The physical premises where equipment is installed. | +| Rack | The rack's location, available mounting space and physical limits. | +| DeviceClaim | What equipment is expected for one installation and which resources are reserved for it. | +| Device | The actual piece of equipment, its identity and its components. | +| Cable | Which physical ports should be connected. | +| PowerFeed | Where electrical supply comes from and how much load it can support. | + +Geographic Location and physical Facility are separate from +[Site rules for choosing where machines may run](cluster-lifecycle.md#site-and-cluster-resources). +A provider's metro name may cover several buildings; it must not be treated as +one physical facility without checking. + +Operators approve installation plans. Authorized registration establishes which +physical equipment matches each plan. Technicians and trusted tools provide +observations; Fleet checks those observations against the approved plan rather +than silently changing the plan to match them. + +Each record has one responsible writer. Providers remain responsible for hardware +controls, networking services for addresses and switch configuration, and Galactic +for routing. Management addresses, customer information and supporting documents +remain visible only to authorized users. + +### From installation plan to ready equipment + +1. **Plan the installation.** Record the expected equipment, location, cables, + power needs and required checks. Reserve the relevant space, ports and power + so another installation cannot claim them, even if requests arrive together. +2. **Record what arrived.** Check the actual equipment against the approved plan. + One installation plan identifies one device, and a device has only one active + placement. Retrying a registration must not create a duplicate asset. +3. **Check the installation.** Verify equipment identity, placement and required + network and power paths. Show missing work and mismatches separately from + completed checks. Connected devices can be checked together; neither must + already be ready before its cable endpoints can be identified. +4. **Report what is ready.** State which checks passed and what they cover. + For example, confirming a facility does not confirm a rack position. Services + using inventory must require the checks appropriate to their task. + +Keep the approved plan, supporting evidence and change history behind each result. +A cable change or component replacement requires new checks where it affects the +installation. Old results must not carry over merely because a name was reused. +If collecting evidence requires starting or changing equipment, that work needs +separate authorization. + +### Location and equipment identity + +Operators should be able to record only what is known: a facility, a rack without +an exact position, an exact rack position, or a side-mounted location. Unknown +space must not appear available. Invented positions cannot justify reservations +or verification; new reservations need enough evidence to avoid existing equipment. + +Keep manufacturer serial numbers, operator asset tags and provider host IDs +separate, including where each value came from. None alone proves that equipment +is trusted. Virtual machines must not become physical Fleet devices just because +an imported system records them alongside hardware. + +Track network, power, console and patch-panel ports separately, along with +replaceable parts. A software interface name is not a physical port identity. +After a repair, preserve the device history but record the replacement part and +recheck affected connections. Reusable model descriptions can reduce repeated +entry, but must be checked against the actual equipment. + +### Connections and power + +Cable records are the single source for planned physical connections. Device +plans reference them rather than keeping another list of expected neighbors. +Checks must follow patch panels and split cables, not assume that a working +end-to-end link proves every connection is correct. + +Power checks must follow the supply through distribution equipment to the device. +Two power supplies do not prove redundancy if they share an upstream failure +point. Reserve enough power for the agreed failure scenario, not just normal +operation. Unknown supply details must remain unverified. + +Operators also need circuit identifiers and the physical handoff points for +internet, transport and out-of-band management connections. The proposal links +these to the service owner's records and local cables. Service delivery, prices, +addresses and routing remain with their owners. Whether Fleet needs a separate +Circuit record is still an open decision, not an approved addition. ### Moves, replacements, and retirement -- **Move the same asset:** create a successor DeviceClaim naming the existing - Device and reserve the destination. A coordinated maintenance transition - transfers active placement authority with exact predecessor/binding - preconditions. The successor cannot become a second active placement claim. - Preserve the Device and MachineCapacity identities; verify the new placement and - paths before restoring eligibility. Release old physical reservations only - after the affected space/terminations are confirmed free. -- **Replace the whole server:** create a new DeviceClaim, Device, and MachineCapacity. - Do not transfer an existing customer Machine or inherit identity from a reused - name, BMC address, serial field, or rack position. Managed-node replacement - uses the separate NodeClaim/fencing contract. -- **Repair a component:** retain Device identity where the asset remains the - same, but record the replacement component identity and inventory/trust - revision. Revalidate affected port, disk, power, and management bindings. - Reusing a slot ID must not make old component evidence current. -- **Retire or remove equipment:** coordinate physical removal, active consumer - obligations, and reference cleanup explicitly. Deleting an inventory object - does not destroy equipment, release a customer Machine, or prove a rack is empty. - -Bound claims retain their committed Device name and private incarnation evidence -as history. A placement handover -changes the registry-owned active relationship, not the historical binding. -Required Cable plans must be explicitly changed or replaced during a move; -they do not silently follow a Device into another rack. Retain fulfilled claims -while Cable references rely on them, or transfer those references through the -placement-change protocol. Protect active references and reservations during -deletion, including recovery from partial transitions. - -## Implementation - -Inventory requires admission/authorization, a durable reservation and binding -coordinator, trusted registration, and evidence evaluation. These are controller -responsibilities, not a requirement for another public type per process. -Implementations may share infrastructure with other Fleet subsystems while -retaining separate field ownership and credentials. - -Hardware providers and network collectors submit authenticated observations; -authorized technicians submit physical-work evidence. Enrollment of passive -infrastructure follows the same claim and binding rules. Backfill existing -assets through explicit approved claims and non-destructive registration; -importing a record must not invoke boot, cleaning, or network changes. - -Consumers read only the inventory projections they are authorized to see. -Privileged BMC/switch endpoints, credentials, and tenant allocation details -remain in their respective management domains. Physical evidence must be -available to the controllers enforcing prerequisites without requiring those -controllers to assume inventory ownership. - -## Rollout plan - -1. Implement Facility/Rack/DeviceClaim/Device/Cable/PowerFeed contracts, typed - components, physical reservation validation, and trusted operator - registration. Qualify one hardware/rack layout, including passive equipment. -2. Exercise one facility's management, data, console where used, and power - paths. Demonstrate wrong identity, wrong port, wrong rack placement, missing - evidence, and stale evidence remaining unavailable without destructive - side effects. Verify patch-panel/breakout paths used by that facility. -3. Integrate current physical-readiness evidence with MachineCapacity eligibility and - network attachment prerequisites. Test concurrent claims, duplicate - registration, lost responses, controller restart, object-name reuse, and - changes to dependencies during evaluation. -4. Qualify moves, component replacement, retirement, and a recovered reservation - database. Demonstrate no duplicate active placement, premature capacity - reuse, or implicit consumer eviction before expanding to more facilities. - -## Open qualification questions - -- Which platform scopes and IAM permissions govern shared Facilities, operator - claims, registrar writes, evidence submission, and cross-scope references? -- Which durable reservation/commit mechanism enforces rack, termination, - power-capacity, and identity uniqueness through crashes and restoration? -- What independently trusted enrollment mechanism and identity-deduplication - rules apply to each active and passive hardware family? -- Which rack/cable/power checks require technician evidence, which have - qualified instrumentation, and what invalidates or expires each result? -- What component, pass-through, breakout, and redundant-power layouts must the - first facility support, and how is unsupported topology reported? -- What explicit maintenance and placement-handover protocol preserves active - allocations and releases old physical reservations only after verification? - -These are implementation qualification gates. None changes the ownership, -exclusive-binding, or no-implicit-destructive-action contracts above. +- **Move equipment:** create a new installation plan for the same device, reserve + its destination and check its new connections. Keep the device and provider + capacity identities. Release old space and ports only after confirming they + are free. +- **Replace equipment:** create a new installation plan, device record and provider + capacity record. Do not transfer customer assignments or successful checks just + because the replacement uses the same rack position or management address. +- **Repair equipment:** keep the device record, record changed parts and repeat + the affected checks. +- **Retire equipment or cancel a plan:** keep the history and outstanding customer + obligations. Deleting a record does not prove removal, data erasure or release. + +A replacement cannot double-book an occupied slot. When work is interrupted or +its outcome is unclear, retain the reservation until it is safe to release it. +Moves also require explicit cable-plan changes; cables do not automatically +follow a device to its new location. + +## Bringing existing records into Fleet + +The [existing manual inventory guide][manual-guide] describes a smaller model: +installation plans represent long-lived slots, locations are text fields, and +expected connections are stored on ports. This proposal instead uses a new plan +for each installation and separate Cable records. That difference must be settled +before automating moves and replacements. + +The current implementation uses manual entry and operator-controlled migration, +not automated import. Fleet does not read any external inventory source. +Migration must preserve existing equipment identities, customer reservations and +history. Change the responsible writer only through an explicit approval. Do not delete +and recreate assets, assume occupied space is free, or mark old records ready +without new checks. + +A separate writer that copies records from another system into Fleet writes +ordinary records through the same API and validation as any other writer. Data +copied that way needs interpretation: one external site may group several +premises, serial fields may contain provider host IDs, device lists may include +virtual machines, and rack positions may have been invented for display. Such a +writer should preserve these limitations rather than turning them into verified +facts. Where facts came from is that writer's concern, recorded on its own labels +and annotations; Fleet does not model it. + +See the [comparison with existing records and migration steps](inventory-reference.md#existing-records-and-migration). + +## First release and success criteria + +Start with a small set of equipment in one facility. Operators should be able to +plan an installation, register equipment, find incorrect or incomplete work, and +see which checks make it suitable for use. + +Before expanding, demonstrate that Fleet prevents conflicting reservations, +keeps unknown facts visible, and preserves occupied resources after interrupted +work. Moves, replacements, repairs and retirement must preserve history without +accidentally releasing customer equipment. Imported records must not trigger +hardware actions or become available capacity on their own. + +The [detailed validation and hardware acceptance checks](inventory-reference.md#validation-and-qualification-matrix) +describe work still required; they are not a report of tests already passed. + +## Decisions still needed + +- Agree how to move from long-lived slot plans to one plan per installation + without losing existing bindings or history. +- Decide who can view and change shared facilities, racks, cables and feeds, + and where their authoritative records live. +- Choose how reservations survive failures, which hardware and connection layouts + are supported first, and what evidence is sufficient and recent enough. +- Assign ownership of circuit references and physical handoff points, and decide + whether a separate Circuit record is needed. + +[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md From 8190cd562ad9fb9316cecd335a9a5059b67fa664 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 14:34:39 -0600 Subject: [PATCH 3/8] feat(inventory)!: remove legacy DeviceClaim slots and inline peers Fleet keeps no legacy physical-inventory shapes. Every DeviceClaim is now a typed installation: - spec.lifecycle is required and only Installation. - spec.placement.scope is required; the text placement.facility and placement.rack fields are gone. - spec.ports, ExpectedPort and PortPeer are gone. Cable records are the only topology authority. - Device interfaces lose peer and keep name and macAddress. The CEL rules that only separated legacy from typed claims are deleted. Scope/reference agreement, the RackUnits position/height/face rule and immutable placement now apply to every claim. The DeviceClaim printer columns show scope and the facilityRef/rackRef names. Existing legacy-shaped objects fail validation on update and must be deleted or re-imported; there is no migration. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 91 +++---------------- internal/api/inventory/v1alpha1/crd_test.go | 34 +++---- .../api/inventory/v1alpha1/physical_test.go | 18 +--- internal/api/inventory/v1alpha1/types.go | 45 ++++----- 4 files changed, 53 insertions(+), 135 deletions(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 49936808..21e606be 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -19,12 +19,15 @@ spec: subresources: status: {} additionalPrinterColumns: + - name: Scope + type: string + jsonPath: .spec.placement.scope - name: Facility type: string - jsonPath: .spec.placement.facility + jsonPath: .spec.placement.facilityRef.name - name: Rack type: string - jsonPath: .spec.placement.rack + jsonPath: .spec.placement.rackRef.name - name: Position type: integer jsonPath: .spec.placement.position @@ -49,17 +52,12 @@ spec: spec: type: object required: + - lifecycle - expectedIdentity - placement x-kubernetes-validations: - - rule: has(self.lifecycle) == has(oldSelf.lifecycle) - message: legacy claims cannot be reinterpreted as installations - - rule: '!has(self.lifecycle) || self.placement == oldSelf.placement' + - rule: self.placement == oldSelf.placement message: installation placement is immutable; migration requires an explicit handover - - rule: '!has(self.lifecycle) || !has(self.ports) || self.ports.all(p, !has(p.expectedPeer))' - message: Cable is the only expected topology authority for installations - - rule: has(self.lifecycle) == has(self.placement.scope) - message: typed placement requires an installation lifecycle; legacy slots keep their text placement properties: expectedIdentity: type: object @@ -79,15 +77,9 @@ spec: maxLength: 253 placement: type: object + required: + - scope properties: - facility: - type: string - minLength: 1 - maxLength: 253 - rack: - type: string - minLength: 1 - maxLength: 253 position: type: integer format: int32 @@ -125,52 +117,13 @@ spec: minLength: 1 maxLength: 253 x-kubernetes-validations: - - rule: 'has(self.scope) ? (!has(self.facility) && !has(self.rack)) : (has(self.facility) && has(self.rack) - && has(self.position) && has(self.face) && !has(self.facilityRef) && !has(self.rackRef) && !has(self.mount))' - message: choose legacy text placement or typed placement, never both - - rule: '!has(self.scope) || (self.scope == ''Facility'' ? (has(self.facilityRef) && !has(self.rackRef)) - : (has(self.rackRef) && !has(self.facilityRef)))' + - rule: 'self.scope == ''Facility'' ? (has(self.facilityRef) && !has(self.rackRef)) : (has(self.rackRef) + && !has(self.facilityRef))' message: typed placement requires exactly the reference appropriate to its scope - - rule: '!has(self.scope) || (self.scope == ''RackUnits'' ? (has(self.position) && has(self.height) - && has(self.face) && !has(self.mount)) : (!has(self.position) && !has(self.height) && !has(self.face) - && (self.scope == ''NonRackUnitMount'' ? has(self.mount) : !has(self.mount))))' + - rule: 'self.scope == ''RackUnits'' ? (has(self.position) && has(self.height) && has(self.face) && !has(self.mount)) + : (!has(self.position) && !has(self.height) && !has(self.face) && (self.scope == ''NonRackUnitMount'' + ? has(self.mount) : !has(self.mount)))' message: partial placement cannot assert rack units; non-unit mounts require a mount identifier - ports: - type: array - maxItems: 128 - x-kubernetes-list-type: map - x-kubernetes-list-map-keys: - - name - items: - type: object - required: - - name - properties: - name: - type: string - minLength: 1 - maxLength: 63 - type: - type: string - maxLength: 253 - speedMbps: - type: integer - format: int64 - minimum: 1 - expectedPeer: - type: object - required: - - device - - port - properties: - device: - type: string - minLength: 1 - maxLength: 253 - port: - type: string - minLength: 1 - maxLength: 253 lifecycle: type: string enum: @@ -268,8 +221,6 @@ spec: has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses))))' message: a MAC address may be recorded only once - - rule: '!has(self.topologyAuthority) || !has(self.interfaces) || self.interfaces.all(p, !has(p.peer))' - message: Cable topology excludes inline peers - rule: '!has(self.components) || has(self.topologyAuthority)' message: typed components require Cable topology - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, (m.from.componentID @@ -450,20 +401,6 @@ spec: type: string maxLength: 17 pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ - peer: - type: object - required: - - device - - port - properties: - device: - type: string - minLength: 1 - maxLength: 253 - port: - type: string - minLength: 1 - maxLength: 253 unmappedMACAddresses: type: array maxItems: 32 diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 41303ce0..f2df4ddb 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -140,12 +140,9 @@ func syntheticClaim() DeviceClaim { TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12", Namespace: "fleet-system"}, Spec: DeviceClaimSpec{ + Lifecycle: ClaimInstallation, ExpectedIdentity: ExpectedIdentity{Manufacturer: "Example Vendor", Model: "Example 1U"}, - Placement: Placement{Facility: "example-facility", Rack: "rack-01", Position: 12, Face: "front"}, - Ports: []ExpectedPort{ - {Name: "eth0", Type: "25gbase-x-sfp28", SpeedMbps: 25000, ExpectedPeer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, - {Name: "bmc0", Type: "1000base-t", SpeedMbps: 1000, ExpectedPeer: &PortPeer{Device: "mgmt-switch-01", Port: "Ethernet5"}}, - }, + Placement: Placement{Scope: "RackUnits", RackRef: &LocalReference{Name: "rack-01"}, Position: 12, Height: 1, Face: "front"}, }, } } @@ -159,7 +156,7 @@ func syntheticDevice() Device { Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, Interfaces: []Interface{ - {Name: "eth0", MACAddress: "00:00:5e:00:53:01", Peer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "eth0", MACAddress: "00:00:5e:00:53:01"}, {Name: "bmc0", MACAddress: "00:00:5e:00:53:02"}, }, UnmappedMACAddresses: []string{"00:00:5e:00:53:03"}, @@ -185,7 +182,9 @@ func TestValidRecordsAreAccepted(t *testing.T) { } func TestClaimDoesNotRequireSerialOrInventHeight(t *testing.T) { - claim := object(t, syntheticClaim()) + membership := syntheticClaim() + membership.Spec.Placement = Placement{Scope: "RackMembership", RackRef: &LocalReference{Name: "rack-01"}} + claim := object(t, membership) if errs := admit(t, "DeviceClaim", claim, nil); len(errs) > 0 { t.Fatal(errs) } @@ -196,14 +195,17 @@ func TestClaimDoesNotRequireSerialOrInventHeight(t *testing.T) { func TestInvalidClaimsAreRejected(t *testing.T) { for name, mutate := range map[string]func(*DeviceClaim){ - "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, - "missing facility": func(c *DeviceClaim) { c.Spec.Placement.Facility = "" }, - "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, - "unknown face": func(c *DeviceClaim) { c.Spec.Placement.Face = "side" }, - "duplicate port": func(c *DeviceClaim) { c.Spec.Ports[1].Name = c.Spec.Ports[0].Name }, - "peer without port": func(c *DeviceClaim) { - c.Spec.Ports[0].ExpectedPeer = &PortPeer{Device: "switch-01"} - }, + "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, + "missing lifecycle": func(c *DeviceClaim) { c.Spec.Lifecycle = "" }, + "unknown lifecycle": func(c *DeviceClaim) { c.Spec.Lifecycle = "Slot" }, + "missing scope": func(c *DeviceClaim) { c.Spec.Placement.Scope = "" }, + "unknown scope": func(c *DeviceClaim) { c.Spec.Placement.Scope = "Row" }, + "missing rack": func(c *DeviceClaim) { c.Spec.Placement.RackRef = nil }, + "facility and rack": func(c *DeviceClaim) { c.Spec.Placement.FacilityRef = &LocalReference{Name: "facility-01"} }, + "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, + "missing height": func(c *DeviceClaim) { c.Spec.Placement.Height = 0 }, + "unknown face": func(c *DeviceClaim) { c.Spec.Placement.Face = "side" }, + "mount on units": func(c *DeviceClaim) { c.Spec.Placement.Mount = "side-a" }, } { claim := syntheticClaim() mutate(&claim) @@ -268,7 +270,7 @@ func TestDeviceIdentityNeedsSerialOrSystemUUID(t *testing.T) { // attribution field; audit logs record who changed a record. func TestEditsDoNotNeedARecordingTimestamp(t *testing.T) { claim := syntheticClaim() - claim.Spec.Placement.Position = 14 + claim.Spec.DisplayName = "Example server" if errs := admit(t, "DeviceClaim", object(t, claim), object(t, syntheticClaim())); len(errs) > 0 { t.Fatalf("claim edit rejected: %v", errs) } diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go index ba337dc4..deab4e74 100644 --- a/internal/api/inventory/v1alpha1/physical_test.go +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -45,7 +45,7 @@ func TestManualInventoryRecordsPassAdmission(t *testing.T) { if spec["provenance"] != nil || record["status"] != nil { t.Fatal("manual example must carry no provenance or status assertion") } - if kind == "DeviceClaim" && spec["lifecycle"] != "Installation" || kind == "Device" && spec["topologyAuthority"] != "Cable" { + if kind == "DeviceClaim" && spec["lifecycle"] != ClaimInstallation || kind == "Device" && spec["topologyAuthority"] != "Cable" { t.Fatal("new manual records must use typed installation and Cable topology") } } @@ -65,10 +65,8 @@ func TestManualInventoryRecordsPassAdmission(t *testing.T) { t.Logf("validated %d records for create and unchanged update; no API writes", count) } -func TestTypedPlacementAndLegacyBinding(t *testing.T) { +func TestTypedPlacementScopes(t *testing.T) { claim := syntheticClaim() - claim.Spec.Lifecycle = "Installation" - claim.Spec.Ports = nil claim.Spec.Placement = Placement{Scope: "RackMembership", RackRef: &LocalReference{Name: "rack-a"}} if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) != 0 { t.Fatal(errs) @@ -92,14 +90,6 @@ func TestTypedPlacementAndLegacyBinding(t *testing.T) { if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { t.Fatal("accepted synthetic units on rack membership") } - candidate = claim - if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, syntheticClaim())); len(errs) == 0 { - t.Fatal("converted a legacy slot in place") - } - candidate.Spec.Ports = syntheticClaim().Spec.Ports - if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { - t.Fatal("accepted competing inline topology") - } } func TestPhysicalKindsSchemeAndAdmission(t *testing.T) { @@ -163,8 +153,8 @@ func TestComponentSafety(t *testing.T) { t.Fatal("accepted incompatible pass-through component types") } candidate = device.DeepCopyObject().(*Device) - candidate.Spec.Interfaces = syntheticDevice().Spec.Interfaces + candidate.Spec.TopologyAuthority = "" if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { - t.Fatal("accepted Cable and inline topology writers") + t.Fatal("accepted typed components without Cable topology") } } diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index cd8cd62c..15383360 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -1,6 +1,6 @@ // Package v1alpha1 holds the six observational physical inventory kinds in -// fleet.datumapis.com. Legacy slot claims retain their historical bindings; -// new typed claims describe individual installations without accepting them. +// fleet.datumapis.com. A DeviceClaim describes one planned installation by +// typed placement without accepting it. // // All are operator-written records. None has a controller. Registering a // Device authorizes no hardware effect and creates or changes no @@ -18,7 +18,7 @@ import ( var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} -// DeviceClaim retains legacy slot plans and typed observational installations. +// DeviceClaim records one typed observational installation. type DeviceClaim struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -27,14 +27,17 @@ type DeviceClaim struct { } type DeviceClaimSpec struct { - DisplayName string `json:"displayName,omitempty"` - Lifecycle string `json:"lifecycle,omitempty"` + DisplayName string `json:"displayName,omitempty"` + // Lifecycle is required and is always ClaimInstallation. + Lifecycle string `json:"lifecycle"` CableRefs []LocalReference `json:"cableRefs,omitempty"` ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` Placement Placement `json:"placement"` - Ports []ExpectedPort `json:"ports,omitempty"` } +// ClaimInstallation is the only DeviceClaim lifecycle. +const ClaimInstallation = "Installation" + // ExpectedIdentity is the planned equipment. Serial is usually unknown at plan // time and is optional. type ExpectedIdentity struct { @@ -43,14 +46,14 @@ type ExpectedIdentity struct { Serial string `json:"serial,omitempty"` } -// Placement retains legacy text placement or an explicit typed scope. +// Placement is the typed installation scope. Facility scope names a +// FacilityRef; the rack scopes name a RackRef. RackUnits also needs Position, +// Height and Face, and NonRackUnitMount needs Mount. Placement is immutable. type Placement struct { - Scope string `json:"scope,omitempty"` + Scope string `json:"scope"` FacilityRef *LocalReference `json:"facilityRef,omitempty"` RackRef *LocalReference `json:"rackRef,omitempty"` Mount string `json:"mount,omitempty"` - Facility string `json:"facility,omitempty"` - Rack string `json:"rack,omitempty"` Position int32 `json:"position,omitempty"` Height int32 `json:"height,omitempty"` // Face is the mounted rack face: the rack face the chassis front points @@ -58,21 +61,6 @@ type Placement struct { Face string `json:"face,omitempty"` } -// ExpectedPort is a planned physical port and the cable peer it should reach. -// Logical LAGs and VLANs are not ports. -type ExpectedPort struct { - Name string `json:"name"` - Type string `json:"type,omitempty"` - SpeedMbps int64 `json:"speedMbps,omitempty"` - ExpectedPeer *PortPeer `json:"expectedPeer,omitempty"` -} - -// PortPeer names the far end of a cable by device name and port. -type PortPeer struct { - Device string `json:"device"` - Port string `json:"port"` -} - // DeviceClaimStatus is reserved for verifiers. Nothing writes it yet. type DeviceClaimStatus struct{} @@ -183,10 +171,11 @@ type BMC struct { Endpoint string `json:"endpoint"` } +// Interface names a detected network interface and its MAC address. Cable +// records carry what it connects to. type Interface struct { - Name string `json:"name"` - MACAddress string `json:"macAddress,omitempty"` - Peer *PortPeer `json:"peer,omitempty"` + Name string `json:"name"` + MACAddress string `json:"macAddress,omitempty"` } // DeviceStatus is reserved for collectors and verifiers to report drift and From 8c9353c4f0315c756342119e061b7c4475c70a1d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 14:34:40 -0600 Subject: [PATCH 4/8] docs(inventory): describe only the typed installation model Remove the legacy slot example, the legacy text placement and inline peer descriptions, and the compatibility decision. Document the required lifecycle and scope and immutable placement. Point the proposal comparison at the implemented types instead of a pinned old revision. Co-Authored-By: Claude Opus 5.5 --- docs/development/README.md | 11 +-- docs/operations/physical-inventory.md | 78 ++++--------------- .../fleet-management/inventory-reference.md | 50 +++++------- docs/proposals/fleet-management/inventory.md | 12 +-- 4 files changed, 44 insertions(+), 107 deletions(-) diff --git a/docs/development/README.md b/docs/development/README.md index 4e964020..fe32d898 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -682,11 +682,12 @@ corrupt or uses an unsupported schema version. `internal/api/inventory/v1alpha1` defines Facility, Rack, DeviceClaim, Device, Cable and PowerFeed records, a Manufacturer and DeviceType -[hardware catalog](hardware-catalog.md), and an observational Site. Legacy slot -claims coexist with new installation claims; no move or replacement handover is -automated. Records live in the provider project in Milo. -`config/components/inventory` holds their CRDs, ProtectedResources, and the -inventory viewer, editor, manager and importer roles. Only `config/milo` +[hardware catalog](hardware-catalog.md), and an observational Site. Each +DeviceClaim is an observational installation claim with typed, immutable +placement, and Cable records are the only topology authority; no move or +replacement handover is automated. Records live in the provider project in +Milo. `config/components/inventory` holds their CRDs, ProtectedResources, and +the inventory viewer, editor, manager and importer roles. Only `config/milo` includes it. Records carry no attribution fields: resource audit logs record who changed a diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 5725abb5..16426ce6 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -23,7 +23,7 @@ where facts came from on its own labels and annotations. | Kind | What it is | Writer | | --- | --- | --- | -| `DeviceClaim` | An observational installation plan with expected model and known placement. New records use typed placement and Cable references; existing long-lived slots retain their legacy representation. | Installation planner, through the record's explicitly assigned writer | +| `DeviceClaim` | An observational installation plan with expected model, typed placement and Cable references. | Installation planner, through the record's explicitly assigned writer | | `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, or an explicit marker that neither is on record, the model, an optional BMC endpoint, and interfaces. | The registrar (an operator, for now) | | `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | | `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | @@ -43,7 +43,7 @@ where facts came from on its own labels and annotations. ## What registration does and does not do Creating a Device is the explicit, manual binding step. It records that the -registrar saw this hardware in this planned slot. It does not: +registrar saw this hardware at this planned installation. It does not: - authorize power, boot, wipe, BMC credential, or network changes; - create, change, or enable any `MachineCapacity`, or make anything @@ -128,11 +128,14 @@ is registered; the kinds are provider-internal, not a catalog offering. | Rule | Kind | Why | | --- | --- | --- | | Records carry no attribution fields | All nine | Resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. A writer that needs to remember where facts came from uses its own labels and annotations. | -| `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | -| `identity` is immutable, including adding missing fields; requires a serial or system UUID, or `unidentified: true` with a reason and neither | Device | Neither proves chassis identity. Legacy bindings are preserved; hardware handover is not automated. See [Devices without hardware identity](#devices-without-hardware-identity). | +| `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another installation is not an edit. | +| `identity` is immutable, including adding missing fields; requires a serial or system UUID, or `unidentified: true` with a reason and neither | Device | Neither proves chassis identity. Hardware handover is not automated. See [Devices without hardware identity](#devices-without-hardware-identity). | | An unidentified Device cannot record a `bmc` endpoint | Device | Equipment that cannot be matched to a chassis must not be enrolled as machine capacity. | | Serial is optional | DeviceClaim | It is usually unknown at plan time. | -| Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | +| `lifecycle` is required and is `Installation` | DeviceClaim | Every claim describes one installation. | +| `placement.scope` is required and names exactly its reference: `Facility` takes `facilityRef`; `RackMembership`, `RackUnits` and `NonRackUnitMount` take `rackRef`. Only `RackUnits` takes `position`, `height` and `face`, all three required; only `NonRackUnitMount` takes `mount`, and requires it | DeviceClaim | Partial placement cannot assert rack units. | +| `placement` is immutable | DeviceClaim | Moving an installation is a new claim, not an edit. | +| Interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | | `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Nothing reads the lifecycle yet. | @@ -218,7 +221,7 @@ authenticated, complete NIC mapping before any network path depends on it. 2. Enter the Facility and Rack facts you actually know. Leave unknown dimensions absent. Rack membership is not a reserved footprint or evidence of available space. -3. For a new installation, set `DeviceClaim.spec.lifecycle: Installation` and +3. For each installation, set `DeviceClaim.spec.lifecycle: Installation` and typed placement. Use `Facility` when only the premises are known, `RackMembership` when the rack is known, or explicitly reviewed `RackUnits` with position, height and face. Never guess a rack position. Use a new record @@ -229,7 +232,7 @@ authenticated, complete NIC mapping before any network path depends on it. [no-hardware-identity marker](#devices-without-hardware-identity); otherwise keep the plan and defer registration. Provider host IDs and asset tags are not serials. Use typed `components` and `topologyAuthority: Cable`; put expected - connections in Cable records, not `ports.expectedPeer` or `interfaces.peer`. + connections in Cable records, the only topology authority. Add PowerFeed facts without inferring usable power or independent redundancy. 5. Review every reference in the same namespace, component type and position, cable endpoint, and potential duplicate against existing records. API validation @@ -335,56 +338,7 @@ placement is reported and not verified. A Cable whose two ends land on opposite rack faces is not an error: a pass-through panel or a reversed peer can make that correct. -## Historical legacy example - -The following representation remains supported for existing long-lived slots. -It is **not the template for new records**. Do not convert existing claims in -place or copy their inline topology into a second Cable authority. - -```yaml -apiVersion: fleet.datumapis.com/v1alpha1 -kind: DeviceClaim -metadata: - name: rack-01-u12 - namespace: fleet-system -spec: - expectedIdentity: - manufacturer: Example Vendor - model: Example 1U - placement: - facility: example-facility - rack: rack-01 - position: 12 - face: front - ports: - - name: eth0 - type: 25gbase-x-sfp28 - speedMbps: 25000 - expectedPeer: {device: switch-01, port: Ethernet1/1} - - name: bmc0 - type: 1000base-t - speedMbps: 1000 - expectedPeer: {device: mgmt-switch-01, port: Ethernet5} ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Device -metadata: - name: rack-01-u12-synthetic-0001 - namespace: fleet-system -spec: - claimRef: - name: rack-01-u12 - identity: - manufacturer: Example Vendor - model: Example 1U - serial: SYNTHETIC-0001 - systemUUID: 00000000-0000-4000-8000-000000000001 - bmc: - endpoint: https://192.0.2.100:443 - unmappedMACAddresses: - - 00:00:5e:00:53:01 - - 00:00:5e:00:53:02 -``` +## Replacing hardware To replace the hardware, create a new Device with its own name and identity that names the same claim. Leave the old Device in place and move its @@ -405,9 +359,7 @@ The names and writers match #63: Still deferred to #63: -- Qualified geometry/reservations and automatic migration of legacy text - placement/inline peers. The four additional physical record kinds now exist; - typed records do not silently take over historical surfaces. +- Qualified geometry and reservations. - Plan acceptance, revisions, and reservations; canonical-identity adjudication and duplicate detection; and the protected ledger. - Trust roots, qualification profiles, enrollment challenges, technician and @@ -432,10 +384,8 @@ for one authoritative record that MachineCapacity can name and that staff can read. #63's ledger, trust, and enrollment protocol would still sit behind these records if adopted. -**Compatibility decision:** legacy slots retain all historical bindings. New -typed records use a distinct `Installation` lifecycle, but no automatic move or -replacement handover exists. Device identity and its original claimRef remain -immutable. No writer may delete/recreate or relabel legacy records to bypass this. +No automatic move or replacement handover exists. Device identity, its +claimRef and the claim's placement remain immutable. ## Applying the records diff --git a/docs/proposals/fleet-management/inventory-reference.md b/docs/proposals/fleet-management/inventory-reference.md index 52fc3dd3..a9d824c3 100644 --- a/docs/proposals/fleet-management/inventory-reference.md +++ b/docs/proposals/fleet-management/inventory-reference.md @@ -759,43 +759,29 @@ transition hold. It never makes the slot free merely because readiness is False. ### Manual Fleet records: implemented subset versus target -The comparison below is pinned to Fleet PR #90, branch -`feat/manual-inventory-records`, commit -`08d6dde8563b7c999ecf839565db2bd37b4dda7e`: its [actual types][manual-types] -and [operations guide][manual-guide]. It is not a claim about merge status or -what is deployed. That revision implements operator-written DeviceClaim/Device -CRDs and access controls, not reservation, enrollment, verification, retirement, -or capacity-publication controllers. Its empty status types do not establish -any of the conditions proposed here. - -| Reviewed implementation | Proposed target and migration constraint | +The comparison below describes the [implemented types][manual-types] and +[operations guide][manual-guide] in this repository. They implement +operator-written physical inventory CRDs and access controls, not reservation, +enrollment, verification, retirement, or capacity-publication controllers. +Their empty status types do not establish any of the conditions proposed here. + +| Implemented subset | Proposed target and remaining constraint | | --- | --- | -| DeviceClaim describes a long-lived slot; a replacement Device names the same claim. Device identity and `claimRef` are immutable. | Retain this proposal's per-installation claim identity: each move/replacement has a successor claim. Keep a stable slot label for operator navigation, not a second binding authority or new Slot kind. This is a proposed resolution, not a schema change already approved in #90. | -| Placement requires string `facility`/`rack`, numeric position, height and face. | Resolve approved Facility/Rack references. Convert to explicit placement scope; do not treat strings as global IDs or retain fabricated positions as authoritative. | -| Claimed ports have name/type/speed and embedded `expectedPeer`; Device interfaces may contain `peer`. | Convert approved expected connections into Cable plans once; preserve actual peer reports as sourced observations. Reconcile reciprocal/contradictory entries before creating a single Cable authority. Keep old inline fields read-only during cutover, then remove/deprecate through a versioned migration. | +| DeviceClaim describes one installation: `lifecycle` is always `Installation` and placement is immutable. A replacement Device names the same claim. Device identity and `claimRef` are immutable. | Each move or replacement has a successor claim. Keep a stable label for operator navigation, not a second binding authority or new Slot kind. | +| Placement has a required scope: `Facility` with `facilityRef`, or `RackMembership`, `RackUnits` or `NonRackUnitMount` with `rackRef`. Only `RackUnits` carries position, height and face. | Qualify geometry and reservations. Do not treat names as global IDs or recorded positions as verified. | +| Cable records are the only expected-topology authority. Device interfaces carry a name and MAC address only. | Record actual peer reports as sourced observations, not as a second Cable authority. Reconcile contradictions before verification. | | Device carries model, serial/system UUID, interfaces and unmapped MACs. | Preserve original values; adjudicate canonical physical identity and component mappings. Do not coerce provider IDs into chassis serials, or turn interface names/MAC lists into trusted component identity. | | Optional BMC endpoint lives on restricted provider-project objects in Milo. | Preserve access restrictions. Endpoint discovery does not authorize access. Transfer endpoint configuration authority explicitly to the provider management surface before exposing only references/read projections; never run two writable copies. | | No controller checks binding exclusivity, evidence or `MachineCapacity.deviceRef` resolution. | Resolve duplicate/multiple bindings and protect existing occupancy before enabling automation. Do not infer Accepted, Bound, Ready or allocator eligibility from schema admission. | **Claim-lifetime decision gate.** The target remains one committed Device binding per installation claim, with one active placement authority per Device. A -long-lived slot is useful for naming and history but must not replace an -installation incarnation: otherwise a serial swap can inherit old cabling, -acceptance or verification. Before implementation, approve the successor-claim -protocol and versioned conversion of the manual API, or explicitly amend this -proposal to provide equivalent immutable incarnation semantics. Do not automate -the long-lived-slot convention while presenting it as the target contract. - -For a legacy slot with several Devices, retain the original claim and all Device -records, their immutable bindings, and available registration/retirement history. -Adjudicate the active asset and create explicit installation-history mappings; -unknown order or occupancy remains unresolved. Do not choose the newest timestamp -as proof of physical replacement. The migration must select a versioned storage/ -conversion mechanism that preserves original bindings while representing the -registry-owned active relationship. A raw patch of immutable `claimRef`, deleting -and recreating Devices, or renaming them to fit a successor claim is not a safe -conversion. Existing MachineCapacity/asset-key references must continue to resolve -to the same asset; a move is not grounds to manufacture a new capacity identity. +replacement Device that names its predecessor's claim must not inherit old +cabling, acceptance or verification. Before automating replacement, approve the +successor-claim protocol, or explicitly amend this proposal to provide +equivalent immutable incarnation semantics. Existing MachineCapacity and +asset-key references must continue to resolve to the same asset; a move is not +grounds to manufacture a new capacity identity. **Home and authority decision gate.** The reviewed manual API deliberately stores records in the provider project's Milo control plane, protected by inventory @@ -869,5 +855,5 @@ actual consumer projection against its retained input revisions. Unsupported hardware or topology stays unavailable for offerings requiring those checks; registration alone does not satisfy this gate. -[manual-types]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/internal/api/inventory/v1alpha1/types.go -[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md +[manual-types]: ../../../internal/api/inventory/v1alpha1/types.go +[manual-guide]: ../../operations/physical-inventory.md diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index 7122fe9f..b80369a5 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -170,9 +170,9 @@ follow a device to its new location. ## Bringing existing records into Fleet The [existing manual inventory guide][manual-guide] describes a smaller model: -installation plans represent long-lived slots, locations are text fields, and -expected connections are stored on ports. This proposal instead uses a new plan -for each installation and separate Cable records. That difference must be settled +one plan per installation with typed placement, and separate Cable records, but +a replacement Device still names its predecessor's plan. This proposal instead +uses a new plan for each move or replacement. That difference must be settled before automating moves and replacements. The current implementation uses manual entry and operator-controlled migration, @@ -210,8 +210,8 @@ describe work still required; they are not a report of tests already passed. ## Decisions still needed -- Agree how to move from long-lived slot plans to one plan per installation - without losing existing bindings or history. +- Agree how moves and replacements create successor installation plans without + losing existing bindings or history. - Decide who can view and change shared facilities, racks, cables and feeds, and where their authoritative records live. - Choose how reservations survive failures, which hardware and connection layouts @@ -219,4 +219,4 @@ describe work still required; they are not a report of tests already passed. - Assign ownership of circuit references and physical handoff points, and decide whether a separate Circuit record is needed. -[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md +[manual-guide]: ../../operations/physical-inventory.md From 32356ac2cd139e5bdb35bdb19dc3aa0c5d631f6e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 14:44:51 -0600 Subject: [PATCH 5/8] docs(inventory): drop environment-specific writer details Describe record ownership generically instead of naming a deployment's GitOps object and path. Co-Authored-By: Claude Opus 5.5 --- docs/operations/physical-inventory.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 16426ce6..8a295720 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -15,7 +15,7 @@ kinds, a Manufacturer and DeviceType hardware catalog, and the observational operational `Site` kind. The primary workflow is **manual entry, operator review, and explicit record ownership**. Authorized direct API creation is supported for new records; -legacy Flux-owned records require a reviewed ownership transition before edits +GitOps-owned records require a reviewed ownership transition before edits by another writer. Fleet does not read or reconcile any external inventory source. A separate writer may copy records in from another system; it writes ordinary records through the same API and validation, and keeps any record of @@ -213,11 +213,9 @@ authenticated, complete NIC mapping before any network path depends on it. ## Manually record a small installation 1. Choose the provider project and namespace, and inspect existing records and - their writers. Records that a Flux Kustomization already applies stay with - Flux until an explicit ownership transition. Do not run a competing apply - against them. New and separately created inventory can be direct - API/operator-managed; GitOps is not required. Establish the authorized writer - per record before making changes. + their writers. A record applied by GitOps keeps that writer; do not run a + competing apply against it. Other inventory is direct API/operator-managed. + Establish the authorized writer per record before making changes. 2. Enter the Facility and Rack facts you actually know. Leave unknown dimensions absent. Rack membership is not a reserved footprint or evidence of available space. From 4edeabb03f5cf6ab0beecdea94abbb0caf1c5060 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 17:24:51 -0600 Subject: [PATCH 6/8] docs(inventory): call the operations task an installation Co-Authored-By: Claude Opus 5.5 --- docs/operations/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/operations/README.md b/docs/operations/README.md index 24f4d1aa..f98bd63f 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -16,7 +16,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | -| Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written inventory records in the provider project in Milo, with immutable identity and binding; no capacity or hardware effect; unit tested | +| Plan an installation and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written inventory records in the provider project in Milo, with immutable identity and binding; no capacity or hardware effect; unit tested | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | | Configure protected acceptance workflow access | [GitHub execution boundary](../../test/acceptance/milo/github-environment.md) | Required environment and runner-group controls | From 82569feaaa37e44ff0a5205a1e7127aaecd0b08d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 08:55:53 -0600 Subject: [PATCH 7/8] fix(inventory)!: limit bmc.endpoint to an https host and port The endpoint rule rejected only userinfo, so a token in the query, path, or fragment was admitted and readable by every inventory viewer. Tightening it after records exist would break them on their next update, so the endpoint is now an https host with an optional port and nothing else. Co-Authored-By: Claude Opus 5.5 --- config/components/inventory/crds/fleet.datumapis.com.yaml | 5 ++--- docs/operations/physical-inventory.md | 2 +- internal/api/inventory/v1alpha1/crd_test.go | 4 ++++ internal/api/inventory/v1alpha1/types.go | 5 +++-- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 21e606be..d5b65bfa 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -379,9 +379,8 @@ spec: type: string maxLength: 2048 x-kubernetes-validations: - - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() - != '' - message: bmc.endpoint must be an https URL without credentials + - rule: isURL(self) && self.matches('^https://[^/?#@]+/?$') && url(self).getHostname() != '' + message: bmc.endpoint must be an https host and optional port, with no credentials, path, query, or fragment interfaces: type: array maxItems: 32 diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 8a295720..c734df68 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -137,7 +137,7 @@ is registered; the kinds are provider-internal, not a catalog offering. | `placement` is immutable | DeviceClaim | Moving an installation is a new claim, not an edit. | | Interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | -| `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `bmc.endpoint` is an `https` host and optional port, with no credentials, path, query, or fragment | Device | Every inventory viewer can read it, so nothing secret can live in it. | | `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Nothing reads the lifecycle yet. | | `status` is a separate subresource that declares no fields | All nine | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index f2df4ddb..76029e95 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -234,6 +234,10 @@ func TestInvalidDevicesAreRejected(t *testing.T) { "plain-http BMC": func(d *Device) { d.Spec.BMC.Endpoint = "http://192.0.2.100" }, "BMC with credentials": func(d *Device) { d.Spec.BMC.Endpoint = "https://admin:secret@192.0.2.100" }, "BMC not a URL": func(d *Device) { d.Spec.BMC.Endpoint = "192.0.2.100" }, + "BMC with a query": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100/redfish?token=x" }, + "BMC with a fragment": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100/#pw=x" }, + "BMC with a path": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100/session/x" }, + "BMC with no host": func(d *Device) { d.Spec.BMC.Endpoint = "https://:443" }, } { device := syntheticDevice() mutate(&device) diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 15383360..4e2b2085 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -165,8 +165,9 @@ type DeviceIdentity struct { UnidentifiedReason string `json:"unidentifiedReason,omitempty"` } -// BMC records where the management controller was reached. Credentials never -// belong here. +// BMC records where the management controller was reached: an https host and +// optional port. Every inventory viewer can read it, so it carries no +// credentials, path, query, or fragment. type BMC struct { Endpoint string `json:"endpoint"` } From 0f3d48841c57f9627a3c5174f717d7ca455edacb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 08:58:12 -0600 Subject: [PATCH 8/8] fix(inventory): admit only a host and port in bmc.endpoint The host may be a DNS name or a bracketed IPv6 literal and the port must be digits, so a ';' suffix or an empty port is rejected. Tests now also pin the endpoints that must stay admitted. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 2 +- internal/api/inventory/v1alpha1/crd_test.go | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index d5b65bfa..e6b8c785 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -379,7 +379,7 @@ spec: type: string maxLength: 2048 x-kubernetes-validations: - - rule: isURL(self) && self.matches('^https://[^/?#@]+/?$') && url(self).getHostname() != '' + - rule: isURL(self) && self.matches('^https://([A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(:[0-9]+)?/?$') && url(self).getHostname() != '' message: bmc.endpoint must be an https host and optional port, with no credentials, path, query, or fragment interfaces: type: array diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 76029e95..aba0eca1 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -238,6 +238,8 @@ func TestInvalidDevicesAreRejected(t *testing.T) { "BMC with a fragment": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100/#pw=x" }, "BMC with a path": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100/session/x" }, "BMC with no host": func(d *Device) { d.Spec.BMC.Endpoint = "https://:443" }, + "BMC with parameters": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100;token=x" }, + "BMC with empty port": func(d *Device) { d.Spec.BMC.Endpoint = "https://192.0.2.100:/" }, } { device := syntheticDevice() mutate(&device) @@ -252,6 +254,24 @@ func TestInvalidDevicesAreRejected(t *testing.T) { } } +func TestBMCEndpointsWithAHostAndPortAreAdmitted(t *testing.T) { + for _, endpoint := range []string{ + "https://192.0.2.100", + "https://192.0.2.100/", + "https://192.0.2.100:8443", + "https://bmc.example.invalid", + "https://bmc.example.invalid:443/", + "https://[2001:db8::1]", + "https://[2001:db8::1]:443", + } { + device := syntheticDevice() + device.Spec.BMC.Endpoint = endpoint + if errs := admit(t, "Device", object(t, device), nil); len(errs) > 0 { + t.Errorf("%s rejected: %v", endpoint, errs) + } + } +} + func TestDeviceIdentityNeedsSerialOrSystemUUID(t *testing.T) { serialOnly := syntheticDevice() serialOnly.Spec.Identity.SystemUUID = ""