From 6e902811556edb4f9bab6bcb683e4f48a466e8bf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 12:09:32 -0600 Subject: [PATCH 1/7] feat(inventory): add observational physical NetBox import --- .github/workflows/ci.yml | 1 + .../inventory/crds/fleet.datumapis.com.yaml | 1247 ++++++++++++++++- .../inventory/protected-resources/cable.yaml | 21 + .../protected-resources/facility.yaml | 21 + .../protected-resources/kustomization.yaml | 4 + .../protected-resources/powerfeed.yaml | 21 + .../inventory/protected-resources/rack.yaml | 21 + config/components/inventory/roles/editor.yaml | 16 + config/components/inventory/roles/viewer.yaml | 12 + docs/development/README.md | 23 +- docs/operations/README.md | 1 + docs/operations/netbox-physical-import.md | 240 ++++ docs/operations/physical-inventory.md | 49 +- docs/proposals/fleet-management/MIGRATION.md | 15 + .../fleet-management/inventory-reference.md | 916 ++++++++++++ docs/proposals/fleet-management/inventory.md | 737 +++------- hack/netbox_inventory.py | 711 ++++++++++ hack/test_netbox_inventory.py | 292 ++++ hack/testdata/netbox/candidates.json | 475 +++++++ hack/testdata/netbox/existing.json | 17 + hack/testdata/netbox/mapping.json | 68 + hack/testdata/netbox/snapshot.json | 209 +++ internal/api/inventory/v1alpha1/crd_test.go | 10 +- internal/api/inventory/v1alpha1/physical.go | 175 +++ .../api/inventory/v1alpha1/physical_test.go | 152 ++ internal/api/inventory/v1alpha1/types.go | 63 +- ui/provider/README.md | 17 +- .../src/components/inventory-table.tsx | 7 +- .../components/physical-inventory.test.tsx | 28 + .../src/components/physical-inventory.tsx | 59 + ui/provider/src/inventory.test.ts | 4 +- ui/provider/src/inventory.ts | 18 +- ui/provider/src/lib/api.ts | 24 +- ui/provider/src/lib/inventory-api.test.ts | 33 + ui/provider/src/pages/device-claim-detail.tsx | 17 +- .../src/pages/device-inventory-list.tsx | 4 +- .../src/pages/device-inventory.test.tsx | 6 +- ui/shared/fleet-api.ts | 52 +- 38 files changed, 5082 insertions(+), 704 deletions(-) create mode 100644 config/components/inventory/protected-resources/cable.yaml create mode 100644 config/components/inventory/protected-resources/facility.yaml create mode 100644 config/components/inventory/protected-resources/powerfeed.yaml create mode 100644 config/components/inventory/protected-resources/rack.yaml create mode 100644 docs/operations/netbox-physical-import.md create mode 100644 docs/proposals/fleet-management/inventory-reference.md create mode 100644 hack/netbox_inventory.py create mode 100644 hack/test_netbox_inventory.py create mode 100644 hack/testdata/netbox/candidates.json create mode 100644 hack/testdata/netbox/existing.json create mode 100644 hack/testdata/netbox/mapping.json create mode 100644 hack/testdata/netbox/snapshot.json create mode 100644 internal/api/inventory/v1alpha1/physical.go create mode 100644 internal/api/inventory/v1alpha1/physical_test.go create mode 100644 ui/provider/src/components/physical-inventory.test.tsx create mode 100644 ui/provider/src/components/physical-inventory.tsx create mode 100644 ui/provider/src/lib/inventory-api.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27b179fb..957de3ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ jobs: - run: go test ./... - run: go test -race ./... - run: go vet ./... + - run: python3 -m unittest discover -s hack -p test_netbox_inventory.py - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 566569f7..181d6839 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -6,77 +6,252 @@ metadata: discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com - names: {kind: DeviceClaim, listKind: DeviceClaimList, plural: deviceclaims, singular: deviceclaim} + names: + kind: DeviceClaim + listKind: DeviceClaimList + plural: deviceclaims + singular: deviceclaim scope: Namespaced versions: - name: v1alpha1 served: true storage: true - subresources: {status: {}} + 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: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + - 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: Recorded At + type: date + jsonPath: .spec.provenance.recordedAt schema: openAPIV3Schema: type: object - required: [spec] + required: + - spec properties: - apiVersion: {type: string} - kind: {type: string} - metadata: {type: object} + apiVersion: + type: string + kind: + type: string + metadata: + type: object spec: type: object - required: [provenance, expectedIdentity, placement] + required: + - provenance + - expectedIdentity + - placement x-kubernetes-validations: - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt message: every change to a claim must advance provenance.recordedAt + - 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: provenance: type: object - required: [method, recordedBy, recordedAt] + required: + - method + - recordedBy + - recordedAt properties: - method: {type: string, enum: [Manual]} - recordedBy: {type: string, minLength: 1, maxLength: 253} - recordedAt: {type: string, format: date-time} - reference: {type: string, minLength: 1, maxLength: 1024} + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable expectedIdentity: type: object - required: [model] + required: + - model properties: - manufacturer: {type: string, maxLength: 253} - model: {type: string, minLength: 1, maxLength: 253} - serial: {type: string, minLength: 1, maxLength: 253} + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 placement: type: object - required: [facility, rack, position, face] 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, default: 1} - face: {type: string, enum: [front, rear]} + 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] + x-kubernetes-list-map-keys: + - name items: type: object - required: [name] + required: + - name properties: - name: {type: string, minLength: 1, maxLength: 63} - type: {type: string, maxLength: 253} - speedMbps: {type: integer, format: int64, minimum: 1} + 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] + required: + - device + - port properties: - device: {type: string, minLength: 1, maxLength: 253} - port: {type: string, minLength: 1, maxLength: 253} - status: {type: object} + 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 @@ -86,30 +261,53 @@ metadata: discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com - names: {kind: Device, listKind: DeviceList, plural: devices, singular: device} + names: + kind: Device + listKind: DeviceList + plural: devices + singular: device scope: Namespaced versions: - name: v1alpha1 served: true storage: true - subresources: {status: {}} + 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: System UUID, type: string, priority: 1, jsonPath: .spec.identity.systemUUID} - - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + - 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: System UUID + type: string + priority: 1 + jsonPath: .spec.identity.systemUUID + - name: Recorded At + type: date + jsonPath: .spec.provenance.recordedAt schema: openAPIV3Schema: type: object - required: [spec] + required: + - spec properties: - apiVersion: {type: string} - kind: {type: string} - metadata: {type: object} + apiVersion: + type: string + kind: + type: string + metadata: + type: object spec: type: object - required: [claimRef, provenance, identity] + required: + - claimRef + - provenance + - identity x-kubernetes-validations: - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt message: every change to a device must advance provenance.recordedAt @@ -117,66 +315,961 @@ spec: 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.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)))) + - 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.identity.sourceIdentity) || self.provenance.method == "NetBoxImport"' + message: source identity is for observational imports only + - 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.identity.sourceIdentity) || (has(self.provenance.source) && self.identity.sourceIdentity.system + == self.provenance.source.system && self.identity.sourceIdentity.type == self.provenance.source.type + && self.identity.sourceIdentity.id == self.provenance.source.id)' + message: observational identity must match provenance source identity + - 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 properties: claimRef: type: object - required: [name] + required: + - name properties: - name: {type: string, minLength: 1, maxLength: 253} + name: + type: string + minLength: 1 + maxLength: 253 provenance: type: object - required: [method, recordedBy, recordedAt] + required: + - method + - recordedBy + - recordedAt properties: - method: {type: string, enum: [Manual]} - recordedBy: {type: string, minLength: 1, maxLength: 253} - recordedAt: {type: string, format: date-time} - reference: {type: string, minLength: 1, maxLength: 1024} + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable identity: type: object - required: [model] + required: + - model x-kubernetes-validations: - - rule: has(self.serial) || has(self.systemUUID) - message: a device needs a serial or a system UUID + - rule: has(self.serial) || has(self.systemUUID) || has(self.sourceIdentity) + message: a device needs serial, UUID, or an observational source identity 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}$'} + 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}$ + sourceIdentity: &id001 + 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 bmc: type: object - required: [endpoint] + required: + - endpoint properties: endpoint: type: string maxLength: 2048 x-kubernetes-validations: - - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() != '' + - 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] + x-kubernetes-list-map-keys: + - name items: type: object - required: [name] + 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}$'} + 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] + required: + - device + - port properties: - device: {type: string, minLength: 1, maxLength: 253} - port: {type: string, minLength: 1, maxLength: 253} + 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}$'} - status: {type: object} + items: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + assetTag: + type: string + minLength: 1 + maxLength: 253 + providerHostRef: *id001 + 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 + sourceRef: *id001 + 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: *id001 + 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 + 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 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + locationRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + required: + - displayName + - provenance + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + 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 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + 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 + - provenance + - facilityRef + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + 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 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + 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 + - provenance + - 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 + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + 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 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + 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 + sourceRef: &id002 + 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: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + upstreamSources: + type: array + maxItems: 64 + items: *id002 + required: + - displayName + - provenance + - facilityRef + - terminations + x-kubernetes-validations: + - rule: self.terminations.all(t, t.type == 'PowerOutlet') + message: feed terminations must be power outlets + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + status: + type: object + required: + - spec 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/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 index 0a5454da..06c15c1a 100644 --- a/config/components/inventory/protected-resources/kustomization.yaml +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -3,3 +3,7 @@ kind: Kustomization resources: - deviceclaim.yaml - device.yaml + - facility.yaml + - rack.yaml + - cable.yaml + - powerfeed.yaml 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/roles/editor.yaml b/config/components/inventory/roles/editor.yaml index e5e28191..fd48db59 100644 --- a/config/components/inventory/roles/editor.yaml +++ b/config/components/inventory/roles/editor.yaml @@ -18,3 +18,19 @@ spec: - 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/viewer.yaml b/config/components/inventory/roles/viewer.yaml index db0d7f9a..32963fa4 100644 --- a/config/components/inventory/roles/viewer.yaml +++ b/config/components/inventory/roles/viewer.yaml @@ -14,3 +14,15 @@ spec: - 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/docs/development/README.md b/docs/development/README.md index d4c274de..e8900d73 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -704,22 +704,29 @@ corrupt or uses an unsupported schema version. ## Physical inventory subset -`internal/api/inventory/v1alpha1` defines `DeviceClaim`, the plan for one rack -slot, and `Device`, the asset bound to one claim. Operators write both by hand -into the provider project in Milo. `config/components/inventory` holds their +`internal/api/inventory/v1alpha1` defines Facility, Rack, DeviceClaim, Device, +Cable and PowerFeed records. Legacy slot claims coexist with new observational +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 `fleet.datumapis.com-inventory-viewer` and `-editor` roles. Only `config/milo` includes it. -CEL requires `Manual` provenance on both kinds and requires every edit to +CEL requires `Manual` or source-attributed `NetBoxImport` provenance and every edit to advance `recordedAt`. It 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. -The staff portal plugin's read-only Inventory tab lists claims and shows each -claim's bound Devices. Unit tests run the API server's validation offline and -check the IAM shape. See -[Planning and registering physical devices](../operations/physical-inventory.md). +The staff portal plugin's read-only Inventory tab pages through all six kinds, +shows physical relationships and components, and can inspect a private import +report locally. Multiple historical bindings remain ambiguous rather than being +resolved by edit time. Python's standard-library `hack/netbox_inventory.py` +exports sanitized GET-only NetBox snapshots and prepares an offline create-only +handoff to the existing Flux writer. Unit tests run API-server validation offline, +check IAM and exercise pagination, source conflicts, omissions and interrupted +imports. See [safe NetBox evaluation](../operations/netbox-physical-import.md). +No live source coverage, deployed revision, physical verification, concurrent +reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run diff --git a/docs/operations/README.md b/docs/operations/README.md index 8139c173..1f1fdf99 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -18,6 +18,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | +| Review and import NetBox's physical side | [Safe physical snapshot and GitOps handoff](netbox-physical-import.md) | Six physical kinds, typed components and relationships, per-record coverage reports and additive handoff to the existing writer; no live import, readiness or provisioning | | 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 | diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md new file mode 100644 index 00000000..7cac4a7c --- /dev/null +++ b/docs/operations/netbox-physical-import.md @@ -0,0 +1,240 @@ +# Evaluate NetBox physical inventory safely + +[Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) + +This milestone provides six provider-project inventory kinds, read-only staff +browsing, a GET-only NetBox snapshot command, and an **offline, create-only GitOps +handoff**. It does not apply anything to Fleet or NetBox. It is not a verification, +reservation, adoption, enrollment, or provisioning controller. + +## What exists and what remains unknown + +`Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed` live in the +existing provider project's Milo control plane. No database, management-cluster +copy, new catalog service, or independently running importer was introduced. +`config/milo` installs their CRDs, ProtectedResources and inventory roles. Existing +consumer Metal roles still grant no inventory access; inventory roles do not +grant status writes. Staff use their own identity through the existing Milo proxy. + +The CRDs validate local shapes, provenance, immutable asset/claim identity, +placement scope, component uniqueness, internal component positions, and Cable +lane multiplicity. The offline planner checks local references, compatible +component categories, and conflicting cable terminations against the supplied +Fleet snapshot. **These checks are not concurrent reservations or cross-object +API admission.** A direct API writer can still create dangling references or +cross-object conflicts; do not interpret successful creation as acceptance. +No qualified physical verification, dependency reservation, deletion protection, +move/replacement handover, electrical budget, or eligibility publisher exists. +No status field is populated. Free space, active binding, redundancy and readiness +remain Unknown. Existing editor delete permissions are not a safe retirement API. + +### Compatibility and migration decisions + +- Existing long-lived slot claims keep their names, text placement, ports, and + historical Device bindings. Existing `Device.spec.identity` and `claimRef` + remain immutable. MachineCapacity and its `deviceRef` are not modified. +- New imported claims use `lifecycle: Installation` and typed placement. This + mode cannot be added to a legacy slot; an installation's placement is immutable. + This is an observational installation record, **not** a reservation or an + accepted plan. Moving an existing asset remains blocked on the proposal's + explicit handover protocol; the importer does not create a replacement identity + to work around immutability. +- A Facility reference means no rack is asserted. `RackMembership` records a known + rack but forbids position, height and face. The importer deliberately imports + no exact rack-unit positions, including seemingly plausible positions. This + prevents servers.com's generated 1U placements from becoming occupied or + verified footprints. The API also represents exact `RackUnits` and + `NonRackUnitMount` plans for separately reviewed manual records. +- `height` no longer defaults to 1 in admission: doing so invents a footprint on + partial placements. Previously stored defaulted values remain unchanged; legacy + UI rendering still treats omitted legacy height as one. New exact-unit plans + must supply height. `Device.modelShape` dimensions do not establish occupancy. +- Devices without a genuine serial may have an immutable `identity.sourceIdentity` + matching import provenance. This is a source-record identity, **not authenticated + chassis identity**. A provider host ID is `providerHostRef`; an asset tag is + `assetTag`, never a serial. The importer quarantines potential collisions with + legacy serials/provider IDs rather than rewriting them. +- Typed Devices opt into `topologyAuthority: Cable` and cannot contain inline + peers. New installation claims cannot contain expected inline peers. Existing + inline peers are retained as unmigrated history; they are not automatically + converted or deleted. Cable endpoints name same-namespace Device components or + PowerFeed terminations; unbound claim endpoints are deferred. No second expected + topology graph is written by the importer. +- Snapshot digest, source instance/class/ID, observation time and mapping revision + are retained in provenance. `recordedBy` identifies the offline tool, not an + authenticated source author. Milo/Git audit identifies the actual submitting + user. Imported source identity cannot change in place. Re-import of matching + physical fields is a no-op; differing existing records are quarantined. Changes + require a separate reviewed correction, not last-import-wins. + +## Source coverage + +The exporter discovers **every advertised DCIM and circuits collection**, follows +pagination, and lists errors or missing required collections. The parameterized +`dcim/connected-device` lookup is +explicitly listed under `excludedEndpoints`, rather than mistaken for a collection. +The result is a sequential observation with bounded requests, not a transactional +NetBox database snapshot. +Changing counts, duplicate IDs and pagination cycles fail the affected collection. +Counts can remain equal while content changes; quiesce loaders and rerun for a +stable review. Repeated failed reads never become complete coverage. + +The report classifies every fetched record. `imported` means representable in a +candidate (or already identical in the supplied Fleet snapshot), **not applied**. +`unresolved` means mapping, identity, or dependency needs review. `unsupported` +means an adapter cannot faithfully represent that class/shape. `excluded` always +has a reason. Collection completeness and record parity are distinct: a complete +fetch may still contain many unresolved or unsupported records. + +| Source classes | Treatment | +| --- | --- | +| `dcim/sites`, `dcim/locations` | Explicit premises mapping only. One metro Site may map to several Facilities. Unmapped records stay unresolved; no Fleet policy Site is created. | +| `dcim/racks` | Explicit Facility mapping, label and known height. No free-capacity inference. | +| `dcim/devices`, `device-types`, `manufacturers` | Explicit physical/virtual and serial interpretation; model metadata, optional dimensions, separate asset tag/provider identity. NetActuate/hosted-VM hints force exclusion. Supporting catalog rows are classified excluded as independent assets; referenced model facts are consumed. | +| `interfaces`, `power-ports`, `power-outlets`, `console-ports`, `console-server-ports`, `front-ports`, `rear-ports` | Typed Device components with source IDs. Logical LAG/bridge/virtual interfaces excluded. Front/rear mappings and outlet/input dependencies retained; missing relationships remain Unknown. | +| `modules`, `inventory-items`, `device-bays` | Typed component records, not public kinds. Nested installation/parent semantics not represented by these fields remain in the private source snapshot; these are not component-incarnation controllers. | +| `cables` | Simple, reviewed-medium cables with resolvable physical endpoints. Multi-termination/breakout imports require explicit reviewed lanes covering every source termination on its original side; unsupported mappings never become all-to-all paths. Multi-position trunks never silently collapse to position one. | +| `power-panels`, `power-feeds` | Feed supply ratings and terminations, external panel dependencies. No fabricated panel Device, derated budget, independent UPS proof or usable power reservation. | +| `circuits/circuits`, `circuit-terminations` | Explicit service-owner identifiers and mapped local component associations; no new Circuit kind, service lifecycle, billing, or routing. Unmapped demarcations remain unresolved. | +| Device/module/port templates, regions, site groups, rack roles, virtual chassis, circuit/provider catalogs | Explicitly excluded as independent installed physical assets; reasons recorded per row. | +| Other advertised classes (including new NetBox-version additions) | Fetched and reported unsupported, never silently discarded. | + +IPAM, VLANs, VRFs, routing, virtualization collections, billing and provisioning +are explicitly outside this export. VMs stored in **DCIM** are still inspected and +excluded per record. OOB IP lists and credential/custom-field bodies are not copied; +existing restricted Device BMC facts remain untouched. Sanitization uses a recursive +physical-field allowlist and excludes URLs, comments, custom fields and config +contexts. This intentionally is **not a lossless NetBox backup**. Exports still +contain private asset identities, serials and topology and must stay outside Git. + +## Start with the checked-in synthetic example + +Python 3 uses only the standard library. No provider SDK or cluster access is +needed. Output directories must not already exist; files are mode 0600 inside +mode 0700 directories. No command overwrites a previous run. +Output paths inside a Git checkout are refused, including worktrees. + +```sh +python3 hack/netbox_inventory.py plan \ + --snapshot hack/testdata/netbox/snapshot.json \ + --mapping hack/testdata/netbox/mapping.json \ + --output /private/tmp/fleet-physical-report-example +``` + +Only `report.json` is emitted by default. Inspect every unresolved/unsupported +row; the example intentionally leaves a room mapping unresolved. Staff can open +the report with the Inventory tab's local file picker; its contents are not +uploaded. The portal shows restricted/loading/empty states, paginated collections, +asset components, facility/rack membership, feeds and cables. Multiple historical +Devices on one claim do not select the most recently edited record as active. + +To exercise the explicit handoff **with synthetic data only**: + +```sh +python3 hack/netbox_inventory.py plan \ + --snapshot hack/testdata/netbox/snapshot.json \ + --mapping hack/testdata/netbox/mapping.json \ + --existing hack/testdata/netbox/existing.json \ + --handoff --allow-partial \ + --output /private/tmp/fleet-physical-handoff-example +``` + +`--allow-partial` explicitly acknowledges unresolved/unsupported records; it does +not bypass collection errors or target conflicts. The handoff emits candidate +objects and a receipt containing the exact target plus source, mapping, Fleet +snapshot and candidate digests. Nothing invokes kubectl apply or writes Git. + +## Prepare a private real-data review + +1. Use existing read credentials: `NETBOX_TOKEN`, otherwise `NETBOX_TOKEN_FILE` + (default `~/.config/netbox/token`). Never paste a token into arguments, logs, + mappings or Git. The existing infra bare-metal reader uses Bearer authentication; + `--auth-scheme Token` explicitly supports installations using the legacy scheme. + Redirects, non-HTTPS origins and off-origin/changed-collection pagination are + refused. All requests are GET; retries are bounded to three for transient errors. +2. Quiesce the source loaders if possible, then capture a private snapshot: + + ```sh + python3 hack/netbox_inventory.py snapshot --source reviewed-netbox-instance \ + --output /private/tmp/fleet-netbox-private-snapshot + ``` + +3. Copy the [synthetic mapping shape](../../hack/testdata/netbox/mapping.json) into + a private file. Review each facility, physical device classification, serial + interpretation, placement scope, feed and cable medium. A Source Site name is + not proof of premises. A missing serial is not permission to invent one. + For a breakout or multi-position termination, a cable mapping can supply `lanes` + in the [Cable Go contract](../../internal/api/inventory/v1alpha1/physical.go): + each lane has an ID, `a` and `b`, each endpoint has exactly one local owner, + `componentID` and `position`. Use stable candidate names from a prior dry-run + handoff or the source-key-derived name function. Positions must exist in the + component model; do not invent transceiver lanes absent from source geometry. +4. Export **all six** Fleet kinds from the explicitly selected **provider project's + Milo context**, including empty collections, before preparing candidates. The + [synthetic existing-state envelope](../../hack/testdata/netbox/existing.json) + shows the exact structure: `target` must exactly match the mapping, `collections` + must list all six kinds, and `items` contains the complete list in the reviewed + namespace. Use the project's established authenticated GET/list path; do not + assume a management-cluster context addresses Milo. The envelope is an operator + attestation, not cryptographic proof of scope or freshness. Retain capturedAt and + read evidence privately; re-read before a GitOps merge. +5. Run `plan` with private `--snapshot`, `--mapping`, `--existing` and a fresh output + directory. Add `--previous` with the earlier source snapshot on subsequent runs. + Review source disappearances: missing rows are **retained**, never deleted, + retired, freed, or marked ready. Existing differences, duplicate target IDs, + identity collisions and topology conflicts need adjudication before handoff. +6. Obtain explicit approval for the mapping, exact target and desired cohort. + Only then generate a handoff. Do not put private exports or imported asset facts + in a public Fleet PR. Do not apply the candidate List directly to Milo. +7. Stage individual **new** records additively in the existing private + `provider-inventory` Flux source. Preserve all existing files and object names; + never replace the collection with this partial candidate list. Review the Git + diff for no deletes, no modifications of existing bindings, no capacities and + no readiness/status. Retain source/mapping/report/receipt in the approved private + evidence store. The importer does not commit, push, merge or roll out this change. + +Flux remains the only writer for staging provider-inventory records. This avoids +the conflict that a direct importer would create with reconciliation. Reviewers +must check for concurrent changes since the Fleet snapshot; the offline handoff +does not provide an optimistic-concurrency apply transaction. After an interrupted +reconciliation, refresh the Fleet snapshot and rerun. Matching records become +no-ops; conflicts stay quarantined. Do not roll back by deleting occupied objects. + +The 2026-11-20 configuration observation names `fleet-provider-inventory`, with +path `apps/fleet-system/staging/provider-inventory`, `prune: false` and +`deletionPolicy: Orphan`. The similarly named legacy inventory reconciliations +are not the provider-project destination. Recheck these settings before handoff; +this feature does not modify them or their kubeconfig references. + +## Acceptance and observed limits + +On 2026-11-20, read-only GitHub checks found both infra staging OCI sources configured +for `v0.0.0-feat-manual-inventory-records`; the corresponding Fleet branch head was +`42086bbe2cf05f5d09362fbc777e514907d64462`. This implementation is stacked there, +including the dependent PXE/runtime code. **Configured tag is not an observed +deployed revision.** No cluster rollout or live import was performed. + +The documented environment/token-file paths did not provide authorized NetBox +access in this implementation checkout. No live inventory audit was performed; +present-day counts, parity, source mappings and schema-version compatibility are +unvalidated. Source interpretation comes from the pinned infra +`d9198940a499be4e744ee0564cf3dc0b3bfcee34` loaders and site-build documents, as +recorded in the [source evidence appendix](../proposals/fleet-management/inventory-reference.md#source-evidence-and-limits). + +Before live evaluation, establish a private source audit, resolve required mappings, +render/install the six-kind schema in an explicitly approved environment, and +confirm authorized staff can browse while consumers cannot. Compare counts and +every classified row, test repeated and interrupted handoffs, and confirm original +Device/claim/Capacity identities remain unchanged. None of this establishes +physical qualification or safe capacity release. + +```sh +python3 -m unittest discover -s hack -p test_netbox_inventory.py +go test ./internal/api/inventory/v1alpha1 +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider test +pnpm --dir ui/provider build +kustomize build config/milo >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 7d0f2063..8e71398e 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -10,22 +10,28 @@ 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 two operator-written kinds in `fleet.datumapis.com/v1alpha1`: +It now has six operator-written kinds in `fleet.datumapis.com/v1alpha1`. +The [NetBox physical import and migration guide](netbox-physical-import.md) +describes the additive physical schema, typed components, partial placement, +same-namespace relationships, import reconciliation and current limits. The +manual examples below preserve the original long-lived-slot representation: | Kind | What it is | Writer | | --- | --- | --- | | `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | | `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | 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 | ## Status | Aspect | State | | --- | --- | | CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | -| Home | Milo. `config/milo` registers both CRDs, two ProtectedResources and two IAM roles, like the `metal.datumapis.com` kinds. `config/overlays/management-plane` and `config/overlays/synthetic-staging` install none of them. | +| Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and two IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Read-only **Inventory** tab in the Bare Metal provider plugin (`ui/provider`): a claim list and a per-claim detail page. | -| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover the list, detail, restricted, and empty states. | -| Controllers | None. No Fleet code reads or writes these kinds. | +| Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds and synthetic importer output. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | +| Controllers | None. Offline import and staff browsing read the records; no reconciler accepts plans, verifies hardware, or publishes eligibility. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | ## What registration does and does not do @@ -48,17 +54,17 @@ namespace resolves by name. Nothing checks that reference yet. ## Where the records live -Milo is the single home. DeviceClaims and Devices are namespaced objects in the +Milo is the single home. All six 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. -Both CRDs carry `discovery.miloapis.com/parent-contexts: Project`, so every +All six 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 `deviceclaims` and `devices` | +| `fleet.datumapis.com-inventory-viewer` | `get`, `list`, `watch` on all six physical kinds | | `fleet.datumapis.com-inventory-editor` | The viewer role plus `create`, `update`, `patch`, `delete` | No `metal.datumapis.com` role includes or inherits either. The consumer, @@ -81,15 +87,15 @@ in the provider project. The plugin never writes. | Rule | Kind | Why | | --- | --- | --- | -| `provenance` is required: `method: Manual`, `recordedBy`, `recordedAt`, and an optional opaque `reference` | Both | Every plan and registration is attributable to a person and a time. | -| Any spec change must set a later `provenance.recordedAt` | Both | An edit cannot pass off new facts under old provenance. | +| `provenance` is required: `Manual` or `NetBoxImport`, `recordedBy`, `recordedAt`, optional opaque reference; imports also require structured source provenance | All six | Attribution is retained; imported claims are observations, not authenticated hardware evidence. | +| Any spec change must set a later `provenance.recordedAt` | All six | An edit cannot pass off new facts under old provenance. | | `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | -| `identity` (manufacturer, model, serial, system UUID) is immutable, including adding a missing field; at least one of serial or system UUID is required | Device | Serial and UUID are matching evidence. A hardware swap is a new Device bound to the same claim. | +| `identity` is immutable, including adding missing fields; requires serial, system UUID, or an import source identity matching provenance | Device | Source identity does not prove chassis identity. Legacy bindings are preserved; hardware handover is not automated. | | 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. | -| `status` is a separate subresource that declares no fields | Both | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | +| `status` is a separate subresource that declares no fields | All six | 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 @@ -172,12 +178,11 @@ The names and writers match #63: - Serial and SMBIOS UUID are matching evidence, not authenticators. - Logical LAGs and VLANs are not ports. -Deferred to #63, and deliberately absent: +Still deferred to #63: -- `Facility`, `Rack`, `Cable`, and `PowerFeed` kinds. Facility and rack are - names on the claim, and the expected cable peer is inline on each claimed - port, until those kinds replace them. Rack geometry beyond position, height, - and face is also deferred. +- 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 @@ -202,11 +207,11 @@ 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. -**Divergence to resolve:** this package's convention is that a whole-server -replacement binds a new Device to the same DeviceClaim, because the planned slot -outlives the hardware. #63's current text says whole-server replacement creates a -new DeviceClaim as well. The schema enforces neither convention. Settle this in -#63 before either path is automated. +**Compatibility decision:** legacy slots retain all historical bindings. New +imports use a distinct `Installation` lifecycle, but no automatic move or +replacement handover exists. Device identity and its original claimRef remain +immutable. The [migration decisions](netbox-physical-import.md#compatibility-and-migration-decisions) +explain why imports cannot delete/recreate or relabel legacy records to bypass this. ## Applying the records @@ -216,7 +221,7 @@ claims before the Devices that name them. 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 two CRDs alone, for an environment that +`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/MIGRATION.md b/docs/proposals/fleet-management/MIGRATION.md index cc06676f..c1fa51ed 100644 --- a/docs/proposals/fleet-management/MIGRATION.md +++ b/docs/proposals/fleet-management/MIGRATION.md @@ -31,6 +31,21 @@ migration configuration remains in infra. ## Post-import amendments +- 2026-11-20: Added the limited [observational physical inventory implementation](../../operations/netbox-physical-import.md) + on the staging-selected manual-inventory feature base. Six record kinds, typed + components, partial placement, read-only staff relationships and offline NetBox + handoff are implemented separately from this proposal's acceptance, reservations, + verification and lifecycle controllers. Legacy identities/bindings remain intact; + no live source parity, deployed readiness or hardware qualification is asserted. + +- 2026-11-20: Expanded the existing [inventory proposal](inventory.md) with the + six physical contracts, partial placement, typed components, circuit-boundary + proposals, evidence and qualification requirements. Recorded the pinned + manual-record implementation's claim-lifetime and authority migration gates, + plus source-backed NetBox import constraints. These remain proposed contracts, + not implementation changes or proof of live-data parity. The proposal keeps + the design narrative; field details, examples, migration evidence and test + cases are retained in its [reference appendix](inventory-reference.md). - 2026-11-17: MachineProfile CPU cores and memory capacity changed from `min` ranges to exact requests, with the resolved request pinned in Machine status. The `standard-metal` example and the capacity publication text were updated diff --git a/docs/proposals/fleet-management/inventory-reference.md b/docs/proposals/fleet-management/inventory-reference.md new file mode 100644 index 00000000..8c6937df --- /dev/null +++ b/docs/proposals/fleet-management/inventory-reference.md @@ -0,0 +1,916 @@ +--- +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, source findings, +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. + +- [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) +- [Source evidence and limits](#source-evidence-and-limits) +- [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, provenance, and +restricted external references. Names and labels are not durable asset identity. +For each imported fact retain source system, source object type and ID, source +revision or snapshot digest when available, observation time, importer identity +and mapping revision. Keep claimed source authors separate from the authenticated +submitter. Conflicting sources require adjudication; last import wins is not a +trust rule. 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. +Foreign source IDs are provenance, 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 with provenance. | 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 imported 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, provenance, +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, provenance 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 imports 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. Imported invented positions never satisfy any placement +check merely because they appear in a source DCIM object. + +### 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. NetBox's +[physical 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 model](https://netboxlabs.com/docs/netbox/models/dcim/powerfeed/) and +[power outlet model](https://netboxlabs.com/docs/netbox/models/dcim/poweroutlet/) precedents. + +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 with provenance. 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 or provenance association 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 with source mapping. 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 and provenance; 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 and manual provenance live 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. + +### NetBox and provider imports + +Import is observational until an explicit ownership transition. These rules are +derived from the pinned source workflows, not from a live NetBox database audit: + +| Source convention or gap | Required treatment | +| --- | --- | +| Loader Sites group provider metros and can union several provider facility codes. | Preserve source Site ID and provider-code mapping. Do not map NetBox Site one-to-one to Fleet Site or Facility. Unresolved premises stay unresolved and block prerequisites needing a physical Facility. | +| Loaders store provider host IDs in NetBox `serial`. | Retain them as owner-qualified external host IDs with the original field provenance. Never claim a verified chassis serial without independent physical evidence. | +| NetActuate VMs are DCIM Devices. | Classify virtual supply through provider/MachineCapacity contracts. Do not create Fleet physical Devices, ports or racks merely because NetBox uses DCIM. | +| servers.com assigns lowest-free 1U positions because physical positions are undisclosed. | Retain those source values only as synthetic display history. Import known rack association as RackMembership, subject to approved premises mapping; neither reserve nor verify invented units, faces or heights. | +| Commissioning uses asset tags, cable labels, circuit IDs, power feeds, photos and as-built records. | Preserve those distinct identifiers and restricted evidence references; do not flatten everything into serial or a free-form note. Address plans remain IPAM-owned. | +| Provisioning joins serial/model/OOB endpoint with networking data. | Preserve authorized consumer projections and explicit joins, not a duplicate networking API. Imported joins authorize no hardware actions, adoption, capacity eligibility or release. | +| Source lifecycle says active, decommissioning, vanished or decommissioned. | Retain as source observations. None proves physical verification, ownership transfer, secure cleanup, released consumer allocations or a free rack/termination. | + +Import batches retain source snapshot identity, mapping decisions, per-record +outcomes and conflicts for repeatable dry runs. The same source object/revision +must not create duplicate assets after a retry. Missing source observations do +not delete records or release occupancy. Never copy local provider tokens, BMC +password custom 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 imported 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 source parity for + the selected cohort, not an assertion of exhaustive NetBox 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 and retain source history. +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. + +## Source evidence and limits + +This amendment reviewed repository sources and read-only snapshots of infra +`main` at `d9198940a499be4e744ee0564cf3dc0b3bfcee34`. No live NetBox database audit, +provider call, electrical inspection, or hardware qualification was performed. +The sources motivate contract and migration requirements, not verified fleet-wide +data quality or proof that every production consumer has been found. + +| Pinned source | Evidence used | +| --- | --- | +| [Inventory sync guide][sync-guide], [NetActuate loader][na-loader], [servers.com loader][sc-loader] | Metro/provider mappings, host-ID serial semantics, virtual DCIM records, synthetic rack positions, and provider lifecycle observations. | +| [NetBox server guide][netbox-guide] | Operator inventory and provisioning inputs; existing networking/IPAM associations. | +| [Site commissioning][site-build], [rack work][rack-build], [network hardware][network-build], [compute hardware][compute-build] | Racks, serials, asset tags, labels, feeds, circuit IDs, address plans and external photos/LOAs/as-built artifacts. | +| [Out-of-band access commissioning][oob-build], [transit circuit commissioning][transit-build], [transport circuit commissioning][transport-build] | Physical delivery/demarcation and circuit identifiers distinct from service/routing readiness. | +| [Provisioning joins][provisioning-joins], [IPAM validation][ipam-validation] | Serial/model/OOB and network joins; address/routing validation stays with its current owner. | +| [Fleet manual types][manual-types], [Fleet manual operations][manual-guide] | The implemented manual subset and explicit slot-lifetime/storage divergences at the reviewed PR #90 revision. | + +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 source 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. | +| Import/cutover | Duplicate batch, conflicting inline peers, invented rack positions, source disappearance, 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 +[sync-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/sync-inventory.md +[na-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-netactuate-inventory +[sc-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-serversdotcom-inventory +[netbox-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/netbox-server.md +[site-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/00-site.md +[oob-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/04-oob.md +[transit-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/05-transit.md +[transport-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/06-transport.md +[network-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/07-nethw.md +[compute-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/08-computehw.md +[rack-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/09-rack.md +[provisioning-joins]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/provisioning/baremetal/lib/common.sh +[ipam-validation]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/validate-netbox-ipam diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index a96068e9..528827ac 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -7,556 +7,213 @@ 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. + +Import should preserve existing equipment identities, customer reservations and +history. Change the responsible writer one record type at a time. Do not delete +and recreate assets, assume occupied space is free, or mark old records ready +without new checks. + +Source data needs interpretation: NetBox sites 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. Preserve these +limitations rather than turning them into verified facts. + +See the [comparison with existing records and migration steps](inventory-reference.md#existing-records-and-migration) +and the [source review and its limits](inventory-reference.md#source-evidence-and-limits). +No live NetBox audit has been performed, and complete coverage of existing data +has not been established. + +## 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 diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py new file mode 100644 index 00000000..1d6f3686 --- /dev/null +++ b/hack/netbox_inventory.py @@ -0,0 +1,711 @@ +#!/usr/bin/env python3 +"""GET-only NetBox snapshot and offline, create-only Fleet GitOps handoff.""" + +import argparse +import copy +import datetime +import hashlib +import json +import os +from pathlib import Path +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +COMPONENTS = { + "interfaces": "NetworkPort", "power-ports": "PowerInlet", + "power-outlets": "PowerOutlet", "console-ports": "ConsolePort", + "console-server-ports": "ConsoleServerPort", "front-ports": "FrontPort", + "rear-ports": "RearPort", "modules": "Module", + "inventory-items": "InventoryItem", "device-bays": "DeviceBay", +} +SUPPORT = {"manufacturers", "device-types", "module-types", "device-roles", "rack-types"} +REQUIRED = {"dcim/" + name for name in ( + "sites", "locations", "racks", "devices", "device-types", "manufacturers", + "cables", "power-feeds", "power-panels", *COMPONENTS, +)} | {"circuits/circuits", "circuits/circuit-terminations"} +FIELDS = { + "id", "name", "display", "slug", "model", "manufacturer", "device_type", + "module_type", "device", "site", "location", "rack", "region", "parent", + "role", "type", "status", "serial", "asset_tag", "position", "face", + "u_height", "is_full_depth", "rear_port", "rear_port_position", "positions", + "power_port", "power_panel", "supply", "voltage", "amperage", "phase", + "a_terminations", "b_terminations", "object_type", "object_id", "object", + "termination_type", "termination_id", "termination", "circuit", "cid", + "provider", "term_side", "label", "value", "last_updated", "created", +} + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + + +def digest(value): + return "sha256:" + hashlib.sha256(canonical(value).encode()).hexdigest() + + +def reference_id(value): + if isinstance(value, dict): + value = value.get("id") + return str(value) if value is not None else "" + + +def value(record, key, default=""): + item = record.get(key, default) + return item.get("value", default) if isinstance(item, dict) else item + + +def sanitize(item): + if isinstance(item, dict): + return {key: sanitize(child) for key, child in item.items() if key in FIELDS} + if isinstance(item, list): + return [sanitize(child) for child in item] + return item + + +def name_ok(name): + return isinstance(name, str) and len(name) <= 253 and re.fullmatch(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", name) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request, response, code, message, headers, url): + raise ValueError("NetBox redirects are refused; configure the canonical HTTPS origin") + + +class Reader: + def __init__(self, url, token, auth_scheme="Bearer"): + self.base = url.rstrip("/") + parsed = urllib.parse.urlsplit(self.base) + if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path: + raise ValueError("NetBox URL must be a credential-free HTTPS origin") + if auth_scheme not in ("Bearer", "Token"): + raise ValueError("unsupported authorization scheme") + self.authorization = auth_scheme + " " + token.strip() + self.opener = urllib.request.build_opener(NoRedirect()) + + def get(self, url): + parsed = urllib.parse.urlsplit(url) + base = urllib.parse.urlsplit(self.base) + if parsed.scheme != base.scheme or parsed.netloc != base.netloc or not parsed.path.startswith("/api/") or parsed.fragment or parsed.username or parsed.password: + raise ValueError("refusing off-origin or non-API pagination link") + request = urllib.request.Request(url, headers={"Authorization": self.authorization, "Accept": "application/json"}, method="GET") + for attempt in range(3): + try: + with self.opener.open(request, timeout=30) as response: + return json.load(response) + except urllib.error.HTTPError as error: + if error.code not in (429, 500, 502, 503, 504) or attempt == 2: + raise ValueError("NetBox GET failed with HTTP " + str(error.code)) from None + except (urllib.error.URLError, TimeoutError): + if attempt == 2: + raise ValueError("NetBox GET failed: network unavailable") from None + time.sleep(2 ** attempt) + + def collection(self, path): + url = self.base + "/api/" + path.strip("/") + "/?limit=200" + seen_urls, records, count = set(), {}, None + while url: + if url in seen_urls: + raise ValueError("pagination cycle") + seen_urls.add(url) + page = self.get(url) + if not isinstance(page, dict) or not isinstance(page.get("results"), list) or not isinstance(page.get("count"), int): + raise ValueError("invalid paginated collection") + if count is not None and count != page["count"]: + raise ValueError("source count changed during export; restart the snapshot") + count = page["count"] + if count < 0 or (not page["results"] and page.get("next")): + raise ValueError("invalid count or empty nonterminal page") + for record in page["results"]: + identity = reference_id(record) + if not identity or identity in records: + raise ValueError("missing or repeated source ID during pagination") + records[identity] = sanitize(record) + if len(records) > count: + raise ValueError("snapshot exceeds advertised source count") + next_url = page.get("next") + url = urllib.parse.urljoin(url, next_url) if next_url else None + if url and urllib.parse.urlsplit(url).path != "/api/" + path.strip("/") + "/": + raise ValueError("pagination changed collection") + if len(records) != count: + raise ValueError("source count does not match snapshot") + return sorted(records.values(), key=lambda record: reference_id(record)) + + +def snapshot(reader, source): + if not name_ok(source): + raise ValueError("source must be a stable DNS-style instance name") + started = datetime.datetime.now(datetime.timezone.utc).isoformat() + objects, errors, excluded_endpoints = {}, {}, {} + for app in ("dcim", "circuits"): + try: + discovery = reader.get(reader.base + "/api/" + app + "/") + if not isinstance(discovery, dict): + raise ValueError("invalid API discovery") + except ValueError as error: + errors[app + "/"] = str(error) + continue + for collection in sorted(discovery): + if not re.fullmatch(r"[a-z0-9-]+", collection): + raise ValueError("invalid API collection name") + path = app + "/" + collection + if path == "dcim/connected-device": + excluded_endpoints[path] = "parameterized connectivity lookup, not an inventory collection" + continue + try: + objects[path] = reader.collection(path) + except ValueError as error: + errors[path] = str(error) + for path in REQUIRED - objects.keys() - errors.keys(): + errors[path] = "required collection not advertised by this NetBox version" + return {"version": 1, "source": source, "observedAt": started, "completedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "objects": objects, "errors": errors, "excludedEndpoints": excluded_endpoints} + + +def local_ref(name): + return {"name": name} + + +class Planner: + def __init__(self, source, mapping, existing=None, previous=None): + self.snapshot = source + self.mapping = mapping + self.source = source.get("source", "") + if source.get("version") != 1 or not name_ok(self.source): + raise ValueError("unsupported snapshot or invalid source identity") + datetime.datetime.fromisoformat(source["observedAt"].replace("Z", "+00:00")) + self.target = mapping.get("target", {}) + self.namespace = self.target.get("namespace", "") + self.revision = mapping.get("revision", "") + self.records, self.report, self.candidates = {}, {}, {} + self.existing = existing + if existing is not None and existing.get("target") != self.target: + raise ValueError("Fleet snapshot target must exactly match the reviewed provider project, namespace and application") + if existing is not None and set(existing.get("collections", [])) != {"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"}: + raise ValueError("Fleet snapshot must attest all six inventory collections, including empty ones") + self.previous = previous + self.digest = digest(source) + self.device_names, self.rack_names, self.feed_names = {}, {}, {} + for collection, records in source.get("objects", {}).items(): + for record in records: + identity = reference_id(record) + key = collection + "/" + identity + if not identity or key in self.records: + raise ValueError("duplicate or absent source identity") + self.records[key] = record + self.report[key] = {"source": key, "classification": "unsupported", "reason": "source object class has no physical adapter", "targets": []} + + def rows(self, collection): + return [(key, record) for key, record in sorted(self.records.items()) if key.rsplit("/", 1)[0] == collection] + + def mark(self, key, classification, reason, targets=()): + self.report[key] = {"source": key, "classification": classification, "reason": reason, "targets": list(targets)} + + def stable_name(self, kind, identity): + return "nb-" + hashlib.sha256((self.source + "/" + kind + "/" + identity).encode()).hexdigest()[:24] + + def external(self, key): + collection, identity = key.rsplit("/", 1) + return {"system": self.source, "type": collection, "id": identity} + + def add(self, key, kind, name, spec): + if not name_ok(name): + raise ValueError("invalid mapped Fleet name") + provenance = {"method": "NetBoxImport", "recordedBy": "netbox-inventory-offline", "recordedAt": self.snapshot["observedAt"], "source": dict(self.external(key), snapshotDigest=self.digest, mappingRevision=self.revision or "unreviewed", observedAt=self.snapshot["observedAt"])} + record = {"apiVersion": "fleet.datumapis.com/v1alpha1", "kind": kind, "metadata": {"name": name, "namespace": self.namespace}, "spec": dict(spec, provenance=provenance)} + target = kind + "/" + name + if target in self.candidates: + raise ValueError("multiple source records mapped to the same target") + self.candidates[target] = record + self.mark(key, "imported", "observational candidate; not applied or verified", [*self.report[key]["targets"], target]) + return target + + def facilities(self): + for key, record in self.rows("dcim/sites") + self.rows("dcim/locations"): + self.mark(key, "unresolved", "provider/metro sites and locations require an explicit premises mapping") + for facility in self.mapping.get("facilities", []): + key = facility["source"] + if key not in self.records or key.rsplit("/", 1)[0] not in ("dcim/sites", "dcim/locations"): + raise ValueError("facility source must name a present site or location") + spec = {"displayName": facility["displayName"]} + if facility.get("locationRef"): + spec["locationRef"] = local_ref(facility["locationRef"]) + self.add(key, "Facility", facility["name"], spec) + for key, record in self.rows("dcim/racks"): + selected = self.mapping.get("racks", {}).get(reference_id(record)) + if not selected or "Facility/" + selected.get("facility", "") not in self.candidates: + self.mark(key, "unresolved", "rack needs a mapped physical facility") + continue + name = self.stable_name("rack", reference_id(record)) + spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"])} + if isinstance(record.get("u_height"), int) and 1 <= record["u_height"] <= 100: + spec["heightUnits"] = record["u_height"] + self.add(key, "Rack", name, spec) + self.rack_names[reference_id(record)] = name + + def devices(self): + for key, record in self.rows("dcim/devices"): + identity = reference_id(record) + selected = self.mapping.get("devices", {}).get(identity, {}) + role = record.get("role") or {} + dtype = record.get("device_type") or {} + model = self.records.get("dcim/device-types/" + reference_id(dtype), dtype) + manufacturer = model.get("manufacturer") or {} + hints = canonical([role, manufacturer, model.get("model", "")]).lower() + if "netactuate" in hints or "hosted-vm" in hints: + self.mark(key, "excluded", "NetActuate/hosted VM represented in DCIM; not a physical asset") + continue + if selected.get("classification") == "excluded" and selected.get("reason"): + self.mark(key, "excluded", selected["reason"]) + continue + if selected.get("classification") != "physical" or not selected.get("serialMeaning") in ("chassis", "providerHostID", "unknown"): + self.mark(key, "unresolved", "review physical classification and serial meaning for this device") + continue + placement = selected.get("placement", {}) + rack_id = reference_id(record.get("rack")) + if placement.get("scope") == "RackMembership" and rack_id in self.rack_names: + placement = {"scope": "RackMembership", "rackRef": local_ref(self.rack_names[rack_id])} + elif placement.get("scope") == "Facility" and "Facility/" + placement.get("facility", "") in self.candidates: + placement = {"scope": "Facility", "facilityRef": local_ref(placement["facility"])} + else: + self.mark(key, "unresolved", "import accepts reviewed facility or known-rack/unknown-position placement only") + continue + if not model.get("model"): + self.mark(key, "unresolved", "device model is absent") + continue + name = self.stable_name("device", identity) + claim_name = self.stable_name("installation", identity) + asset_identity = {"model": model["model"], "sourceIdentity": self.external(key)} + if manufacturer.get("name"): + asset_identity["manufacturer"] = manufacturer["name"] + serial = record.get("serial") + if serial and ("servers.com" in hints or "serversdotcom" in hints) and selected["serialMeaning"] == "chassis": + self.mark(key, "unresolved", "servers.com loader serial is a provider host ID, not a chassis serial") + continue + if serial and selected["serialMeaning"] == "chassis": + asset_identity["serial"] = serial + spec = {"displayName": record.get("name") or name, "claimRef": local_ref(claim_name), "identity": asset_identity, "topologyAuthority": "Cable"} + shape = {} + try: + height = float(model.get("u_height", "")) + if 0 <= height <= 100: + shape["heightUnits"] = height + except (ValueError, TypeError): + pass + if isinstance(model.get("is_full_depth"), bool): + shape["fullDepth"] = model["is_full_depth"] + if shape: + spec["modelShape"] = shape + if serial and selected["serialMeaning"] == "providerHostID": + if not selected.get("provider"): + self.mark(key, "unresolved", "provider host ID requires its provider authority") + continue + spec["providerHostRef"] = {"system": selected["provider"], "type": "host", "id": serial} + if record.get("asset_tag"): + spec["assetTag"] = record["asset_tag"] + self.add(key, "DeviceClaim", claim_name, {"displayName": record.get("name") or name, "lifecycle": "Installation", "expectedIdentity": {name: item for name, item in asset_identity.items() if name != "sourceIdentity"}, "placement": placement}) + self.add(key, "Device", name, spec) + self.device_names[identity] = name + + def components(self): + for collection, kind in COMPONENTS.items(): + for key, record in self.rows("dcim/" + collection): + device_id = reference_id(record.get("device")) + if device_id not in self.device_names: + parent = self.report.get("dcim/devices/" + device_id, {}) + state = "excluded" if parent.get("classification") == "excluded" else "unresolved" + self.mark(key, state, "parent device is excluded or unresolved") + continue + if collection == "interfaces" and value(record, "type") in ("virtual", "lag", "bridge"): + self.mark(key, "excluded", "logical interface belongs to networking, not physical inventory") + continue + target = "Device/" + self.device_names[device_id] + component = {"id": collection + "-" + reference_id(record), "name": record.get("name") or record.get("display") or reference_id(record), "type": kind, "sourceRef": self.external(key)} + connector = value(record, "type") + if connector: + component["connector"] = connector + positions = record.get("positions") + if isinstance(positions, int) and 1 <= positions <= 256: + component["positions"] = positions + for source_field, target_field in (("serial", "serial"), ("asset_tag", "assetTag")): + if record.get(source_field): + component[target_field] = record[source_field] + self.candidates[target]["spec"].setdefault("components", []).append(component) + self.mark(key, "imported", "typed component on the parent asset", [target]) + for collection, parent_field, parent_collection in (("front-ports", "rear_port", "rear-ports"), ("power-outlets", "power_port", "power-ports")): + for key, record in self.rows("dcim/" + collection): + if self.report[key]["classification"] != "imported": + continue + parent_id = reference_id(record.get(parent_field)) + if not parent_id: + self.report[key]["reason"] += "; internal dependency Unknown" + continue + target = self.report[key]["targets"][0] + parent_key = "dcim/" + parent_collection + "/" + parent_id + if self.report.get(parent_key, {}).get("targets") != [target]: + self.mark(key, "unresolved", "internal dependency has a missing or different parent device", [target]) + continue + mapping = {"from": {"componentID": collection + "-" + reference_id(record), "position": 1}, "to": {"componentID": parent_collection + "-" + parent_id, "position": record.get("rear_port_position") or 1}} + self.candidates[target]["spec"].setdefault("internalMappings", []).append(mapping) + + def feeds(self): + for key, record in self.rows("dcim/power-panels"): + self.mark(key, "unresolved", "panel is external electrical dependency evidence, not a fabricated asset") + for key, record in self.rows("dcim/power-feeds"): + selected = self.mapping.get("feeds", {}).get(reference_id(record), {}) + if "Facility/" + selected.get("facility", "") not in self.candidates: + self.mark(key, "unresolved", "feed requires an explicit facility mapping") + continue + name = self.stable_name("feed", reference_id(record)) + spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"]), "terminations": [{"id": "output", "name": "output", "type": "PowerOutlet"}]} + rack = self.rack_names.get(reference_id(record.get("rack"))) + if rack: + spec["rackRef"] = local_ref(rack) + supply = {"type": str(value(record, "supply", "Unknown")).upper()} + if supply["type"] not in ("AC", "DC"): + supply["type"] = "Unknown" + for field, target_field in (("voltage", "voltageV"), ("amperage", "currentA")): + if isinstance(record.get(field), int) and 0 < record[field] <= 100000: + supply[target_field] = record[field] + if value(record, "phase") in ("single-phase", "three-phase"): + supply["phase"] = value(record, "phase") + spec["supply"] = supply + panel_key = "dcim/power-panels/" + reference_id(record.get("power_panel")) + if panel_key in self.records: + spec["upstreamSources"] = [self.external(panel_key)] + self.mark(panel_key, "imported", "external electrical panel reference only; upstream independence Unknown", sorted(set(self.report[panel_key]["targets"] + ["PowerFeed/" + name]))) + self.add(key, "PowerFeed", name, spec) + self.feed_names[reference_id(record)] = name + + def endpoint(self, termination): + kind = termination.get("object_type") or termination.get("termination_type") + identity = reference_id(termination.get("object_id") or termination.get("termination_id") or termination.get("object") or termination.get("termination")) + if kind == "dcim.powerfeed" and identity in self.feed_names: + return {"powerFeedRef": local_ref(self.feed_names[identity]), "componentID": "output", "position": 1} + collection = next((name for name in COMPONENTS if "dcim." + name.replace("-", "").rstrip("s") == kind), None) + if kind == "dcim.inventoryitem": + collection = "inventory-items" + key = "dcim/" + str(collection) + "/" + identity + if kind == "circuits.circuittermination": + selected = self.mapping.get("demarcations", {}).get(identity) + if not selected: + return None + key = selected.get("componentSource", "") + state = self.report.get(key, {}) + if state.get("classification") != "imported" or not state.get("targets"): + return None + target = state["targets"][0] + if not target.startswith("Device/"): + return None + source_class, source_id = key.rsplit("/", 1) + return {"deviceRef": local_ref(target.split("/", 1)[1]), "componentID": source_class.split("/")[1] + "-" + source_id, "position": 1} + + def circuits(self): + for key, record in self.rows("circuits/circuits"): + self.mark(key, "unresolved", "circuit requires an external service-owner reference; no Fleet Circuit kind") + for key, record in self.rows("circuits/circuit-terminations"): + circuit_key = "circuits/circuits/" + reference_id(record.get("circuit")) + owner = self.mapping.get("circuits", {}).get(reference_id(record.get("circuit"))) + endpoint = self.endpoint({"object_type": "circuits.circuittermination", "object_id": reference_id(record)}) + if not owner or not all(owner.get(field) for field in ("system", "type", "id")) or not endpoint or circuit_key not in self.records: + self.mark(key, "unresolved", "local demarcation and external service owner must both be mapped") + continue + target = "Device/" + endpoint["deviceRef"]["name"] + self.candidates[target]["spec"].setdefault("serviceAssociations", []).append({"serviceRef": {field: owner[field] for field in ("system", "type", "id")}, "componentID": endpoint["componentID"]}) + self.mark(key, "imported", "local physical demarcation association only", [target]) + self.mark(circuit_key, "imported", "external service-owner reference only; no service or IPAM migration", sorted(set(self.report[circuit_key]["targets"] + [target]))) + + def cables(self): + for key, record in self.rows("dcim/cables"): + ends = [record.get("a_terminations", []), record.get("b_terminations", [])] + selected = self.mapping.get("cables", {}).get(reference_id(record), {}) + lanes = selected.get("lanes") + available = [[self.endpoint(termination) for termination in end] for end in ends] + if not all(available) or any(endpoint is None for side in available for endpoint in side): + self.mark(key, "unresolved", "cable endpoint is missing, excluded, or has no reviewed demarcation") + continue + if lanes: + lanes = copy.deepcopy(lanes) + represented = [set(), set()] + valid = isinstance(lanes, list) and len(lanes) <= 64 + for lane in lanes if valid else []: + if not isinstance(lane, dict) or not name_ok(lane.get("id")): + valid = False + break + for index, side in enumerate(("a", "b")): + endpoint = lane.get(side) + if not isinstance(endpoint, dict) or not isinstance(endpoint.get("position"), int) or endpoint["position"] < 1: + valid = False + break + base_endpoint = dict(endpoint, position=1) + if base_endpoint not in available[index]: + valid = False + break + represented[index].add(canonical(base_endpoint)) + if not valid or any(represented[index] != {canonical(endpoint) for endpoint in available[index]} for index in (0, 1)): + self.mark(key, "unresolved", "reviewed lanes must account for every source termination on its original side") + continue + else: + if any(len(end) != 1 for end in ends): + self.mark(key, "unsupported", "multi-termination cable needs reviewed explicit lane mappings; no all-to-all inference") + continue + endpoints = [end[0] for end in available] + multiposition = False + for endpoint in endpoints: + if endpoint.get("deviceRef"): + device = self.candidates["Device/" + endpoint["deviceRef"]["name"]] + component = next(component for component in device["spec"]["components"] if component["id"] == endpoint["componentID"]) + multiposition |= component.get("positions", 1) > 1 + if multiposition: + self.mark(key, "unresolved", "multi-position termination needs explicit lanes; never infer position one for a trunk") + continue + lanes = [{"id": "lane-1", "a": endpoints[0], "b": endpoints[1]}] + medium = selected.get("medium") + if medium not in ("Copper", "Fiber", "Power", "Console"): + self.mark(key, "unresolved", "cable medium requires review; source connector codes are not qualification") + continue + name = self.stable_name("cable", reference_id(record)) + self.add(key, "Cable", name, {"displayName": record.get("label") or name, "medium": medium, "lanes": lanes}) + + def reconcile(self): + current = {} + for record in (self.existing or {}).get("items", []): + if record.get("apiVersion") != "fleet.datumapis.com/v1alpha1" or record.get("metadata", {}).get("namespace") != self.namespace: + raise ValueError("Fleet snapshot must contain only this namespace's physical inventory") + key = record["kind"] + "/" + record["metadata"]["name"] + if key in current: + raise ValueError("duplicate Fleet target identity") + current[key] = record + conflicts, unchanged = {}, set() + for key, candidate in self.candidates.items(): + if key in current: + old_spec, new_spec = copy.deepcopy(current[key]["spec"]), copy.deepcopy(candidate["spec"]) + old_provenance, new_provenance = old_spec.pop("provenance"), new_spec.pop("provenance") + source_fields = ("system", "type", "id") + same_source = all(old_provenance.get("source", {}).get(field) == new_provenance["source"][field] for field in source_fields) + if same_source and old_spec == new_spec: + unchanged.add(key) + else: + conflicts[key] = "existing target differs; no automatic update, claim rebinding, or ownership takeover" + if candidate["kind"] == "Device": + spec = candidate["spec"] + for other_key, other in {**current, **self.candidates}.items(): + if other_key == key or other.get("kind") != "Device": + continue + other_spec = other["spec"] + pairs = [(spec.get("assetTag"), other_spec.get("assetTag")), (spec.get("providerHostRef"), other_spec.get("providerHostRef")), (spec.get("providerHostRef", {}).get("id"), other_spec["identity"].get("serial")), (spec["identity"].get("serial"), other_spec["identity"].get("serial")), (spec["identity"].get("sourceIdentity"), other_spec["identity"].get("sourceIdentity"))] + if any(left and left == right for left, right in pairs): + conflicts[key] = "possible existing asset identity; preserve Device/claim/capacity and adjudicate privately" + all_records = {**current, **self.candidates} + for key, reasons in validate_graph(all_records).items(): + if key in self.candidates: + conflicts[key] = "; ".join(reasons) + changed = True + while changed: + changed = False + for entry in self.report.values(): + if entry["classification"] == "unresolved": + for target in entry["targets"]: + if target not in conflicts: + conflicts[target] = "one or more source relationships are unresolved" + changed = True + if any(target in conflicts for target in entry["targets"]): + for target in entry["targets"]: + if target not in conflicts: + conflicts[target] = "same source record has a quarantined dependency" + changed = True + for key, record in self.candidates.items(): + if key not in conflicts and any(target in conflicts for target in dependencies(record)): + conflicts[key] = "referenced candidate is quarantined" + changed = True + for entry in self.report.values(): + failed = [target for target in entry["targets"] if target in conflicts] + if failed: + entry.update(classification="unresolved", reason=conflicts[failed[0]]) + elif entry["targets"] and all(target in unchanged for target in entry["targets"]): + entry["reason"] = "already present with same source identity and physical fields; no write" + self.candidates = {key: record for key, record in self.candidates.items() if key not in conflicts and key not in unchanged} + return conflicts + + def run(self): + self.facilities() + self.devices() + self.components() + self.feeds() + self.circuits() + self.cables() + for key in self.records: + collection = key.rsplit("/", 1)[0] + if collection.startswith("dcim/") and collection.split("/")[1] in SUPPORT: + self.mark(key, "excluded", "model/catalog metadata consumed where referenced; no independent physical asset") + elif collection.endswith("-templates"): + self.mark(key, "excluded", "model template is not installed hardware; actual instances imported separately") + elif collection in ("dcim/regions", "dcim/site-groups", "dcim/rack-roles", "dcim/virtual-chassis", "circuits/providers", "circuits/provider-accounts", "circuits/provider-networks", "circuits/circuit-types"): + self.mark(key, "excluded", "grouping or service-owner metadata; not physical premises or installed assets") + conflicts = self.reconcile() + omitted = sorted(set((self.previous or {}).get("objects", {})) - set(self.snapshot.get("objects", {}))) + prior_keys = {collection + "/" + reference_id(record) for collection, rows in (self.previous or {}).get("objects", {}).items() for record in rows} + if self.previous and self.previous.get("source") != self.source: + raise ValueError("previous snapshot belongs to another source") + errors = dict(self.snapshot.get("errors", {})) + for collection in REQUIRED - self.snapshot.get("objects", {}).keys(): + errors.setdefault(collection, "required collection absent; coverage unknown") + retained = [] + for record in (self.existing or {}).get("items", []): + source = record.get("spec", {}).get("provenance", {}).get("source", {}) + if source.get("system") == self.source and source.get("type", "") + "/" + source.get("id", "") not in self.records: + retained.append(record["kind"] + "/" + record["metadata"]["name"]) + return {"version": 1, "source": self.source, "snapshotDigest": self.digest, "observedAt": self.snapshot["observedAt"], "target": self.target, "mappingRevision": self.revision, "coverageComplete": not errors, "collectionErrors": errors, "excludedEndpoints": self.snapshot.get("excludedEndpoints", {}), "omittedCollections": omitted, "missingSincePrevious": sorted(prior_keys - self.records.keys()), "retainedMissingSource": retained, "deletions": [], "conflicts": conflicts, "records": list(self.report.values()), "candidateCount": len(self.candidates), "readiness": "Unknown", "applied": False}, list(self.candidates.values()) + + +def dependencies(record): + spec = record["spec"] + references = [] + for field, kind in (("claimRef", "DeviceClaim"), ("facilityRef", "Facility"), ("rackRef", "Rack")): + if spec.get(field): + references.append(kind + "/" + spec[field]["name"]) + if spec.get("placement", {}).get(field): + references.append(kind + "/" + spec["placement"][field]["name"]) + for lane in spec.get("lanes", []): + for endpoint in (lane["a"], lane["b"]): + for field, kind in (("deviceRef", "Device"), ("powerFeedRef", "PowerFeed")): + if endpoint.get(field): + references.append(kind + "/" + endpoint[field]["name"]) + return references + + +def validate_graph(records): + errors, occupied = {}, {} + def fail(key, reason): + errors.setdefault(key, []).append(reason) + for key, record in records.items(): + for target in dependencies(record): + if target not in records: + fail(key, "missing local reference " + target) + spec = record["spec"] + components = {component["id"]: component for component in spec.get("components", [])} + mapped_positions = set() + for mapping in spec.get("internalMappings", []): + for end in (mapping["from"], mapping["to"]): + component = components.get(end["componentID"]) + if not component or not 1 <= end["position"] <= component.get("positions", 1): + fail(key, "invalid internal component mapping") + source_type = components.get(mapping["from"]["componentID"], {}).get("type") + target_type = components.get(mapping["to"]["componentID"], {}).get("type") + if (source_type, target_type) not in (("FrontPort", "RearPort"), ("PowerOutlet", "PowerInlet")): + fail(key, "incompatible internal component types") + if source_type == "FrontPort": + position = canonical(mapping["to"]) + if position in mapped_positions: + fail(key, "pass-through rear position mapped more than once") + mapped_positions.add(position) + for association in spec.get("serviceAssociations", []): + if association["componentID"] not in components: + fail(key, "service demarcation names a missing component") + for lane in spec.get("lanes", []): + kinds = [] + for endpoint in (lane["a"], lane["b"]): + owner = ("Device/" + endpoint["deviceRef"]["name"]) if endpoint.get("deviceRef") else ("PowerFeed/" + endpoint["powerFeedRef"]["name"]) + target = records.get(owner, {}).get("spec", {}) + components = target.get("components", []) + target.get("terminations", []) + component = next((component for component in components if component["id"] == endpoint["componentID"]), None) + if not component or not 1 <= endpoint["position"] <= component.get("positions", 1): + fail(key, "unresolved endpoint component or position") + continue + kinds.append(component["type"]) + connector = component.get("connector", "").lower() + if spec.get("medium") == "Fiber" and ("base-t" in connector or "rj45" in connector): + fail(key, "fiber cable on a copper termination") + identity = owner + "/" + endpoint["componentID"] + "/" + str(endpoint["position"]) + if identity in occupied: + fail(key, "termination already used") + fail(occupied[identity], "termination already used") + occupied[identity] = key + allowed = {"Power": {"PowerInlet", "PowerOutlet"}, "Console": {"ConsolePort", "ConsoleServerPort", "FrontPort", "RearPort"}, "Copper": {"NetworkPort", "FrontPort", "RearPort"}, "Fiber": {"NetworkPort", "FrontPort", "RearPort"}} + if spec.get("medium") not in allowed or not set(kinds) <= allowed[spec["medium"]]: + fail(key, "incompatible or unknown cable medium and component types") + if spec.get("medium") == "Power" and sorted(kinds) != ["PowerInlet", "PowerOutlet"]: + fail(key, "power cable must connect an outlet to an inlet") + if spec.get("medium") == "Console" and all(kind in ("ConsolePort", "ConsoleServerPort") for kind in kinds) and sorted(kinds) != ["ConsolePort", "ConsoleServerPort"]: + fail(key, "unsupported console direction; adapter mapping required") + return errors + + +def read_json(path): + with open(path) as stream: + return json.load(stream) + + +def write_private(path, content): + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(descriptor, "w") as stream: + json.dump(content, stream, sort_keys=True, indent=2) + stream.write("\n") + + +def private_output(path): + resolved = path.resolve() + if any((parent / ".git").exists() for parent in (resolved, *resolved.parents)): + raise ValueError("private snapshots and handoffs must be written outside Git checkouts") + path.mkdir(mode=0o700, parents=False, exist_ok=False) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + export = subparsers.add_parser("snapshot") + export.add_argument("--url", default=os.environ.get("NETBOX_URL", "https://netbox.datum-infra.net")) + export.add_argument("--source", required=True) + export.add_argument("--auth-scheme", choices=("Bearer", "Token"), default="Bearer") + export.add_argument("--output", required=True) + plan = subparsers.add_parser("plan") + plan.add_argument("--snapshot", required=True) + plan.add_argument("--mapping") + plan.add_argument("--existing") + plan.add_argument("--previous") + plan.add_argument("--output", required=True) + plan.add_argument("--handoff", action="store_true") + plan.add_argument("--allow-partial", action="store_true") + args = parser.parse_args(argv) + output = Path(args.output) + private_output(output) + if args.command == "snapshot": + token = os.environ.get("NETBOX_TOKEN") + if not token: + token_path = Path(os.environ.get("NETBOX_TOKEN_FILE", "~/.config/netbox/token")).expanduser() + if not token_path.is_file(): + raise ValueError("no authorized NetBox read credential in the documented environment/file paths") + token = token_path.read_text().strip() + result = snapshot(Reader(args.url, token, args.auth_scheme), args.source) + write_private(output / "snapshot.json", result) + print("Private snapshot saved; collection errors:", len(result["errors"])) + return 2 if result["errors"] else 0 + mapping = read_json(args.mapping) if args.mapping else {} + planner = Planner(read_json(args.snapshot), mapping, read_json(args.existing) if args.existing else None, read_json(args.previous) if args.previous else None) + report, candidates = planner.run() + write_private(output / "report.json", report) + if args.handoff: + target = mapping.get("target", {}) + if not args.existing or not mapping.get("revision") or not name_ok(target.get("project")) or not name_ok(target.get("namespace")) or target.get("writer") != "Flux" or target.get("application") != "provider-inventory": + raise ValueError("handoff requires an explicit provider project/namespace, reviewed mapping revision, Flux/provider-inventory target, and current Fleet snapshot") + if report["collectionErrors"] or report["conflicts"]: + raise ValueError("handoff blocked by incomplete source coverage or reconciliation conflicts; inspect the private report") + if not args.allow_partial and any(row["classification"] in ("unresolved", "unsupported") for row in report["records"]): + raise ValueError("handoff has unresolved or unsupported records; review the report and explicitly choose --allow-partial for a partial cohort") + write_private(output / "candidates.json", {"apiVersion": "v1", "kind": "List", "items": candidates}) + write_private(output / "handoff.json", {"target": target, "snapshotDigest": report["snapshotDigest"], "mappingDigest": digest(mapping), "existingDigest": digest(planner.existing), "candidateDigest": digest(candidates), "application": "review and add individual new records to the private Flux provider-inventory source; never replace or prune that source", "applied": False}) + print("Private report saved; observational candidates:", len(candidates), "(nothing applied)") + counts = {state: sum(row["classification"] == state for row in report["records"]) for state in ("imported", "unresolved", "unsupported", "excluded")} + print("Record classifications:", canonical(counts), "; collection errors:", len(report["collectionErrors"]), "; readiness: Unknown") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (ValueError, OSError, KeyError, TypeError) as error: + print("Inventory import stopped:", str(error) if isinstance(error, ValueError) else type(error).__name__, file=sys.stderr) + sys.exit(2) diff --git a/hack/test_netbox_inventory.py b/hack/test_netbox_inventory.py new file mode 100644 index 00000000..6be9732f --- /dev/null +++ b/hack/test_netbox_inventory.py @@ -0,0 +1,292 @@ +import copy +import io +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +import urllib.error + +import netbox_inventory as inventory + + +def fixture(): + objects = {collection: [] for collection in inventory.REQUIRED} + objects.update({ + "dcim/sites": [{"id": 1, "name": "Example metro grouping"}], + "dcim/locations": [{"id": 1, "name": "Example room"}], + "dcim/racks": [{"id": 1, "name": "Example rack", "u_height": 42}], + "dcim/manufacturers": [{"id": 1, "name": "Example"}], + "dcim/device-types": [{"id": 1, "model": "Example physical model", "manufacturer": {"id": 1, "name": "Example"}}], + "dcim/devices": [ + {"id": 1, "name": "Example server", "serial": "provider-001", "asset_tag": "asset-001", "device_type": {"id": 1}, "rack": {"id": 1}, "position": 1}, + {"id": 2, "name": "Example PDU", "device_type": {"id": 1}, "rack": {"id": 1}}, + {"id": 3, "name": "Example panel", "device_type": {"id": 1}}, + {"id": 4, "name": "Example VM", "device_type": {"model": "netactuate VM"}}, + ], + "dcim/interfaces": [{"id": 1, "name": "eth0", "device": {"id": 1}, "type": "1000base-t"}, {"id": 2, "name": "bond0", "device": {"id": 1}, "type": "lag"}], + "dcim/power-ports": [{"id": 1, "name": "PSU1", "device": {"id": 1}}, {"id": 2, "name": "inlet", "device": {"id": 2}}], + "dcim/power-outlets": [{"id": 1, "name": "outlet-1", "device": {"id": 2}, "power_port": {"id": 2}}], + "dcim/front-ports": [{"id": 1, "name": "front-1", "device": {"id": 3}, "rear_port": {"id": 1}, "rear_port_position": 1}], + "dcim/rear-ports": [{"id": 1, "name": "rear-1", "device": {"id": 3}, "positions": 2}], + "dcim/power-panels": [{"id": 1, "name": "Panel A"}], + "dcim/power-feeds": [{"id": 1, "name": "Feed A", "power_panel": {"id": 1}, "rack": {"id": 1}, "supply": "ac", "voltage": 208, "amperage": 30}], + "dcim/cables": [{"id": 1, "label": "Power 1", "a_terminations": [{"object_type": "dcim.poweroutlet", "object_id": 1}], "b_terminations": [{"object_type": "dcim.powerport", "object_id": 1}]}], + "circuits/circuits": [{"id": 1, "cid": "Example-service"}], + "circuits/circuit-terminations": [{"id": 1, "circuit": {"id": 1}}], + }) + source = {"version": 1, "source": "example-netbox", "observedAt": "2026-11-20T12:00:00Z", "objects": objects, "errors": {}} + mapping = { + "revision": "example-reviewed-1", + "target": {"project": "example-provider", "namespace": "inventory", "writer": "Flux", "application": "provider-inventory"}, + "facilities": [{"source": "dcim/sites/1", "name": "example-premises", "displayName": "Example premises"}], + "racks": {"1": {"facility": "example-premises"}}, + "devices": { + "1": {"classification": "physical", "serialMeaning": "providerHostID", "provider": "example-provider", "placement": {"scope": "RackMembership"}}, + "2": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "RackMembership"}}, + "3": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "Facility", "facility": "example-premises"}}, + }, + "feeds": {"1": {"facility": "example-premises"}}, + "cables": {"1": {"medium": "Power"}}, + "circuits": {"1": {"system": "example-service-owner", "type": "transport", "id": "Example-service"}}, + "demarcations": {"1": {"componentSource": "dcim/rear-ports/1"}}, + } + return source, mapping + + +class PlanTests(unittest.TestCase): + def setUp(self): + self.source, self.mapping = fixture() + + def plan(self, existing=None, previous=None): + if existing is not None: + existing = dict(existing, target=self.mapping["target"], collections=["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]) + return inventory.Planner(self.source, self.mapping, existing, previous).run() + + def test_physical_shapes_and_no_hardware_authority(self): + report, records = self.plan() + self.assertTrue(report["coverageComplete"]) + self.assertEqual({}, report["conflicts"]) + self.assertEqual({"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"}, {record["kind"] for record in records}) + self.assertEqual(sum(len(rows) for rows in self.source["objects"].values()), len(report["records"])) + server = next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag")) + self.assertNotIn("serial", server["spec"]["identity"]) + self.assertEqual("provider-001", server["spec"]["providerHostRef"]["id"]) + self.assertEqual("asset-001", server["spec"]["assetTag"]) + for record in records: + self.assertNotIn("status", record) + self.assertNotIn("bmc", record["spec"]) + if record["kind"] == "DeviceClaim": + self.assertNotIn("position", record["spec"]["placement"]) + self.assertNotIn("height", record["spec"]["placement"]) + states = {row["source"]: row["classification"] for row in report["records"]} + self.assertEqual("excluded", states["dcim/devices/4"]) + self.assertEqual("excluded", states["dcim/interfaces/2"]) + self.assertEqual("imported", states["circuits/circuit-terminations/1"]) + + def test_checked_in_synthetic_handoff_matches_planner(self): + _, records = self.plan() + fixture_path = Path(__file__).parent / "testdata/netbox/candidates.json" + self.assertEqual(inventory.read_json(fixture_path)["items"], records) + + def test_existing_snapshot_wrong_project_and_missing_collections(self): + with self.assertRaisesRegex(ValueError, "target"): + inventory.Planner(self.source, self.mapping, {"items": [], "target": {"project": "other"}}) + with self.assertRaisesRegex(ValueError, "six"): + inventory.Planner(self.source, self.mapping, {"items": [], "target": self.mapping["target"]}) + + def test_repeated_and_interrupted_run(self): + report, records = self.plan() + self.assertEqual((report, records), self.plan()) + second, remaining = self.plan({"items": records}) + self.assertEqual({}, second["conflicts"]) + self.assertEqual([], remaining) + partial, remaining = self.plan({"items": records[:2]}) + self.assertEqual({}, partial["conflicts"]) + self.assertEqual(len(records) - 2, len(remaining)) + + def test_existing_identity_is_never_recreated(self): + _, records = self.plan() + server = copy.deepcopy(next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag"))) + server["metadata"]["name"] = "original-asset" + server["spec"]["identity"] = {"model": "Legacy", "serial": "provider-001"} + server["spec"].pop("assetTag") + server["spec"].pop("providerHostRef") + report, candidates = self.plan({"items": [server]}) + self.assertTrue(report["conflicts"]) + self.assertFalse(any(record["kind"] == "Device" and record["spec"].get("providerHostRef") for record in candidates)) + self.assertEqual("original-asset", server["metadata"]["name"]) + + def test_changed_source_and_different_writer_are_conflicts(self): + _, records = self.plan() + records[0]["spec"]["displayName"] = "Manual correction" + report, _ = self.plan({"items": records}) + self.assertTrue(report["conflicts"]) + _, records = self.plan() + records[0]["spec"]["provenance"]["source"]["system"] = "other-source" + report, _ = self.plan({"items": records}) + self.assertTrue(report["conflicts"]) + + def test_omission_preserves_records_and_does_not_prune(self): + previous = copy.deepcopy(self.source) + self.source["objects"]["dcim/devices"] = self.source["objects"]["dcim/devices"][1:] + report, _ = self.plan(previous=previous) + self.assertIn("dcim/devices/1", report["missingSincePrevious"]) + self.assertEqual([], report["deletions"]) + + def test_unknown_collections_and_missing_collections_are_visible(self): + self.source["objects"]["dcim/new-physical-kind"] = [{"id": 1}] + del self.source["objects"]["dcim/console-ports"] + report, _ = self.plan() + self.assertFalse(report["coverageComplete"]) + self.assertEqual("unsupported", next(row for row in report["records"] if row["source"] == "dcim/new-physical-kind/1")["classification"]) + + def test_duplicate_identity_and_target_mapping_rejected(self): + self.source["objects"]["dcim/sites"].append({"id": 1}) + with self.assertRaises(ValueError): + self.plan() + self.source, self.mapping = fixture() + self.mapping["facilities"].append(copy.deepcopy(self.mapping["facilities"][0])) + with self.assertRaises(ValueError): + self.plan() + + def test_site_can_map_to_several_premises(self): + self.mapping["facilities"].append({"source": "dcim/sites/1", "name": "another-premises", "displayName": "Other premises"}) + _, records = self.plan() + self.assertEqual(2, sum(record["kind"] == "Facility" for record in records)) + + def test_no_mapping_means_no_guessed_assets(self): + self.mapping = {} + report, records = self.plan() + self.assertEqual([], records) + self.assertTrue(any(row["classification"] == "unresolved" for row in report["records"])) + + def test_duplicate_cable_termination_quarantines_both(self): + cable = copy.deepcopy(self.source["objects"]["dcim/cables"][0]) + cable["id"] = 2 + self.source["objects"]["dcim/cables"].append(cable) + self.mapping["cables"]["2"] = {"medium": "Power"} + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + self.assertTrue(report["conflicts"]) + + def test_breakout_requires_reviewed_lanes_and_every_termination(self): + self.source["objects"]["dcim/interfaces"].append({"id": 3, "name": "eth1", "device": {"id": 1}, "type": "1000base-t"}) + self.source["objects"]["dcim/cables"] = [{"id": 2, "a_terminations": [{"object_type": "dcim.rearport", "object_id": 1}], "b_terminations": [{"object_type": "dcim.interface", "object_id": 1}, {"object_type": "dcim.interface", "object_id": 3}]}] + planner = inventory.Planner(self.source, self.mapping) + panel = planner.stable_name("device", "3") + server = planner.stable_name("device", "1") + self.mapping["cables"]["2"] = {"medium": "Copper"} + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + lanes = [{"id": "lane-" + str(position), "a": {"deviceRef": {"name": panel}, "componentID": "rear-ports-1", "position": position}, "b": {"deviceRef": {"name": server}, "componentID": "interfaces-" + identity, "position": 1}} for position, identity in ((1, "1"), (2, "3"))] + self.mapping["cables"]["2"]["lanes"] = lanes + report, records = self.plan() + self.assertEqual({}, report["conflicts"]) + self.assertEqual(1, sum(record["kind"] == "Cable" for record in records)) + self.mapping["cables"]["2"]["lanes"] = lanes[:1] + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + + def test_incompatible_medium_and_missing_internal_mapping(self): + self.mapping["cables"]["1"]["medium"] = "Fiber" + self.source["objects"]["dcim/front-ports"][0]["rear_port_position"] = 3 + report, _ = self.plan() + self.assertGreaterEqual(len(report["conflicts"]), 2) + + def test_redaction_uses_allowlisted_fields(self): + source = {"id": 1, "comments": "SECRET", "custom_fields": {"bmc_password": "SECRET"}, "config_context": {"token": "SECRET"}, "device": {"id": 2, "url": "https://user:SECRET@example.invalid"}} + self.assertNotIn("SECRET", json.dumps(inventory.sanitize(source))) + + def test_output_is_private_and_never_overwritten(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "report.json" + inventory.write_private(path, {"example": True}) + self.assertEqual(0o600, path.stat().st_mode & 0o777) + with self.assertRaises(FileExistsError): + inventory.write_private(path, {}) + + def test_export_refuses_repository_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / ".git").write_text("gitdir: example") + with self.assertRaisesRegex(ValueError, "outside Git"): + inventory.private_output(root / "private-export") + self.assertFalse((root / "private-export").exists()) + + def test_handoff_requires_target_existing_and_partial_acknowledgement(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name, data in (("source", self.source), ("mapping", self.mapping), ("existing", {"items": [], "target": self.mapping["target"], "collections": ["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]})): + inventory.write_private(root / (name + ".json"), data) + args = ["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--output", str(root / "blocked"), "--handoff"] + with self.assertRaises(ValueError): + inventory.main(args) + self.assertFalse((root / "blocked/candidates.json").exists()) + args[args.index(str(root / "blocked"))] = str(root / "allowed") + args.extend(["--existing", str(root / "existing.json"), "--allow-partial"]) + self.assertEqual(0, inventory.main(args)) + self.assertTrue((root / "allowed/candidates.json").exists()) + with self.assertRaises(FileExistsError): + inventory.main(args) + + +class ReaderTests(unittest.TestCase): + def reader(self): + return inventory.Reader("https://example.invalid", "synthetic-token") + + def test_discovery_reports_lookup_exclusion_and_missing_collections(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"devices": "unused", "connected-device": "unused"}, {}]), patch.object(reader, "collection", return_value=[]) as collection: + result = inventory.snapshot(reader, "example-netbox") + collection.assert_called_once_with("dcim/devices") + self.assertIn("dcim/connected-device", result["excludedEndpoints"]) + self.assertIn("dcim/sites", result["errors"]) + + def test_discovery_permission_error_retains_partial_snapshot(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"devices": "unused"}, ValueError("NetBox GET failed with HTTP 403")]), patch.object(reader, "collection", return_value=[{"id": 1}]): + result = inventory.snapshot(reader, "example-netbox") + self.assertEqual([{"id": 1}], result["objects"]["dcim/devices"]) + self.assertIn("HTTP 403", result["errors"]["circuits/"]) + + def test_pagination_and_duplicates(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 2}], "next": None}]): + self.assertEqual(2, len(reader.collection("dcim/devices"))) + with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 1}], "next": None}]): + with self.assertRaisesRegex(ValueError, "repeated"): + reader.collection("dcim/devices") + + def test_partial_pagination_and_cycles_fail_closed(self): + reader = self.reader() + for page in ({"count": 2, "results": [{"id": 1}], "next": None}, {"count": 1, "results": [], "next": "?limit=200"}, {"count": 1, "results": [], "next": "/api/users/"}): + with patch.object(reader, "get", return_value=page), self.assertRaises(ValueError): + reader.collection("dcim/devices") + + def test_cross_origin_and_http_and_credentials_refused(self): + reader = self.reader() + with patch.object(reader.opener, "open") as opener: + for url in ("https://attacker.invalid/api/dcim/devices", "http://example.invalid/api/dcim/devices", "https://user:password@example.invalid/api/dcim/devices"): + with self.assertRaises(ValueError): + reader.get(url) + opener.assert_not_called() + + def test_retries_get_only_and_permission_errors_redacted(self): + reader = self.reader() + forbidden = urllib.error.HTTPError("https://example.invalid", 403, "SECRET", {}, None) + with patch.object(reader.opener, "open", side_effect=forbidden) as opener: + with self.assertRaisesRegex(ValueError, "HTTP 403") as caught: + reader.get("https://example.invalid/api/dcim/") + self.assertNotIn("SECRET", str(caught.exception)) + self.assertEqual("GET", opener.call_args.args[0].method) + self.assertEqual(1, opener.call_count) + unavailable = urllib.error.HTTPError("https://example.invalid", 503, "SECRET", {}, None) + with patch.object(reader.opener, "open", side_effect=[unavailable, io.StringIO('{"ok":true}')]) as opener, patch.object(inventory.time, "sleep"): + self.assertTrue(reader.get("https://example.invalid/api/dcim/")["ok"]) + self.assertEqual(2, opener.call_count) + + +if __name__ == "__main__": + unittest.main() diff --git a/hack/testdata/netbox/candidates.json b/hack/testdata/netbox/candidates.json new file mode 100644 index 00000000..66ecd1ce --- /dev/null +++ b/hack/testdata/netbox/candidates.json @@ -0,0 +1,475 @@ +{ + "apiVersion": "v1", + "items": [ + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Facility", + "metadata": { + "name": "example-premises", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example premises", + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/sites" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Rack", + "metadata": { + "name": "nb-2f51dc9cdc336da3c50b9a8b", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example rack", + "facilityRef": { + "name": "example-premises" + }, + "heightUnits": 42, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/racks" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-d2728cbb6945a3e726ab702b", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example server", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "scope": "RackMembership" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-b4a16a61aea025fc10ded221", + "namespace": "inventory" + }, + "spec": { + "assetTag": "asset-001", + "claimRef": { + "name": "nb-d2728cbb6945a3e726ab702b" + }, + "components": [ + { + "connector": "1000base-t", + "id": "interfaces-1", + "name": "eth0", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/interfaces" + }, + "type": "NetworkPort" + }, + { + "id": "power-ports-1", + "name": "PSU1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-ports" + }, + "type": "PowerInlet" + } + ], + "displayName": "Example server", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "1", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "providerHostRef": { + "id": "provider-001", + "system": "example-provider", + "type": "host" + }, + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-80a1dd16980a83974841e810", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example PDU", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "scope": "RackMembership" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "2", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-64e11cbf2b3c9f4866fa9eda", + "namespace": "inventory" + }, + "spec": { + "claimRef": { + "name": "nb-80a1dd16980a83974841e810" + }, + "components": [ + { + "id": "power-ports-2", + "name": "inlet", + "sourceRef": { + "id": "2", + "system": "example-netbox", + "type": "dcim/power-ports" + }, + "type": "PowerInlet" + }, + { + "id": "power-outlets-1", + "name": "outlet-1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-outlets" + }, + "type": "PowerOutlet" + } + ], + "displayName": "Example PDU", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "2", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "internalMappings": [ + { + "from": { + "componentID": "power-outlets-1", + "position": 1 + }, + "to": { + "componentID": "power-ports-2", + "position": 1 + } + } + ], + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "2", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-9032aa5e04cb441d10d37851", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example panel", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "facilityRef": { + "name": "example-premises" + }, + "scope": "Facility" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "3", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-25d8e4b769fdb899553c233e", + "namespace": "inventory" + }, + "spec": { + "claimRef": { + "name": "nb-9032aa5e04cb441d10d37851" + }, + "components": [ + { + "id": "front-ports-1", + "name": "front-1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/front-ports" + }, + "type": "FrontPort" + }, + { + "id": "rear-ports-1", + "name": "rear-1", + "positions": 2, + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/rear-ports" + }, + "type": "RearPort" + } + ], + "displayName": "Example panel", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "3", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "internalMappings": [ + { + "from": { + "componentID": "front-ports-1", + "position": 1 + }, + "to": { + "componentID": "rear-ports-1", + "position": 1 + } + } + ], + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "3", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "serviceAssociations": [ + { + "componentID": "rear-ports-1", + "serviceRef": { + "id": "Example-service", + "system": "example-service-owner", + "type": "transport" + } + } + ], + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "PowerFeed", + "metadata": { + "name": "nb-15e9e7aa88e11d9ab395e929", + "namespace": "inventory" + }, + "spec": { + "displayName": "Feed A", + "facilityRef": { + "name": "example-premises" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/power-feeds" + } + }, + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "supply": { + "currentA": 30, + "type": "AC", + "voltageV": 208 + }, + "terminations": [ + { + "id": "output", + "name": "output", + "type": "PowerOutlet" + } + ], + "upstreamSources": [ + { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-panels" + } + ] + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Cable", + "metadata": { + "name": "nb-4cf1484ca48ba078ba94107c", + "namespace": "inventory" + }, + "spec": { + "displayName": "Power 1", + "lanes": [ + { + "a": { + "componentID": "power-outlets-1", + "deviceRef": { + "name": "nb-64e11cbf2b3c9f4866fa9eda" + }, + "position": 1 + }, + "b": { + "componentID": "power-ports-1", + "deviceRef": { + "name": "nb-b4a16a61aea025fc10ded221" + }, + "position": 1 + }, + "id": "lane-1" + } + ], + "medium": "Power", + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/cables" + } + } + } + } + ], + "kind": "List" +} diff --git a/hack/testdata/netbox/existing.json b/hack/testdata/netbox/existing.json new file mode 100644 index 00000000..1e972629 --- /dev/null +++ b/hack/testdata/netbox/existing.json @@ -0,0 +1,17 @@ +{ + "collections": [ + "Facility", + "Rack", + "DeviceClaim", + "Device", + "Cable", + "PowerFeed" + ], + "items": [], + "target": { + "application": "provider-inventory", + "namespace": "inventory", + "project": "example-provider", + "writer": "Flux" + } +} diff --git a/hack/testdata/netbox/mapping.json b/hack/testdata/netbox/mapping.json new file mode 100644 index 00000000..c0499aee --- /dev/null +++ b/hack/testdata/netbox/mapping.json @@ -0,0 +1,68 @@ +{ + "cables": { + "1": { + "medium": "Power" + } + }, + "circuits": { + "1": { + "id": "Example-service", + "system": "example-service-owner", + "type": "transport" + } + }, + "demarcations": { + "1": { + "componentSource": "dcim/rear-ports/1" + } + }, + "devices": { + "1": { + "classification": "physical", + "placement": { + "scope": "RackMembership" + }, + "provider": "example-provider", + "serialMeaning": "providerHostID" + }, + "2": { + "classification": "physical", + "placement": { + "scope": "RackMembership" + }, + "serialMeaning": "unknown" + }, + "3": { + "classification": "physical", + "placement": { + "facility": "example-premises", + "scope": "Facility" + }, + "serialMeaning": "unknown" + } + }, + "facilities": [ + { + "displayName": "Example premises", + "name": "example-premises", + "source": "dcim/sites/1" + } + ], + "feeds": { + "1": { + "facility": "example-premises" + } + }, + "racks": { + "1": { + "facility": "example-premises" + } + }, + "revision": "example-reviewed-1", + "target": { + "application": "provider-inventory", + "namespace": "inventory", + "project": "example-provider", + "writer": "Flux" + } +} diff --git a/hack/testdata/netbox/snapshot.json b/hack/testdata/netbox/snapshot.json new file mode 100644 index 00000000..c839e5c0 --- /dev/null +++ b/hack/testdata/netbox/snapshot.json @@ -0,0 +1,209 @@ +{ + "errors": {}, + "objects": { + "circuits/circuit-terminations": [ + { + "circuit": { + "id": 1 + }, + "id": 1 + } + ], + "circuits/circuits": [ + { + "cid": "Example-service", + "id": 1 + } + ], + "dcim/cables": [ + { + "a_terminations": [ + { + "object_id": 1, + "object_type": "dcim.poweroutlet" + } + ], + "b_terminations": [ + { + "object_id": 1, + "object_type": "dcim.powerport" + } + ], + "id": 1, + "label": "Power 1" + } + ], + "dcim/console-ports": [], + "dcim/console-server-ports": [], + "dcim/device-bays": [], + "dcim/device-types": [ + { + "id": 1, + "manufacturer": { + "id": 1, + "name": "Example" + }, + "model": "Example physical model" + } + ], + "dcim/devices": [ + { + "asset_tag": "asset-001", + "device_type": { + "id": 1 + }, + "id": 1, + "name": "Example server", + "position": 1, + "rack": { + "id": 1 + }, + "serial": "provider-001" + }, + { + "device_type": { + "id": 1 + }, + "id": 2, + "name": "Example PDU", + "rack": { + "id": 1 + } + }, + { + "device_type": { + "id": 1 + }, + "id": 3, + "name": "Example panel" + }, + { + "device_type": { + "model": "netactuate VM" + }, + "id": 4, + "name": "Example VM" + } + ], + "dcim/front-ports": [ + { + "device": { + "id": 3 + }, + "id": 1, + "name": "front-1", + "rear_port": { + "id": 1 + }, + "rear_port_position": 1 + } + ], + "dcim/interfaces": [ + { + "device": { + "id": 1 + }, + "id": 1, + "name": "eth0", + "type": "1000base-t" + }, + { + "device": { + "id": 1 + }, + "id": 2, + "name": "bond0", + "type": "lag" + } + ], + "dcim/inventory-items": [], + "dcim/locations": [ + { + "id": 1, + "name": "Example room" + } + ], + "dcim/manufacturers": [ + { + "id": 1, + "name": "Example" + } + ], + "dcim/modules": [], + "dcim/power-feeds": [ + { + "amperage": 30, + "id": 1, + "name": "Feed A", + "power_panel": { + "id": 1 + }, + "rack": { + "id": 1 + }, + "supply": "ac", + "voltage": 208 + } + ], + "dcim/power-outlets": [ + { + "device": { + "id": 2 + }, + "id": 1, + "name": "outlet-1", + "power_port": { + "id": 2 + } + } + ], + "dcim/power-panels": [ + { + "id": 1, + "name": "Panel A" + } + ], + "dcim/power-ports": [ + { + "device": { + "id": 1 + }, + "id": 1, + "name": "PSU1" + }, + { + "device": { + "id": 2 + }, + "id": 2, + "name": "inlet" + } + ], + "dcim/racks": [ + { + "id": 1, + "name": "Example rack", + "u_height": 42 + } + ], + "dcim/rear-ports": [ + { + "device": { + "id": 3 + }, + "id": 1, + "name": "rear-1", + "positions": 2 + } + ], + "dcim/sites": [ + { + "id": 1, + "name": "Example metro grouping" + } + ] + }, + "observedAt": "2026-11-20T12:00:00Z", + "source": "example-netbox", + "version": 1 +} diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 3f498f83..ae30e735 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -55,8 +55,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestInventoryCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 2 || crds["DeviceClaim"] == nil || crds["Device"] == nil { - t.Fatalf("got CRDs %v, want exactly DeviceClaim and Device", crds) + if len(crds) != 6 || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got %d CRDs, want six physical 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 { @@ -188,13 +188,13 @@ func TestValidRecordsAreAccepted(t *testing.T) { } } -func TestClaimDoesNotRequireSerialAndDefaultsHeight(t *testing.T) { +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 != int64(1) { - t.Fatalf("height defaulted to %v", height) + 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) } } diff --git a/internal/api/inventory/v1alpha1/physical.go b/internal/api/inventory/v1alpha1/physical.go new file mode 100644 index 00000000..c50f6451 --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical.go @@ -0,0 +1,175 @@ +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"` +} + +type ModelShape struct { + HeightUnits *float64 `json:"heightUnits,omitempty"` + FullDepth *bool `json:"fullDepth,omitempty"` +} + +type SourceReference struct { + ExternalReference `json:",inline"` + SnapshotDigest string `json:"snapshotDigest"` + MappingRevision string `json:"mappingRevision"` + ObservedAt metav1.Time `json:"observedAt"` +} + +type PhysicalMetadata struct { + DisplayName string `json:"displayName"` + Provenance Provenance `json:"provenance"` +} + +type FacilitySpec struct { + PhysicalMetadata `json:",inline"` + LocationRef *LocalReference `json:"locationRef,omitempty"` +} + +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"` + SourceRef *ExternalReference `json:"sourceRef,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..8229849b --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -0,0 +1,152 @@ +package v1alpha1 + +import ( + "encoding/json" + "os" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func TestSyntheticNetBoxHandoffPassesAdmission(t *testing.T) { + data, err := os.ReadFile("../../../../hack/testdata/netbox/candidates.json") + if err != nil { + t.Fatal(err) + } + var list struct { + Items []json.RawMessage `json:"items"` + } + if err := json.Unmarshal(data, &list); err != nil { + t.Fatal(err) + } + for _, raw := range list.Items { + var record map[string]any + if err := json.Unmarshal(raw, &record); err != nil { + t.Fatal(err) + } + kind := record["kind"].(string) + if errs := admit(t, kind, object(t, record), nil); len(errs) != 0 { + t.Fatalf("%s: %v", kind, errs) + } + } +} + +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) + } + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + 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 + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + 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", Provenance: provenance(recordedAt)} + 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 TestObservationalIdentityAndComponentSafety(t *testing.T) { + device := syntheticDevice() + device.Spec.Interfaces = nil + device.Spec.TopologyAuthority = "Cable" + device.Spec.Identity.Serial, device.Spec.Identity.SystemUUID = "", "" + source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} + device.Spec.Identity.SourceIdentity = &source + device.Spec.Provenance.Method = "NetBoxImport" + device.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:" + strings.Repeat("a", 64), MappingRevision: "example-1", ObservedAt: metav1.NewTime(recordedAt)} + 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.Provenance.Source.ID = "2" + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, candidate), object(t, device)); len(errs) == 0 { + t.Fatal("accepted source identity takeover") + } + 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/types.go b/internal/api/inventory/v1alpha1/types.go index 66351684..eb77dfb1 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -1,8 +1,8 @@ -// Package v1alpha1 holds a minimal subset of the proposed physical inventory -// API in fleet.datumapis.com: DeviceClaim, the installation plan for one slot, -// and Device, the actual asset bound to a claim. +// 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. // -// Both are operator-written records. Neither has a controller. Registering a +// 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. @@ -29,11 +29,11 @@ type Provenance struct { RecordedAt metav1.Time `json:"recordedAt"` // Reference is an optional, opaque pointer to where the facts came from. // Fleet does not interpret it. - Reference string `json:"reference,omitempty"` + Reference string `json:"reference,omitempty"` + Source *SourceReference `json:"source,omitempty"` } -// DeviceClaim is the plan for one physical slot, written by the installation -// planner before hardware arrives. The slot outlives any one Device. +// DeviceClaim retains legacy slot plans and typed observational installations. type DeviceClaim struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -42,6 +42,9 @@ type DeviceClaim struct { } type DeviceClaimSpec struct { + DisplayName string `json:"displayName,omitempty"` + Lifecycle string `json:"lifecycle,omitempty"` + CableRefs []LocalReference `json:"cableRefs,omitempty"` Provenance Provenance `json:"provenance"` ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` Placement Placement `json:"placement"` @@ -56,14 +59,17 @@ type ExpectedIdentity struct { Serial string `json:"serial,omitempty"` } -// Placement is the planned mount: the lowest occupied rack unit, the number of -// units, and the face. Facility and Rack are names until those kinds exist. +// Placement retains legacy text placement or an explicit typed scope. type Placement struct { - Facility string `json:"facility"` - Rack string `json:"rack"` - Position int32 `json:"position"` - Height int32 `json:"height,omitempty"` - Face string `json:"face"` + 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 string `json:"face,omitempty"` } // ExpectedPort is a planned physical port and the cable peer it should reach. @@ -95,11 +101,19 @@ type Device struct { } type DeviceSpec struct { - ClaimRef LocalReference `json:"claimRef"` - Provenance Provenance `json:"provenance"` - Identity DeviceIdentity `json:"identity"` - BMC *BMC `json:"bmc,omitempty"` - Interfaces []Interface `json:"interfaces,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"` + Provenance Provenance `json:"provenance"` + 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"` @@ -110,11 +124,12 @@ type LocalReference struct { } // DeviceIdentity is the detected chassis identity. Serial and SystemUUID are -// matching evidence, not authenticators. At least one is required. +// matching evidence, not authenticators. Imports can instead retain source identity. type DeviceIdentity struct { - Manufacturer string `json:"manufacturer,omitempty"` - Model string `json:"model"` - Serial string `json:"serial,omitempty"` + SourceIdentity *ExternalReference `json:"sourceIdentity,omitempty"` + 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"` } @@ -148,7 +163,7 @@ type DeviceList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}) + s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}, &Facility{}, &FacilityList{}, &Rack{}, &RackList{}, &Cable{}, &CableList{}, &PowerFeed{}, &PowerFeedList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } diff --git a/ui/provider/README.md b/ui/provider/README.md index 3514062f..eccd8ba6 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -26,15 +26,16 @@ Operations in the navigation. The page has three tabs: missing claim are listed separately. `inventory/:namespace/:claim` shows one claim's planned placement, expected ports and peers, and provenance. It also shows every Device bound to it: model, serial, system UUID, BMC endpoint, - interfaces, unmapped MACs and provenance, with the most recently recorded - Device as the current one. Operators write these records through GitOps; the + interfaces, typed components, separate asset tags/provider IDs, unmapped MACs + and provenance. Multiple historical Devices keep the active binding Unknown; + edit time does not establish current hardware. Operators write through GitOps; the plugin never writes them. The portal proxy forwards the staff member's own token, so creating capacity, profiles and classes needs a Bare Metal role with `machinecapacities.create`, `machineprofiles.create` and `machineclasses.create` in the provider project, -such as `metal.datumapis.com-provider`. The Inventory tab needs `deviceclaims.list` -and `devices.list` in `fleet.datumapis.com`, which +such as `metal.datumapis.com-provider`. The Inventory tab needs list access to +all six physical kinds in `fleet.datumapis.com`, which `fleet.datumapis.com-inventory-viewer` grants; metal roles grant no inventory access. Errors show inside the create dialog, because staff-portal does not share its toast module with plugins. @@ -86,6 +87,14 @@ to that array instead. ## Differences from the consumer plugin +The read-only Inventory tab now loads all six physical inventory collections +with pagination. It retains unknown placement and ambiguous historical bindings, +shows Facility/Rack/Cable/PowerFeed relationships and typed asset components, +and supports local-only review of import reports. These reads require the +provider-scoped inventory viewer role, not a consumer Metal role. See the +[physical import operator guide](../../docs/operations/netbox-physical-import.md) +for the offline Flux handoff and the distinction between records and readiness. + - staff-portal runs react-router 7, so this plugin pins it for types and shares it with `requiredVersion: false`. - staff-portal shares only the `badge`, `button`, `card`, `icons` and diff --git a/ui/provider/src/components/inventory-table.tsx b/ui/provider/src/components/inventory-table.tsx index f8552506..8076ad40 100644 --- a/ui/provider/src/components/inventory-table.tsx +++ b/ui/provider/src/components/inventory-table.tsx @@ -17,10 +17,11 @@ function matchesSearch(slot: InventorySlot, search: string): boolean { const { claim } = slot; return [ claim.metadata.name, + claim.spec.displayName, placementLabel(claim), modelLabel(claim.spec.expectedIdentity), claim.spec.expectedIdentity.serial, - ...slot.devices.flatMap((d) => [d.metadata.name, d.spec.identity.serial, d.spec.identity.systemUUID]), + ...slot.devices.flatMap((d) => [d.metadata.name, d.spec.displayName, d.spec.assetTag, d.spec.providerHostRef?.id, d.spec.identity.serial, d.spec.identity.systemUUID]), ] .filter(Boolean) .join(' ') @@ -38,7 +39,7 @@ export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: - {row.original.claim.metadata.name} + {row.original.claim.spec.displayName ?? row.original.claim.metadata.name} ), }, @@ -53,7 +54,7 @@ export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: header: 'Device', cell: ({ row }) => { const device = currentDevice(row.original); - if (!device) return Not registered; + if (!device) return {row.original.devices.length > 1 ? 'Active binding Unknown' : 'Not registered'}; return {device.metadata.name}; }, }, diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx new file mode 100644 index 00000000..dcd255a2 --- /dev/null +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -0,0 +1,28 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { PhysicalInventory } from './physical-inventory'; +import { toInventory, placementLabel } from '../inventory'; +import { fixtureDeviceClaims } from '../lib/fixtures'; + +describe('physical inventory', () => { + it('keeps partial placement and free space unknown', () => { + const claim = { ...fixtureDeviceClaims[0], spec: { ...fixtureDeviceClaims[0].spec, placement: { scope: 'RackMembership' as const, rackRef: { name: 'rack-example' } } } }; + expect(placementLabel(claim)).toContain('no reserved units'); + const inventory = toInventory([claim], [], [{ kind: 'Rack', metadata: { name: 'rack-example', namespace: 'default' }, spec: { displayName: 'Rack example', facilityRef: { name: 'example' }, provenance: claim.spec.provenance } }]); + render(); + expect(screen.getByText(/Free space: Unknown/)).toBeInTheDocument(); + expect(screen.queryByText(/1 registered assets/)).not.toBeInTheDocument(); + expect(screen.getByText(/0 registered assets; occupancy unverified/)).toBeInTheDocument(); + }); + + it('reads reconciliation locally and rejects malformed reports', async () => { + render(); + const input = screen.getByLabelText(/Inspect a private import report/); + fireEvent.change(input, { target: { files: [{ size: 100, text: async () => JSON.stringify({ version: 1, records: [{ source: 'dcim/devices/1', classification: 'unresolved', reason: 'Review premises' }] }) }] } }); + await waitFor(() => expect(screen.getByText(/dcim\/devices\/1: unresolved/)).toBeInTheDocument()); + expect(screen.getByText(/Incomplete or Unknown/)).toBeInTheDocument(); + fireEvent.change(input, { target: { files: [{ size: 100, text: async () => '{"version":1,"records":[null]}' }] } }); + await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument()); + expect(screen.queryByText(/dcim\/devices\/1: unresolved/)).not.toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx new file mode 100644 index 00000000..0c032dca --- /dev/null +++ b/ui/provider/src/components/physical-inventory.tsx @@ -0,0 +1,59 @@ +import type { Inventory } from '../inventory'; +import type { CableEndpoint } from '../../../shared/fleet-api'; +import { useState } from 'react'; + +export function endpointLabel(endpoint: CableEndpoint): string { + return `${endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? 'Unknown'}/${endpoint.componentID}:${endpoint.position}`; +} + +export function PhysicalInventory({ inventory }: { inventory: Inventory }) { + const [report, setReport] = useState<{ source: string; classification: string; reason: string }[]>([]); + const [error, setError] = useState(''); + const [summary, setSummary] = useState<{ complete: boolean; errors: string[]; missing: string[] }>(); + const [search, setSearch] = useState(''); + const matching = report.filter((row) => `${row.source} ${row.classification} ${row.reason}`.toLowerCase().includes(search.toLowerCase())); + return
+

Physical records · verification Unknown

+

Observational records do not reserve space, establish an active binding, or authorize hardware operations. Cable is the typed topology authority; legacy inline peers remain unmigrated history.

+ + {error &&

{error}

} + {summary &&

Import reconciliation — candidates, not applied records

+

Collection fetch: {summary.complete ? 'Complete (not physical parity)' : 'Incomplete or Unknown'} · {report.length} classified records

+
    {summary.errors.map((message) =>
  • {message}
  • )}
+

Missing source records are retained, never deleted: {summary.missing.length}

+
    {summary.missing.map((identity, index) =>
  • {identity}
  • )}
+ +

Showing {Math.min(matching.length, 250)} of {matching.length} matching rows

+
    {matching.slice(0, 250).map((row) =>
  • {row.source}: {row.classification} — {row.reason}
  • )}
+
} + {inventory.physical.map((record) =>
+ {record.kind}: {record.spec.displayName} ({record.metadata.name}) +

Namespace: {record.metadata.namespace} · Source: {record.spec.provenance.method} · Verification: Unknown

+ {record.spec.provenance.source &&

Source object: {record.spec.provenance.source.system}/{record.spec.provenance.source.type}/{record.spec.provenance.source.id} · Mapping: {record.spec.provenance.source.mappingRevision}

} + {record.spec.facilityRef &&

Facility: {record.spec.facilityRef.name}

} + {record.spec.rackRef &&

Rack: {record.spec.rackRef.name}

} + {record.spec.locationRef &&

Geographic location reference: {record.spec.locationRef.name}

} + {record.kind === 'Rack' &&

Height: {record.spec.heightUnits ?? 'Unknown'} · Free space: Unknown

} + {record.spec.lanes?.map((lane) =>

{lane.id}: {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)} ({record.spec.medium})

)} + {record.kind === 'PowerFeed' &&

Supply: {record.spec.supply?.type ?? 'Unknown'} · Voltage: {record.spec.supply?.voltageV ?? 'Unknown'} V · Current rating: {record.spec.supply?.currentA ?? 'Unknown'} A · Usable budget and redundancy: Unknown

} + {record.spec.upstreamSources?.map((source) =>

Upstream: {source.system}/{source.type}/{source.id}

)} +
    {inventory.slots.filter((slot) => slot.claim.metadata.namespace === record.metadata.namespace && (slot.claim.spec.placement.rackRef?.name === record.metadata.name && record.kind === 'Rack' || slot.claim.spec.placement.facilityRef?.name === record.metadata.name && record.kind === 'Facility')).map((slot) =>
  • {slot.claim.metadata.name} — {slot.devices.length} registered assets; occupancy unverified
  • )}
+
)} +
; +} diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts index 4581e800..b938ceab 100644 --- a/ui/provider/src/inventory.test.ts +++ b/ui/provider/src/inventory.test.ts @@ -19,7 +19,7 @@ describe('toInventory', () => { expect(inventory.unboundDevices).toHaveLength(1); }); - it('treats the most recently recorded Device as the current hardware', () => { + it('does not infer active hardware from the most recently edited record', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, @@ -28,7 +28,7 @@ describe('toInventory', () => { const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; expect(u12.devices).toHaveLength(2); - expect(currentDevice(u12)?.metadata.name).toBe('rack-01-u12-synthetic-0002'); + expect(currentDevice(u12)).toBeUndefined(); }); it('labels single and multi-unit placements', () => { diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index cceed449..54b8efc5 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -2,7 +2,7 @@ // Device that names it in the same namespace; a replacement leaves more than // one. Devices whose claim is missing are kept separately so they stay visible. -import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List } from '../../shared/fleet-api'; +import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List, PhysicalRecord } from '../../shared/fleet-api'; export type { RawDevice, RawDeviceClaim }; export type RawDeviceList = List; @@ -17,6 +17,7 @@ export interface InventorySlot { export interface Inventory { slots: InventorySlot[]; unboundDevices: RawDevice[]; + physical: PhysicalRecord[]; } export function slotKey(namespace: string | undefined, name: string): string { @@ -27,7 +28,7 @@ function byRecordedAt(a: RawDevice, b: RawDevice): number { return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); } -export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[]): Inventory { +export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], physical: PhysicalRecord[] = []): Inventory { const slots = new Map(); for (const claim of claims) { const key = slotKey(claim.metadata.namespace, claim.metadata.name); @@ -41,22 +42,27 @@ export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[]): Inv } for (const slot of slots.values()) slot.devices.sort(byRecordedAt); return { + physical, slots: [...slots.values()].sort((a, b) => a.key.localeCompare(b.key)), unboundDevices: unboundDevices.sort((a, b) => a.metadata.name.localeCompare(b.metadata.name)), }; } export function placementLabel(claim: RawDeviceClaim): string { - const { facility, rack, position, height = 1, face } = claim.spec.placement; + const { facility, rack, position, height = 1, face, scope, facilityRef, rackRef, mount } = claim.spec.placement; + if (scope === 'Facility') return `${facilityRef?.name} · rack and position Unknown`; + if (scope === 'RackMembership') return `${rackRef?.name} · position Unknown (no reserved units)`; + if (scope === 'NonRackUnitMount') return `${rackRef?.name} · mount ${mount}`; + if (position === undefined) return 'Placement Unknown'; const units = height > 1 ? `U${position}–U${position + height - 1}` : `U${position}`; - return `${facility} · ${rack} · ${units} ${face}`; + return `${facility ?? 'Facility via rack'} · ${rack ?? rackRef?.name} · ${units} ${face}`; } export function modelLabel(identity: { manufacturer?: string; model: string }): string { return identity.manufacturer ? `${identity.manufacturer} ${identity.model}` : identity.model; } -// The newest Device bound to a slot is the one currently recorded there. +// Multiple historical registrations cannot establish the active binding. export function currentDevice(slot: InventorySlot): RawDevice | undefined { - return slot.devices.at(-1); + return slot.devices.length === 1 ? slot.devices[0] : undefined; } diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index 5937bda1..9e8cf42f 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -1,5 +1,6 @@ import { fixtureClasses, fixtureCapacities, fixtureDeviceClaims, fixtureDevices, fixtureProfiles } from './fixtures'; import { toInventory, type Inventory, type RawDeviceClaimList, type RawDeviceList } from '../inventory'; +import type { List, PhysicalRecord } from '../../../shared/fleet-api'; import { toMachineCapacity, toMachineClass, @@ -261,11 +262,26 @@ export function useDeleteMachineClass(): UseMutationResult { if (USE_FIXTURES) return toInventory(fixtureDeviceClaims, fixtureDevices); - const [claims, devices] = await Promise.all([ - proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/deviceclaims?limit=500`), - proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/devices?limit=500`), + const [claims, devices, ...physical] = await Promise.all([ + fetchInventoryCollection[number]>('deviceclaims'), + fetchInventoryCollection[number]>('devices'), + ...['facilities', 'racks', 'cables', 'powerfeeds'].map((kind) => fetchInventoryCollection(kind)), ]); - return toInventory(claims.items ?? [], devices.items ?? []); + return toInventory(claims, devices, physical.flat()); +} + +export async function fetchInventoryCollection(plural: string): Promise { + const items: T[] = []; + const seen = new Set(); + let continuation = ''; + do { + const page = await proxyFetch & { metadata?: { continue?: string } }>(PROVIDER_PROJECT, `${INVENTORY_API}/${plural}?limit=500${continuation ? `&continue=${encodeURIComponent(continuation)}` : ''}`); + items.push(...(page.items ?? [])); + continuation = page.metadata?.continue ?? ''; + if (continuation && seen.has(continuation)) throw new ApiError(502, 'Inventory pagination repeated; completeness Unknown'); + seen.add(continuation); + } while (continuation); + return items; } export function useInventory(): UseQueryResult { diff --git a/ui/provider/src/lib/inventory-api.test.ts b/ui/provider/src/lib/inventory-api.test.ts new file mode 100644 index 00000000..16e68802 --- /dev/null +++ b/ui/provider/src/lib/inventory-api.test.ts @@ -0,0 +1,33 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fetchInventory, fetchInventoryCollection } from './api'; + +afterEach(() => vi.unstubAllGlobals()); + +function response(data: unknown, status = 200) { + return { ok: status === 200, status, json: async () => ({ data }) }; +} + +describe('physical inventory reads', () => { + it('reads every page with the project proxy and only GET', async () => { + const fetch = vi.fn().mockResolvedValueOnce(response({ items: [{ id: 1 }], metadata: { continue: 'opaque+/=' } })).mockResolvedValueOnce(response({ items: [{ id: 2 }] })); + vi.stubGlobal('fetch', fetch); + expect(await fetchInventoryCollection('racks')).toEqual([{ id: 1 }, { id: 2 }]); + expect(fetch.mock.calls[1][0]).toContain('continue=opaque%2B%2F%3D'); + expect(fetch.mock.calls[0][0]).toContain('/projects/datum-cloud/control-plane/'); + expect(fetch.mock.calls.every((call) => call[1].method === 'GET')).toBe(true); + }); + + it('does not treat a pagination cycle as complete', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ items: [], metadata: { continue: 'repeat' } }))); + await expect(fetchInventoryCollection('racks')).rejects.toThrow('completeness Unknown'); + }); + + it('requires all six collections and propagates restricted errors', async () => { + const fetch = vi.fn().mockResolvedValue(response({ items: [] })); + vi.stubGlobal('fetch', fetch); + expect((await fetchInventory()).physical).toEqual([]); + expect(fetch).toHaveBeenCalledTimes(6); + fetch.mockResolvedValue(response(undefined, 403)); + await expect(fetchInventory()).rejects.toMatchObject({ status: 403 }); + }); +}); diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index 465c667e..bd00eda0 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -1,4 +1,5 @@ import { FleetPage } from '../components/fleet-page'; +import { endpointLabel } from '../components/physical-inventory'; import { ErrorOrRestrictedState, LoadingState } from '../components/states'; import { StatusBadge } from '../components/status-badge'; import { PROVIDER_PROJECT, useInventory } from '../lib/api'; @@ -35,6 +36,7 @@ function ProvenanceFields({ provenance }: { provenance: Provenance }) { {provenance.recordedBy} {provenance.recordedAt} {provenance.method} + {provenance.source && {provenance.source.system}/{provenance.source.type}/{provenance.source.id} · mapping {provenance.source.mappingRevision} · observed {provenance.source.observedAt} · verification Unknown} {provenance.reference && (
{provenance.reference} @@ -48,14 +50,21 @@ function DeviceSection({ device, current }: { device: RawDevice; current: boolea const { identity, bmc, interfaces = [], unmappedMACAddresses = [] } = device.spec; return (
- {!current && Earlier hardware for this slot} + {!current && Historical binding; active placement Unknown}
{modelLabel(identity)} + {device.spec.displayName ?? device.metadata.name} + {device.spec.modelShape?.heightUnits ?? 'Unknown'} U {identity.serial ?? '—'} {identity.systemUUID ?? '—'} {bmc?.endpoint ?? '—'} {device.spec.claimRef.name} + {device.spec.assetTag ?? 'Unknown'} + {device.spec.providerHostRef ? `${device.spec.providerHostRef.system}/${device.spec.providerHostRef.id}` : 'Unknown'}
+ {device.spec.components?.map((component) => {component.name} ({component.type}) · {component.id} · connector {component.connector ?? 'Unknown'})} + {device.spec.internalMappings?.map((mapping) => Internal path: {mapping.from.componentID}:{mapping.from.position} → {mapping.to.componentID}:{mapping.to.position})} + {device.spec.serviceAssociations?.map((association) => Demarcation {association.componentID} → {association.serviceRef.system}/{association.serviceRef.type}/{association.serviceRef.id})} {interfaces.length > 0 && (
Interfaces @@ -117,7 +126,7 @@ export default function DeviceClaimDetail() { {slot.claim.spec.expectedIdentity.serial ?? '—'} {slot.claim.metadata.namespace ?? '—'} - {current ? current.metadata.name : Not registered} + {current ? current.metadata.name : {slot.devices.length > 1 ? 'Multiple records; active binding Unknown' : 'Not registered'}}
{(slot.claim.spec.ports ?? []).length > 0 && ( @@ -137,6 +146,10 @@ export default function DeviceClaimDetail() { {[...slot.devices].reverse().map((device) => ( ))} +
+ {data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
{cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)})}
)} + No displayed path proves an uncabled or free termination. +
)} diff --git a/ui/provider/src/pages/device-inventory-list.tsx b/ui/provider/src/pages/device-inventory-list.tsx index ecaad7a4..c17b2655 100644 --- a/ui/provider/src/pages/device-inventory-list.tsx +++ b/ui/provider/src/pages/device-inventory-list.tsx @@ -1,4 +1,5 @@ import { FleetPage } from '../components/fleet-page'; +import { PhysicalInventory } from '../components/physical-inventory'; import { InventoryTable } from '../components/inventory-table'; import { ErrorOrRestrictedState, LoadingState } from '../components/states'; import { PROVIDER_PROJECT, useInventory } from '../lib/api'; @@ -14,10 +15,11 @@ export default function DeviceInventoryList() { const { slug } = useParams(); const base = `/plugins/${slug}`; const { data, isLoading, error, refetch } = useInventory(); - const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0; + const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0 && data.physical.length === 0; return ( + {!isLoading && !error && data && } {isLoading && } {!isLoading && error && ( diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 7745ad74..2e018184 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -112,7 +112,7 @@ describe('DeviceClaimDetail', () => { expect(screen.getByTestId('fleet-plugin-claim-missing')).toBeInTheDocument(); }); - it('lists earlier hardware after the current Device', () => { + it('preserves history without guessing an active replacement', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, @@ -120,7 +120,7 @@ describe('DeviceClaimDetail', () => { }; mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); - expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('rack-01-u12-synthetic-0002')).toBeInTheDocument(); - expect(within(screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001')).getByText('Earlier hardware for this slot')).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('Multiple records; active binding Unknown')).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001')).getByText('Historical binding; active placement Unknown')).toBeInTheDocument(); }); }); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 935c2d5f..3cbf6f06 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -237,10 +237,11 @@ export const INVENTORY_API_GROUP = 'fleet.datumapis.com'; export const INVENTORY_API_VERSION = 'v1alpha1'; export interface Provenance { - method: 'Manual'; + method: 'Manual' | 'NetBoxImport'; recordedBy: string; recordedAt: string; reference?: string; + source?: ExternalReference & { snapshotDigest: string; mappingRevision: string; observedAt: string }; } export interface PortPeer { @@ -255,7 +256,10 @@ export interface DeviceClaim { spec: { provenance: Provenance; expectedIdentity: { manufacturer?: string; model: string; serial?: string }; - placement: { facility: string; rack: string; position: number; height?: number; face: 'front' | 'rear' }; + lifecycle?: 'Installation'; + displayName?: string; + cableRefs?: LocalReference[]; + placement: { facility?: string; rack?: string; position?: number; height?: number; face?: 'front' | 'rear'; scope?: 'Facility' | 'RackMembership' | 'RackUnits' | 'NonRackUnitMount'; facilityRef?: LocalReference; rackRef?: LocalReference; mount?: string }; ports?: { name: string; type?: string; speedMbps?: number; expectedPeer?: PortPeer }[]; }; } @@ -267,9 +271,51 @@ export interface Device { spec: { claimRef: LocalReference; provenance: Provenance; - identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string }; + identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; + assetTag?: string; + displayName?: string; + modelShape?: { heightUnits?: number; fullDepth?: boolean }; + providerHostRef?: ExternalReference; + topologyAuthority?: 'Cable'; + components?: PhysicalComponent[]; + internalMappings?: { from: ComponentPosition; to: ComponentPosition }[]; + serviceAssociations?: { serviceRef: ExternalReference; componentID: string }[]; bmc?: { endpoint: string }; interfaces?: { name: string; macAddress?: string; peer?: PortPeer }[]; unmappedMACAddresses?: string[]; }; } + +export interface ExternalReference { system: string; type: string; id: string } +export interface ComponentPosition { componentID: string; position: number } +export interface PhysicalComponent { + id: string; + name: string; + type: 'NetworkPort' | 'PowerInlet' | 'PowerOutlet' | 'ConsolePort' | 'ConsoleServerPort' | 'FrontPort' | 'RearPort' | 'Module' | 'InventoryItem' | 'DeviceBay'; + connector?: string; + positions?: number; + serial?: string; + assetTag?: string; + sourceRef?: ExternalReference; +} +export interface CableEndpoint extends ComponentPosition { + deviceRef?: LocalReference; + powerFeedRef?: LocalReference; +} +export interface PhysicalRecord { + metadata: ObjectMeta; + kind: 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; + spec: { + displayName: string; + provenance: Provenance; + facilityRef?: LocalReference; + rackRef?: LocalReference; + locationRef?: LocalReference; + heightUnits?: number; + medium?: string; + lanes?: { id: string; a: CableEndpoint; b: CableEndpoint }[]; + supply?: { type: string; voltageV?: number; currentA?: number; phase?: string }; + terminations?: PhysicalComponent[]; + upstreamSources?: ExternalReference[]; + }; +} From 180e438006e0adae7a74511dfeb605a9ae9d0758 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 13:34:45 -0600 Subject: [PATCH 2/7] fix(manager): drain in-flight reconciles before project departure --- internal/manager/projects.go | 19 ++++++ internal/manager/projects_test.go | 97 +++++++++++++++++++++++++++++++ internal/manager/reconcilers.go | 6 +- 3 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 internal/manager/projects_test.go diff --git a/internal/manager/projects.go b/internal/manager/projects.go index aa67f387..d9948e06 100644 --- a/internal/manager/projects.go +++ b/internal/manager/projects.go @@ -41,6 +41,24 @@ type ProjectRuntime struct { Mappers Mappers Machine *LifecycleOwner Installation *LifecycleOwner + + reconcileMu sync.RWMutex + stopped bool +} + +func (r *ProjectRuntime) acquire() bool { + r.reconcileMu.RLock() + if r.stopped { + r.reconcileMu.RUnlock() + return false + } + return true +} + +func (r *ProjectRuntime) stop() { + r.reconcileMu.Lock() + defer r.reconcileMu.Unlock() + r.stopped = true } // ProjectResolver resolves an engaged cluster name to its immutable project @@ -125,6 +143,7 @@ func (p *Projects) Engage(ctx context.Context, name multicluster.ClusterName, cl } func (p *Projects) unbind(name multicluster.ClusterName, runtime *ProjectRuntime) { + runtime.stop() p.mu.Lock() defer p.mu.Unlock() if p.byCluster[name] != runtime { diff --git a/internal/manager/projects_test.go b/internal/manager/projects_test.go new file mode 100644 index 00000000..d16e73ba --- /dev/null +++ b/internal/manager/projects_test.go @@ -0,0 +1,97 @@ +package manager + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + + "go.datum.net/fleet/internal/controller" +) + +func TestProjectDepartureDrainsReconciliation(t *testing.T) { + for _, routed := range []bool{false, true} { + name := "direct" + if routed { + name = "dependency route" + } + t.Run(name, func(t *testing.T) { + identity := controller.ProjectIdentity{AuthorityID: testAuthority, RouteName: "east", UID: "east-project"} + consumer := newConsumer(t, "east", mcMachine("m", "machine", "general")) + started, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + defer unblock() + var calls atomic.Int32 + owner := NewLifecycleOwner(HandlerFunc(func(context.Context, ProjectRequest) Outcome { + if calls.Add(1) == 1 { + close(started) + <-release + } + return Outcome{} + }), BlockedHandler, nil) + runtime := &ProjectRuntime{ + Binding: ProjectBinding{ClusterName: "east", Project: identity}, + Verifier: ProjectVerifierFunc(func(context.Context, controller.ProjectIdentity) error { return nil }), + Mappers: Mappers{Reader: consumer.Client, Project: identity, ClusterName: "east"}, + Machine: owner, + } + projects := newProjects(nil, nil, nil) + projects.byCluster["east"] = runtime + projects.byProject[projectKey{identity.AuthorityID, identity.UID}] = multicluster.ClusterName("east") + selectOwner := func(runtime *ProjectRuntime) *LifecycleOwner { return runtime.Machine } + reconcile := func() error { + if routed { + _, err := (ClusterRouteReconciler{Projects: projects, Owner: selectOwner}).Reconcile(context.Background(), RouteRequest{ClusterName: "east", AuthorityID: identity.AuthorityID, ProjectUID: identity.UID, Kind: RouteProfile, Name: "general", UID: "profile", Deleted: true}) + return err + } + _, err := (ClusterProjectReconciler{Projects: projects, Owner: selectOwner}).Reconcile(context.Background(), ProjectRequest{ClusterName: "east", AuthorityID: identity.AuthorityID, ProjectUID: identity.UID, Namespace: "default", Name: "m", UID: "machine"}) + return err + } + done := make(chan error, 1) + go func() { done <- reconcile() }() + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("handler did not start") + } + departed := make(chan struct{}) + go func() { projects.unbind("east", runtime); close(departed) }() + select { + case <-departed: + t.Fatal("departure completed while a handler could still write") + case <-time.After(50 * time.Millisecond): + } + if projects.Get("east") != runtime { + t.Fatal("runtime removed before reconciliation drained") + } + unblock() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("reconciliation did not drain") + } + select { + case <-departed: + case <-time.After(5 * time.Second): + t.Fatal("departure did not finish") + } + if projects.Get("east") != nil || projects.ForProject(identity.AuthorityID, identity.UID) != nil { + t.Fatal("departed runtime still registered") + } + if err := reconcile(); err != nil || calls.Load() != 1 { + t.Fatalf("post-departure reconcile: error=%v calls=%d", err, calls.Load()) + } + if runtime.acquire() { + runtime.reconcileMu.RUnlock() + t.Fatal("a previously resolved runtime admitted work after departure") + } + }) + } +} diff --git a/internal/manager/reconcilers.go b/internal/manager/reconcilers.go index efe5d109..c4816ae3 100644 --- a/internal/manager/reconcilers.go +++ b/internal/manager/reconcilers.go @@ -97,9 +97,10 @@ func (r ClusterProjectReconciler) Reconcile(ctx context.Context, request Project return reconcile.Result{}, ErrEventWiringUnavailable } runtime := r.Projects.For(request) - if runtime == nil { + if runtime == nil || !runtime.acquire() { return reconcile.Result{}, nil } + defer runtime.reconcileMu.RUnlock() return ProjectReconciler{Project: runtime.Binding.Project, Handler: r.Owner(runtime), Verifier: runtime.Verifier}.Reconcile(ctx, request) } @@ -115,8 +116,9 @@ func (r ClusterRouteReconciler) Reconcile(ctx context.Context, request RouteRequ return reconcile.Result{}, ErrEventWiringUnavailable } runtime := r.Projects.Get(request.ClusterName) - if runtime == nil { + if runtime == nil || !runtime.acquire() { return reconcile.Result{}, nil } + defer runtime.reconcileMu.RUnlock() return RouteReconciler{Project: runtime.Binding.Project, Verifier: runtime.Verifier, Mappers: runtime.Mappers, Handler: r.Owner(runtime)}.Reconcile(ctx, request) } From 8007368aa787c6017e0b4f560b43250adaf79bdf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 13:34:45 -0600 Subject: [PATCH 3/7] fix(inventory): make manual migration the primary workflow --- docs/development/README.md | 20 ++- docs/operations/README.md | 2 +- docs/operations/netbox-physical-import.md | 50 ++++--- docs/operations/physical-inventory-staging.md | 127 ++++++++++++++++++ docs/operations/physical-inventory.md | 79 +++++++++-- docs/proposals/fleet-management/inventory.md | 6 +- hack/netbox_inventory.py | 12 +- hack/testdata/physical/manual.yaml | 94 +++++++++++++ .../api/inventory/v1alpha1/physical_test.go | 58 ++++++++ ui/provider/README.md | 6 +- .../components/physical-inventory.test.tsx | 22 ++- .../src/components/physical-inventory.tsx | 7 +- 12 files changed, 438 insertions(+), 45 deletions(-) create mode 100644 docs/operations/physical-inventory-staging.md create mode 100644 hack/testdata/physical/manual.yaml diff --git a/docs/development/README.md b/docs/development/README.md index e8900d73..6bf1c59a 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -184,7 +184,15 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no consumer set. It does not release custody, call a provider, delete records, or rewrite status, including for a project with active custody. Its deadlines and queued events are dropped, and re-engagement resumes from the - retained private records. + retained private records. Unbinding drains direct and dependency-route + reconciliations that already acquired the runtime before removing it from the + registry; a retained runtime pointer cannot start work after that barrier. + A blocked in-flight handler therefore delays completed departure rather than + falsely reporting it. This fixes an inherited race where informer removal and + registry removal could finish while a handler could still write. It does not + roll back effects already admitted before departure. Regression tests block a + handler explicitly and assert the barrier, in addition to the active-custody + no-write/no-release test. - **Observational discovery.** The provider declares no managed resources, teardowns, or suspend hooks, so it adds no ServiceConsumer finalizer. Its discovery clients refuse every write. The library would otherwise patch @@ -720,12 +728,14 @@ No metal role grants inventory access. The staff portal plugin's read-only Inventory tab pages through all six kinds, shows physical relationships and components, and can inspect a private import report locally. Multiple historical bindings remain ambiguous rather than being -resolved by edit time. Python's standard-library `hack/netbox_inventory.py` -exports sanitized GET-only NetBox snapshots and prepares an offline create-only -handoff to the existing Flux writer. Unit tests run API-server validation offline, +resolved by edit time. The primary workflow is [manual entry and review](../operations/physical-inventory.md#manually-record-a-small-installation) +through the existing Flux writer, with no NetBox dependency. The optional, +operator-invoked standard-library `hack/netbox_inventory.py` reads GET-only snapshots +and generates offline review candidates; it never applies, schedules, synchronizes, +deletes or changes Git. Unit tests run API-server validation offline, check IAM and exercise pagination, source conflicts, omissions and interrupted imports. See [safe NetBox evaluation](../operations/netbox-physical-import.md). -No live source coverage, deployed revision, physical verification, concurrent +No live source coverage, deployment of this physical extension, physical verification, concurrent reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run diff --git a/docs/operations/README.md b/docs/operations/README.md index 1f1fdf99..c229fb0d 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -18,7 +18,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | -| Review and import NetBox's physical side | [Safe physical snapshot and GitOps handoff](netbox-physical-import.md) | Six physical kinds, typed components and relationships, per-record coverage reports and additive handoff to the existing writer; no live import, readiness or provisioning | +| Optionally compare an existing NetBox source | [Operator-run snapshot and candidate review](netbox-physical-import.md) | Optional local review aids only; manual inventory needs no NetBox, automated migration or live import | | 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 | diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md index 7cac4a7c..150e0401 100644 --- a/docs/operations/netbox-physical-import.md +++ b/docs/operations/netbox-physical-import.md @@ -1,11 +1,19 @@ -# Evaluate NetBox physical inventory safely +# Optional NetBox review aids for manual inventory [Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) -This milestone provides six provider-project inventory kinds, read-only staff -browsing, a GET-only NetBox snapshot command, and an **offline, create-only GitOps -handoff**. It does not apply anything to Fleet or NetBox. It is not a verification, -reservation, adoption, enrollment, or provisioning controller. +Start with [manual entry and operator review](physical-inventory.md#manually-record-a-small-installation). +Physical inventory needs neither NetBox access nor a bulk importer. Operators +write and review records individually; Flux remains the sole staging writer. + +This guide covers **optional, explicitly invoked review aids**: a GET-only snapshot +command and offline candidate generation. They help compare an existing source +when an operator chooses to use it; they are not an automated migration. There +are no scheduled imports, discovery or sync controllers, background NetBox updates, +auto-apply or auto-delete. Neither command applies anything to Fleet or NetBox. +The retained `--handoff` option writes candidate files for human review only; it +does not hand execution to Flux, change Git, or transfer ownership. No verification, +reservation, adoption, enrollment, or provisioning controller is included. ## What exists and what remains unknown @@ -33,7 +41,7 @@ remain Unknown. Existing editor delete permissions are not a safe retirement API - Existing long-lived slot claims keep their names, text placement, ports, and historical Device bindings. Existing `Device.spec.identity` and `claimRef` remain immutable. MachineCapacity and its `deviceRef` are not modified. -- New imported claims use `lifecycle: Installation` and typed placement. This +- New manually entered or optionally generated claims use `lifecycle: Installation` and typed placement. This mode cannot be added to a legacy slot; an installation's placement is immutable. This is an observational installation record, **not** a reservation or an accepted plan. Moving an existing asset remains blocked on the proposal's @@ -107,7 +115,7 @@ physical-field allowlist and excludes URLs, comments, custom fields and config contexts. This intentionally is **not a lossless NetBox backup**. Exports still contain private asset identities, serials and topology and must stay outside Git. -## Start with the checked-in synthetic example +## Optionally compare the checked-in synthetic example Python 3 uses only the standard library. No provider SDK or cluster access is needed. Output directories must not already exist; files are mode 0600 inside @@ -121,7 +129,9 @@ python3 hack/netbox_inventory.py plan \ --output /private/tmp/fleet-physical-report-example ``` -Only `report.json` is emitted by default. Inspect every unresolved/unsupported +Only `report.json` is emitted by default. The historical `imported` classification +means an offline candidate was representable, **not that any record was applied**. +Inspect every unresolved/unsupported row; the example intentionally leaves a room mapping unresolved. Staff can open the report with the Inventory tab's local file picker; its contents are not uploaded. The portal shows restricted/loading/empty states, paginated collections, @@ -144,7 +154,11 @@ not bypass collection errors or target conflicts. The handoff emits candidate objects and a receipt containing the exact target plus source, mapping, Fleet snapshot and candidate digests. Nothing invokes kubectl apply or writes Git. -## Prepare a private real-data review +## Optional private source comparison + +Skip this entire section for manual entry. No NetBox credentials or parity audit +are required to evaluate the manual physical-inventory features. Only perform a +source comparison when separately requested and authorized by the operator. 1. Use existing read credentials: `NETBOX_TOKEN`, otherwise `NETBOX_TOKEN_FILE` (default `~/.config/netbox/token`). Never paste a token into arguments, logs, @@ -211,8 +225,11 @@ this feature does not modify them or their kubeconfig references. On 2026-11-20, read-only GitHub checks found both infra staging OCI sources configured for `v0.0.0-feat-manual-inventory-records`; the corresponding Fleet branch head was `42086bbe2cf05f5d09362fbc777e514907d64462`. This implementation is stacked there, -including the dependent PXE/runtime code. **Configured tag is not an observed -deployed revision.** No cluster rollout or live import was performed. +including the dependent PXE/runtime code. **That original configured-tag check +was not a deployed-revision observation.** A subsequent read-only staging API +check is recorded in the [staging baseline and acceptance checklist](physical-inventory-staging.md#read-only-baseline-observed-on-november-20-2026). +It observed the manual-inventory base, not this physical extension. No cluster +rollout or live import was performed. The documented environment/token-file paths did not provide authorized NetBox access in this implementation checkout. No live inventory audit was performed; @@ -221,12 +238,11 @@ unvalidated. Source interpretation comes from the pinned infra `d9198940a499be4e744ee0564cf3dc0b3bfcee34` loaders and site-build documents, as recorded in the [source evidence appendix](../proposals/fleet-management/inventory-reference.md#source-evidence-and-limits). -Before live evaluation, establish a private source audit, resolve required mappings, -render/install the six-kind schema in an explicitly approved environment, and -confirm authorized staff can browse while consumers cannot. Compare counts and -every classified row, test repeated and interrupted handoffs, and confirm original -Device/claim/Capacity identities remain unchanged. None of this establishes -physical qualification or safe capacity release. +For manual staging evaluation, use the [acceptance and rollback checklist](physical-inventory-staging.md). +If an operator separately chooses the optional source comparison, establish its +private audit and mappings, compare every classified row, and test repeated and +interrupted candidate generation. No live NetBox access means no claim of source +parity, not a blocker for manually entering and reviewing physical records. ```sh python3 -m unittest discover -s hack -p test_netbox_inventory.py diff --git a/docs/operations/physical-inventory-staging.md b/docs/operations/physical-inventory-staging.md new file mode 100644 index 00000000..ae80f318 --- /dev/null +++ b/docs/operations/physical-inventory-staging.md @@ -0,0 +1,127 @@ +# Evaluate manual physical inventory in staging + +[Manual entry and review](physical-inventory.md#manually-record-a-small-installation) · +[Optional source comparison](netbox-physical-import.md) + +This checklist is for an explicitly approved staging evaluation after independent +adversarial review. It is not approval to deploy or evidence of physical readiness. +No live imports, deployment, source-tag changes, hardware actions, or inventory +writes were performed during the implementation checks below. + +## Read-only baseline observed on November 20, 2026 + +The physical-inventory PR is stacked on `feat/manual-inventory-records` at +`42086bbe2cf05f5d09362fbc777e514907d64462`. Infrastructure configuration was read +at `3bde916629c7b6c49a6820bc40c2546bbf2afdc1`. Preserve that dependent base; +do not retarget the PR or mistake a new artifact publication for deployment. + +Read-only staging API queries on that date found: + +- Both `fleet-kustomize` and `fleet-inventory-kustomize` configured for + `v0.0.0-feat-manual-inventory-records`, with artifact digest + `sha256:45dfd12971b44a92d3d078007cfd41dcb23f4d278d17e3c5ea8f02c65d3f2fdc`. +- `fleet-milo-configuration` reporting Ready with that exact applied artifact. +- `fleet-provider-inventory` reporting Ready at the infrastructure revision above, + with `prune: false`, `deletionPolicy: Orphan`, and the private + `apps/fleet-system/staging/provider-inventory` source. +- Manager and provider/consumer UI Deployments referencing the manual-inventory + build ending `20261120-165214`, with one manager and two replicas of each UI ready. + +The three DeviceClaims and one Device in that applied Git source passed offline +creation and unchanged-update validation against the proposed six-kind schemas. +The source files were handled privately outside Git; no real identities were +added to public fixtures. Existing identity and claim-binding immutability also +have negative regression tests. This is schema compatibility, not a live-object +or hardware audit: the management-cluster project API route did not expose the +provider project, so direct live provider-record comparison remains an operator +acceptance step. No production project context was used as a substitute. + +## Acceptance gates for an authorized operator + +1. Require independent adversarial sign-off and successful CI for the exact PR + head. In particular, run both formerly optional manager envtest tests with real + Kubernetes binaries, not skips. Retain the reviewed head and artifact digests. +2. Re-read staging source and applied revisions, the provider project/namespace, + existing DeviceClaim/Device identities and bindings, and MachineCapacity + references through the established authorized project route. Keep a private + before-state. Stop if the baseline changed or the intended target is unclear. +3. Separately approve and review the infrastructure change that selects the exact + reviewed build. Preserve Flux ownership, provider-project placement, and + non-pruning inventory reconciliation. Apply the additive CRDs and IAM before + introducing new record kinds; retain old claims, Devices and capacity unchanged. +4. Manually prepare a small, separately approved cohort using the + [synthetic six-kind example](../../hack/testdata/physical/manual.yaml) as a shape + reference. Review premises, references and every cable endpoint. For new + records use `Installation`, typed components and Cable-only expected topology. + Include facility-only or rack-membership placement; missing units, electrical + budgets, verification and readiness must remain Unknown. Do not register an + asset without a genuine identity or manufacture a serial from a provider ID. +5. Review and merge individual records into the private provider-inventory Git + source; let Flux be the only API writer. No NetBox access, bulk conversion, + discovery, sync, or scheduled import is needed. No capacity, billing, IPAM, + routing, provisioning, hardware, customer-release or status changes are allowed. +6. Verify authorized staff can browse all six kinds, typed components, relationships, + partial placement and historical bindings. Confirm consumer identities cannot + read them and inventory roles cannot write status. Test denied and missing + references without treating them as empty or ready. Verify before/after immutable + bindings and capacity references privately, including across reconciliation retries. +7. Stop on mismatches, unknown execution or authorization failures. Record these as + unknown/failed acceptance, not readiness. Even successful acceptance establishes + only manual recordkeeping and restricted browsing, not qualification or eligibility. + +## Rollback without losing inventory + +- Record the last known-good manager/UI artifacts and Git revisions before the + approved rollout. Revert an unsuccessful application change through its existing + infrastructure GitOps source; do not patch a competing live writer. +- Do **not** blindly downgrade the six-kind schema to the two-kind base after new + data exists. Retain additive CRDs, typed fields and records until a separate + compatibility review proves any schema rollback preserves them. Older software + may not display the new records; missing UI visibility is not permission to delete. +- Keep `prune: false` and `deletionPolicy: Orphan`. Reverting an additive Git entry + alone does not delete its live object. Never delete/recreate an occupied Device, + rewrite its identity/claimRef, or release capacity to make rollback appear clean. +- If reconciliation is interrupted, inspect actual records and Flux state, retain + the before-state and unresolved work, and reconcile only the reviewed Git intent. + No automatic cleanup, readiness assertion or ownership handover follows a rollback. + +## Local validation + +Implementation checks passed `go test ./...`, `go test -race ./...` and `go vet +./...` with Kubernetes 1.37.0 envtest assets installed. Both named envtest cases +also passed an explicit uncached race run without skips. The departure regression +and existing active-custody test passed 50 repetitions under the race detector. +The new blocked-handler reproducer failed on the original manager for both direct +and dependency-route reconciliation; that manager code was unchanged from the +stack's base. No safety assertion or timeout was relaxed. + +The manual six-kind fixture, private Git-source compatibility checks, 24 optional +review-aid tests, 58 provider UI tests, 44 consumer UI tests, both UI typechecks and +builds, Milo packaging, all five CI Kustomize renders, overlay isolation, standalone +render/source/preflight and mocked smoke checks, multi-plane harness, shellcheck, +local documentation links and whitespace checks passed. The local Docker daemon +was unavailable, so `hack/test-standalone-build-context.sh` could not complete; +no real disposable standalone smoke was run locally. Require the fresh CI build +context and standalone-smoke gates, not the previous head's results. UI builds +retain non-fatal dependency/Module Federation warnings. + +```sh +export KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" +go test ./... +go test -race ./... +go vet ./... +go test -race ./internal/manager -run 'TestProjectDepartureDrainsReconciliation|TestDisengageWithActiveCustody' -count=50 +go test -race ./internal/manager -run '^(TestManagerEndToEndAgainstSyntheticMilo|TestConsumerDiscoveryIgnoresOtherServicesAndBacksOff)$' -count=1 -v +python3 -m unittest discover -s hack -p test_netbox_inventory.py +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider test +pnpm --dir ui/provider build +go run ./test/acceptance/milo/cmd validate --root . +kustomize build config/milo >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +There is no live NetBox parity claim. Optional snapshots and candidate conversion +remain solely to help an operator compare a source when separately requested; +they never apply records or change Git. Their synthetic tests are not a source audit. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 8e71398e..edab0661 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -11,14 +11,14 @@ 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 now has six operator-written kinds in `fleet.datumapis.com/v1alpha1`. -The [NetBox physical import and migration guide](netbox-physical-import.md) -describes the additive physical schema, typed components, partial placement, -same-namespace relationships, import reconciliation and current limits. The -manual examples below preserve the original long-lived-slot representation: +The primary workflow is **manual entry, operator review, and explicit GitOps +ownership**. NetBox, bulk conversion, and a source reconciliation service are not +required. The [optional NetBox comparison guide](netbox-physical-import.md) +describes a separately invoked review aid, not an automated migration. | Kind | What it is | Writer | | --- | --- | --- | -| `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | +| `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 existing GitOps writer | | `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | 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 | @@ -31,7 +31,7 @@ manual examples below preserve the original long-lived-slot representation: | Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and two IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Read-only **Inventory** tab in the Bare Metal provider plugin (`ui/provider`): a claim list and a per-claim detail page. | | Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds and synthetic importer output. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | -| Controllers | None. Offline import and staff browsing read the records; no reconciler accepts plans, verifies hardware, or publishes eligibility. | +| Controllers | None for inventory. Staff browsing is read-only; no reconciler accepts plans, verifies hardware, discovers or synchronizes NetBox, 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 @@ -105,7 +105,65 @@ 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. -## Example +## Manually record a small installation + +1. Choose the provider project and namespace, and inspect its existing private + inventory source. In staging, `fleet-provider-inventory` reconciles + `apps/fleet-system/staging/provider-inventory` with `prune: false` and + `deletionPolicy: Orphan`. Flux is the sole API writer. Do not run a parallel + `kubectl apply`, importer, scheduled job, or discovery controller. +2. Enter the Facility and Rack facts you actually know. Record the operator and + time with `provenance.method: Manual`. 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 is known, + 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 private Git diff with another operator. It must contain no status, + capacity publication, hardware action, deletion or ownership transfer. Submit + only the individually approved records through the established Flux source. + After reconciliation, compare the intended records with read-only API and + staff views. An interrupted or failed reconciliation is not readiness. + +The [complete synthetic six-record example](../../hack/testdata/physical/manual.yaml) +shows this workflow without NetBox 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 +``` + +## 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 @@ -208,7 +266,7 @@ 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 -imports use a distinct `Installation` lifecycle, but no automatic move or +typed records use a distinct `Installation` lifecycle, but no automatic move or replacement handover exists. Device identity and its original claimRef remain immutable. The [migration decisions](netbox-physical-import.md#compatibility-and-migration-decisions) explain why imports cannot delete/recreate or relabel legacy records to bypass this. @@ -216,8 +274,9 @@ explain why imports cannot delete/recreate or relabel legacy records to bypass t ## Applying the records `config/milo` installs the CRDs, ProtectedResources, and roles into Milo. Apply -claims and Devices into the provider project after those are established, -claims before the Devices that name them. Keep records with real serials, +operator-reviewed records through the provider project's established GitOps +source after those are established, claims before the Devices that name them. +Do not apply directly to staging; Flux remains its only writer. Keep records with real serials, UUIDs, MACs, endpoints, or cabling in the environment's private configuration, not in this repository. diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index 528827ac..69d4fcce 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -175,8 +175,10 @@ 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. -Import should preserve existing equipment identities, customer reservations and -history. Change the responsible writer one record type at a time. Do not delete +The current implementation uses manual entry and operator-controlled migration, +not automated import. NetBox and optional offline candidate review are not required. +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. diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py index 1d6f3686..c2072240 100644 --- a/hack/netbox_inventory.py +++ b/hack/netbox_inventory.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""GET-only NetBox snapshot and offline, create-only Fleet GitOps handoff.""" +"""Optional operator-run review aid: GET-only snapshots and offline candidates. + +Manual inventory entry needs neither NetBox nor this tool. Nothing is applied, +scheduled, synchronized, or deleted; an operator reviews every proposed record. +""" import argparse import copy @@ -656,18 +660,18 @@ def private_output(path): def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) subparsers = parser.add_subparsers(dest="command", required=True) - export = subparsers.add_parser("snapshot") + export = subparsers.add_parser("snapshot", help="explicitly read a private NetBox snapshot; optional") export.add_argument("--url", default=os.environ.get("NETBOX_URL", "https://netbox.datum-infra.net")) export.add_argument("--source", required=True) export.add_argument("--auth-scheme", choices=("Bearer", "Token"), default="Bearer") export.add_argument("--output", required=True) - plan = subparsers.add_parser("plan") + plan = subparsers.add_parser("plan", help="review a local snapshot offline; never apply records") plan.add_argument("--snapshot", required=True) plan.add_argument("--mapping") plan.add_argument("--existing") plan.add_argument("--previous") plan.add_argument("--output", required=True) - plan.add_argument("--handoff", action="store_true") + plan.add_argument("--handoff", action="store_true", help="also write optional review candidates; never apply, commit, or push") plan.add_argument("--allow-partial", action="store_true") args = parser.parse_args(argv) output = Path(args.output) diff --git a/hack/testdata/physical/manual.yaml b/hack/testdata/physical/manual.yaml new file mode 100644 index 00000000..e6c3dc81 --- /dev/null +++ b/hack/testdata/physical/manual.yaml @@ -0,0 +1,94 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Facility +metadata: + name: example-facility + namespace: default +spec: + displayName: Example premises + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Rack +metadata: + name: example-rack + namespace: default +spec: + displayName: Example rack + facilityRef: {name: example-facility} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +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}] + provenance: + method: Manual + recordedBy: planner@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +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} + provenance: + method: Manual + recordedBy: registrar@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +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} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +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} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go index 8229849b..4497c3dc 100644 --- a/internal/api/inventory/v1alpha1/physical_test.go +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -1,7 +1,10 @@ package v1alpha1 import ( + "bytes" "encoding/json" + "flag" + "io" "os" "strings" "testing" @@ -9,8 +12,63 @@ import ( 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) + provenance := spec["provenance"].(map[string]any) + if provenance["method"] != "Manual" || provenance["source"] != nil || record["status"] != nil { + t.Fatal("manual example must have no source dependency 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 TestSyntheticNetBoxHandoffPassesAdmission(t *testing.T) { data, err := os.ReadFile("../../../../hack/testdata/netbox/candidates.json") if err != nil { diff --git a/ui/provider/README.md b/ui/provider/README.md index eccd8ba6..fe7f6b4e 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -90,9 +90,11 @@ to that array instead. The read-only Inventory tab now loads all six physical inventory collections with pagination. It retains unknown placement and ambiguous historical bindings, shows Facility/Rack/Cable/PowerFeed relationships and typed asset components, -and supports local-only review of import reports. These reads require the +and supports optional local-only review of source-comparison reports. Manual +inventory needs no NetBox or report; operators review the private Git source and +Flux is the sole staging writer. The portal never writes or synchronizes records. These reads require the provider-scoped inventory viewer role, not a consumer Metal role. See the -[physical import operator guide](../../docs/operations/netbox-physical-import.md) +[optional source-comparison guide](../../docs/operations/netbox-physical-import.md) for the offline Flux handoff and the distinction between records and readiness. - staff-portal runs react-router 7, so this plugin pins it for types and diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index dcd255a2..a3e454fc 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -5,6 +5,25 @@ import { toInventory, placementLabel } from '../inventory'; import { fixtureDeviceClaims } from '../lib/fixtures'; describe('physical inventory', () => { + it('browses manual facilities, racks, cables and feeds without a source report', () => { + const provenance = fixtureDeviceClaims[0].spec.provenance; + const inventory = toInventory([], [], [ + { kind: 'Facility', metadata: { name: 'premises', namespace: 'default' }, spec: { displayName: 'Manual premises', provenance } }, + { kind: 'Rack', metadata: { name: 'rack', namespace: 'default' }, spec: { displayName: 'Manual rack', facilityRef: { name: 'premises' }, provenance } }, + { kind: 'PowerFeed', metadata: { name: 'feed', namespace: 'default' }, spec: { displayName: 'Manual feed', facilityRef: { name: 'premises' }, rackRef: { name: 'rack' }, provenance } }, + { kind: 'Cable', metadata: { name: 'cable', namespace: 'default' }, spec: { displayName: 'Manual cable', medium: 'Power', lanes: [{ id: 'power', a: { powerFeedRef: { name: 'feed' }, componentID: 'outlet', position: 1 }, b: { deviceRef: { name: 'server' }, componentID: 'psu', position: 1 } }], provenance } }, + ]); + render(); + for (const kind of ['Facility', 'Rack', 'PowerFeed', 'Cable']) { + expect(screen.getByText(new RegExp(`^${kind}: Manual`))).toBeInTheDocument(); + } + expect(screen.getByText(/feed\/outlet:1 ↔ server\/psu:1/)).toBeInTheDocument(); + expect(screen.getByText(/Usable budget and redundancy: Unknown/)).toBeInTheDocument(); + expect(screen.getAllByText(/Verification: Unknown/)).toHaveLength(4); + expect(screen.queryByText(/classified records/)).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /apply|sync|import|delete/i })).not.toBeInTheDocument(); + }); + it('keeps partial placement and free space unknown', () => { const claim = { ...fixtureDeviceClaims[0], spec: { ...fixtureDeviceClaims[0].spec, placement: { scope: 'RackMembership' as const, rackRef: { name: 'rack-example' } } } }; expect(placementLabel(claim)).toContain('no reserved units'); @@ -17,7 +36,8 @@ describe('physical inventory', () => { it('reads reconciliation locally and rejects malformed reports', async () => { render(); - const input = screen.getByLabelText(/Inspect a private import report/); + expect(screen.getByText(/NetBox and import reports are not required/)).toBeInTheDocument(); + const input = screen.getByLabelText(/Optional: inspect a private review report/); fireEvent.change(input, { target: { files: [{ size: 100, text: async () => JSON.stringify({ version: 1, records: [{ source: 'dcim/devices/1', classification: 'unresolved', reason: 'Review premises' }] }) }] } }); await waitFor(() => expect(screen.getByText(/dcim\/devices\/1: unresolved/)).toBeInTheDocument()); expect(screen.getByText(/Incomplete or Unknown/)).toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 0c032dca..e7e790f0 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -15,7 +15,8 @@ export function PhysicalInventory({ inventory }: { inventory: Inventory }) { return

Physical records · verification Unknown

Observational records do not reserve space, establish an active binding, or authorize hardware operations. Cable is the typed topology authority; legacy inline peers remain unmigrated history.

-