Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions cmd/fleet-multiplane/site.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"go.datum.net/fleet/internal/redfish"
"go.datum.net/fleet/internal/site"
"go.datum.net/fleet/internal/site/fixture"
"go.datum.net/fleet/internal/site/powerwork"
"go.datum.net/fleet/internal/site/redfishwork"
"go.datum.net/fleet/internal/site/vmwork"
)
Expand Down Expand Up @@ -212,11 +213,19 @@ func siteRunner(_ context.Context, config *rest.Config, cell string, store *site
return nil, err
}
_, burnIn, _ := strings.Cut(image, "@")
runner.Kinds = map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work},
"DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn}}
runner.Kinds = redfishKinds(work, burnIn)
return runner, nil
}

// redfishKinds are the workers a Redfish site runs. Power runs only over
// Redfish: the local VM site has no BMC, so it refuses a power operation as
// an unsupported kind with nothing sent.
func redfishKinds(work redfishwork.Config, burnIn string) map[string]site.Kind {
return map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work},
"DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn},
"DevicePowerOperation": powerwork.Power{}}
}

// boot serves network boots, the DHCP reservation feed, or probes that
// every closed admission is denied.
func boot(command, origin, extraMAC, syncToken string) error {
Expand Down
20 changes: 20 additions & 0 deletions cmd/fleet-multiplane/site_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package main
import (
"os"
"path/filepath"
"strings"
"testing"

"go.datum.net/fleet/internal/site/powerwork"
"go.datum.net/fleet/internal/site/redfishwork"
)

// TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator refuses a runtime
Expand All @@ -23,3 +27,19 @@ func TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator(t *testing.T) {
t.Fatalf("a TCG worker refused a TCG runtime: %v", err)
}
}

// TestARedfishSiteRunsPowerOperations requires the Redfish site's worker kinds,
// which siteRunner installs, to include power beside the install, wipe and
// commissioning workers. siteRunner itself reads the site image's artifacts,
// so the multi-plane Redfish run covers that it uses them.
func TestARedfishSiteRunsPowerOperations(t *testing.T) {
kinds := redfishKinds(redfishwork.Config{}, "sha256:"+strings.Repeat("0", 64))
if _, ok := kinds["DevicePowerOperation"].(powerwork.Power); !ok {
t.Fatalf("kinds = %v", kinds)
}
for _, kind := range []string{"DeviceInstallation", "DeviceWipe", "DeviceCommissioning"} {
if kinds[kind] == nil {
t.Fatalf("%s is not registered", kind)
}
}
}
59 changes: 50 additions & 9 deletions docs/development/device-custody.md
Original file line number Diff line number Diff line change
Expand Up @@ -1211,12 +1211,15 @@ against a real API server.

This section records how Fleet implements the power kind of the [device power
operations proposal](https://github.com/datum-cloud/fleet/pull/173) (#173,
pinned at `d6744ab`) on this foundation. Step P1 is **implemented**: the
coordinator admits, holds and settles power operations in every mode the
cutover wires, but no site worker runs them and nothing creates them. It
follows [Adding an operation kind](#adding-an-operation-kind), and adds no
change to the coordinator. The kind joins the creator webhook's governed
kinds, standalone's creator policy and each coordinator's access, and
pinned at `d6744ab`) on this foundation. Step P1, the control plane, is
**implemented**: the coordinator admits, holds and settles power operations in
every mode the cutover wires. Step P2, the site worker, is **implemented**
behind the site worker contract. Nothing creates power operations yet. It
follows [Adding an operation kind](#adding-an-operation-kind), and adds the
two [foundation seams](#foundation-seams-power-added) below. The worker
changes no coordinator behavior and no site framework code, and adds only
reasons to the kind's reason table. The kind joins the creator webhook's
governed kinds, standalone's creator policy and each coordinator's access, and
`TestEveryOperationKindIsGoverned` requires every operation kind to be
governed.

Expand All @@ -1234,9 +1237,22 @@ governed.
| Roles | The **device power operator** inherits the viewer and creates only `DevicePowerOperation`. It does not read MachineAllocations. The **device power requester** is the Fleet provider for Metal's role. The viewer and coordinator cover the new kind. |
| Discovery | Power reads the `ComputerSystem.Reset` types the Device's observed System offers, which BMC discovery records with GETs only. |

The worker reasons `Stale`, `NotPoweredOn` and `PowerStateNotSettled` before
a command, the start-by window and the journal payload arrive with the worker
in B.
### The power worker

| Piece | Decision |
| --- | --- |
| Before the command | The framework checks the credential, the pin and the System's identity. The worker then checks the expected system UUID against that System (`SystemUUIDMismatch`) and that the BMC still offers the action (`ResetTypeNotOffered`). It reads the power state once: a transition state refuses with `PowerStateNotSettled`, and a restart or power cycle of a server that is off refuses with `NotPoweredOn`. Each refusal sends nothing and ends `Failed`. |
| Start-by window | Two minutes after admission. A later start with nothing sent ends `Failed` with the shared reason `Stale`. |
| Already in the requested state | `On` of a server that is on and `ForceOff` of one that is off send nothing and succeed, with no `requestSentAt`. |
| The one reset | One journaled step. Its payload records when the command was sent, the power state read before it, and the BMC's `LastResetTime` as the baseline. A response the BMC returns refusing the command is an error. A lost response is not: the worker watches for the effect. |
| Success | `On` and `ForceOff`: the requested state appears within three minutes of the command. A restart or power cycle: the BMC's `LastResetTime` moves past the baseline, or the worker sees the server off, and then the server is on again. `resetEvidence` records which. When the BMC reported no reset time before the command, only seeing the server off proves a restart. A restart the server made by itself between the baseline read and the command would also move the reset time; the window is one request long, and the BMC's clock is not trusted enough to compare against the send time. |
| Crash or lost response | A resumed worker reads the journaled payload instead of reading the server again, and watches for the effect. It never sends a second reset. |
| Not proven | A reset whose effect does not appear in time, a BMC that refused the command, and a BMC that starts reporting another system after the command all end `OutcomeUnknown`, which places a recovery hold. |
| Registration | A Redfish site registers the worker as `DevicePowerOperation`. The local VM and simulator sites have no BMC and no power worker, so they refuse a power operation as an unsupported kind, with nothing sent. |

The lab BMC records `LastResetTime` and adds faults for a withheld request, a
hidden reset time and an identity swap, as [the Redfish
lab](../operations/redfish-lab.md) describes.

### Foundation seams power added

Expand All @@ -1254,6 +1270,29 @@ working around their absence:
a `Succeeded` restart with no reset proof, or with the empty object `{}`,
was accepted. `ProvesSuccess` runs on a `Succeeded` result's evidence only.

### Worker gaps that remain

Each needs a change in the site framework or the harness, and none is worked
around here.

- **No end-to-end run creates a power operation yet.** Both multi-plane runs
and the synthetic staging write fixture discovery, which reports every
server off and records no reset types. Admission then leaves the reset-type
check to the worker's live read, but no run's phases create a power
operation, and a `Settle` has no real power state to cite. The power phases
need real BMC discovery in the Redfish run, or fixture discovery that
reports the server's power.
- **A swap before the command is reported as `DeviceIdentityMismatch`.** The
framework verifies the System's identity before a kind runs, with the
shared reason. #173 names this refusal `SystemUUIDMismatch` at the worker.
Power raises `SystemUUIDMismatch` only for a swap after the framework's
check.
- **A command the BMC refused ends `OutcomeUnknown`, not `Failed`.** Once a
step is journaled, the framework ends any refusal as `OutcomeUnknown`.
#173 asks for `Failed` when the BMC refused and the power state did not
change. The result is safe, but it places a hold that a recovery must
settle.

## Tests

Run `task test:envtest`. It runs these tests with the race detector against
Expand All @@ -1279,6 +1318,8 @@ a real API server:
| Power: each refusal with custody unchanged, both rows and every other pair, staff racing an allocation, replacement only by the provider row and waiting under a hold, expiry, an early staff retry settling after `Retry`, `Settle` evidence, required evidence, a provider request waiting for discovery (its bound, its replacement, and two coordinators admitting it once), and proof of a success, including a retry's | `TestPowerOperations` |
| A check refusal that waits only on a queue row, within its bound from when the Device was last free, and only with a declared reason; proof of success needs required evidence | `TestExtensionSeams`, `TestRegistryRequiresEvidenceForProofOfSuccess` |
| Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` |
| Power worker: one reset per action and its proof, sending nothing when already in the requested state, each refusal with nothing sent, a lost response, a request never applied, an unprovable restart, a swap after the command, a resumed worker, two workers for one assignment | `go test ./internal/site/powerwork` |
| The BMC's reset time and the lab's power faults | `TestObserveReadsTheLastResetTime`; the lab adapter self-test |

Increment A has no site, so "nothing was sent" means custody admitted nothing
and the fence did not rise. Increment D's phases prove it end to end, with the
Expand Down
3 changes: 2 additions & 1 deletion docs/operations/redfish-lab.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,14 @@ 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 |
| `LastResetTime`, set for each System when the adapter first starts, persisted on the site volume, and moved forward each time a reset starts the domain | 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 |
| Bounded, one-shot lab faults (`reject-auth`, `hide-reset`, `drop-response`) from a fault file | Adapter, lab only |
| Bounded lab faults from a fault file: one-shot `reject-auth`, `drop-response` (any applied reset, response withheld) and `drop-request` (response withheld, reset never applied); and, until cleared, `hide-reset` (a reset type), `hide-reset-time` and `swap-identity` (the System reports another UUID) | Adapter, lab only |

`hack/redfish-lab/test_adapter.py` runs inside the built image, with the real
upstream emulator and a fake `virsh`, in the `bmc-self-test` phase.
Expand Down
41 changes: 37 additions & 4 deletions hack/redfish-lab/fleet_lab_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* 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;
* LastResetTime, persisted per System and moved forward each time a reset
starts the domain;
* 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.
Expand Down Expand Up @@ -161,6 +163,13 @@ def __init__(self, targets, state, boot_ip):
for sid in targets:
self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'})
atomic_write(self.nvram_path, self.nvram)
self.reset_path = os.path.join(state, 'last-reset.json')
self.last_reset = read_json(self.reset_path, {})
# A real BMC reports a reset time from its first read, so a restart
# always has a baseline to move past.
for sid in targets:
self.last_reset.setdefault(sid, now())
atomic_write(self.reset_path, self.last_reset)

def ensure(self, sid):
"""Define lost libvirt objects (the runtime Pod's libvirt config is not durable)."""
Expand Down Expand Up @@ -203,6 +212,9 @@ def power_on(self, sid):
require_accelerator()
virsh('define', '/dev/stdin', input=domain_xml(t, boot))
virsh('start', t['domain'])
# The System came out of a reset now, as a BMC reports it.
self.last_reset[sid] = now()
atomic_write(self.reset_path, self.last_reset)
return boot


Expand Down Expand Up @@ -238,7 +250,9 @@ def create_app(targets, state, credentials, boot_ip):

def publish(sid, power=None):
m = cs.members[sid]
m['UUID'] = targets[sid]['uuid']
current = faults.read()
# Lab fault: the BMC reports another server, as after a board swap.
m['UUID'] = current.get('swapIdentity', {}).get(sid, 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']
Expand All @@ -254,7 +268,11 @@ def publish(sid, power=None):
'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)})
if power:
m['PowerState'] = power
hidden = set(faults.read().get('hideResetTypes', []))
if sid in lab.last_reset and sid not in current.get('hideResetTime', []):
m['LastResetTime'] = lab.last_reset[sid]
else:
m.pop('LastResetTime', None)
hidden = set(current.get('hideResetTypes', []))
rai.members[sid]['Parameters'][0]['AllowableValues'] = [v for v in RESET_TYPES if v not in hidden]

for sid in targets:
Expand Down Expand Up @@ -366,6 +384,13 @@ def reset(sid):
if kind not in allowed:
return error(400, 'unsupported ResetType')
domain = targets[sid]['domain']
withheld = take('dropRequest', lambda f: f.get('system') == sid and f.get('resetType') == kind)
if withheld:
# Lab fault: the request is withheld past the client timeout and
# never applied.
request_context.detail = {'resetType': kind, 'effect': 'none', 'fault': 'drop-request'}
time.sleep(min(int(withheld.get('seconds', 45)), 120))
return error(503, 'lab BMC dropped the request')
try:
with LOCK:
power = lab.power(sid)
Expand All @@ -379,7 +404,7 @@ def reset(sid):
except LibvirtError as e:
return error(503, 'lab hardware unavailable: %s' % e)
request_context.detail = {'resetType': kind, 'effect': effect}
drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect.startswith('started') else None
drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect != 'none' else None
if drop:
# Lab fault: the effect is applied, the response is withheld past the client timeout.
request_context.detail['fault'] = 'drop-response-after-effect'
Expand Down Expand Up @@ -429,12 +454,20 @@ def fault_cli(args):
faults.update(lambda v: v.__setitem__('rejectAuth', int(args[1])))
elif args[:1] == ['hide-reset'] and len(args) == 2:
faults.update(lambda v: v.setdefault('hideResetTypes', []).append(args[1]))
elif args[:1] == ['drop-request'] and len(args) in (4, 5):
skip = int(args[4]) if len(args) == 5 else 0
faults.update(lambda v: v.setdefault('dropRequest', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip}))
elif args[:1] == ['swap-identity'] and len(args) == 3:
faults.update(lambda v: v.setdefault('swapIdentity', {}).__setitem__(args[1], args[2]))
elif args[:1] == ['hide-reset-time'] and len(args) == 2:
faults.update(lambda v: v.setdefault('hideResetTime', []).append(args[1]))
elif args == ['clear']:
faults.update(lambda v: v.clear())
elif args == ['show']:
pass
else:
raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | reject-auth COUNT | hide-reset TYPE | clear | show')
raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | drop-request SYSTEM RESETTYPE SECONDS [SKIP]'
' | swap-identity SYSTEM UUID | hide-reset-time SYSTEM | reject-auth COUNT | hide-reset TYPE | clear | show')
print(json.dumps(faults.read(), sort_keys=True))


Expand Down
Loading
Loading