From cc047e3f86b4913a9b5891f1319db08d49cb9601 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 21:26:40 -0600 Subject: [PATCH 1/3] feat(site): Commission a server over Redfish Add the DeviceCommissioning worker. It inspects the server and checks its firmware with GETs only, stores that passing evidence, then boots the plan's burn-in image once over the network and reads its one result receipt. A resumed worker reuses the stored inspection, so nothing read after an effect becomes an inspection verdict. A mismatch, a failed or short burn-in, or an unhealthy server after burn-in is a proven Failed verdict. A plan whose burn-in image the site does not serve is refused before anything is sent. Burn-in is timed from the boot server's delivery of the image, not from power-on, so a slow firmware start or network boot cannot make an early-reporting image long enough. The Redfish client reads processors, memory, storage, network interfaces and the firmware inventory. Absent and Disabled memory does not count. Drives come from Storage, counted once however often they are linked, or from SimpleStorage when Storage yields no disk. The boot server passes the burn-in duration to the image, and the lab boot image gains a burn-in mode. Evidence names the approved plan reference, not a UID. The lab adapter reports each target's serial, no longer links the emulator's sample Storage drives, and serves a read-only firmware inventory, so a commissioning can pass against the lab. No site registers the worker yet. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 33 ++ docs/operations/redfish-lab.md | 6 +- hack/local-vm/init | 25 +- hack/redfish-lab/Containerfile | 2 +- hack/redfish-lab/firmware.json | 4 + hack/redfish-lab/fleet_lab_adapter.py | 39 ++ hack/redfish-lab/targets.json | 4 +- hack/redfish-lab/test_adapter.py | 16 + internal/redfish/hardware.go | 293 ++++++++++++++ internal/redfish/hardware_test.go | 18 + internal/site/redfishwork/boot.go | 6 +- internal/site/redfishwork/commissioning.go | 376 ++++++++++++++++++ .../site/redfishwork/commissioning_test.go | 318 +++++++++++++++ internal/site/redfishwork/kinds.go | 40 +- internal/site/redfishwork/kinds_test.go | 119 +++++- 15 files changed, 1282 insertions(+), 17 deletions(-) create mode 100644 hack/redfish-lab/firmware.json create mode 100644 internal/redfish/hardware.go create mode 100644 internal/redfish/hardware_test.go create mode 100644 internal/site/redfishwork/commissioning.go create mode 100644 internal/site/redfishwork/commissioning_test.go diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index e4783c87..aa341df2 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -909,6 +909,39 @@ which a test pins, because the coordinator lists every registered kind. The boot interface is fixed at `primary`, like the allocator's in every mode. +### The Redfish commissioning worker + +The Redfish worker for `DeviceCommissioning` is **implemented and inert**. It +is tested against a TLS BMC stub, and no site registers it yet. The lab +emulator's adapter reports each target's serial, its one disk and a firmware +inventory, which a local read with the worker's Redfish client matched to a +plan's hardware and firmware. + +- **Preflight.** It reads the system's identity, processors, memory, storage, + network interfaces and firmware inventory with GETs only, and compares them + with the plan and the admission snapshot. A mismatch is a `Failed` result + with nothing sent. The passing evidence is stored before burn-in sends + anything, and a resumed worker reuses it. +- **Health.** Only `Warning` or `Critical` is unhealthy. Redfish lets a + component omit its health, and an omitted health counts as healthy. +- **Disks.** Drives come from `Storage`, or from `SimpleStorage` when + `Storage` yields no disk, as on a BMC that links an empty `Storage` + collection. A drive may sit under the System or under a Chassis, and a + drive linked twice counts once. +- **Memory.** An `Absent` or `Disabled` module does not count. +- **Burn-in.** The site serves one burn-in image, and a plan that names + another digest is refused before anything is sent. The worker powers the + server off, arms a one-time network boot, powers it on once, and waits for + exactly one result receipt. The boot server passes the plan's duration to + the image. Burn-in starts when the boot server finished delivering the + image, not at power-on, so firmware start and the network boot do not + count. It ends when the worker journals the receipt. A burn-in that + reported before the plan's duration is a `Failed` result. The boot server + and the worker share the site's clock. +- **Evidence.** Strings the BMC supplies are cut to 128 bytes, and the + component lists are dropped before the verdict if the evidence would pass + the kind's limit. + ## Points for a person These need a decision before the increment that depends on them. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 0b099967..a52cf661 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -58,7 +58,7 @@ hardware. The 1.2.2 release was 14 months old at integration and is the newest release. The emulator tree is copied into the image **unmodified**. Configuration comes from Fleet files: `emulator-config.json`, an infragen `populate-config.json` -with one chassis and two Systems, and `targets.json`. The image ID, its registry +with one chassis and two Systems, `targets.json` and `firmware.json`. The image ID, its registry digest and the archive provenance are recorded in `evidence/image-id` and `evidence/redfish-upstream.json`. @@ -91,7 +91,9 @@ does not fork or patch upstream files. | `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | | `PowerState` read from libvirt on every System read | Adapter | | `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | -| `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` set from the lab target | Adapter | +| `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` and `SerialNumber` set from the lab target | Adapter | +| No `Storage` link on the lab Systems: upstream's sample `Storage` drives are not the target's disk, so commissioning reads the populated `SimpleStorage` device | Adapter | +| A read-only `UpdateService` and `FirmwareInventory` from `firmware.json`, synthetic versions upstream does not serve, so a commissioning plan's firmware baseline can be checked | Adapter | | Definition of the lab domains and the provisioning network, re-created with the same identity if the runtime loses them | Adapter | | Append-only request audit: method, path, status, principal class, client User-Agent, ResetType, boot override, effect and fault. It never records bodies or credentials. | Adapter | | `DELETE /redfish/v1/reset` and non-Redfish paths | Refused by the adapter | diff --git a/hack/local-vm/init b/hack/local-vm/init index 56c2d598..a3e9d0bf 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -10,7 +10,7 @@ modprobe virtio_pci modprobe virtio_blk modprobe ext4 mode=install -for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; esac; done +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; fleet.duration=*) duration=${arg#fleet.duration=};; esac; done [ ${#receipt} = 64 ] || /bin/busybox poweroff -f if [ "$mode" = wipe ]; then # Redfish-mode cleanup environment: zero the whole disk, then verify by @@ -33,6 +33,29 @@ if [ "$mode" = wipe ]; then sync exit 0 fi +if [ "$mode" = burnin ]; then + # Lab burn-in: read the whole disk, then keep every CPU busy for the plan's + # duration, then report the result. It writes nothing to the disk. A real + # burn-in image is operator policy; this one only proves the boot and + # receipt path. Tracing stops for the loop, so the console stays small. + trap '/bin/busybox poweroff -f' EXIT + case "$duration" in ''|*[!0-9]*) exit 1;; esac + result=passed + /bin/busybox dd if=/dev/vda of=/dev/null bs=4M || result=failed + set +x + cpus=$(grep -c ^processor /proc/cpuinfo) + end=$(($(cut -d. -f1 /proc/uptime) + duration)) + i=0 + while [ "$i" -lt "$cpus" ]; do + ( while [ "$(cut -d. -f1 /proc/uptime)" -lt "$end" ]; do /bin/busybox sha256sum /proc/meminfo >/dev/null; done ) & + i=$((i + 1)) + done + wait || result=failed + set -x + printf 'FLEET-BURNIN:%s:%s\n' "$receipt" "$result" + sync + exit 0 +fi [ "$mode" = install ] || /bin/busybox poweroff -f printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda # One line, in one write, once the disk is partitioned: the shell trace above diff --git a/hack/redfish-lab/Containerfile b/hack/redfish-lab/Containerfile index 90191e4c..51982003 100644 --- a/hack/redfish-lab/Containerfile +++ b/hack/redfish-lab/Containerfile @@ -9,7 +9,7 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-ins COPY requirements.lock /tmp/requirements.lock RUN pip install --no-cache-dir --no-deps --require-hashes -r /tmp/requirements.lock && rm /tmp/requirements.lock COPY --from=upstream . /opt/redfish-emulator -COPY emulator-config.json populate-config.json targets.json /etc/fleet-bmc/ +COPY emulator-config.json populate-config.json targets.json firmware.json /etc/fleet-bmc/ COPY fleet_lab_adapter.py test_adapter.py fake_virsh.py /opt/fleet-lab/ RUN chmod 755 /opt/fleet-lab/*.py ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 diff --git a/hack/redfish-lab/firmware.json b/hack/redfish-lab/firmware.json new file mode 100644 index 00000000..2a740369 --- /dev/null +++ b/hack/redfish-lab/firmware.json @@ -0,0 +1,4 @@ +[ + {"Id": "BMC", "Name": "Fleet lab BMC firmware", "Version": "1.2.2-fleet-lab.1"}, + {"Id": "BIOS", "Name": "Fleet lab system firmware", "Version": "lab-bios-1.0.0"} +] diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 3771b9ea..42497719 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -12,6 +12,9 @@ persistent libvirt domain per System, and PowerState read from libvirt; * Boot source override (Pxe or Hdd, Once) persisted like BMC NVRAM and consumed when the domain is started; + * a firmware inventory (UpdateService and FirmwareInventory) from + firmware.json, which upstream does not serve, so a commissioning plan's + firmware baseline can be checked against the lab; * an append-only request audit log (no bodies, no credentials), each entry naming the client's User-Agent so a check can tell readers apart; * bounded, one-shot lab fault injection driven by a state file. @@ -236,6 +239,13 @@ def create_app(targets, state, credentials, boot_ip): def publish(sid, power=None): m = cs.members[sid] m['UUID'] = targets[sid]['uuid'] + # The serial the target's synthetic Device records, so commissioning + # can match the chassis to the Device. + m['SerialNumber'] = targets[sid]['serial'] + # The target's one disk is the populated SimpleStorage device. The + # upstream Storage collection links sample drives the target does not + # have, so the System does not link it. + m.pop('Storage', None) m['Name'] = targets[sid]['name'] m['Manufacturer'] = 'DMTF Redfish Interface Emulator (Fleet lab adapter)' m['Model'] = 'libvirt/QEMU lab target' @@ -282,6 +292,18 @@ def fn(value): return None return faults.update(fn) + firmware = load_firmware() + inventory = '/redfish/v1/UpdateService/FirmwareInventory' + firmware_docs = { + '/redfish/v1/UpdateService': {'@odata.id': '/redfish/v1/UpdateService', '@odata.type': '#UpdateService.v1_11_0.UpdateService', + 'Id': 'UpdateService', 'Name': 'Update Service', 'FirmwareInventory': {'@odata.id': inventory}}, + inventory: {'@odata.id': inventory, '@odata.type': '#SoftwareInventoryCollection.SoftwareInventoryCollection', 'Name': 'Firmware Inventory', + 'Members@odata.count': len(firmware), 'Members': [{'@odata.id': inventory + '/' + f['Id']} for f in firmware]}, + } + for f in firmware: + firmware_docs[inventory + '/' + f['Id']] = dict(f, **{'@odata.id': inventory + '/' + f['Id'], '@odata.type': '#SoftwareInventory.v1_10_0.SoftwareInventory', + 'Status': {'State': 'Enabled', 'Health': 'OK'}, 'Updateable': False}) + @g.app.before_request def guard(): request_context.principal, request_context.detail = 'anonymous', {} @@ -297,6 +319,8 @@ def guard(): request_context.principal, request_context.detail = 'rejected', {'fault': 'reject-auth'} return challenge() request_context.principal = 'authenticated' + if path in firmware_docs: + return (firmware_docs[path], 200) if request.method == 'GET' else error(405, 'the lab firmware inventory is read-only') m = re.fullmatch(r'/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?', path) if not m: return None @@ -362,6 +386,16 @@ def reset(sid): time.sleep(min(int(drop.get('seconds', 45)), 120)) return '', 204 + @g.app.after_request + def link_update_service(response): + # Upstream's service root names no UpdateService; link the adapter's. + if request.method == 'GET' and (request.path.rstrip('/') or '/') == '/redfish/v1' and response.status_code == 200: + root = response.get_json(silent=True) + if isinstance(root, dict): + root['UpdateService'] = {'@odata.id': '/redfish/v1/UpdateService'} + response.set_data(json.dumps(root)) + return response + @g.app.after_request def audit(response): entry = {'at': now(), 'method': request.method, 'path': request.path, 'status': response.status_code, @@ -376,6 +410,11 @@ def audit(response): return g.app +def load_firmware(): + with open(os.path.join(CONFIG_DIR, 'firmware.json')) as f: + return json.load(f) + + def load_targets(): with open(os.path.join(CONFIG_DIR, 'targets.json')) as f: return {t['system']: t for t in json.load(f)} diff --git a/hack/redfish-lab/targets.json b/hack/redfish-lab/targets.json index 23e256b0..da07cce7 100644 --- a/hack/redfish-lab/targets.json +++ b/hack/redfish-lab/targets.json @@ -1,8 +1,8 @@ [ - {"system": "System-1", "name": "fleet-lab-target-a", "domain": "fleet-lab-target-a", + {"system": "System-1", "name": "fleet-lab-target-a", "domain": "fleet-lab-target-a", "serial": "serial-synthetic-device-central-01", "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a", "mac": "52:54:00:77:01:0a", "ip": "192.168.77.10", "disk": "/var/lib/fleet-lab/disks/target-a.raw", "console": "/var/lib/fleet-lab-console/target-a.log"}, - {"system": "System-2", "name": "fleet-lab-target-b", "domain": "fleet-lab-target-b", + {"system": "System-2", "name": "fleet-lab-target-b", "domain": "fleet-lab-target-b", "serial": "serial-fleet-lab-target-b", "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b", "mac": "52:54:00:77:01:0b", "ip": "192.168.77.11", "disk": "/var/lib/fleet-lab/disks/target-b.raw", "console": "/var/lib/fleet-lab-console/target-b.log"} ] diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index c8518e4b..9d85c5eb 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -44,6 +44,7 @@ def test_1_service_root_is_upstream_and_unauthenticated(self): r = self.app.get('/redfish/v1/') self.assertEqual(r.status_code, 200) self.assertEqual(r.json['Systems'], {'@odata.id': '/redfish/v1/Systems'}) + self.assertEqual(r.json['UpdateService'], {'@odata.id': '/redfish/v1/UpdateService'}) self.assertEqual(self.app.delete('/redfish/v1/reset/').status_code, 404) def test_2_authentication_is_enforced(self): @@ -56,7 +57,22 @@ def test_3_system_identity_and_capabilities(self): s = self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json self.assertEqual(s['UUID'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') self.assertEqual(s['PowerState'], 'Off') + # Commissioning reads the serial the Device records and the one + # populated disk, never the upstream sample drives. + self.assertEqual(s['SerialNumber'], 'serial-synthetic-device-central-01') + self.assertNotIn('Storage', s) + controllers = self.app.get(s['SimpleStorage']['@odata.id'], headers=AUTH).json['Members'] + devices = [d for c in controllers for d in self.app.get(c['@odata.id'], headers=AUTH).json['Devices']] + self.assertEqual([d['CapacityBytes'] for d in devices], [2 * 1024 ** 3]) self.assertEqual(s['Boot']['BootSourceOverrideTarget@Redfish.AllowableValues'], ['None', 'Pxe', 'Hdd']) + # Commissioning checks firmware against the lab's inventory, behind + # authentication and read-only. + self.assertEqual(self.app.get('/redfish/v1/UpdateService/FirmwareInventory').status_code, 401) + service = self.app.get(self.app.get('/redfish/v1/').json['UpdateService']['@odata.id'], headers=AUTH).json + members = self.app.get(service['FirmwareInventory']['@odata.id'], headers=AUTH).json['Members'] + versions = {f['Id']: f['Version'] for f in (self.app.get(m['@odata.id'], headers=AUTH).json for m in members)} + self.assertEqual(versions, {'BMC': '1.2.2-fleet-lab.1', 'BIOS': 'lab-bios-1.0.0'}) + self.assertEqual(self.app.patch(members[0]['@odata.id'], headers=AUTH, json={'Version': 'x'}).status_code, 405) info = self.app.get(s['Actions']['#ComputerSystem.Reset']['@Redfish.ActionInfo'], headers=AUTH).json self.assertEqual(info['Parameters'][0]['AllowableValues'], ['On', 'ForceOff', 'ForceRestart']) diff --git a/internal/redfish/hardware.go b/internal/redfish/hardware.go new file mode 100644 index 00000000..571a9530 --- /dev/null +++ b/internal/redfish/hardware.go @@ -0,0 +1,293 @@ +package redfish + +import ( + "context" + "errors" + "strings" + + "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" +) + +// maxComponents bounds each hardware collection a commissioning reads. +const maxComponents = 64 + +// Hardware is what a System reports about its identity, components and +// health. It is read with GETs only. +type Hardware struct { + SerialNumber string + UUID string + // Healthy is false when the System or any present component reports + // Warning or Critical health. Redfish allows a component to omit its + // health, and an omitted health counts as healthy. + Healthy bool + Unhealthy []string + Processors []Processor + MemoryMiB int64 + Disks []Disk + Interfaces []NetworkInterface +} + +type Processor struct { + ID string + Model string + Architecture string + Cores int64 +} + +type Disk struct { + Name string + CapacityBytes int64 +} + +// Firmware is one FirmwareInventory member. +type Firmware struct { + ID string + Name string + Version string +} + +type status struct { + State string + Health string +} + +// skip reports whether a component is not present to judge. ok reports +// whether a present component reports neither Warning nor Critical. +func (s status) skip() bool { return s.State == "Absent" || s.State == "Disabled" } +func (s status) ok() bool { return s.Health != "Warning" && s.Health != "Critical" } + +// Hardware reads the verified System and its processors, memory, storage and +// network interfaces. Every member must sit under the System. +func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { + api, err := c.connect(ctx) + if err != nil { + return Hardware{}, err + } + var doc struct { + SerialNumber string + UUID string + Status status + Processors link + Memory link + Storage link + SimpleStorage link + EthernetInterfaces link + } + if err := getJSON(api, sys.Path, &doc); err != nil { + return Hardware{}, err + } + hw := Hardware{SerialNumber: strings.TrimSpace(doc.SerialNumber), UUID: canonicalUUID(doc.UUID), Healthy: true} + // Two Storage controllers may link the same drive; it counts once. + seen := map[string]bool{} + check := func(name string, s status) { + if !s.skip() && !s.ok() { + hw.Healthy = false + if len(hw.Unhealthy) < maxComponents { + hw.Unhealthy = append(hw.Unhealthy, name) + } + } + } + check("System", doc.Status) + under := func(collection string) (string, error) { + if collection == "" { + return "", nil + } + p, err := cleanPath(collection) + if err != nil || !strings.HasPrefix(p, sys.Path+"/") { + return "", errors.New("redfish: hardware collection outside the System") + } + return p, nil + } + each := func(collection string, read func(path string) error) error { + p, err := under(collection) + if err != nil || p == "" { + return err + } + paths, err := members(api, p, maxComponents) + if err != nil { + return err + } + for _, member := range paths { + if err := read(member); err != nil { + return err + } + } + return nil + } + if err := each(doc.Processors.ID, func(p string) error { + var cpu struct { + ID string `json:"Id"` + Model string + ProcessorArchitecture string + InstructionSet string + TotalCores int64 + Status status + } + if err := getJSON(api, p, &cpu); err != nil { + return err + } + if cpu.Status.State == "Absent" { + return nil + } + check("Processor "+cpu.ID, cpu.Status) + hw.Processors = append(hw.Processors, Processor{ID: cpu.ID, Model: cpu.Model, Architecture: architecture(cpu.ProcessorArchitecture, cpu.InstructionSet), Cores: cpu.TotalCores}) + return nil + }); err != nil { + return Hardware{}, err + } + if err := each(doc.Memory.ID, func(p string) error { + var dimm struct { + ID string `json:"Id"` + CapacityMiB int64 + Status status + } + if err := getJSON(api, p, &dimm); err != nil { + return err + } + // An Absent or Disabled module is not memory the server can use. + if dimm.Status.skip() { + return nil + } + check("Memory "+dimm.ID, dimm.Status) + hw.MemoryMiB += dimm.CapacityMiB + return nil + }); err != nil { + return Hardware{}, err + } + if err := each(doc.Storage.ID, func(p string) error { + var storage struct { + Drives []link + } + if err := getJSON(api, p, &storage); err != nil { + return err + } + for _, d := range storage.Drives { + // Drives sit under the System or, on some BMCs, under a Chassis. + dp, err := cleanPath(d.ID) + if err != nil || !(strings.HasPrefix(dp, sys.Path+"/") || strings.HasPrefix(dp, "/redfish/v1/Chassis/")) { + return errors.New("redfish: drive outside the System and its Chassis") + } + if seen[dp] { + continue + } + seen[dp] = true + var drive struct { + Name string + CapacityBytes int64 + Status status + } + if err := getJSON(api, dp, &drive); err != nil { + return err + } + if drive.Status.State == "Absent" || drive.CapacityBytes <= 0 { + continue + } + check("Disk "+drive.Name, drive.Status) + if len(hw.Disks) < maxComponents { + hw.Disks = append(hw.Disks, Disk{Name: drive.Name, CapacityBytes: drive.CapacityBytes}) + } + } + return nil + }); err != nil { + return Hardware{}, err + } + // A BMC may list the same drives under both Storage and SimpleStorage. + // Storage is the current schema, so SimpleStorage is read only when + // Storage yields no disk: some BMCs link a Storage collection that lists + // none of the drives SimpleStorage reports. + if len(hw.Disks) == 0 { + if err := each(doc.SimpleStorage.ID, func(p string) error { + var controller struct { + ID string `json:"Id"` + Devices []struct { + Name string + CapacityBytes int64 + Status status + } + } + if err := getJSON(api, p, &controller); err != nil { + return err + } + for _, device := range controller.Devices { + if device.Status.State == "Absent" || device.CapacityBytes <= 0 { + continue + } + check("Disk "+device.Name, device.Status) + if len(hw.Disks) < maxComponents { + hw.Disks = append(hw.Disks, Disk{Name: device.Name, CapacityBytes: device.CapacityBytes}) + } + } + return nil + }); err != nil { + return Hardware{}, err + } + } + p, err := under(doc.EthernetInterfaces.ID) + if err != nil { + return Hardware{}, err + } + nics, err := interfaces(api, sys.Path, p) + if err != nil { + return Hardware{}, err + } + hw.Interfaces = nics + return hw, nil +} + +// architecture maps Redfish processor fields to a Kubernetes architecture. +func architecture(processor, instructionSet string) string { + switch { + case instructionSet == "x86-64" || (processor == "x86" && instructionSet == ""): + return "amd64" + case instructionSet == "ARM-A64": + return "arm64" + case instructionSet != "": + return instructionSet + } + return processor +} + +// Firmware reads the UpdateService's FirmwareInventory. A service without +// one reports no components. +func (c *Client) Firmware(ctx context.Context) ([]Firmware, error) { + api, err := c.connect(ctx) + if err != nil { + return nil, err + } + return firmware(api) +} + +func firmware(api *gofish.APIClient) ([]Firmware, error) { + var root struct{ UpdateService link } + if err := getJSON(api, schemas.DefaultServiceRoot, &root); err != nil { + return nil, err + } + if root.UpdateService.ID == "" { + return nil, nil + } + var service struct{ FirmwareInventory link } + if err := getJSON(api, root.UpdateService.ID, &service); err != nil { + return nil, err + } + if service.FirmwareInventory.ID == "" { + return nil, nil + } + paths, err := members(api, service.FirmwareInventory.ID, maxComponents) + if err != nil { + return nil, err + } + var out []Firmware + for _, p := range paths { + var doc struct { + ID string `json:"Id"` + Name string + Version string + } + if err := getJSON(api, p, &doc); err != nil { + return nil, err + } + out = append(out, Firmware{ID: doc.ID, Name: doc.Name, Version: doc.Version}) + } + return out, nil +} diff --git a/internal/redfish/hardware_test.go b/internal/redfish/hardware_test.go new file mode 100644 index 00000000..92617b8d --- /dev/null +++ b/internal/redfish/hardware_test.go @@ -0,0 +1,18 @@ +package redfish + +import "testing" + +func TestArchitecture(t *testing.T) { + for _, c := range []struct{ processor, set, want string }{ + {"x86", "x86-64", "amd64"}, + {"x86", "", "amd64"}, + {"ARM", "ARM-A64", "arm64"}, + {"ARM", "ARM-A32", "ARM-A32"}, + {"ARM", "", "ARM"}, + {"", "", ""}, + } { + if got := architecture(c.processor, c.set); got != c.want { + t.Errorf("architecture(%q, %q) = %q, want %q", c.processor, c.set, got, c.want) + } + } +} diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index e1ed146c..9581587d 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -122,7 +122,11 @@ func (b BootServer) Handler() http.Handler { var size int64 if name == "boot.ipxe" { base := b.Origin + "/" + Key(boot.Operation) + "/" + boot.Token - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, boot.Mode, base)) + args := "" + if boot.DurationSeconds > 0 { + args = " fleet.duration=" + strconv.FormatInt(boot.DurationSeconds, 10) + } + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, boot.Mode, args, base)) size = int64(len(data)) } else { // Hash the pinned artifact, then serve the same open file. diff --git a/internal/site/redfishwork/commissioning.go b/internal/site/redfishwork/commissioning.go new file mode 100644 index 00000000..099611b0 --- /dev/null +++ b/internal/site/redfishwork/commissioning.go @@ -0,0 +1,376 @@ +package redfishwork + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" + "k8s.io/apimachinery/pkg/api/resource" +) + +var burnInPhase = phase{"burnin", "Pxe", "FLEET-BURNIN:", "burnin"} + +// Commissioning is the DeviceCommissioning worker. It inspects the server and +// checks its firmware with GETs only, then runs the plan's burn-in image +// with one network boot. A proven verdict, pass or fail, is a success; the +// evidence carries the result. +type Commissioning struct { + Config + // BurnInDigest is the digest of the boot image the site serves. A plan + // whose burn-in image has another digest is refused before anything is + // sent. + BurnInDigest string +} + +var _ site.Kind = Commissioning{} + +func (k Commissioning) Check(_ context.Context, work *site.Work) *custody.Refusal { + if conn(work) == nil { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site does not reach the server over Redfish"} + } + spec, err := commissioningSpec(work) + if err != nil { + return &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceCommissioning spec"} + } + content := spec.Plan.Content + if d := content.BurnIn.Duration.Duration; d < time.Minute || d > 24*time.Hour { + return &custody.Refusal{Reason: ReasonInputs, Message: "the burn-in duration is outside 1 minute to 24 hours"} + } + if _, ok := mib(content.Inspection.Memory.Capacity); !ok { + return &custody.Refusal{Reason: ReasonInputs, Message: "the plan's memory capacity does not parse"} + } + if _, ok := mib(content.Inspection.Disks.MinCapacity); !ok { + return &custody.Refusal{Reason: ReasonInputs, Message: "the plan's minimum disk capacity does not parse"} + } + if k.BurnInDigest == "" || spec.Plan.Content.BurnIn.Image.Digest != k.BurnInDigest { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the site does not serve the plan's burn-in image"} + } + if conn(work).Target.Console == "" { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the site's enrollment names no console for receipts"} + } + if !contains(conn(work).System.BootTargets, "Pxe") || !conn(work).System.OffersOnce() { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the system does not offer a one-time network boot"} + } + for _, need := range []string{"On", "ForceOff"} { + if !contains(conn(work).System.ResetTypes, need) { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the system does not offer reset " + need} + } + } + return nil +} + +func commissioningSpec(work *site.Work) (ops.DeviceCommissioningSpec, error) { + var spec ops.DeviceCommissioningSpec + err := json.Unmarshal(work.Inputs, &spec) + return spec, err +} + +func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { + spec, err := commissioningSpec(work) + if err != nil { + return nil, &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceCommissioning spec"} + } + plan := spec.Plan.Content + fail := func(evidence ops.CommissioningEvidence, phase ops.CommissioningPhase, mismatches []string) (any, error) { + evidence.Result, evidence.FailedPhase = ops.CommissioningFailed, phase + evidence.Mismatches = bound(mismatches) + return fit(evidence), nil + } + + // Inspection and the firmware check run once, before any effect, and + // their passing evidence is stored before the first burn-in step. A + // resumed worker reuses it instead of reading the server again, so + // nothing it reads after an effect can become an inspection verdict. + var record preflight + found, err := work.Store().GetRecord(work.Device, preflightRecords, work.Key(), &record) + if err != nil { + return nil, err + } + if !found { + if work.Journaled(burnInPhase.name + "-power-off") { + return nil, errors.New("burn-in began without a stored inspection") + } + evidence, phase, mismatches, err := k.preflight(ctx, work, spec) + if err != nil { + return nil, err + } + if len(mismatches) > 0 { + return fail(evidence, phase, mismatches) + } + record = preflight{Evidence: evidence} + if err := work.Store().PutRecord(work.Device, work.Fence, preflightRecords, work.Key(), record); err != nil { + return nil, err + } + } + evidence := record.Evidence + + // Burn in: one network boot of the plan's image. + steps, result, err := k.burnIn(ctx, work, plan.BurnIn.Duration.Duration) + if err != nil { + return nil, err + } + evidence.Steps = steps + // Burn-in is timed from the boot server's delivery of the image, not from + // power-on, so firmware start and the network boot do not count towards + // it. An image that reports early fails however long the server took to + // fetch it. + started, delivered := k.deliveredAt(work) + completed, verified := work.JournaledAt(burnInPhase.name + "-verified") + if !delivered || !verified { + return nil, errors.New("the boot log and journal do not record when burn-in began and ended") + } + evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metaNow(started), CompletedAt: metaNow(completed)} + if result != ops.BurnInPassed { + return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported a failure"}) + } + if completed.Sub(started) < plan.BurnIn.Duration.Duration { + return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported before the plan's duration"}) + } + after, err := conn(work).BMC.Hardware(ctx, conn(work).System) + if err != nil { + return nil, fmt.Errorf("the server could not be read after burn-in: %w", err) + } + if !after.Healthy { + return fail(evidence, ops.PhaseBurnIn, append([]string{"unhealthy after burn-in"}, after.Unhealthy...)) + } + evidence.Result = ops.CommissioningPassed + return fit(evidence), nil +} + +// preflightRecords holds each operation's passing inspection and firmware +// evidence, stored before burn-in sends anything. +const preflightRecords = "commissioning" + +type preflight struct { + Evidence ops.CommissioningEvidence `json:"evidence"` +} + +// preflight inspects the server and checks its firmware with GETs only. It +// returns the failing phase and what failed, if anything did. +func (k Commissioning) preflight(ctx context.Context, work *site.Work, spec ops.DeviceCommissioningSpec) (ops.CommissioningEvidence, ops.CommissioningPhase, []string, error) { + evidence := ops.CommissioningEvidence{Plan: spec.Plan.ApprovedPlanReference, BMCPublicKeySHA256: work.Snapshot.BMCPublicKeySHA256} + hw, err := conn(work).BMC.Hardware(ctx, conn(work).System) + if err != nil { + return evidence, "", nil, fmt.Errorf("inspection could not read the server: %w", err) + } + evidence.SerialNumber, evidence.SystemUUID = clip(hw.SerialNumber), hw.UUID + evidence.Hardware = inspected(hw) + if mismatches := inspect(spec.Plan.Content.Inspection, hw, work.Snapshot); len(mismatches) > 0 { + return evidence, ops.PhaseInspect, mismatches, nil + } + firmware, err := conn(work).BMC.Firmware(ctx) + if err != nil { + return evidence, "", nil, fmt.Errorf("the firmware inventory could not be read: %w", err) + } + reported, mismatches := checkFirmware(spec.Plan.Content.Firmware, firmware) + evidence.Firmware = reported + if len(mismatches) > 0 { + return evidence, ops.PhaseFirmware, mismatches, nil + } + return evidence, "", nil, nil +} + +// burnIn boots the burn-in image once and reads its one result receipt. +func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration time.Duration) ([]ops.StepEvidence, ops.BurnInResult, error) { + boot, err := k.boot(ctx, work, burnInPhase.mode) + if err != nil { + return nil, "", err + } + if boot.DurationSeconds == 0 { + boot.DurationSeconds = int64(duration / time.Second) + if err := k.saveBoot(work, boot); err != nil { + return nil, "", err + } + } + steps, err := k.run(ctx, work, []phase{burnInPhase}) + if err != nil { + return nil, "", err + } + result, err := k.burnInResult(work, boot) + if err != nil { + return nil, "", err + } + return steps, result, nil +} + +// burnInResult reads the result of the operation's one burn-in receipt. +// More than one receipt, of either result, proves nothing. +func (c Config) burnInResult(work *site.Work, boot Boot) (ops.BurnInResult, error) { + if n, err := c.receipts(work, boot, burnInPhase); err != nil { + return "", err + } else if n != 1 { + return "", fmt.Errorf("found %d burn-in receipts for this operation, want one", n) + } + data, err := os.ReadFile(filepath.Join(c.ConsoleRoot, filepath.Base(conn(work).Target.Console))) + if err != nil { + return "", err + } + prefix := burnInPhase.marker + boot.Receipt + ":" + for _, line := range strings.Split(string(data), "\n") { + switch strings.TrimSpace(line) { + case prefix + "passed": + return ops.BurnInPassed, nil + case prefix + "failed": + return ops.BurnInFailed, nil + } + } + return "", errors.New("no burn-in result for this operation") +} + +// maxEvidence is the kind's evidence limit, less room for the envelope. +const maxEvidence = 15 << 10 + +// clip bounds a string the BMC supplied. +func clip(value string) string { + if len(value) > 128 { + return value[:128] + } + return value +} + +// fit keeps the evidence within the kind's limit. It drops the inspected +// component lists before it would drop the verdict. +func fit(evidence ops.CommissioningEvidence) ops.CommissioningEvidence { + if data, err := json.Marshal(evidence); err == nil && len(data) <= maxEvidence { + return evidence + } + if evidence.Hardware != nil { + hw := *evidence.Hardware + hw.Disks, hw.Interfaces = nil, nil + evidence.Hardware = &hw + } + if data, err := json.Marshal(evidence); err == nil && len(data) <= maxEvidence { + return evidence + } + evidence.Mismatches = evidence.Mismatches[:min(len(evidence.Mismatches), 4)] + evidence.Firmware = nil + return evidence +} + +func bound(list []string) []string { + if len(list) > 32 { + list = list[:32] + } + for i, value := range list { + list[i] = clip(value) + } + return list +} + +func mib(capacity string) (int64, bool) { + q, err := resource.ParseQuantity(capacity) + if err != nil { + return 0, false + } + return q.Value() / (1 << 20), true +} + +func quantity(bytes int64) string { + return resource.NewQuantity(bytes, resource.BinarySI).String() +} + +// inspect compares what the BMC reported with the plan and the Device's +// recorded identity. CPU and memory must match exactly; disks and interfaces +// are minimums. +func inspect(plan ops.CommissioningInspection, hw redfish.Hardware, snapshot ops.DeviceSnapshot) []string { + var out []string + if serial := snapshot.Extra[custody.SnapshotSerialNumber]; serial == "" || !strings.EqualFold(strings.TrimSpace(serial), hw.SerialNumber) { + out = append(out, "the BMC reports another serial number than the Device records") + } + if !strings.EqualFold(hw.UUID, snapshot.SystemUUID) { + out = append(out, "the BMC reports another system UUID than the Device records") + } + if !hw.Healthy { + out = append(out, "unhealthy: "+strings.Join(hw.Unhealthy, ", ")) + } + var cores int64 + for _, cpu := range hw.Processors { + cores += cpu.Cores + if cpu.Architecture != plan.CPU.Architecture { + out = append(out, fmt.Sprintf("processor %s is %q, want %s", cpu.ID, cpu.Architecture, plan.CPU.Architecture)) + } + } + if cores != plan.CPU.Cores { + out = append(out, fmt.Sprintf("%d cores, want %d", cores, plan.CPU.Cores)) + } + if want, ok := mib(plan.Memory.Capacity); !ok || hw.MemoryMiB != want { + out = append(out, fmt.Sprintf("%d MiB of memory, want %s", hw.MemoryMiB, plan.Memory.Capacity)) + } + minimum, ok := mib(plan.Disks.MinCapacity) + if !ok { + out = append(out, "the plan's minimum disk capacity does not parse") + } + var disks int64 + for _, disk := range hw.Disks { + if disk.CapacityBytes/(1<<20) >= minimum { + disks++ + } + } + if disks < plan.Disks.Count { + out = append(out, fmt.Sprintf("%d disks of at least %s, want %d", disks, plan.Disks.MinCapacity, plan.Disks.Count)) + } + if int64(len(hw.Interfaces)) < plan.Interfaces.Count { + out = append(out, fmt.Sprintf("%d network interfaces, want %d", len(hw.Interfaces), plan.Interfaces.Count)) + } + return out +} + +func inspected(hw redfish.Hardware) *ops.InspectedHardware { + out := &ops.InspectedHardware{Memory: quantity(hw.MemoryMiB << 20)} + for _, cpu := range hw.Processors { + out.CPU.Sockets++ + out.CPU.Cores += cpu.Cores + if out.CPU.Architecture == "" { + out.CPU.Architecture, out.CPU.Model = clip(cpu.Architecture), clip(cpu.Model) + } + } + for _, disk := range hw.Disks { + if len(out.Disks) < 64 { + out.Disks = append(out.Disks, ops.InspectedDisk{Name: clip(disk.Name), Capacity: quantity(disk.CapacityBytes)}) + } + } + for _, nic := range hw.Interfaces { + if len(out.Interfaces) < 64 { + iface := ops.InspectedInterface{Name: clip(nic.ID), MACAddress: nic.MACAddress} + if nic.SpeedMbps > 0 { + iface.Speed = strconv.FormatInt(nic.SpeedMbps, 10) + "Mbps" + } + out.Interfaces = append(out.Interfaces, iface) + } + } + return out +} + +// checkFirmware returns every baseline component as the BMC reported it, and +// what does not match. A component matches by Id or by Name. +func checkFirmware(baseline []ops.FirmwareBaseline, inventory []redfish.Firmware) ([]ops.FirmwareBaseline, []string) { + var reported []ops.FirmwareBaseline + var mismatches []string + for _, want := range baseline { + found := false + for _, item := range inventory { + if item.ID == want.Component || item.Name == want.Component { + found = true + reported = append(reported, ops.FirmwareBaseline{Component: want.Component, Version: clip(item.Version)}) + if item.Version != want.Version { + mismatches = append(mismatches, fmt.Sprintf("%s is %q, want %q", want.Component, clip(item.Version), want.Version)) + } + break + } + } + if !found { + mismatches = append(mismatches, want.Component+" is not reported") + } + } + return reported, mismatches +} diff --git a/internal/site/redfishwork/commissioning_test.go b/internal/site/redfishwork/commissioning_test.go new file mode 100644 index 00000000..bd4744ef --- /dev/null +++ b/internal/site/redfishwork/commissioning_test.go @@ -0,0 +1,318 @@ +package redfishwork + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "sync" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +var labBurnIn = "sha256:" + strings.Repeat("d", 64) + +func commissioningRunner(t *testing.T, l *lab) *site.Runner { + t.Helper() + r := runner(t, l) + // The store's clock moves ahead while burn-in runs, so the journal shows + // a burn-in as long as the plan's without the test waiting for it. + root := t.TempDir() + if err := os.Chmod(root, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(root, func() time.Time { + l.mu.Lock() + defer l.mu.Unlock() + return time.Now().Add(l.skew) + }) + if err != nil { + t.Fatal(err) + } + r.Store, r.Results, l.store = store, site.NewResults(store), store + config := r.Kinds["DeviceWipe"].(Wipe).Config + r.Kinds["DeviceCommissioning"] = Commissioning{Config: config, BurnInDigest: labBurnIn} + return r +} + +func planSpec(t *testing.T, mutate func(*ops.CommissioningPlanContent)) ops.DeviceCommissioningSpec { + t.Helper() + content := ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "32Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + Firmware: []ops.FirmwareBaseline{{Component: "BMC", Version: "1.0.0"}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: labBurnIn}, Duration: metav1.Duration{Duration: time.Minute}}, + } + if mutate != nil { + mutate(&content) + } + return ops.DeviceCommissioningSpec{Plan: ops.CommissioningPlanInput{ApprovedPlanReference: ops.ApprovedPlanReference{PlanReference: ops.PlanReference{Name: "plan-example", Generation: 1, Digest: "sha256:" + strings.Repeat("e", 64)}, Approval: "plan-example-0123456789abcdef"}, Content: content}} +} + +func commission(t *testing.T, l *lab, r *site.Runner, uid string, spec ops.DeviceCommissioningSpec) (custody.SiteResult, ops.CommissioningEvidence) { + t.Helper() + work := assignment(l, "DeviceCommissioning", uid, 1, spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + var evidence ops.CommissioningEvidence + if result.Phase == ops.PhaseSucceeded { + if err := json.Unmarshal(result.Evidence, &evidence); err != nil { + t.Fatal(err) + } + // The evidence passes the kind's own validation. + operation := &ops.DeviceCommissioning{Spec: spec, Status: ops.OperationStatus{Snapshot: &work.Snapshot}} + if _, err := custody.DeviceCommissioningKind().Evidence(operation, result.Evidence); err != nil { + t.Fatalf("the kind rejects the worker's evidence: %v", err) + } + } + return result, evidence +} + +func TestCommissioningPassesAServerThatMeetsThePlan(t *testing.T) { + l := newLab(t) + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-commission", planSpec(t, nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningPassed || l.onCount() != 1 { + t.Fatalf("result = %+v, evidence %+v, %d power-ons", result, evidence, l.onCount()) + } + hardware := evidence.Hardware + if hardware.CPU.Architecture != "amd64" || hardware.CPU.Cores != 2 || hardware.Memory != "2Gi" || len(hardware.Disks) != 1 || hardware.Disks[0].Capacity != "64Gi" || len(hardware.Interfaces) != 1 { + t.Fatalf("hardware = %+v", hardware) + } + if evidence.SerialNumber != "SERIAL-001" || evidence.BurnIn.Result != ops.BurnInPassed || len(evidence.Firmware) != 1 || evidence.Firmware[0].Version != "1.0.0" { + t.Fatalf("evidence = %+v", evidence) + } + if _, open, _ := OpenAdmission(r.Store, mac, time.Now()); open { + t.Fatal("the burn-in admission stayed open") + } +} + +// A mismatch found by inspection or the firmware check is a proven verdict. +// It sends nothing to the server. +func TestCommissioningFailsAMismatchWithoutSendingAnything(t *testing.T) { + for name, setup := range map[string]struct { + lab func(*lab) + plan func(*ops.CommissioningPlanContent) + phase ops.CommissioningPhase + expect string + }{ + "cores": {plan: func(p *ops.CommissioningPlanContent) { p.Inspection.CPU.Cores = 4 }, phase: ops.PhaseInspect, expect: "2 cores, want 4"}, + "memory": {plan: func(p *ops.CommissioningPlanContent) { p.Inspection.Memory.Capacity = "4Gi" }, phase: ops.PhaseInspect, expect: "MiB of memory"}, + "disks": {plan: func(p *ops.CommissioningPlanContent) { p.Inspection.Disks.Count = 2 }, phase: ops.PhaseInspect, expect: "disks of at least"}, + "unhealthy": {lab: func(l *lab) { l.unhealthy = "DIMM0" }, phase: ops.PhaseInspect, expect: "Memory DIMM0"}, + "serial": {lab: func(l *lab) { l.serial = "OTHER" }, phase: ops.PhaseInspect, expect: "serial number"}, + "firmware": {lab: func(l *lab) { l.bmcFW = "0.9.0" }, phase: ops.PhaseFirmware, expect: `BMC is "0.9.0"`}, + "missing": {plan: func(p *ops.CommissioningPlanContent) { + p.Firmware = append(p.Firmware, ops.FirmwareBaseline{Component: "BIOS", Version: "1"}) + }, phase: ops.PhaseFirmware, expect: "BIOS is not reported"}, + } { + t.Run(name, func(t *testing.T) { + l := newLab(t) + if setup.lab != nil { + setup.lab(l) + } + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-"+name, planSpec(t, setup.plan)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != setup.phase || !strings.Contains(strings.Join(evidence.Mismatches, ";"), setup.expect) { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + if l.effectCount() != 0 { + t.Fatalf("%d effectful requests reached the BMC", l.effectCount()) + } + }) + } +} + +func TestABurnInFailureIsAProvenVerdictAndLeavesTheServerOff(t *testing.T) { + l := newLab(t) + l.burnIn = "failed" + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-burn-fail", planSpec(t, nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || evidence.BurnIn.Result != ops.BurnInFailed { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + if l.power != "Off" || l.onCount() != 1 { + t.Fatalf("power %s after %d power-ons", l.power, l.onCount()) + } +} + +// The site serves one burn-in image. A plan that names another is refused +// before anything is sent. +func TestCommissioningRefusesABurnInImageTheSiteDoesNotServe(t *testing.T) { + l := newLab(t) + r := commissioningRunner(t, l) + spec := planSpec(t, func(p *ops.CommissioningPlanContent) { p.BurnIn.Image.Digest = "sha256:" + strings.Repeat("f", 64) }) + result, _ := commission(t, l, r, "op-other-image", spec) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonUnsupportedTarget || l.effectCount() != 0 { + t.Fatalf("result = %+v, %d effects", result, l.effectCount()) + } +} + +func TestTheBootServerPassesTheBurnInDuration(t *testing.T) { + l := newLab(t) + r := commissioningRunner(t, l) + commission(t, l, r, "op-duration", planSpec(t, nil)) + var boot Boot + if _, err := r.Store.GetRecord(device, "boot", l.operation, &boot); err != nil || boot.Mode != "burnin" || boot.DurationSeconds != 60 { + t.Fatalf("boot = %+v, %v", boot, err) + } +} + +// A worker resumed after burn-in powered the server on reuses the stored +// inspection. A fault it reads afterwards fails burn-in, never inspection, +// and it powers on no second time. +func TestAResumedCommissioningKeepsItsInspection(t *testing.T) { + l := newLab(t) + r := commissioningRunner(t, l) + work := assignment(l, "DeviceCommissioning", "op-resume", 1, planSpec(t, nil)) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + ctx, cancel := context.WithCancel(context.Background()) + var once sync.Once + l.onHook = func() { once.Do(func() { l.setUnhealthy("DIMM0"); cancel() }) } + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + l.onHook = nil + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + var evidence ops.CommissioningEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil { + t.Fatalf("result = %+v", result) + } + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || l.onCount() != 1 { + t.Fatalf("result = %+v, evidence %+v, %d power-ons", result, evidence, l.onCount()) + } + if evidence.BurnIn.StartedAt.IsZero() || evidence.BurnIn.CompletedAt.Before(&evidence.BurnIn.StartedAt) { + t.Fatalf("burn-in times = %+v", evidence.BurnIn) + } +} + +func TestTwoBurnInReceiptsProveNothing(t *testing.T) { + l := newLab(t) + l.receipts = 2 + r := commissioningRunner(t, l) + result, _ := commission(t, l, r, "op-two-receipts", planSpec(t, nil)) + if result.Phase != ops.PhaseOutcomeUnknown { + t.Fatalf("result = %+v", result) + } +} + +func TestAServerUnhealthyAfterBurnInFails(t *testing.T) { + l := newLab(t) + r := commissioningRunner(t, l) + l.onHook = func() { l.setUnhealthy("CPU0") } + result, evidence := commission(t, l, r, "op-after", planSpec(t, nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || !strings.Contains(strings.Join(evidence.Mismatches, ";"), "Processor CPU0") { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +// Redfish lets a component omit its health. That is not a fault. +func TestAnOmittedHealthIsNotAFault(t *testing.T) { + l := newLab(t) + l.noHealth = true + r := commissioningRunner(t, l) + if result, evidence := commission(t, l, r, "op-no-health", planSpec(t, nil)); evidence.Result != ops.CommissioningPassed { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +// A drive listed under Storage and SimpleStorage, or linked twice, counts +// once, and a drive under a Chassis is read. +func TestADriveListedTwiceCountsOnce(t *testing.T) { + l := newLab(t) + l.both = true + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-both", planSpec(t, func(p *ops.CommissioningPlanContent) { p.Inspection.Disks.Count = 2 })) + if result.Phase != ops.PhaseSucceeded || evidence.FailedPhase != ops.PhaseInspect || len(evidence.Hardware.Disks) != 1 { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +// A Storage collection that lists no drives does not hide the drive under +// SimpleStorage. +func TestAnEmptyStorageFallsBackToSimpleStorage(t *testing.T) { + l := newLab(t) + l.emptyStorage = true + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-empty-storage", planSpec(t, nil)) + if evidence.Result != ops.CommissioningPassed || len(evidence.Hardware.Disks) != 1 { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +// A Disabled memory module is not memory the server has. +func TestADisabledMemoryModuleDoesNotCount(t *testing.T) { + l := newLab(t) + l.disabledDIMM = true + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-disabled-dimm", planSpec(t, nil)) + if evidence.Result != ops.CommissioningPassed || evidence.Hardware.Memory != "2Gi" { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +func TestCommissioningRefusesUnusablePlanValues(t *testing.T) { + for name, mutate := range map[string]func(*ops.CommissioningPlanContent){ + "short burn-in": func(p *ops.CommissioningPlanContent) { p.BurnIn.Duration.Duration = time.Second }, + "memory": func(p *ops.CommissioningPlanContent) { p.Inspection.Memory.Capacity = "lots" }, + "disk minimum": func(p *ops.CommissioningPlanContent) { p.Inspection.Disks.MinCapacity = "big" }, + } { + l := newLab(t) + r := commissioningRunner(t, l) + result, _ := commission(t, l, r, "op-"+strings.ReplaceAll(name, " ", "-"), planSpec(t, mutate)) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonInputs || l.effectCount() != 0 { + t.Fatalf("%s: result = %+v", name, result) + } + } +} + +func TestOversizedEvidenceKeepsTheVerdict(t *testing.T) { + evidence := ops.CommissioningEvidence{Result: ops.CommissioningFailed, FailedPhase: ops.PhaseInspect, Hardware: &ops.InspectedHardware{}} + for i := range 64 { + evidence.Hardware.Disks = append(evidence.Hardware.Disks, ops.InspectedDisk{Name: strings.Repeat("d", 128) + fmt.Sprint(i), Capacity: "1Ti"}) + evidence.Hardware.Interfaces = append(evidence.Hardware.Interfaces, ops.InspectedInterface{Name: strings.Repeat("n", 128), MACAddress: mac}) + } + for range 32 { + evidence.Mismatches = append(evidence.Mismatches, strings.Repeat("m", 128)) + } + fitted := fit(evidence) + data, _ := json.Marshal(fitted) + if len(data) > maxEvidence || fitted.Result != ops.CommissioningFailed || fitted.FailedPhase != ops.PhaseInspect { + t.Fatalf("fitted evidence is %d bytes: %+v", len(data), fitted.Result) + } +} + +func TestABurnInShorterThanThePlanFails(t *testing.T) { + l := newLab(t) + l.burnTime = 0 + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-short", planSpec(t, nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} + +// A burn-in is timed from the image's delivery: a slow firmware start and +// network boot do not make an early-reporting image long enough. +func TestASlowBootDoesNotLengthenTheBurnIn(t *testing.T) { + l := newLab(t) + l.pxeTime, l.burnTime = 5*time.Minute, 30*time.Second + r := commissioningRunner(t, l) + result, evidence := commission(t, l, r, "op-slow-boot", planSpec(t, nil)) + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index f7f207cb..b1705330 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -19,6 +19,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strconv" "strings" "time" @@ -211,6 +212,8 @@ type Boot struct { // are not this operation's. Created time.Time `json:"created"` Expires time.Time `json:"expires"` + // DurationSeconds is how long a burn-in image runs. Other modes omit it. + DurationSeconds int64 `json:"durationSeconds,omitempty"` // Phase is the network-booting phase, set while it may boot. Phase string `json:"phase,omitempty"` Closed bool `json:"closed,omitempty"` @@ -433,13 +436,17 @@ func (c Config) receipts(work *site.Work, boot Boot, ph phase) (int, error) { if err != nil { return 0, err } - want := ph.marker + boot.Receipt - if ph.name == "wipe" { - want += ":" + strconv.FormatInt(conn(work).Target.DiskBytes, 10) + want := []string{ph.marker + boot.Receipt} + switch ph.name { + case "wipe": + want[0] += ":" + strconv.FormatInt(conn(work).Target.DiskBytes, 10) + case burnInPhase.name: + // A burn-in receipt carries the image's result. + want = []string{want[0] + ":passed", want[0] + ":failed"} } n := 0 for _, line := range strings.Split(string(data), "\n") { - if strings.TrimSpace(line) == want { + if slices.Contains(want, strings.TrimSpace(line)) { n++ } } @@ -477,6 +484,31 @@ func (c Config) deliveries(work *site.Work) map[string]bool { return done } +// deliveredAt is when the boot server finished delivering the operation's +// last boot file, rounded up to the next second because the log records +// whole seconds. The boot server and the worker share the site's clock. +func (c Config) deliveredAt(work *site.Work) (time.Time, bool) { + data, _ := os.ReadFile(filepath.Join(BootDirectory(c.BootRoot, work.Key()), "boot-delivery.log")) + var last time.Time + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) != 4 || fields[1] != "write-complete" { + continue + } + at, err := time.Parse(time.RFC3339, fields[0]) + if err != nil { + return time.Time{}, false + } + if at.After(last) { + last = at + } + } + if last.IsZero() { + return time.Time{}, false + } + return last.Add(time.Second), true +} + func (c Config) verifyDelivery(work *site.Work) error { done := c.deliveries(work) for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index ebb466c1..737fa7b9 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -55,6 +55,31 @@ type lab struct { operation string // silent keeps the server running with no console receipt. silent bool + // Commissioning: the serial and firmware the BMC reports, a component + // to report unhealthy, the burn-in result, and every effectful request. + serial string + bmcFW string + unhealthy string + burnIn string + effects int + // noHealth omits Health from the memory module; both lists the drive + // under Storage as well as SimpleStorage; receipts is how many burn-in + // receipts one boot prints. + noHealth bool + both bool + receipts int + // emptyStorage links a Storage collection that lists no drives, so the + // drive is only under SimpleStorage; disabledDIMM adds a Disabled memory + // module. + emptyStorage bool + disabledDIMM bool + // burnTime is how long a burn-in boot takes on the store's clock, and + // skew is how far that clock has moved ahead. + burnTime time.Duration + skew time.Duration + // pxeTime is how long firmware start and the network boot take before + // the boot server delivers the image. + pxeTime time.Duration } func newLab(t *testing.T) *lab { @@ -68,7 +93,7 @@ func newLab(t *testing.T) *lab { if err != nil { t.Fatal(err) } - l := &lab{t: t, power: "Off", enabled: "Disabled", target: "None", console: filepath.Join(t.TempDir(), "console.log"), bootRoot: t.TempDir()} + l := &lab{t: t, power: "Off", enabled: "Disabled", target: "None", console: filepath.Join(t.TempDir(), "console.log"), bootRoot: t.TempDir(), serial: "SERIAL-001", bmcFW: "1.0.0", burnIn: "passed", receipts: 1, burnTime: 2 * time.Minute} l.server = httptest.NewUnstartedServer(l) l.server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} l.server.StartTLS() @@ -86,6 +111,9 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := "/redfish/v1/Systems/A" l.mu.Lock() defer l.mu.Unlock() + if r.Method != http.MethodGet { + l.effects++ + } switch { case r.Method == http.MethodPatch && r.URL.Path == path: var body struct{ Boot map[string]string } @@ -115,9 +143,27 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } docs := map[string]any{ - "/redfish/v1": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, - "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, - path: map[string]any{"@odata.id": path, "Id": "A", "UUID": uuid, "PowerState": l.power, + "/redfish/v1": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}, "UpdateService": map[string]string{"@odata.id": "/redfish/v1/UpdateService"}}, + "/redfish/v1/UpdateService": map[string]any{"FirmwareInventory": map[string]string{"@odata.id": "/redfish/v1/UpdateService/FirmwareInventory"}}, + "/redfish/v1/UpdateService/FirmwareInventory": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/UpdateService/FirmwareInventory/BMC"}}}, + "/redfish/v1/UpdateService/FirmwareInventory/BMC": map[string]any{"Id": "BMC", "Name": "BMC firmware", "Version": l.bmcFW}, + path + "/Processors": map[string]any{"Members": []any{map[string]string{"@odata.id": path + "/Processors/CPU0"}}}, + path + "/Processors/CPU0": map[string]any{"Id": "CPU0", "Model": "Example CPU", "ProcessorArchitecture": "x86", "InstructionSet": "x86-64", "TotalCores": 2, "Status": l.health("CPU0")}, + path + "/Memory": map[string]any{"Members": l.dimms(path)}, + path + "/Memory/DIMM0": map[string]any{"Id": "DIMM0", "CapacityMiB": 2048, "Status": l.health("DIMM0")}, + path + "/Memory/DIMM1": map[string]any{"Id": "DIMM1", "CapacityMiB": 2048, "Status": map[string]string{"State": "Disabled", "Health": "OK"}}, + path + "/Storage": map[string]any{"Members": []any{map[string]string{"@odata.id": path + "/Storage/1"}}}, + path + "/Storage/1": map[string]any{"Drives": l.drives()}, + "/redfish/v1/Chassis/1/Drives/0": map[string]any{"Name": "disk-0", "CapacityBytes": diskBytes, "Status": l.health("disk-0")}, + path + "/SimpleStorage": map[string]any{"Members": []any{map[string]string{"@odata.id": path + "/SimpleStorage/S0"}}}, + path + "/SimpleStorage/S0": map[string]any{"Id": "S0", "Devices": []any{map[string]any{"Name": "disk-0", "CapacityBytes": diskBytes, "Status": l.health("disk-0")}}}, + path + "/EthernetInterfaces": map[string]any{"Members": []any{map[string]string{"@odata.id": path + "/EthernetInterfaces/NIC0"}}}, + path + "/EthernetInterfaces/NIC0": map[string]any{"Id": "NIC0", "MACAddress": mac, "SpeedMbps": 1000}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, + path: map[string]any{"@odata.id": path, "Id": "A", "UUID": uuid, "PowerState": l.power, "SerialNumber": l.serial, "Status": l.health("System"), + "Processors": map[string]string{"@odata.id": path + "/Processors"}, "Memory": map[string]string{"@odata.id": path + "/Memory"}, + "SimpleStorage": map[string]string{"@odata.id": path + "/SimpleStorage"}, "EthernetInterfaces": map[string]string{"@odata.id": path + "/EthernetInterfaces"}, + "Storage": l.storageLink(path), "Boot": map[string]any{"BootSourceOverrideEnabled": l.enabled, "BootSourceOverrideTarget": l.target, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}}, } @@ -142,6 +188,19 @@ func (l *lab) boot(target string) { } var line string switch { + case target == "Pxe" && boot.Mode == "burnin": + l.mu.Lock() + l.skew += l.pxeTime + l.mu.Unlock() + l.deliver() + l.mu.Lock() + result := l.burnIn + l.skew += l.burnTime + l.mu.Unlock() + line = fmt.Sprintf("FLEET-BURNIN:%s:%s", boot.Receipt, result) + for range l.receipts - 1 { + line += fmt.Sprintf("\nFLEET-BURNIN:%s:%s", boot.Receipt, result) + } case target == "Pxe" && boot.Mode == "wipe": l.deliver() line = fmt.Sprintf("FLEET-WIPED:%s:%d", boot.Receipt, diskBytes) @@ -161,12 +220,60 @@ func (l *lab) boot(target string) { l.mu.Unlock() } +func (l *lab) storageLink(path string) any { + if !l.both && !l.emptyStorage { + return nil + } + return map[string]string{"@odata.id": path + "/Storage"} +} + +func (l *lab) drives() []any { + if l.emptyStorage { + return []any{} + } + return []any{map[string]string{"@odata.id": "/redfish/v1/Chassis/1/Drives/0"}, map[string]string{"@odata.id": "/redfish/v1/Chassis/1/Drives/0"}} +} + +func (l *lab) dimms(path string) []any { + members := []any{map[string]string{"@odata.id": path + "/Memory/DIMM0"}} + if l.disabledDIMM { + members = append(members, map[string]string{"@odata.id": path + "/Memory/DIMM1"}) + } + return members +} + +func (l *lab) effectCount() int { + l.mu.Lock() + defer l.mu.Unlock() + return l.effects +} + +func (l *lab) setUnhealthy(component string) { + l.mu.Lock() + defer l.mu.Unlock() + l.unhealthy = component +} + +func (l *lab) health(component string) map[string]string { + if component == "DIMM0" && l.noHealth { + return map[string]string{"State": "Enabled"} + } + if component == l.unhealthy { + return map[string]string{"State": "Enabled", "Health": "Critical"} + } + return map[string]string{"State": "Enabled", "Health": "OK"} +} + func (l *lab) deliver() { dir := BootDirectory(l.bootRoot, l.operation) os.MkdirAll(dir, 0o700) - log := "t admitted boot.ipxe bytes=1\n" + // The boot server logs on the site's clock, which the store shares. + l.mu.Lock() + at := time.Now().Add(l.skew).UTC().Format(time.RFC3339) + l.mu.Unlock() + log := at + " admitted boot.ipxe bytes=1\n" for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { - log += "t write-complete " + name + " bytes=1\n" + log += at + " write-complete " + name + " bytes=1\n" } os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600) } From 38e85c88ed4eee070fe2fc42c283d6fe040e36e5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 08:14:27 -0600 Subject: [PATCH 2/3] test(site): Pin the delivery round-up The boot log records whole seconds, so burn-in is timed from the second after the last delivered file. Nothing tested that round-up: timing from the logged second passed every test. Pin it with a log whose files finish out of order. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/kinds_test.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 737fa7b9..76f3996e 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -494,3 +494,27 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { t.Fatalf("result = %+v, %d power-ons after %s", result, l.onCount(), time.Since(started)) } } + +// The boot log records whole seconds, so a file logged at 10:00:05 may have +// finished at any point up to 10:00:06. Burn-in is timed from the next whole +// second after the last file, so the log's truncation can never shorten the +// time an image must run. +func TestDeliveryIsRoundedUpToTheNextSecond(t *testing.T) { + cfg := Config{BootRoot: t.TempDir()} + work := &site.Work{Assignment: site.Assignment{Device: "metal/server-a", Fence: 1}} + dir := BootDirectory(cfg.BootRoot, work.Key()) + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + log := "2026-01-02T10:00:00Z admitted boot.ipxe bytes=1\n" + + "2026-01-02T10:00:00Z write-complete boot.ipxe bytes=1\n" + + "2026-01-02T10:00:05Z write-complete installer.gz bytes=1\n" + + "2026-01-02T10:00:03Z write-complete kernel bytes=1\n" + if err := os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600); err != nil { + t.Fatal(err) + } + at, ok := cfg.deliveredAt(work) + if want := time.Date(2026, 1, 2, 10, 0, 6, 0, time.UTC); !ok || !at.Equal(want) { + t.Fatalf("deliveredAt = %v, %v; want %v", at, ok, want) + } +} From 54d9276c45fd9b5430140b340cf25de881cb9f23 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 11:35:12 -0600 Subject: [PATCH 3/3] fix(site): Prove inspection on large servers Three ways the Redfish commissioning worker could report a wrong answer: - Hardware collections stopped silently at 64 members, so a server with more DIMM slots or firmware entries was undercounted and a faulty module past the 64th never checked. Inspection now follows every Members@odata.nextLink page and fails at 1,024 members or 64 pages. - Burn-in ended when the worker journaled it, so a worker restarted after an early report passed the too-short check. It now ends at the last time a worker saw no receipt, stored as burn-in runs. - A firmware baseline took the first entry matching Name. It now takes the entry with that Id, and refuses a Name two entries share. A BMC reporting another serial or UUID is now refused instead of getting a Failed verdict, which custody no longer accepts without the identity. Each GET's limit is the client's per-request timeout, now documented and pinned by a test. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 30 +++- internal/redfish/hardware.go | 55 ++++++-- internal/redfish/hardware_test.go | 82 ++++++++++- internal/redfish/inventory.go | 38 ++++-- internal/site/redfishwork/commissioning.go | 129 ++++++++++++++---- .../site/redfishwork/commissioning_test.go | 99 +++++++++++++- internal/site/redfishwork/kinds.go | 6 + internal/site/redfishwork/kinds_test.go | 9 ++ internal/site/store.go | 4 + 9 files changed, 397 insertions(+), 55 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index aa341df2..177de8ed 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -918,10 +918,23 @@ inventory, which a local read with the worker's Redfish client matched to a plan's hardware and firmware. - **Preflight.** It reads the system's identity, processors, memory, storage, - network interfaces and firmware inventory with GETs only, and compares them - with the plan and the admission snapshot. A mismatch is a `Failed` result - with nothing sent. The passing evidence is stored before burn-in sends - anything, and a resumed worker reuses it. + network interfaces and firmware inventory with GETs only. A serial number + or system UUID other than the admission snapshot's gets no verdict: the + operation is refused with `DeviceIdentityMismatch` before anything is sent. + Otherwise it compares the hardware and firmware with the plan, and a + mismatch is a `Failed` result with nothing sent. The passing evidence is + stored before burn-in sends anything, and a resumed worker reuses it. +- **Collections.** Every member of each hardware and firmware collection is + read, following `Members@odata.nextLink`, so no component goes uncounted + or unchecked. A collection that reaches 1,024 members or 64 pages, or a + Storage controller set that links 1,024 drives, fails the inspection + rather than being read in part. Each GET is bounded by the Redfish + client's per-request timeout, 30 seconds for a pinned client, and the + whole inspection by the operation's deadline. +- **Firmware.** A baseline component matches the inventory entry whose `Id` + it names. Only when no entry has that `Id` does it match by `Name`, and + only a `Name` exactly one entry has: a BMC may list a previous version + beside the running one under the same name. - **Health.** Only `Warning` or `Critical` is unhealthy. Redfish lets a component omit its health, and an omitted health counts as healthy. - **Disks.** Drives come from `Storage`, or from `SimpleStorage` when @@ -935,8 +948,13 @@ plan's hardware and firmware. exactly one result receipt. The boot server passes the plan's duration to the image. Burn-in starts when the boot server finished delivering the image, not at power-on, so firmware start and the network boot do not - count. It ends when the worker journals the receipt. A burn-in that - reported before the plan's duration is a `Failed` result. The boot server + count. It ends at the last time a worker saw the console without the + receipt, which is never after the image reported. A worker stores that + time at least every 30 seconds while burn-in runs, and exactly when it + sees the receipt appear. A worker restarted after the receipt appeared + uses the stored time, so a restart can shorten the recorded burn-in but + never lengthen it. A burn-in that reported before the plan's duration, or + that no worker saw run that long, is a `Failed` result. The boot server and the worker share the site's clock. - **Evidence.** Strings the BMC supplies are cut to 128 bytes, and the component lists are dropped before the verdict if the evidence would pass diff --git a/internal/redfish/hardware.go b/internal/redfish/hardware.go index 571a9530..c4caf016 100644 --- a/internal/redfish/hardware.go +++ b/internal/redfish/hardware.go @@ -9,8 +9,22 @@ import ( "github.com/stmcginnis/gofish/schemas" ) -// maxComponents bounds each hardware collection a commissioning reads. -const maxComponents = 64 +// Commissioning reads every member of each hardware collection, following +// Members@odata.nextLink, because a component it never reads is never +// counted or health-checked. These bound a misbehaving BMC: a collection +// that reaches either bound fails the inspection instead of being read in +// part. Each GET is bounded by the client's per-request timeout (the +// http.Client Timeout set when the client is built), and the whole read by +// the caller's context, which is the operation's deadline. +const ( + maxComponents = 1024 + maxComponentPages = 64 + reportedComponents = 64 +) + +// ErrTooManyMembers means a collection reached a commissioning bound, so +// reading it in part would undercount the server. +var ErrTooManyMembers = errors.New("redfish: collection reaches the commissioning bound") // Hardware is what a System reports about its identity, components and // health. It is read with GETs only. @@ -83,7 +97,7 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { check := func(name string, s status) { if !s.skip() && !s.ok() { hw.Healthy = false - if len(hw.Unhealthy) < maxComponents { + if len(hw.Unhealthy) < reportedComponents { hw.Unhealthy = append(hw.Unhealthy, name) } } @@ -104,7 +118,7 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { if err != nil || p == "" { return err } - paths, err := members(api, p, maxComponents) + paths, err := allMembers(api, p) if err != nil { return err } @@ -171,6 +185,9 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { if seen[dp] { continue } + if len(seen) >= maxComponents { + return ErrTooManyMembers + } seen[dp] = true var drive struct { Name string @@ -184,9 +201,7 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { continue } check("Disk "+drive.Name, drive.Status) - if len(hw.Disks) < maxComponents { - hw.Disks = append(hw.Disks, Disk{Name: drive.Name, CapacityBytes: drive.CapacityBytes}) - } + hw.Disks = append(hw.Disks, Disk{Name: drive.Name, CapacityBytes: drive.CapacityBytes}) } return nil }); err != nil { @@ -213,10 +228,11 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { if device.Status.State == "Absent" || device.CapacityBytes <= 0 { continue } - check("Disk "+device.Name, device.Status) - if len(hw.Disks) < maxComponents { - hw.Disks = append(hw.Disks, Disk{Name: device.Name, CapacityBytes: device.CapacityBytes}) + if len(hw.Disks) >= maxComponents { + return ErrTooManyMembers } + check("Disk "+device.Name, device.Status) + hw.Disks = append(hw.Disks, Disk{Name: device.Name, CapacityBytes: device.CapacityBytes}) } return nil }); err != nil { @@ -227,7 +243,7 @@ func (c *Client) Hardware(ctx context.Context, sys System) (Hardware, error) { if err != nil { return Hardware{}, err } - nics, err := interfaces(api, sys.Path, p) + nics, err := interfacesFrom(api, sys.Path, p, allMembers) if err != nil { return Hardware{}, err } @@ -273,7 +289,7 @@ func firmware(api *gofish.APIClient) ([]Firmware, error) { if service.FirmwareInventory.ID == "" { return nil, nil } - paths, err := members(api, service.FirmwareInventory.ID, maxComponents) + paths, err := allMembers(api, service.FirmwareInventory.ID) if err != nil { return nil, err } @@ -291,3 +307,18 @@ func firmware(api *gofish.APIClient) ([]Firmware, error) { } return out, nil } + +// allMembers returns every member path of a collection, following +// Members@odata.nextLink pages. A collection that reaches maxComponents +// members, or still links a next page after maxComponentPages, fails with +// ErrTooManyMembers. +func allMembers(api *gofish.APIClient, collection string) ([]string, error) { + paths, more, err := walkMembers(api, collection, maxComponents, maxComponentPages) + if err != nil { + return nil, err + } + if more || len(paths) >= maxComponents { + return nil, ErrTooManyMembers + } + return paths, nil +} diff --git a/internal/redfish/hardware_test.go b/internal/redfish/hardware_test.go index 92617b8d..b2b23c93 100644 --- a/internal/redfish/hardware_test.go +++ b/internal/redfish/hardware_test.go @@ -1,6 +1,12 @@ package redfish -import "testing" +import ( + "context" + "errors" + "fmt" + "testing" + "time" +) func TestArchitecture(t *testing.T) { for _, c := range []struct{ processor, set, want string }{ @@ -16,3 +22,77 @@ func TestArchitecture(t *testing.T) { } } } + +// memoryStub serves System A with n memory modules, perPage to a page of +// the Memory collection. The last module reports Critical health. +func memoryStub(n, perPage int) *bmcStub { + b := newStub() + sys := "/redfish/v1/Systems/A" + b.docs[sys].(map[string]any)["Memory"] = map[string]string{"@odata.id": sys + "/Memory"} + for page := 0; page*perPage < n || page == 0; page++ { + key := sys + "/Memory" + if page > 0 { + key += fmt.Sprintf("?$skip=%d", page*perPage) + } + var list []any + for i := page * perPage; i < min(n, (page+1)*perPage); i++ { + list = append(list, map[string]string{"@odata.id": fmt.Sprintf("%s/Memory/DIMM%d", sys, i)}) + } + doc := map[string]any{"Members": list} + if (page+1)*perPage < n { + doc["Members@odata.nextLink"] = fmt.Sprintf("%s/Memory?$skip=%d", sys, (page+1)*perPage) + } + b.docs[key] = doc + } + for i := range n { + health := "OK" + if i == n-1 { + health = "Critical" + } + b.docs[fmt.Sprintf("%s/Memory/DIMM%d", sys, i)] = map[string]any{"Id": fmt.Sprintf("DIMM%d", i), "CapacityMiB": 1024, "Status": map[string]string{"State": "Enabled", "Health": health}} + } + return b +} + +// Every module is read and health-checked, across pages, however many slots +// the server has up to the bound: a faulty module past the 64th is found. +func TestHardwareReadsEveryMemoryModule(t *testing.T) { + b := memoryStub(96, 40) + c := stubClient(t, b, time.Second) + hw, err := c.Hardware(context.Background(), System{Path: "/redfish/v1/Systems/A"}) + if err != nil { + t.Fatal(err) + } + if hw.MemoryMiB != 96*1024 || hw.Healthy || len(hw.Unhealthy) != 1 || hw.Unhealthy[0] != "Memory DIMM95" { + t.Fatalf("memory %d MiB, healthy %v %v", hw.MemoryMiB, hw.Healthy, hw.Unhealthy) + } +} + +// A collection that reaches the member or page bound fails the inspection +// instead of being read in part. +func TestHardwareFailsACollectionAtTheBound(t *testing.T) { + for name, b := range map[string]*bmcStub{ + "members": memoryStub(maxComponents, maxComponents), + "pages": memoryStub(maxComponentPages+1, 1), + } { + c := stubClient(t, b, time.Second) + if _, err := c.Hardware(context.Background(), System{Path: "/redfish/v1/Systems/A"}); !errors.Is(err, ErrTooManyMembers) { + t.Errorf("%s: %v", name, err) + } + } +} + +// Each GET is bounded by the client's per-request timeout, not only by the +// caller's context: one stalled member read fails the inspection. +func TestHardwareBoundsEachRequest(t *testing.T) { + b := memoryStub(2, 2) + b.hold["GET /redfish/v1/Systems/A/Memory/DIMM1"] = 2 * time.Second + c := stubClient(t, b, 100*time.Millisecond) + start := time.Now() + if _, err := c.Hardware(context.Background(), System{Path: "/redfish/v1/Systems/A"}); err == nil { + t.Fatal("a stalled member read passed") + } + if elapsed := time.Since(start); elapsed > time.Second { + t.Fatalf("a stalled read took %s, past the client's timeout", elapsed) + } +} diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index ac95f211..e38a6f1a 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -142,21 +142,31 @@ func getJSON(api *gofish.APIClient, path string, out any) error { // members returns up to limit member paths of a collection, following // Members@odata.nextLink pages. Every member must sit under the collection. +// Discovery reads only up to its bounds. func members(api *gofish.APIClient, collection string, limit int) ([]string, error) { + out, _, err := walkMembers(api, collection, limit, maxCollectionPages) + return out, err +} + +// walkMembers reads at most pages pages and keeps at most limit members. more +// reports whether the collection has members or pages past those bounds. +func walkMembers(api *gofish.APIClient, collection string, limit, pages int) (out []string, more bool, err error) { base, err := cleanPath(collection) if err != nil { - return nil, err + return nil, false, err } - var out []string next := base - for page := 0; next != "" && page < maxCollectionPages && len(out) < limit; page++ { + for page := 0; next != ""; page++ { + if page >= pages || len(out) >= limit { + return out, true, nil + } var doc struct { Members []link NextLink string `json:"Members@odata.nextLink"` } path, query, _ := strings.Cut(next, "?") if _, err := cleanPath(path); err != nil || (path != base && !strings.HasPrefix(path, base+"/")) { - return nil, errors.New("redfish: collection page outside the collection") + return nil, false, errors.New("redfish: collection page outside the collection") } if query != "" { path += "?" + query @@ -167,31 +177,41 @@ func members(api *gofish.APIClient, collection string, limit int) ([]string, err } schemas.DeferredCleanupHTTPResponse(resp) if err != nil { - return nil, classify(err) + return nil, false, classify(err) } for _, m := range doc.Members { p, err := cleanPath(m.ID) if err != nil || !strings.HasPrefix(p, base+"/") { - return nil, errors.New("redfish: collection member outside the collection") + return nil, false, errors.New("redfish: collection member outside the collection") } if len(out) < limit { out = append(out, p) + } else { + more = true } } next = doc.NextLink } - return out, nil + return out, more, nil } -// interfaces reads an EthernetInterfaces collection that must belong to owner. +// interfaces reads an EthernetInterfaces collection that must belong to +// owner, up to discovery's bounds. func interfaces(api *gofish.APIClient, owner, collection string) ([]NetworkInterface, error) { + return interfacesFrom(api, owner, collection, func(api *gofish.APIClient, collection string) ([]string, error) { + return members(api, collection, maxInventoryInterfaces) + }) +} + +// interfacesFrom reads the interfaces at the member paths list returns. +func interfacesFrom(api *gofish.APIClient, owner, collection string, list func(*gofish.APIClient, string) ([]string, error)) ([]NetworkInterface, error) { if collection == "" { return nil, nil } if p, err := cleanPath(collection); err != nil || !strings.HasPrefix(p, owner+"/") { return nil, errors.New("redfish: EthernetInterfaces outside its owner") } - paths, err := members(api, collection, maxInventoryInterfaces) + paths, err := list(api, collection) if err != nil { return nil, err } diff --git a/internal/site/redfishwork/commissioning.go b/internal/site/redfishwork/commissioning.go index 099611b0..8b5e9c56 100644 --- a/internal/site/redfishwork/commissioning.go +++ b/internal/site/redfishwork/commissioning.go @@ -123,18 +123,26 @@ func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { // Burn-in is timed from the boot server's delivery of the image, not from // power-on, so firmware start and the network boot do not count towards // it. An image that reports early fails however long the server took to - // fetch it. + // fetch it. It ends at the last time a worker saw no receipt, which is + // never after the image reported, so a worker restarted after an early + // report cannot lengthen it. started, delivered := k.deliveredAt(work) - completed, verified := work.JournaledAt(burnInPhase.name + "-verified") - if !delivered || !verified { - return nil, errors.New("the boot log and journal do not record when burn-in began and ended") + if !delivered { + return nil, errors.New("the boot log does not record when burn-in began") + } + completed, err := receiptBound(work) + if err != nil { + return nil, err + } + if completed.Before(started) { + completed = started } evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metaNow(started), CompletedAt: metaNow(completed)} if result != ops.BurnInPassed { return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported a failure"}) } if completed.Sub(started) < plan.BurnIn.Duration.Duration { - return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported before the plan's duration"}) + return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported before the plan's duration, or no worker saw it run that long"}) } after, err := conn(work).BMC.Hardware(ctx, conn(work).System) if err != nil { @@ -147,6 +155,62 @@ func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { return fit(evidence), nil } +// receiptRecords holds, for each operation, the last time a worker saw no +// burn-in receipt on the console, on the store's clock. +const receiptRecords = "burnin-receipt" + +// receiptPersistEvery is how often a worker stores the time it last saw no +// receipt while burn-in runs. A worker that sees the receipt appear stores +// its exact last sighting of none; one restarted after the receipt appeared +// uses the stored time, at most this much earlier, so a restart can shorten +// a burn-in's recorded length but never lengthen it. +const receiptPersistEvery = 30 * time.Second + +type receiptRecord struct { + AbsentAt time.Time `json:"absentAt"` +} + +// receiptAbsence tracks one worker's sightings of the burn-in console. +type receiptAbsence struct { + last, stored time.Time + seen bool +} + +// observe records one poll of the console: seen is the number of burn-in +// receipts found. +func (a *receiptAbsence) observe(work *site.Work, seen int) error { + store := work.Store() + switch { + case a.seen: + return nil + case seen == 0: + a.last = store.Now() + if a.stored.IsZero() || a.last.Sub(a.stored) >= receiptPersistEvery { + a.stored = a.last + return store.PutRecord(work.Device, work.Fence, receiptRecords, work.Key(), receiptRecord{AbsentAt: a.last}) + } + return nil + } + a.seen = true + if a.last.IsZero() { + // This worker never saw the console without the receipt: keep what + // an earlier worker stored. + return nil + } + return store.PutRecord(work.Device, work.Fence, receiptRecords, work.Key(), receiptRecord{AbsentAt: a.last}) +} + +// receiptBound is the stored last time a worker saw no burn-in receipt. With +// none stored, nothing shows the burn-in ran at all, and the zero time makes +// it as short as possible. +func receiptBound(work *site.Work) (time.Time, error) { + var record receiptRecord + if _, err := work.Store().GetRecord(work.Device, receiptRecords, work.Key(), &record); err != nil { + return time.Time{}, err + } + return record.AbsentAt, nil +} + // preflightRecords holds each operation's passing inspection and firmware // evidence, stored before burn-in sends anything. const preflightRecords = "commissioning" @@ -163,9 +227,15 @@ func (k Commissioning) preflight(ctx context.Context, work *site.Work, spec ops. if err != nil { return evidence, "", nil, fmt.Errorf("inspection could not read the server: %w", err) } + // A verdict is about the admitted server only. A BMC that reports + // another identity gets none: the operation is refused before anything + // is sent. + if serial := work.Snapshot.Extra[custody.SnapshotSerialNumber]; serial == "" || !strings.EqualFold(strings.TrimSpace(serial), hw.SerialNumber) || !strings.EqualFold(hw.UUID, work.Snapshot.SystemUUID) { + return evidence, "", nil, &custody.Refusal{Reason: custody.ReasonDeviceIdentityMismatch, Message: "the BMC reports another serial number or system UUID than the Device records"} + } evidence.SerialNumber, evidence.SystemUUID = clip(hw.SerialNumber), hw.UUID evidence.Hardware = inspected(hw) - if mismatches := inspect(spec.Plan.Content.Inspection, hw, work.Snapshot); len(mismatches) > 0 { + if mismatches := inspect(spec.Plan.Content.Inspection, hw); len(mismatches) > 0 { return evidence, ops.PhaseInspect, mismatches, nil } firmware, err := conn(work).BMC.Firmware(ctx) @@ -279,17 +349,10 @@ func quantity(bytes int64) string { return resource.NewQuantity(bytes, resource.BinarySI).String() } -// inspect compares what the BMC reported with the plan and the Device's -// recorded identity. CPU and memory must match exactly; disks and interfaces -// are minimums. -func inspect(plan ops.CommissioningInspection, hw redfish.Hardware, snapshot ops.DeviceSnapshot) []string { +// inspect compares what the BMC reported with the plan. CPU and memory must +// match exactly; disks and interfaces are minimums. +func inspect(plan ops.CommissioningInspection, hw redfish.Hardware) []string { var out []string - if serial := snapshot.Extra[custody.SnapshotSerialNumber]; serial == "" || !strings.EqualFold(strings.TrimSpace(serial), hw.SerialNumber) { - out = append(out, "the BMC reports another serial number than the Device records") - } - if !strings.EqualFold(hw.UUID, snapshot.SystemUUID) { - out = append(out, "the BMC reports another system UUID than the Device records") - } if !hw.Healthy { out = append(out, "unhealthy: "+strings.Join(hw.Unhealthy, ", ")) } @@ -352,24 +415,38 @@ func inspected(hw redfish.Hardware) *ops.InspectedHardware { } // checkFirmware returns every baseline component as the BMC reported it, and -// what does not match. A component matches by Id or by Name. +// what does not match. A component matches the inventory entry whose Id it +// names. Only when no entry has that Id does it match by Name, and then only +// a Name that one entry has: a BMC may list a previous version beside the +// running one under the same Name, and either could be the one running. func checkFirmware(baseline []ops.FirmwareBaseline, inventory []redfish.Firmware) ([]ops.FirmwareBaseline, []string) { var reported []ops.FirmwareBaseline var mismatches []string for _, want := range baseline { - found := false + var byID, byName []redfish.Firmware for _, item := range inventory { - if item.ID == want.Component || item.Name == want.Component { - found = true - reported = append(reported, ops.FirmwareBaseline{Component: want.Component, Version: clip(item.Version)}) - if item.Version != want.Version { - mismatches = append(mismatches, fmt.Sprintf("%s is %q, want %q", want.Component, clip(item.Version), want.Version)) - } - break + if item.ID == want.Component { + byID = append(byID, item) + } + if item.Name == want.Component { + byName = append(byName, item) } } - if !found { + matches := byID + if len(matches) == 0 { + matches = byName + } + switch len(matches) { + case 0: mismatches = append(mismatches, want.Component+" is not reported") + case 1: + item := matches[0] + reported = append(reported, ops.FirmwareBaseline{Component: want.Component, Version: clip(item.Version)}) + if item.Version != want.Version { + mismatches = append(mismatches, fmt.Sprintf("%s is %q, want %q", want.Component, clip(item.Version), want.Version)) + } + default: + mismatches = append(mismatches, fmt.Sprintf("%s matches %d firmware inventory entries", want.Component, len(matches))) } } return reported, mismatches diff --git a/internal/site/redfishwork/commissioning_test.go b/internal/site/redfishwork/commissioning_test.go index bd4744ef..6d24d521 100644 --- a/internal/site/redfishwork/commissioning_test.go +++ b/internal/site/redfishwork/commissioning_test.go @@ -13,6 +13,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -110,7 +111,6 @@ func TestCommissioningFailsAMismatchWithoutSendingAnything(t *testing.T) { "memory": {plan: func(p *ops.CommissioningPlanContent) { p.Inspection.Memory.Capacity = "4Gi" }, phase: ops.PhaseInspect, expect: "MiB of memory"}, "disks": {plan: func(p *ops.CommissioningPlanContent) { p.Inspection.Disks.Count = 2 }, phase: ops.PhaseInspect, expect: "disks of at least"}, "unhealthy": {lab: func(l *lab) { l.unhealthy = "DIMM0" }, phase: ops.PhaseInspect, expect: "Memory DIMM0"}, - "serial": {lab: func(l *lab) { l.serial = "OTHER" }, phase: ops.PhaseInspect, expect: "serial number"}, "firmware": {lab: func(l *lab) { l.bmcFW = "0.9.0" }, phase: ops.PhaseFirmware, expect: `BMC is "0.9.0"`}, "missing": {plan: func(p *ops.CommissioningPlanContent) { p.Firmware = append(p.Firmware, ops.FirmwareBaseline{Component: "BIOS", Version: "1"}) @@ -316,3 +316,100 @@ func TestASlowBootDoesNotLengthenTheBurnIn(t *testing.T) { t.Fatalf("result = %+v, evidence %+v", result, evidence) } } + +// A BMC that reports another serial number gets no verdict: a Failed one +// would be about another server. The operation is refused before anything +// is sent. +func TestCommissioningRefusesAnotherServer(t *testing.T) { + l := newLab(t) + l.serial = "OTHER" + r := commissioningRunner(t, l) + result, _ := commission(t, l, r, "op-other-serial", planSpec(t, nil)) + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonDeviceIdentityMismatch || len(result.Evidence) != 0 || l.effectCount() != 0 { + t.Fatalf("result = %+v, %d effects", result, l.effectCount()) + } +} + +// A worker killed after the image reported early, before it journaled the +// burn-in done, is replaced later. The replacement's journal time is long +// after the plan's duration, but burn-in ends when the receipt appeared, so +// it still fails as too short. +func TestARestartAfterAnEarlyReceiptStillFailsTooShort(t *testing.T) { + l := newLab(t) + l.burnTime = 0 + r := commissioningRunner(t, l) + spec := planSpec(t, nil) + work := assignment(l, "DeviceCommissioning", "op-early-restart", 1, spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + ctx, cancel := context.WithCancel(context.Background()) + var once sync.Once + l.afterReceipt = func() { + once.Do(func() { + cancel() + // The replacement starts well after the plan's duration. + l.mu.Lock() + l.skew += 10 * time.Minute + l.mu.Unlock() + }) + } + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + journal, err := r.Store.Journal(device) + if err != nil { + t.Fatal(err) + } + for _, entry := range journal { + if entry.Operation == work.Key() && entry.Step == burnInPhase.name+"-verified" && entry.State == site.StepDone { + t.Fatal("the first worker journaled the burn-in before it was stopped") + } + } + l.afterReceipt = nil + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + var evidence ops.CommissioningEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil { + t.Fatalf("result = %+v", result) + } + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || l.onCount() != 1 { + t.Fatalf("result = %+v, evidence %+v, %d power-ons", result, evidence, l.onCount()) + } + if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got >= time.Minute { + t.Fatalf("burn-in recorded as %s", got) + } + operation := &ops.DeviceCommissioning{Spec: spec, Status: ops.OperationStatus{Snapshot: &work.Snapshot}} + if _, err := custody.DeviceCommissioningKind().Evidence(operation, result.Evidence); err != nil { + t.Fatalf("the kind rejects the worker's evidence: %v", err) + } +} + +// A baseline matches the entry whose Id it names before any entry by Name, +// and a Name two entries share matches neither: a previous version listed +// first must not stand in for the running one. +func TestFirmwareMatchesByIdAndRefusesAnAmbiguousName(t *testing.T) { + for name, c := range map[string]struct { + inventory []redfish.Firmware + want ops.FirmwareBaseline + mismatch string + }{ + "id before name": { + inventory: []redfish.Firmware{{ID: "Previous", Name: "BMC", Version: "1.0.0"}, {ID: "BMC", Name: "BMC firmware", Version: "2.0.0"}}, + want: ops.FirmwareBaseline{Component: "BMC", Version: "1.0.0"}, mismatch: `BMC is "2.0.0"`, + }, + "shared name": { + inventory: []redfish.Firmware{{ID: "BIOS-previous", Name: "BIOS", Version: "1"}, {ID: "BIOS-current", Name: "BIOS", Version: "2"}}, + want: ops.FirmwareBaseline{Component: "BIOS", Version: "1"}, mismatch: "BIOS matches 2 firmware inventory entries", + }, + "unique name": { + inventory: []redfish.Firmware{{ID: "0", Name: "BIOS", Version: "1"}}, + want: ops.FirmwareBaseline{Component: "BIOS", Version: "1"}, + }, + } { + _, mismatches := checkFirmware([]ops.FirmwareBaseline{c.want}, c.inventory) + if got := strings.Join(mismatches, ";"); (c.mismatch == "") != (got == "") || !strings.Contains(got, c.mismatch) { + t.Errorf("%s: mismatches %q, want %q", name, got, c.mismatch) + } + } +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index b1705330..9aa2c9c4 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -385,6 +385,7 @@ func (c Config) started(ctx context.Context, work *site.Work, boot Boot, ph phas func (c Config) complete(ctx context.Context, work *site.Work, boot Boot, ph phase) error { poll, offGrace, outage, _ := c.durations() var offSince, failingSince time.Time + var absence receiptAbsence for { power, err := conn(work).Observe(ctx) switch { @@ -403,6 +404,11 @@ func (c Config) complete(ctx context.Context, work *site.Work, boot Boot, ph pha if err != nil { return err } + if ph.name == burnInPhase.name { + if err := absence.observe(work, seen); err != nil { + return err + } + } if power.State == "Off" { if seen == 1 { if ph.mode != "" { diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 76f3996e..288c76cc 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -80,6 +80,9 @@ type lab struct { // pxeTime is how long firmware start and the network boot take before // the boot server delivers the image. pxeTime time.Duration + // afterReceipt runs once the receipt is on the console, before the + // server powers off. + afterReceipt func() } func newLab(t *testing.T) *lab { @@ -197,6 +200,9 @@ func (l *lab) boot(target string) { result := l.burnIn l.skew += l.burnTime l.mu.Unlock() + // Let the worker poll the console once more on the moved clock + // before the receipt appears, as it would while a real burn-in ran. + time.Sleep(50 * time.Millisecond) line = fmt.Sprintf("FLEET-BURNIN:%s:%s", boot.Receipt, result) for range l.receipts - 1 { line += fmt.Sprintf("\nFLEET-BURNIN:%s:%s", boot.Receipt, result) @@ -215,6 +221,9 @@ func (l *lab) boot(target string) { fmt.Fprintln(file, line) file.Close() } + if l.afterReceipt != nil { + l.afterReceipt() + } l.mu.Lock() l.power = "Off" l.mu.Unlock() diff --git a/internal/site/store.go b/internal/site/store.go index 9cad0c07..2ef38ef6 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -330,6 +330,10 @@ func (s *Store) tryRunLock(device string) (*runLock, error) { func (l *runLock) release() { l.file.Close() } +// Now is the store's clock, which stamps the journal. A kind records +// times it compares with journal times on it. +func (s *Store) Now() time.Time { return s.now() } + // PutRecord stores a kind's per-operation record for a Device, such as its // boot admission, beside the journal. A record below the stored fence is // refused.