From e36ed8f29101c6416ef909a87ebad75bdb194a09 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 16:39:11 -0600 Subject: [PATCH 1/3] feat: Record the reset types each BMC offers Power operations must refuse an action the server does not offer before anything is sent. Discovery now records the ComputerSystem.Reset types each System advertises, inline or from its own ActionInfo, in status.discovery.inventory.systems[].resetTypes. It reads them with GETs and never invokes the action. The Redfish client also gains the read side a power worker needs: find the one System carrying a UUID across every collection page, re-read its power state and LastResetTime with an identity check, and send one reset. Discover now shares the reset-type reader, so the executor and discovery parse ActionInfo the same way. Co-Authored-By: Claude Opus 5.5 --- .../examples/credential-secret.yaml | 4 +- .../inventory/crds/fleet.datumapis.com.yaml | 4 + docs/operations/bmc-discovery.md | 13 +- internal/api/inventory/v1alpha1/types.go | 4 +- internal/bmcdiscovery/discovery_test.go | 10 +- internal/bmcdiscovery/status.go | 16 +- internal/redfish/client.go | 36 +--- internal/redfish/inventory.go | 18 +- internal/redfish/power.go | 155 +++++++++++++++ internal/redfish/power_test.go | 185 ++++++++++++++++++ 10 files changed, 404 insertions(+), 41 deletions(-) create mode 100644 internal/redfish/power.go create mode 100644 internal/redfish/power_test.go diff --git a/config/base/bmc-discovery/examples/credential-secret.yaml b/config/base/bmc-discovery/examples/credential-secret.yaml index c832d9dd..8d9ed533 100644 --- a/config/base/bmc-discovery/examples/credential-secret.yaml +++ b/config/base/bmc-discovery/examples/credential-secret.yaml @@ -1,9 +1,11 @@ # Synthetic example of one BMC credential Secret. Not part of the base: create # one per Device, in the namespace where discovery runs, outside Git. +# Discovery accepts any name; a power operation worker mounts the Secret named +# bmc.., so use that form. apiVersion: v1 kind: Secret metadata: - name: bmc-example-device-01 + name: bmc.default.example-device-01 labels: fleet.datumapis.com/bmc-credential: "true" annotations: diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 3bb23d60..c6534990 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -641,6 +641,10 @@ spec: serialNumber: {type: string, maxLength: 253} sku: {type: string, maxLength: 253} powerState: {type: string, maxLength: 63} + resetTypes: + type: array + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} networkInterfaces: type: array maxItems: 32 diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 29f139e0..f596a826 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -167,6 +167,11 @@ Device. `examples/credential-secret.yaml` is a synthetic example. | `data.username`, `data.password` | Single-line BMC credential. | | `data.tlsPublicKeySHA256` | Optional. The approved pin, 64 hex digits, colons and case ignored. | +Name the Secret `bmc..` when the Device may +receive [power operations](device-power.md#credentials): a power worker mounts +that Secret by name. Discovery itself selects by annotation and accepts any +name. + A Device is discovered only when it has `spec.bmc` and exactly one Secret names it. A Device with neither is skipped and its status is not written. Two Secrets naming one Device report `CredentialConflict` and send nothing. @@ -273,6 +278,7 @@ status: serialNumber: SYNTHETIC-0001 sku: TAG0001 powerState: "On" + resetTypes: ["On", ForceOff, ForceRestart] networkInterfaces: - {id: NIC.1, macAddress: "00:00:5e:00:53:01", linkStatus: LinkUp, speedMbps: 25000} conditions: [...] @@ -324,7 +330,12 @@ is `StaleObservation`. ## What is read Service root, then every Manager and every ComputerSystem (up to 16 of each), -with each one's EthernetInterfaces (up to 32). Collections follow +with each one's EthernetInterfaces (up to 32). For each System it records +the `ComputerSystem.Reset` types the BMC advertises, inline or from the +System's own ActionInfo, as `resetTypes`; a reset target or ActionInfo off the +System is ignored and records none. It reads the action's description and +never invokes it. [Device power operations](device-power.md) use these values +to refuse an action the server does not offer. Collections follow `Members@odata.nextLink` for up to 8 pages. Every member must sit under its collection. Documents are decoded leniently: only the named properties are read, so an off-schema vendor property elsewhere in a document does not fail diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 973e9433..562a23f9 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -256,7 +256,8 @@ type ObservedManager struct { } // ObservedSystem is one Redfish ComputerSystem. PowerState is an observation -// only; discovery never changes power. +// only; discovery never changes power. ResetTypes are the ComputerSystem.Reset +// types the BMC advertises for the System, read but never invoked. type ObservedSystem struct { ID string `json:"id"` UUID string `json:"uuid,omitempty"` @@ -266,6 +267,7 @@ type ObservedSystem struct { SKU string `json:"sku,omitempty"` PowerState string `json:"powerState,omitempty"` NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` + ResetTypes []string `json:"resetTypes,omitempty"` } // ObservedNetworkInterface is one Redfish EthernetInterface. diff --git a/internal/bmcdiscovery/discovery_test.go b/internal/bmcdiscovery/discovery_test.go index e32a4c21..e4f6c361 100644 --- a/internal/bmcdiscovery/discovery_test.go +++ b/internal/bmcdiscovery/discovery_test.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "sync" "sync/atomic" @@ -587,7 +588,9 @@ func TestEndToEndOverTLS(t *testing.T) { "/redfish/v1/Managers": `{"Members":[{"@odata.id":"/redfish/v1/Managers/BMC"}]}`, "/redfish/v1/Managers/BMC": `{"Id":"BMC","Model":"Example BMC","FirmwareVersion":"1.2.3"}`, "/redfish/v1/Systems": `{"Members":[{"@odata.id":"/redfish/v1/Systems/1"}]}`, - "/redfish/v1/Systems/1": `{"Id":"1","UUID":"00000000-0000-4000-8000-000000000001","Model":"Example 1U","SerialNumber":"SYNTHETIC-0001","PowerState":"Off"}`, + "/redfish/v1/Systems/1": `{"Id":"1","UUID":"00000000-0000-4000-8000-000000000001","Model":"Example 1U","SerialNumber":"SYNTHETIC-0001","PowerState":"Off", + "Actions":{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","@Redfish.ActionInfo":"/redfish/v1/Systems/1/ResetActionInfo"}}}`, + "/redfish/v1/Systems/1/ResetActionInfo": `{"Parameters":[{"Name":"ResetType","Required":"true","DataType":"String","AllowableValues":["On","ForceOff","ForceRestart"]}]}`, } server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, authed := r.BasicAuth() @@ -640,6 +643,11 @@ func TestEndToEndOverTLS(t *testing.T) { if c := condition(t, got.Status, inventory.ConditionIdentityMatched); c.Status != metav1.ConditionTrue { t.Fatalf("IdentityMatched = %+v", c) } + // Offered reset types come from the ActionInfo, read with a GET; the + // action itself is never invoked. + if types := got.Status.Discovery.Inventory.Systems[0].ResetTypes; !slices.Equal(types, []string{"On", "ForceOff", "ForceRestart"}) { + t.Fatalf("resetTypes = %v", types) + } mu.Lock() defer mu.Unlock() for _, l := range log { diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go index 47dab77d..954e6e93 100644 --- a/internal/bmcdiscovery/status.go +++ b/internal/bmcdiscovery/status.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "sort" "strings" "time" @@ -217,7 +218,20 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) * for _, s := range inv.Systems { if s.ID != "" && len(out.Systems) < 16 { out.Systems = append(out.Systems, inventory.ObservedSystem{ID: clip(s.ID, 253), UUID: canonicalUUIDOrEmpty(s.UUID), Manufacturer: clip(s.Manufacturer, 253), - Model: clip(s.Model, 253), SerialNumber: clip(s.SerialNumber, 253), SKU: clip(s.SKU, 253), PowerState: clip(s.PowerState, 63), NetworkInterfaces: nics(s.NetworkInterfaces)}) + Model: clip(s.Model, 253), SerialNumber: clip(s.SerialNumber, 253), SKU: clip(s.SKU, 253), PowerState: clip(s.PowerState, 63), NetworkInterfaces: nics(s.NetworkInterfaces), + ResetTypes: resetTypes(s.ResetTypes)}) + } + } + return out +} + +// resetTypes keeps up to 16 distinct, nonempty advertised reset types. +func resetTypes(in []string) []string { + var out []string + for _, v := range in { + v = clip(v, 63) + if v != "" && !slices.Contains(out, v) && len(out) < 16 { + out = append(out, v) } } return out diff --git a/internal/redfish/client.go b/internal/redfish/client.go index d3e6576a..ed490909 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -311,40 +311,8 @@ func (c *Client) Discover(ctx context.Context, t Target) (System, error) { if err := json.Unmarshal(s.RawData, &raw); err != nil { return System{}, classify(err) } - reset := raw.Actions.Reset - target, err := cleanPath(reset.Target) - if err != nil || !strings.HasPrefix(target, sys.Path+"/") { - return System{}, fmt.Errorf("%w: ComputerSystem.Reset target not on the enrolled System", ErrUnsupported) - } - sys.ResetTarget = target - sys.ResetTypes = reset.Allowed - if len(sys.ResetTypes) == 0 && reset.Info != "" { - info, err := cleanPath(reset.Info) - if err != nil || !strings.HasPrefix(info, sys.Path+"/") { - return System{}, fmt.Errorf("%w: ActionInfo not on the enrolled System", ErrUnsupported) - } - // Not schemas.ActionInfo: its typed decode rejects the whole document - // for one off-schema property, as the DMTF emulator's string - // "Required": "true". Only the ResetType values are read. - resp, err := api.Get(info) - var ai struct { - Parameters []struct { - Name, DataType string - AllowableValues []string - } - } - if err == nil { - err = json.NewDecoder(resp.Body).Decode(&ai) - } - schemas.DeferredCleanupHTTPResponse(resp) - if err != nil { - return System{}, classify(err) - } - for _, p := range ai.Parameters { - if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { - sys.ResetTypes = p.AllowableValues - } - } + if sys.ResetTarget, sys.ResetTypes, err = resetTypes(api, sys.Path, raw); err != nil { + return System{}, err } for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { sys.BootTargets = append(sys.BootTargets, string(b)) diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index ac95f211..72db121c 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -44,6 +44,9 @@ type InventorySystem struct { PowerState string // NetworkInterfaces are the System's EthernetInterfaces. NetworkInterfaces []NetworkInterface + // ResetTypes are the ComputerSystem.Reset types the System advertises. + // Discovery reads them and never invokes the action. + ResetTypes []string } // NetworkInterface is one Redfish EthernetInterface. @@ -109,6 +112,7 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { SKU string PowerState string EthernetInterfaces link + resetAction } if err := getJSON(api, p, &doc); err != nil { return Inventory{}, err @@ -117,8 +121,18 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { if err != nil { return Inventory{}, err } - inv.Systems = append(inv.Systems, InventorySystem{ID: doc.ID, UUID: canonicalUUID(doc.UUID), Manufacturer: doc.Manufacturer, - Model: doc.Model, SerialNumber: doc.SerialNumber, SKU: doc.SKU, PowerState: doc.PowerState, NetworkInterfaces: nics}) + system := InventorySystem{ID: doc.ID, UUID: canonicalUUID(doc.UUID), Manufacturer: doc.Manufacturer, + Model: doc.Model, SerialNumber: doc.SerialNumber, SKU: doc.SKU, PowerState: doc.PowerState, NetworkInterfaces: nics} + if doc.Actions.Reset.Target != "" { + // A reset target or ActionInfo off the System is not read: + // the System then offers no reset types. + if _, types, err := resetTypes(api, p, doc.resetAction); err == nil { + system.ResetTypes = types + } else if !errors.Is(err, ErrUnsupported) { + return Inventory{}, err + } + } + inv.Systems = append(inv.Systems, system) } } return inv, nil diff --git a/internal/redfish/power.go b/internal/redfish/power.go new file mode 100644 index 00000000..50d16693 --- /dev/null +++ b/internal/redfish/power.go @@ -0,0 +1,155 @@ +package redfish + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" +) + +// resetTypes returns the ComputerSystem.Reset types a System advertises, +// inline or through its ActionInfo, and the action target. Both must belong to +// the System at sysPath. It issues at most one GET, of the ActionInfo. +func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, err error) { + reset := raw.Actions.Reset + target, err = cleanPath(reset.Target) + if err != nil || !strings.HasPrefix(target, sysPath+"/") { + return "", nil, fmt.Errorf("%w: ComputerSystem.Reset target not on the System", ErrUnsupported) + } + if len(reset.Allowed) != 0 || reset.Info == "" { + return target, reset.Allowed, nil + } + info, err := cleanPath(reset.Info) + if err != nil || !strings.HasPrefix(info, sysPath+"/") { + return "", nil, fmt.Errorf("%w: ActionInfo not on the System", ErrUnsupported) + } + // Not schemas.ActionInfo: its typed decode rejects the whole document + // for one off-schema property, as the DMTF emulator's string + // "Required": "true". Only the ResetType values are read. + var ai struct { + Parameters []struct { + Name, DataType string + AllowableValues []string + } + } + if err := getJSON(api, info, &ai); err != nil { + return "", nil, err + } + for _, p := range ai.Parameters { + if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { + types = p.AllowableValues + } + } + return target, types, nil +} + +// PowerSystem is the one System a power operation acts on, found by UUID. +type PowerSystem struct { + Path string + ID string + UUID string + ResetTarget string + ResetTypes []string +} + +// PowerState is one read of a System's power. +type PowerState struct { + State string + // LastResetTime is when the BMC reports the System last came out of a + // reset, or zero when it does not report one. + LastResetTime time.Time + ObservedAt time.Time +} + +// FindPowerSystem reads every member of the Systems collection, across all +// pages, and returns the only one that carries uuid with its reset target and +// offered reset types. No member, or more than one, is ErrIdentity: a +// replaced server behind the same BMC address is refused here. It issues GETs +// only. +func (c *Client) FindPowerSystem(ctx context.Context, uuid string) (PowerSystem, error) { + api, err := c.connect(ctx) + if err != nil { + return PowerSystem{}, err + } + var root struct{ Systems link } + if err := getJSON(api, schemas.DefaultServiceRoot, &root); err != nil { + return PowerSystem{}, err + } + if root.Systems.ID == "" { + return PowerSystem{}, fmt.Errorf("%w: service root has no Systems collection", ErrUnsupported) + } + collection, err := cleanPath(root.Systems.ID) + if err != nil { + return PowerSystem{}, err + } + members, err := schemas.GetCollectionObjects[schemas.ComputerSystem](api, collection) + if err != nil { + // A partially read collection cannot prove the UUID is unique. + return PowerSystem{}, classify(err) + } + var found []*schemas.ComputerSystem + for _, s := range members { + p, err := cleanPath(s.ODataID) + if err != nil || !strings.HasPrefix(p, collection+"/") { + return PowerSystem{}, fmt.Errorf("%w: system member outside the collection", ErrIdentity) + } + if canonicalUUID(s.UUID) == uuid { + found = append(found, s) + } + } + if len(found) != 1 { + return PowerSystem{}, fmt.Errorf("%w: %d members carry the expected UUID", ErrIdentity, len(found)) + } + sys := PowerSystem{ID: found[0].ID, UUID: uuid} + sys.Path, _ = cleanPath(found[0].ODataID) + var raw resetAction + if err := json.Unmarshal(found[0].RawData, &raw); err != nil { + return PowerSystem{}, classify(err) + } + if sys.ResetTarget, sys.ResetTypes, err = resetTypes(api, sys.Path, raw); err != nil { + return PowerSystem{}, err + } + return sys, nil +} + +// ObservePower reads the System again, re-checks that it still carries the +// same Id and UUID, and returns its power state. A GET only. +func (c *Client) ObservePower(ctx context.Context, sys PowerSystem) (PowerState, error) { + api, err := c.connect(ctx) + if err != nil { + return PowerState{}, err + } + var doc struct { + ID string `json:"Id"` + UUID string + PowerState string + LastResetTime string + } + if err := getJSON(api, sys.Path, &doc); err != nil { + return PowerState{}, err + } + if doc.ID != sys.ID || canonicalUUID(doc.UUID) != sys.UUID { + return PowerState{}, fmt.Errorf("%w: the System changed identity", ErrIdentity) + } + out := PowerState{State: doc.PowerState, ObservedAt: time.Now().UTC()} + if doc.LastResetTime != "" { + if t, err := time.Parse(time.RFC3339, doc.LastResetTime); err == nil { + out.LastResetTime = t.UTC() + } + } + return out, nil +} + +// ResetPower posts exactly one ComputerSystem.Reset of kind to the System's +// own action target. It is never retried, and HTTP success is not evidence of +// the effect: callers observe the System afterwards. +func (c *Client) ResetPower(ctx context.Context, sys PowerSystem, kind string) error { + if !contains(sys.ResetTypes, kind) { + return fmt.Errorf("%w: ResetType %s", ErrUnsupported, kind) + } + return c.Reset(ctx, System{ResetTarget: sys.ResetTarget, ResetTypes: sys.ResetTypes}, kind) +} diff --git a/internal/redfish/power_test.go b/internal/redfish/power_test.go new file mode 100644 index 00000000..925997b0 --- /dev/null +++ b/internal/redfish/power_test.go @@ -0,0 +1,185 @@ +package redfish + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +const ( + powerUUID = "00000000-0000-4000-8000-0000000000a1" + otherUUID = "00000000-0000-4000-8000-0000000000b2" +) + +// powerBMC serves one System, or two, and counts Reset POSTs. +func powerBMC(t *testing.T, mutate func(docs map[string]any)) (*httptest.Server, *inventoryBMC, *atomic.Int32, func(http.HandlerFunc)) { + t.Helper() + b := &inventoryBMC{docs: map[string]any{ + "/redfish/v1/": map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/1"}}}, + "/redfish/v1/Systems/1": map[string]any{"@odata.id": "/redfish/v1/Systems/1", "Id": "1", "UUID": strings.ToUpper(powerUUID), "PowerState": "On", + "LastResetTime": "2026-01-02T03:04:05Z", + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", + "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}}}, + "/redfish/v1/Systems/1/ResetActionInfo": map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "Required": "true", "DataType": "String", + "AllowableValues": []string{"On", "ForceOff", "ForceRestart"}}}}, + }} + if mutate != nil { + mutate(b.docs) + } + var resets atomic.Int32 + var onReset atomic.Pointer[http.HandlerFunc] + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset" { + resets.Add(1) + if h := onReset.Load(); h != nil { + (*h)(w, r) + return + } + w.WriteHeader(http.StatusNoContent) + return + } + b.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + return server, b, &resets, func(h http.HandlerFunc) { onReset.Store(&h) } +} + +func pinnedClient(t *testing.T, server *httptest.Server, timeout time.Duration) *Client { + t.Helper() + c, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), timeout) + if err != nil { + t.Fatal(err) + } + return c +} + +func TestFindPowerSystemByUUID(t *testing.T) { + server, bmc, resets, _ := powerBMC(t, nil) + c := pinnedClient(t, server, 5*time.Second) + sys, err := c.FindPowerSystem(context.Background(), powerUUID) + if err != nil { + t.Fatal(err) + } + if sys.ID != "1" || sys.ResetTarget != "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset" || !slices.Equal(sys.ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) { + t.Fatalf("system = %+v", sys) + } + p, err := c.ObservePower(context.Background(), sys) + if err != nil || p.State != "On" || !p.LastResetTime.Equal(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) { + t.Fatalf("power = %+v %v", p, err) + } + bmc.mu.Lock() + defer bmc.mu.Unlock() + for _, r := range bmc.requests { + if !strings.HasPrefix(r, "GET ") { + t.Fatalf("finding and observing issued %s", r) + } + } + if resets.Load() != 0 { + t.Fatal("a reset was sent") + } +} + +func TestFindPowerSystemRefusesAnyOtherServer(t *testing.T) { + for name, mutate := range map[string]func(map[string]any){ + "replaced server": func(d map[string]any) { d["/redfish/v1/Systems/1"].(map[string]any)["UUID"] = otherUUID }, + "duplicate UUID": func(d map[string]any) { + d["/redfish/v1/Systems"] = map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/1"}, map[string]string{"@odata.id": "/redfish/v1/Systems/2"}}} + two := map[string]any{} + for k, v := range d["/redfish/v1/Systems/1"].(map[string]any) { + two[k] = v + } + two["@odata.id"], two["Id"] = "/redfish/v1/Systems/2", "2" + d["/redfish/v1/Systems/2"] = two + }, + } { + t.Run(name, func(t *testing.T) { + server, _, resets, _ := powerBMC(t, mutate) + if _, err := pinnedClient(t, server, 5*time.Second).FindPowerSystem(context.Background(), powerUUID); !errors.Is(err, ErrIdentity) { + t.Fatalf("err = %v", err) + } + if resets.Load() != 0 { + t.Fatal("a reset was sent") + } + }) + } +} + +func TestFindPowerSystemRefusesAResetTargetOffTheSystem(t *testing.T) { + server, _, _, _ := powerBMC(t, func(d map[string]any) { + d["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/2/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On"}}} + }) + if _, err := pinnedClient(t, server, 5*time.Second).FindPowerSystem(context.Background(), powerUUID); !errors.Is(err, ErrUnsupported) { + t.Fatalf("err = %v", err) + } +} + +func TestObservePowerRefusesAChangedIdentity(t *testing.T) { + server, bmc, _, _ := powerBMC(t, nil) + c := pinnedClient(t, server, 5*time.Second) + sys, err := c.FindPowerSystem(context.Background(), powerUUID) + if err != nil { + t.Fatal(err) + } + bmc.mu.Lock() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["UUID"] = otherUUID + bmc.mu.Unlock() + if _, err := c.ObservePower(context.Background(), sys); !errors.Is(err, ErrIdentity) { + t.Fatalf("err = %v", err) + } +} + +// A reset whose response is lost is sent exactly once; the caller observes. +func TestResetPowerIsSentOnceWhenTheResponseIsLost(t *testing.T) { + server, _, resets, onReset := powerBMC(t, nil) + c := pinnedClient(t, server, 300*time.Millisecond) + sys, err := c.FindPowerSystem(context.Background(), powerUUID) + if err != nil { + t.Fatal(err) + } + onReset(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Second) }) + err = c.ResetPower(context.Background(), sys, "ForceRestart") + if err == nil || errors.Is(err, ErrUnauthorized) { + t.Fatalf("err = %v", err) + } + if n := resets.Load(); n != 1 { + t.Fatalf("%d resets reached the BMC", n) + } + if err := c.ResetPower(context.Background(), sys, "PowerCycle"); !errors.Is(err, ErrUnsupported) || resets.Load() != 1 { + t.Fatalf("an unoffered reset was sent: %v", err) + } +} + +// Discovery reads offered reset types inline or from the ActionInfo, with +// GETs only. +func TestInventoryRecordsResetTypes(t *testing.T) { + server, bmc, resets, _ := powerBMC(t, func(d map[string]any) { + d["/redfish/v1/Systems"] = map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/1"}, map[string]string{"@odata.id": "/redfish/v1/Systems/2"}}} + d["/redfish/v1/Systems/2"] = map[string]any{"Id": "2", "UUID": otherUUID, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/2/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "PowerCycle"}}}} + }) + inv, err := pinnedClient(t, server, 5*time.Second).Inventory(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(inv.Systems) != 2 || !slices.Equal(inv.Systems[0].ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) || !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) { + t.Fatalf("systems = %+v", inv.Systems) + } + bmc.mu.Lock() + defer bmc.mu.Unlock() + for _, r := range bmc.requests { + if !strings.HasPrefix(r, "GET ") { + t.Fatalf("inventory issued %s", r) + } + } + if resets.Load() != 0 { + t.Fatal("inventory sent a reset") + } +} From 1afddb67d483e1ba3e95771e9db2e2789b4274cf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 16:39:40 -0600 Subject: [PATCH 2/3] feat: Add staff power operations Staff power servers on and off by hand through each BMC today, with no record, none of discovery's credential and TLS checks, and nothing to stop a reset of a server that backs customer capacity. DevicePowerOperation asks for one action on one Device. A dispatcher in the site accepts or refuses it, starts one worker Job, and is the only writer of its status. It holds no BMC credential. The worker mounts one credential, re-checks the TLS key, the server's UUID and the offered actions, sends at most one ComputerSystem.Reset, and reports Succeeded only when it observes the result. Anything it cannot prove is Unknown, and nothing retries. The worker cannot reach Milo. It records its progress in a site stage record. Claiming the record and writing it before the command are optimistic updates, so a second worker, a second dispatcher or a fenced lost worker sends nothing. A site Lease admits one running operation per Device. Site admission policies pin every dispatcher write to the worker shape: one approved image, one credential named after the Device, no privilege, and a Role limited to the worker's own record. The bindings select a labelled namespace, because the policy parameter is looked up before match conditions and an unscoped binding would deny writes cluster-wide. The Milo component ships the CRD, roles and a requester policy, and is in no root. Milo v0.32.5 does not enforce that policy in a project; see docs/operations/device-power.md. Co-Authored-By: Claude Opus 5.5 --- build/manager.Dockerfile | 4 +- cmd/fleet-device-power/main.go | 118 +++++ config/base/device-power/config.yaml | 14 + config/base/device-power/deployment.yaml | 68 +++ config/base/device-power/kustomization.yaml | 17 + config/base/device-power/rbac.yaml | 41 ++ .../device-power/worker-policy-params.yaml | 9 + config/base/device-power/worker-policy.yaml | 192 ++++++++ .../device-power/admission/kustomization.yaml | 4 + .../device-power/admission/requester.yaml | 32 ++ ...t.datumapis.com_devicepoweroperations.yaml | 115 +++++ .../device-power/crds/kustomization.yaml | 4 + .../device-power/kustomization.yaml | 13 + .../devicepoweroperation.yaml | 20 + .../protected-resources/kustomization.yaml | 4 + .../device-power/roles/dispatcher.yaml | 24 + .../device-power/roles/kustomization.yaml | 5 + .../device-power/roles/operator.yaml | 19 + internal/api/inventory/v1alpha1/power.go | 129 +++++ internal/api/inventory/v1alpha1/types.go | 4 + internal/devicepower/api_envtest_test.go | 212 +++++++++ internal/devicepower/checks.go | 106 +++++ internal/devicepower/checks_test.go | 99 ++++ internal/devicepower/config.go | 98 ++++ internal/devicepower/dispatcher.go | 434 +++++++++++++++++ internal/devicepower/dispatcher_test.go | 409 ++++++++++++++++ internal/devicepower/fixtures_test.go | 84 ++++ internal/devicepower/manifest_test.go | 53 +++ internal/devicepower/objects.go | 95 ++++ internal/devicepower/record.go | 173 +++++++ internal/devicepower/runtime.go | 107 +++++ internal/devicepower/site_envtest_test.go | 268 +++++++++++ internal/devicepower/worker.go | 373 +++++++++++++++ internal/devicepower/worker_test.go | 444 ++++++++++++++++++ 34 files changed, 3790 insertions(+), 1 deletion(-) create mode 100644 cmd/fleet-device-power/main.go create mode 100644 config/base/device-power/config.yaml create mode 100644 config/base/device-power/deployment.yaml create mode 100644 config/base/device-power/kustomization.yaml create mode 100644 config/base/device-power/rbac.yaml create mode 100644 config/base/device-power/worker-policy-params.yaml create mode 100644 config/base/device-power/worker-policy.yaml create mode 100644 config/components/device-power/admission/kustomization.yaml create mode 100644 config/components/device-power/admission/requester.yaml create mode 100644 config/components/device-power/crds/fleet.datumapis.com_devicepoweroperations.yaml create mode 100644 config/components/device-power/crds/kustomization.yaml create mode 100644 config/components/device-power/kustomization.yaml create mode 100644 config/components/device-power/protected-resources/devicepoweroperation.yaml create mode 100644 config/components/device-power/protected-resources/kustomization.yaml create mode 100644 config/components/device-power/roles/dispatcher.yaml create mode 100644 config/components/device-power/roles/kustomization.yaml create mode 100644 config/components/device-power/roles/operator.yaml create mode 100644 internal/api/inventory/v1alpha1/power.go create mode 100644 internal/devicepower/api_envtest_test.go create mode 100644 internal/devicepower/checks.go create mode 100644 internal/devicepower/checks_test.go create mode 100644 internal/devicepower/config.go create mode 100644 internal/devicepower/dispatcher.go create mode 100644 internal/devicepower/dispatcher_test.go create mode 100644 internal/devicepower/fixtures_test.go create mode 100644 internal/devicepower/manifest_test.go create mode 100644 internal/devicepower/objects.go create mode 100644 internal/devicepower/record.go create mode 100644 internal/devicepower/runtime.go create mode 100644 internal/devicepower/site_envtest_test.go create mode 100644 internal/devicepower/worker.go create mode 100644 internal/devicepower/worker_test.go diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index d6af25cd..418ff206 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -9,7 +9,8 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpat && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-registration ./cmd/fleet-registration \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync \ - && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-device-power ./cmd/fleet-device-power FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager @@ -17,4 +18,5 @@ COPY --from=build /out/fleet-registration /fleet-registration COPY --from=build /out/fleet-simulator /fleet-simulator COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync COPY --from=build /out/fleet-bmc-discovery /fleet-bmc-discovery +COPY --from=build /out/fleet-device-power /fleet-device-power ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-device-power/main.go b/cmd/fleet-device-power/main.go new file mode 100644 index 00000000..ea7905c7 --- /dev/null +++ b/cmd/fleet-device-power/main.go @@ -0,0 +1,118 @@ +// fleet-device-power runs staff power operations on unallocated Devices. +// +// fleet-device-power dispatcher --config=FILE +// fleet-device-power worker +// +// The dispatcher runs in a site, next to BMC discovery, for one Milo project. +// It accepts or refuses each DevicePowerOperation, starts one worker Job per +// accepted operation and writes operation status. It holds no BMC credential. +// A worker runs one operation: it reads its mounted credential and its stage +// record, sends at most one ComputerSystem.Reset and records the outcome. It +// holds no Milo credential. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "time" + + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + "go.datum.net/fleet/internal/devicepower" +) + +func main() { + if len(os.Args) < 2 { + fmt.Fprintln(os.Stderr, "usage: fleet-device-power dispatcher --config=FILE | worker") + os.Exit(64) + } + switch os.Args[1] { + case "dispatcher": + flags := flag.NewFlagSet("dispatcher", flag.ExitOnError) + configPath := flags.String("config", "/etc/fleet/device-power/config.yaml", "dispatcher configuration file") + zapOptions := zap.Options{Development: false} + zapOptions.BindFlags(flags) + _ = flags.Parse(os.Args[2:]) + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zapOptions))) + if err := dispatch(ctrl.SetupSignalHandler(), *configPath); err != nil && !errors.Is(err, context.Canceled) { + fmt.Fprintln(os.Stderr, "fleet-device-power dispatcher:", err) + os.Exit(1) + } + case "worker": + err := work(ctrl.SetupSignalHandler()) + switch { + case errors.Is(err, devicepower.ErrNotClaimed): + // A second worker for one operation stops here, having contacted + // no BMC, and leaves the first worker's result in place. + fmt.Fprintln(os.Stderr, "fleet-device-power worker:", err) + case err != nil: + fmt.Fprintln(os.Stderr, "fleet-device-power worker:", err) + os.Exit(1) + } + default: + fmt.Fprintln(os.Stderr, "usage: fleet-device-power dispatcher --config=FILE | worker") + os.Exit(64) + } +} + +func dispatch(ctx context.Context, configPath string) error { + config, err := devicepower.LoadConfig(configPath) + if err != nil { + return err + } + milo, err := clientcmd.BuildConfigFromFlags("", config.MiloKubeconfig) + if err != nil { + return fmt.Errorf("Milo project kubeconfig: %w", err) + } + var local *rest.Config + if config.LocalKubeconfig != "" { + local, err = clientcmd.BuildConfigFromFlags("", config.LocalKubeconfig) + } else { + local, err = rest.InClusterConfig() + } + if err != nil { + return fmt.Errorf("local cluster config: %w", err) + } + scheme, err := devicepower.NewScheme() + if err != nil { + return err + } + mgr, err := devicepower.NewManager(config, milo, local, scheme) + if err != nil { + return err + } + return mgr.Start(ctx) +} + +func work(ctx context.Context) error { + namespace, name, pod := os.Getenv("POD_NAMESPACE"), os.Getenv(devicepower.RecordEnv), os.Getenv(devicepower.PodUIDEnv) + if namespace == "" || name == "" || pod == "" { + return fmt.Errorf("%s, %s and POD_NAMESPACE are required", devicepower.RecordEnv, devicepower.PodUIDEnv) + } + local, err := rest.InClusterConfig() + if err != nil { + return fmt.Errorf("local cluster config: %w", err) + } + scheme, err := devicepower.NewScheme() + if err != nil { + return err + } + records, err := client.New(local, client.Options{Scheme: scheme}) + if err != nil { + return err + } + w := &devicepower.Worker{Records: records, Record: types.NamespacedName{Namespace: namespace, Name: name}, PodUID: pod, + CredentialDir: devicepower.CredentialMount, NewBMC: devicepower.PinnedBMC, Poll: 2 * time.Second, + Log: func(format string, args ...any) { + fmt.Fprintf(os.Stderr, time.Now().UTC().Format(time.RFC3339)+" "+format+"\n", args...) + }} + return w.Run(ctx) +} diff --git a/config/base/device-power/config.yaml b/config/base/device-power/config.yaml new file mode 100644 index 00000000..5e19ff29 --- /dev/null +++ b/config/base/device-power/config.yaml @@ -0,0 +1,14 @@ +# Synthetic values; the deploying repository replaces them. +project: example-provider-project +miloKubeconfig: /var/run/fleet/milo/kubeconfig +deviceNamespaces: [default] +# workerNamespace defaults to the pod's namespace ($POD_NAMESPACE). It must +# be the namespace that holds the BMC credential Secrets. +# The image worker Jobs run. Keep it equal to workerImage in +# worker-policy.yaml's parameter, which admission enforces. +workerImage: ghcr.io/datum-cloud/fleet:latest +discoveryMaxAge: 2h +observeTimeout: 3m +requestTimeout: 20s +retention: 24h +healthProbeAddress: ":8081" diff --git a/config/base/device-power/deployment.yaml b/config/base/device-power/deployment.yaml new file mode 100644 index 00000000..61a08282 --- /dev/null +++ b/config/base/device-power/deployment.yaml @@ -0,0 +1,68 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-device-power-dispatcher +spec: + # One replica and no leader election. Acceptance, the per-Device lock, the + # stage record and the worker Job are each written once or optimistically, + # so an accidental second replica starts no second worker. + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: fleet-device-power-dispatcher + template: + metadata: + labels: + app.kubernetes.io/name: fleet-device-power-dispatcher + spec: + serviceAccountName: fleet-device-power-dispatcher + automountServiceAccountToken: true + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: dispatcher + image: ghcr.io/datum-cloud/fleet:latest + command: [/fleet-device-power, dispatcher] + args: + - --config=/etc/fleet/device-power/config.yaml + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + ports: + - name: probes + containerPort: 8081 + livenessProbe: + httpGet: {path: /healthz, port: probes} + readinessProbe: + httpGet: {path: /readyz, port: probes} + resources: + requests: {cpu: 20m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - {name: config, mountPath: /etc/fleet/device-power, readOnly: true} + - {name: milo, mountPath: /var/run/fleet/milo, readOnly: true} + volumes: + - name: config + configMap: + name: fleet-device-power-config + # A kubeconfig for the one Milo project, bound to the + # fleet.datumapis.com-device-power-dispatcher role. Environment-owned. + - name: milo + secret: + secretName: fleet-device-power-milo-kubeconfig + defaultMode: 0440 + items: [{key: kubeconfig, path: kubeconfig}] diff --git a/config/base/device-power/kustomization.yaml b/config/base/device-power/kustomization.yaml new file mode 100644 index 00000000..e334ff15 --- /dev/null +++ b/config/base/device-power/kustomization.yaml @@ -0,0 +1,17 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +# The power operation dispatcher for one Milo project, and the site admission +# policies for its workers. Apply it in the namespace that holds BMC +# discovery's credential Secrets; the deploying repository sets that +# namespace, the image digest (in images: and both workerImage values), the +# Milo kubeconfig Secret and the config values. worker-policy.yaml is +# cluster-scoped. See docs/operations/device-power.md. +resources: + - rbac.yaml + - deployment.yaml + - worker-policy.yaml + - worker-policy-params.yaml +configMapGenerator: + - name: fleet-device-power-config + files: + - config.yaml diff --git a/config/base/device-power/rbac.yaml b/config/base/device-power/rbac.yaml new file mode 100644 index 00000000..3cfec9bf --- /dev/null +++ b/config/base/device-power/rbac.yaml @@ -0,0 +1,41 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-device-power-dispatcher +--- +# The dispatcher writes stage records, worker Jobs, their ServiceAccounts and +# Roles, and per-Device Leases in its own namespace. It holds no Secret or +# Pod permission, so it cannot read a BMC credential. It may create a Job +# that mounts one; worker-policy.yaml limits what that Job can be. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-device-power-dispatcher +rules: + - apiGroups: [""] + resources: [configmaps] + verbs: [get, list, watch, create, update, delete] + - apiGroups: [coordination.k8s.io] + resources: [leases] + verbs: [get, list, watch, create, update, delete] + - apiGroups: [batch] + resources: [jobs] + verbs: [get, list, watch, create] + - apiGroups: [""] + resources: [serviceaccounts] + verbs: [get, create] + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [get, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-device-power-dispatcher +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-device-power-dispatcher +subjects: + - kind: ServiceAccount + name: fleet-device-power-dispatcher diff --git a/config/base/device-power/worker-policy-params.yaml b/config/base/device-power/worker-policy-params.yaml new file mode 100644 index 00000000..7c2ae241 --- /dev/null +++ b/config/base/device-power/worker-policy-params.yaml @@ -0,0 +1,9 @@ +# The image every worker Job must run, read by the dispatcher-writes policy. +# The deploying repository sets it to the same digest as the dispatcher's +# workerImage. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-device-power-worker-policy +data: + workerImage: ghcr.io/datum-cloud/fleet:latest diff --git a/config/base/device-power/worker-policy.yaml b/config/base/device-power/worker-policy.yaml new file mode 100644 index 00000000..4bf1d3d6 --- /dev/null +++ b/config/base/device-power/worker-policy.yaml @@ -0,0 +1,192 @@ +# Admission in the site cluster for what the dispatcher and its workers may +# write. RBAC lets the dispatcher create Jobs, ServiceAccounts, Roles and +# RoleBindings in its namespace; these policies pin each write to the one +# worker shape. They apply only in namespaces labelled +# fleet.datumapis.com/device-power-site=true, and match only the dispatcher's +# own ServiceAccount and the per-operation worker ServiceAccounts there. Label +# the site namespace; unlabelled, the dispatcher's writes are unchecked. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-power-dispatcher-writes +spec: + failurePolicy: Fail + paramKind: + apiVersion: v1 + kind: ConfigMap + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE, UPDATE, DELETE] + resources: [configmaps, serviceaccounts] + - apiGroups: [batch] + apiVersions: [v1] + operations: [CREATE, UPDATE, DELETE] + resources: [jobs] + - apiGroups: [rbac.authorization.k8s.io] + apiVersions: [v1] + operations: [CREATE, UPDATE, DELETE] + resources: [roles, rolebindings] + - apiGroups: [coordination.k8s.io] + apiVersions: [v1] + operations: [CREATE, UPDATE, DELETE] + resources: [leases] + matchConditions: + - name: dispatcher + expression: >- + request.userInfo.username == 'system:serviceaccount:' + request.namespace + ':fleet-device-power-dispatcher' + variables: + - name: target + expression: 'request.operation == "DELETE" ? oldObject : object' + - name: name + expression: variables.target.metadata.name + - name: isJob + expression: request.resource.resource == 'jobs' + - name: pod + expression: 'variables.isJob && request.operation != "DELETE" ? object.spec.template.spec : null' + - name: container + expression: 'variables.pod != null && size(variables.pod.containers) == 1 ? variables.pod.containers[0] : null' + - name: credential + expression: >- + variables.isJob && request.operation != "DELETE" && has(object.metadata.annotations) && + 'fleet.datumapis.com/device-namespace' in object.metadata.annotations && + 'fleet.datumapis.com/device-name' in object.metadata.annotations ? + 'bmc.' + object.metadata.annotations['fleet.datumapis.com/device-namespace'] + '.' + object.metadata.annotations['fleet.datumapis.com/device-name'] : '' + validations: + - expression: variables.name.startsWith('pwr-') + reason: Forbidden + message: The dispatcher writes only pwr- objects. + - expression: >- + request.operation == 'DELETE' || + (has(object.metadata.labels) && 'app.kubernetes.io/part-of' in object.metadata.labels && + object.metadata.labels['app.kubernetes.io/part-of'] == 'fleet-device-power') + reason: Forbidden + message: Dispatcher objects carry app.kubernetes.io/part-of=fleet-device-power. + - expression: >- + request.operation != 'DELETE' || + request.resource.resource == 'configmaps' || request.resource.resource == 'leases' + reason: Forbidden + message: The dispatcher deletes only stage records and Device locks. + - expression: >- + request.resource.resource != 'leases' || variables.name.startsWith('pwr-lock-') + reason: Forbidden + message: Device locks are named pwr-lock-. + - expression: >- + request.resource.resource != 'configmaps' || request.operation != 'UPDATE' || + (has(oldObject.data) && 'inputs' in oldObject.data && has(object.data) && 'inputs' in object.data && + object.data['inputs'] == oldObject.data['inputs']) + reason: Forbidden + message: A stage record's inputs are fixed when it is created. + - expression: >- + request.resource.resource != 'roles' || request.operation == 'DELETE' || + (size(object.rules) == 1 && object.rules[0].apiGroups == [''] && object.rules[0].resources == ['configmaps'] && + has(object.rules[0].resourceNames) && object.rules[0].resourceNames == [object.metadata.name] && + object.rules[0].verbs.all(v, v == 'get' || v == 'update') && + (!has(object.rules[0].nonResourceURLs) || size(object.rules[0].nonResourceURLs) == 0)) + reason: Forbidden + message: A worker Role grants only get and update on its own stage record. + - expression: >- + request.resource.resource != 'rolebindings' || request.operation == 'DELETE' || + (object.roleRef.kind == 'Role' && object.roleRef.name == object.metadata.name && size(object.subjects) == 1 && + object.subjects[0].kind == 'ServiceAccount' && object.subjects[0].name == object.metadata.name && + object.subjects[0].namespace == request.namespace) + reason: Forbidden + message: A worker RoleBinding binds its own Role to its own ServiceAccount. + - expression: >- + !variables.isJob || request.operation == 'DELETE' || + (object.spec.backoffLimit == 0 && + variables.pod.serviceAccountName == object.metadata.name && + variables.pod.restartPolicy == 'Never' && + (!has(variables.pod.hostNetwork) || !variables.pod.hostNetwork) && + (!has(variables.pod.hostPID) || !variables.pod.hostPID) && + (!has(variables.pod.hostIPC) || !variables.pod.hostIPC) && + !has(variables.pod.initContainers) && !has(variables.pod.ephemeralContainers) && + has(variables.pod.securityContext) && has(variables.pod.securityContext.runAsNonRoot) && variables.pod.securityContext.runAsNonRoot) + reason: Forbidden + message: A worker Job runs one Pod, never retried, as its own ServiceAccount, without host namespaces, as non-root. + - expression: >- + !variables.isJob || request.operation == 'DELETE' || + (variables.container != null && + params != null && has(params.data) && 'workerImage' in params.data && + variables.container.image == params.data.workerImage && + variables.container.command == ['/fleet-device-power', 'worker'] && + (!has(variables.container.args) || size(variables.container.args) == 0) && + !has(variables.container.envFrom) && + (!has(variables.container.env) || variables.container.env.all(e, !has(e.valueFrom) || has(e.valueFrom.fieldRef))) && + has(variables.container.securityContext) && + (!has(variables.container.securityContext.privileged) || !variables.container.securityContext.privileged) && + has(variables.container.securityContext.allowPrivilegeEscalation) && !variables.container.securityContext.allowPrivilegeEscalation && + has(variables.container.securityContext.capabilities) && !has(variables.container.securityContext.capabilities.add) && + 'ALL' in variables.container.securityContext.capabilities.drop) + reason: Forbidden + message: A worker runs the approved image's worker command, unprivileged, with no Secret or ConfigMap environment. + - expression: >- + !variables.isJob || request.operation == 'DELETE' || + (variables.credential != '' && has(variables.pod.volumes) && size(variables.pod.volumes) == 1 && + has(variables.pod.volumes[0].secret) && variables.pod.volumes[0].secret.secretName == variables.credential && + (!has(variables.container.volumeMounts) || variables.container.volumeMounts.all(m, m.name == variables.pod.volumes[0].name))) + reason: Forbidden + message: A worker mounts exactly one volume, the named Device's credential Secret bmc... +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-power-dispatcher-writes +spec: + policyName: fleet-device-power-dispatcher-writes + validationActions: [Deny] + # Only the labelled site namespace. The parameter is looked up before match + # conditions run, so without this selector every write in a namespace that + # lacks the parameter would be denied, including system leader election. + matchResources: + namespaceSelector: + matchLabels: + fleet.datumapis.com/device-power-site: "true" + # The parameter lives in the request's namespace; without it every + # dispatcher write there is denied. + paramRef: + name: fleet-device-power-worker-policy + parameterNotFoundAction: Deny +--- +# A worker may change only the progress of its own stage record. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-power-worker-writes +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE, UPDATE, DELETE] + resources: [configmaps] + matchConditions: + - name: worker + expression: >- + request.userInfo.username.startsWith('system:serviceaccount:' + request.namespace + ':pwr-') + validations: + - expression: >- + request.operation == 'UPDATE' && + request.userInfo.username == 'system:serviceaccount:' + request.namespace + ':' + object.metadata.name && + has(oldObject.data) && 'inputs' in oldObject.data && has(object.data) && 'inputs' in object.data && + object.data['inputs'] == oldObject.data['inputs'] && + object.metadata.labels == oldObject.metadata.labels && + object.metadata.annotations == oldObject.metadata.annotations + reason: Forbidden + message: A worker only updates the progress of its own stage record. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-power-worker-writes +spec: + policyName: fleet-device-power-worker-writes + validationActions: [Deny] + matchResources: + namespaceSelector: + matchLabels: + fleet.datumapis.com/device-power-site: "true" diff --git a/config/components/device-power/admission/kustomization.yaml b/config/components/device-power/admission/kustomization.yaml new file mode 100644 index 00000000..5e579cf6 --- /dev/null +++ b/config/components/device-power/admission/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - requester.yaml diff --git a/config/components/device-power/admission/requester.yaml b/config/components/device-power/admission/requester.yaml new file mode 100644 index 00000000..d62055cf --- /dev/null +++ b/config/components/device-power/admission/requester.yaml @@ -0,0 +1,32 @@ +# The requester on an operation is the user who created it. The CRD fixes the +# spec after creation, so this check on CREATE covers the operation's life. +# A standard API server enforces it. Milo v0.32.5 does not evaluate policies +# stored in a project, and at Milo's root this policy rejects every project +# create; see docs/operations/device-power.md#the-requester-check-is-not-enforced-in-milo. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-power-requester +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [CREATE] + resources: [devicepoweroperations] + validations: + - expression: >- + request.userInfo.username != '' && + object.spec.requester == request.userInfo.username + reason: Forbidden + message: spec.requester must be the username of the user creating the operation. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-power-requester +spec: + policyName: fleet-device-power-requester + validationActions: [Deny] diff --git a/config/components/device-power/crds/fleet.datumapis.com_devicepoweroperations.yaml b/config/components/device-power/crds/fleet.datumapis.com_devicepoweroperations.yaml new file mode 100644 index 00000000..0201ccec --- /dev/null +++ b/config/components/device-power/crds/fleet.datumapis.com_devicepoweroperations.yaml @@ -0,0 +1,115 @@ +# One staff power action on one Device. The whole spec is fixed at creation; +# the status has one writer, the site dispatcher, and its result is set once. +# See docs/operations/device-power.md and the proposal in +# https://github.com/datum-cloud/fleet/pull/173. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicepoweroperations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DevicePowerOperation + listKind: DevicePowerOperationList + plural: devicepoweroperations + singular: devicepoweroperation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Action + type: string + jsonPath: .spec.action + - name: Result + type: string + jsonPath: .status.result + - name: Reason + type: string + jsonPath: .status.conditions[?(@.type=="Finished")].reason + - name: Requester + type: string + priority: 1 + jsonPath: .spec.requester + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [deviceRef, action, expectedSystemUUID, requester, reason] + # A changed request is a new operation. + x-kubernetes-validations: + - rule: self == oldSelf + message: spec is immutable; create a new operation instead + properties: + deviceRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 253} + action: + type: string + enum: ['On', ForceOff, ForceRestart, PowerCycle] + expectedSystemUUID: + type: string + pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + requester: {type: string, minLength: 1, maxLength: 253} + reason: {type: string, minLength: 1, maxLength: 1024} + status: + type: object + # The result is set once and never changed or removed. + x-kubernetes-validations: + - rule: '!has(oldSelf.result) || (has(self.result) && self.result == oldSelf.result)' + message: status.result is set once + properties: + conditions: + type: array + maxItems: 8 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [type] + items: + type: object + required: [type, status, lastTransitionTime, reason, message] + properties: + type: {type: string, enum: [Accepted, Executing, Finished]} + status: {type: string, enum: ['True', 'False', 'Unknown']} + observedGeneration: {type: integer, format: int64, minimum: 0} + lastTransitionTime: {type: string, format: date-time} + reason: {type: string, minLength: 1, maxLength: 1024, pattern: '^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$'} + message: {type: string, maxLength: 1024} + result: + type: string + enum: [Succeeded, Failed, Unknown] + requestSentAt: {type: string, format: date-time} + power: + type: object + properties: + before: + type: object + required: [state, observedAt] + properties: + state: {type: string, maxLength: 63} + observedAt: {type: string, format: date-time} + after: + type: object + required: [state, observedAt] + properties: + state: {type: string, maxLength: 63} + observedAt: {type: string, format: date-time} + finishedAt: {type: string, format: date-time} diff --git a/config/components/device-power/crds/kustomization.yaml b/config/components/device-power/crds/kustomization.yaml new file mode 100644 index 00000000..be1b9afa --- /dev/null +++ b/config/components/device-power/crds/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - fleet.datumapis.com_devicepoweroperations.yaml diff --git a/config/components/device-power/kustomization.yaml b/config/components/device-power/kustomization.yaml new file mode 100644 index 00000000..49b02e0a --- /dev/null +++ b/config/components/device-power/kustomization.yaml @@ -0,0 +1,13 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +# DevicePowerOperation in Milo: its CRD, ProtectedResource, the power operator +# and dispatcher roles, and the admission policy that binds the requester to +# the creating user. No root in this repository includes it yet; a deploying +# repository adds it next to config/milo. Without a site dispatcher an +# operation is never accepted and has no effect. +# See docs/operations/device-power.md. +resources: + - crds + - protected-resources + - roles + - admission diff --git a/config/components/device-power/protected-resources/devicepoweroperation.yaml b/config/components/device-power/protected-resources/devicepoweroperation.yaml new file mode 100644 index 00000000..75819dc5 --- /dev/null +++ b/config/components/device-power/protected-resources/devicepoweroperation.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicepoweroperation +spec: + serviceRef: + name: fleet.datumapis.com + kind: DevicePowerOperation + plural: devicepoweroperations + singular: devicepoweroperation + # Staff create and read operations. Only the dispatcher role holds + # updateStatus and the status subresource's update and patch. update, patch + # and delete exist for completeness; no role in this component grants them. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-power/protected-resources/kustomization.yaml b/config/components/device-power/protected-resources/kustomization.yaml new file mode 100644 index 00000000..e05f2b07 --- /dev/null +++ b/config/components/device-power/protected-resources/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - devicepoweroperation.yaml diff --git a/config/components/device-power/roles/dispatcher.yaml b/config/components/device-power/roles/dispatcher.yaml new file mode 100644 index 00000000..68d7cad2 --- /dev/null +++ b/config/components/device-power/roles/dispatcher.yaml @@ -0,0 +1,24 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-dispatcher + annotations: + kubernetes.io/display-name: Fleet Device Power Dispatcher + kubernetes.io/description: Accept or refuse power operations, and write only their status +spec: + launchStage: Alpha + # Reads what acceptance checks need and writes operation status. It cannot + # create, change or delete an operation, and cannot write a Device. + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicepoweroperations.updateStatus + - fleet.datumapis.com/devicepoweroperations/status.update + - fleet.datumapis.com/devicepoweroperations/status.patch + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - metal.datumapis.com/machinecapacities.get + - metal.datumapis.com/machinecapacities.list + - metal.datumapis.com/machinecapacities.watch diff --git a/config/components/device-power/roles/kustomization.yaml b/config/components/device-power/roles/kustomization.yaml new file mode 100644 index 00000000..c2dd52d1 --- /dev/null +++ b/config/components/device-power/roles/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - operator.yaml + - dispatcher.yaml diff --git a/config/components/device-power/roles/operator.yaml b/config/components/device-power/roles/operator.yaml new file mode 100644 index 00000000..1f7426b4 --- /dev/null +++ b/config/components/device-power/roles/operator.yaml @@ -0,0 +1,19 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-operator + annotations: + kubernetes.io/display-name: Fleet Device Power Operator + kubernetes.io/description: Request power actions on unallocated Devices and read their results +spec: + launchStage: Alpha + # No update, patch or delete: an operation is a permanent request, and its + # status belongs to the dispatcher. + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.create + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch diff --git a/internal/api/inventory/v1alpha1/power.go b/internal/api/inventory/v1alpha1/power.go new file mode 100644 index 00000000..afc80555 --- /dev/null +++ b/internal/api/inventory/v1alpha1/power.go @@ -0,0 +1,129 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// DevicePowerOperation asks for one power action on one Device in the same +// namespace. Staff create it; the whole spec is fixed at creation, and a +// changed request is a new operation. The site dispatcher alone writes its +// status, and sends at most one command for it through a worker. See +// docs/operations/device-power.md and the proposal in +// https://github.com/datum-cloud/fleet/pull/173. +type DevicePowerOperation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DevicePowerOperationSpec `json:"spec"` + Status DevicePowerOperationStatus `json:"status,omitempty"` +} + +type DevicePowerOperationSpec struct { + // DeviceRef names the Device to act on, in the same namespace. + DeviceRef LocalReference `json:"deviceRef"` + // Action is one of On, ForceOff, ForceRestart or PowerCycle. + Action PowerAction `json:"action"` + // ExpectedSystemUUID is the server staff expect behind the BMC, in + // lowercase canonical form. The operation fails if the Device record or + // the BMC reports another. + ExpectedSystemUUID string `json:"expectedSystemUUID"` + // Requester is the user who created the operation. Admission requires it + // to equal the authenticated username of the create request. + Requester string `json:"requester"` + // Reason is free text for the audit record. + Reason string `json:"reason"` +} + +// PowerAction is one ComputerSystem.Reset type Fleet sends for staff. +// Graceful actions are excluded. +type PowerAction string + +const ( + PowerOn PowerAction = "On" + PowerForceOff PowerAction = "ForceOff" + PowerForceRestart PowerAction = "ForceRestart" + PowerCycle PowerAction = "PowerCycle" +) + +// PowerResult is set once and never changed. +type PowerResult string + +const ( + // PowerSucceeded means Fleet observed the requested state, or observed + // the reset. + PowerSucceeded PowerResult = "Succeeded" + // PowerFailed means Fleet knows nothing was sent, or the BMC refused the + // command and the power did not change. + PowerFailed PowerResult = "Failed" + // PowerUnknown means a command may have been sent and Fleet cannot prove + // the outcome. Nothing retries it. + PowerUnknown PowerResult = "Unknown" +) + +// DevicePowerOperationStatus is written only by the site dispatcher. It never +// carries a credential or any BMC response content. +type DevicePowerOperationStatus struct { + // Conditions are Accepted, Executing and Finished. + Conditions []metav1.Condition `json:"conditions,omitempty"` + // Result is Succeeded, Failed or Unknown, set once. + Result PowerResult `json:"result,omitempty"` + // RequestSentAt is when the one command was sent. It is absent when none + // was sent. + RequestSentAt *metav1.Time `json:"requestSentAt,omitempty"` + // Power is the power state seen before and after the command. + Power *PowerObservations `json:"power,omitempty"` + // FinishedAt is when the result was set. + FinishedAt *metav1.Time `json:"finishedAt,omitempty"` +} + +type PowerObservations struct { + Before *PowerObservation `json:"before,omitempty"` + After *PowerObservation `json:"after,omitempty"` +} + +// PowerObservation is one read of a System's PowerState. +type PowerObservation struct { + State string `json:"state"` + ObservedAt metav1.Time `json:"observedAt"` +} + +// DevicePowerOperation condition types. +const ( + ConditionPowerAccepted = "Accepted" + ConditionPowerExecuting = "Executing" + ConditionPowerFinished = "Finished" +) + +// Reasons the dispatcher refuses an operation at acceptance. Each ends the +// operation as Failed with nothing sent. +const ( + ReasonCapacityBacked = "CapacityBacked" + ReasonOperationInProgress = "OperationInProgress" + ReasonDeviceNotFound = "DeviceNotFound" + ReasonDeviceRetired = "DeviceRetired" + ReasonSystemUUIDNotRecorded = "SystemUUIDNotRecorded" + ReasonSystemUUIDMismatch = "SystemUUIDMismatch" + ReasonDiscoveryNotCurrent = "DiscoveryNotCurrent" + ReasonSystemNotObserved = "SystemNotObserved" + ReasonSharedPublicKey = "SharedPublicKey" + ReasonResetTypeNotOffered = "ResetTypeNotOffered" + ReasonExpired = "Expired" +) + +type DevicePowerOperationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DevicePowerOperation `json:"items"` +} + +func (in *DevicePowerOperation) DeepCopyObject() runtime.Object { + out := new(DevicePowerOperation) + deepCopy(in, out) + return out +} + +func (in *DevicePowerOperationList) DeepCopyObject() runtime.Object { + out := new(DevicePowerOperationList) + deepCopy(in, out) + return out +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 562a23f9..4ac82e1e 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -2,6 +2,9 @@ // fleet.datumapis.com. A DeviceClaim describes one planned installation by // typed placement without accepting it. // +// DevicePowerOperation (power.go) is the one kind here that asks for a +// hardware effect; only the site dispatcher writes its status. +// // All are operator-written records. Registering a Device authorizes no // hardware effect and creates or changes no MachineCapacity. Device status has // one writer, read-only BMC discovery (internal/bmcdiscovery); every other @@ -293,6 +296,7 @@ type DeviceList struct { func addKnown(s *runtime.Scheme) error { s.AddKnownTypes(GroupVersion, &Manufacturer{}, &ManufacturerList{}, &DeviceType{}, &DeviceTypeList{}) s.AddKnownTypes(GroupVersion, &Site{}, &SiteList{}, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}, &Facility{}, &FacilityList{}, &Rack{}, &RackList{}, &Cable{}, &CableList{}, &PowerFeed{}, &PowerFeedList{}) + s.AddKnownTypes(GroupVersion, &DevicePowerOperation{}, &DevicePowerOperationList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } diff --git a/internal/devicepower/api_envtest_test.go b/internal/devicepower/api_envtest_test.go new file mode 100644 index 00000000..fb4900fe --- /dev/null +++ b/internal/devicepower/api_envtest_test.go @@ -0,0 +1,212 @@ +package devicepower + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + admissionv1 "k8s.io/api/admissionregistration/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +var componentRoot = filepath.Join("..", "..", "config", "components", "device-power") + +func decodeFile[T any](t *testing.T, path string) []T { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var out []T + for { + var item T + if err := decoder.Decode(&item); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + out = append(out, item) + } +} + +// TestOperationAPIOnARealAPIServer applies the shipped CRD and requester +// policy to a disposable API server and checks, as real users: +// - the requester must be the creating user; +// - the spec is fixed after creation; +// - the result is set once; +// - a staff user cannot write status, and the dispatcher cannot create, +// change or delete an operation. +func TestOperationAPIOnARealAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable API server validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(componentRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + if err := admissionv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + policies := decodeFile[admissionv1.ValidatingAdmissionPolicy](t, filepath.Join(componentRoot, "admission", "requester.yaml")) + bindings := decodeFile[admissionv1.ValidatingAdmissionPolicyBinding](t, filepath.Join(componentRoot, "admission", "requester.yaml")) + policy, binding := policies[0], bindings[1] + binding.TypeMeta = metav1.TypeMeta{} + for _, obj := range []client.Object{&policy, &binding, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: deviceNS + "-api"}}} { + if err := admin.Create(ctx, obj); err != nil { + t.Fatal(err) + } + } + // The Kubernetes RBAC equivalents of the operator and dispatcher roles. + rules := map[string][]rbacv1.PolicyRule{ + "staff@example.com": {{APIGroups: []string{inventory.GroupVersion.Group}, Resources: []string{"devicepoweroperations"}, Verbs: []string{"create", "get", "list", "watch"}}}, + "dispatcher": {{APIGroups: []string{inventory.GroupVersion.Group}, Resources: []string{"devicepoweroperations"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{inventory.GroupVersion.Group}, Resources: []string{"devicepoweroperations/status"}, Verbs: []string{"update", "patch"}}}, + } + as := map[string]client.Client{} + for user, rule := range rules { + name := strings.Split(user, "@")[0] + for _, obj := range []client.Object{&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: name}, Rules: rule}, + &rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: name}, RoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: name}, + Subjects: []rbacv1.Subject{{APIGroup: rbacv1.GroupName, Kind: rbacv1.UserKind, Name: user}}}} { + if err := admin.Create(ctx, obj); err != nil { + t.Fatal(err) + } + } + impersonated := rest.CopyConfig(config) + impersonated.Impersonate = rest.ImpersonationConfig{UserName: user} + if as[user], err = client.New(impersonated, client.Options{Scheme: scheme}); err != nil { + t.Fatal(err) + } + } + staff, dispatcher := as["staff@example.com"], as["dispatcher"] + newOp := func(name, requester string) *inventory.DevicePowerOperation { + op := operation(name, "device-a", inventory.PowerForceRestart) + op.Namespace, op.UID, op.CreationTimestamp, op.Generation, op.Spec.Requester = deviceNS+"-api", "", metav1.Time{}, 0, requester + return op + } + // The policy may take a moment to be enforced. + var err2 error + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { + if err2 = staff.Create(ctx, newOp("forged", "someone-else@example.com")); apierrors.IsInvalid(err2) || apierrors.IsForbidden(err2) { + break + } + if err2 == nil { + _ = admin.Delete(ctx, newOp("forged", "")) + } + } + if !apierrors.IsInvalid(err2) && !apierrors.IsForbidden(err2) { + t.Fatalf("a forged requester was admitted: %v", err2) + } + op := newOp("restart", "staff@example.com") + if err := staff.Create(ctx, op); err != nil { + t.Fatal(err) + } + if err := dispatcher.Create(ctx, newOp("by-dispatcher", "dispatcher")); !apierrors.IsForbidden(err) { + t.Fatalf("the dispatcher created an operation: %v", err) + } + // Staff may not write status or change the request. + op.Status.Result = inventory.PowerSucceeded + if err := staff.Status().Update(ctx, op); !apierrors.IsForbidden(err) { + t.Fatalf("staff wrote status: %v", err) + } + if err := admin.Get(ctx, client.ObjectKeyFromObject(op), op); err != nil { + t.Fatal(err) + } + changed := op.DeepCopyObject().(*inventory.DevicePowerOperation) + changed.Spec.Action = inventory.PowerForceOff + if err := admin.Update(ctx, changed); !apierrors.IsInvalid(err) { + t.Fatalf("the spec was changed: %v", err) + } + if err := dispatcher.Delete(ctx, op); !apierrors.IsForbidden(err) { + t.Fatalf("the dispatcher deleted an operation: %v", err) + } + // The dispatcher writes the result once. + meta.SetStatusCondition(&op.Status.Conditions, metav1.Condition{Type: inventory.ConditionPowerFinished, Status: metav1.ConditionTrue, Reason: ReasonWorkerLost, Message: "synthetic"}) + op.Status.Result = inventory.PowerUnknown + if err := dispatcher.Status().Update(ctx, op); err != nil { + t.Fatal(err) + } + op.Status.Result = inventory.PowerSucceeded + if err := dispatcher.Status().Update(ctx, op); !apierrors.IsInvalid(err) { + t.Fatalf("the result was changed: %v", err) + } + if err := admin.Get(ctx, client.ObjectKeyFromObject(op), op); err != nil { + t.Fatal(err) + } + op.Status.Result = "" + if err := dispatcher.Status().Update(ctx, op); !apierrors.IsInvalid(err) { + t.Fatalf("the result was removed: %v", err) + } +} + +// The Milo roles keep requesting, dispatching and discovery apart. +func TestShippedRolesSplitRequestFromDispatch(t *testing.T) { + type role struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + Inherited []struct{ Name string } `json:"inheritedRoles"` + Included []string `json:"includedPermissions"` + } `json:"spec"` + } + roles := map[string][]string{} + for _, file := range []string{"operator.yaml", "dispatcher.yaml"} { + for _, r := range decodeFile[role](t, filepath.Join(componentRoot, "roles", file)) { + if len(r.Spec.Inherited) != 0 { + t.Fatalf("%s inherits roles", r.Metadata.Name) + } + roles[r.Metadata.Name] = r.Spec.Included + } + } + operator, dispatcher := roles["fleet.datumapis.com-device-power-operator"], roles["fleet.datumapis.com-device-power-dispatcher"] + for _, p := range operator { + if strings.Contains(p, "status") || strings.HasSuffix(p, ".update") || strings.HasSuffix(p, ".patch") || strings.HasSuffix(p, ".delete") { + t.Fatalf("operator role holds %s", p) + } + } + if !slices.Contains(operator, "fleet.datumapis.com/devicepoweroperations.create") { + t.Fatal("operator role cannot create operations") + } + for _, p := range dispatcher { + if strings.HasSuffix(p, ".create") || strings.HasSuffix(p, ".delete") || p == "fleet.datumapis.com/devicepoweroperations.update" || + p == "fleet.datumapis.com/devicepoweroperations.patch" || strings.HasPrefix(p, "fleet.datumapis.com/devices") && !strings.HasSuffix(p, ".get") && !strings.HasSuffix(p, ".list") && !strings.HasSuffix(p, ".watch") { + t.Fatalf("dispatcher role holds %s", p) + } + } + for _, need := range []string{"fleet.datumapis.com/devicepoweroperations/status.update", "metal.datumapis.com/machinecapacities.list"} { + if !slices.Contains(dispatcher, need) { + t.Fatalf("dispatcher role lacks %s", need) + } + } +} diff --git a/internal/devicepower/checks.go b/internal/devicepower/checks.go new file mode 100644 index 00000000..142fb3fa --- /dev/null +++ b/internal/devicepower/checks.go @@ -0,0 +1,106 @@ +package devicepower + +import ( + "slices" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +// Refusal is why the dispatcher refuses an operation, with nothing sent. +type Refusal struct { + Reason, Message string +} + +// Acceptance is what the dispatcher read for one operation's checks. +type Acceptance struct { + Operation *inventory.DevicePowerOperation + // Device is nil when it does not exist in the operation's namespace. + Device *inventory.Device + // Capacities are the MachineCapacities in the operation's namespace. + Capacities []metal.MachineCapacity + // Others are the other operations in the namespace. + Others []inventory.DevicePowerOperation + // DiscoveryMaxAge bounds how old discovery's inventory read may be. + DiscoveryMaxAge time.Duration + Now time.Time +} + +// BacksCapacity reports whether any MachineCapacity names the Device. +func BacksCapacity(capacities []metal.MachineCapacity, device string) bool { + return slices.ContainsFunc(capacities, func(c metal.MachineCapacity) bool { return c.Spec.DeviceRef.Name == device }) +} + +// Running reports whether an operation was accepted and has no result. +func Running(op *inventory.DevicePowerOperation) bool { + return op.Status.Result == "" && meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerAccepted) +} + +// Check runs the acceptance checks in order and returns the first refusal, +// or nil when the operation may be accepted. It reads only what it is given. +func Check(a Acceptance) *Refusal { + op, device := a.Operation, a.Device + refuse := func(reason, message string) *Refusal { return &Refusal{Reason: reason, Message: message} } + if a.Now.Sub(op.CreationTimestamp.Time) > AcceptanceWindow { + return refuse(inventory.ReasonExpired, "the operation waited more than five minutes to be accepted; create a new one") + } + if device == nil { + return refuse(inventory.ReasonDeviceNotFound, "the Device does not exist in this namespace") + } + if inventory.LifecycleOf(device) == inventory.DeviceRetired { + return refuse(inventory.ReasonDeviceRetired, "the Device is retired") + } + if BacksCapacity(a.Capacities, device.Name) { + return refuse(inventory.ReasonCapacityBacked, "customer capacity is defined on the Device; its power belongs to the allocation") + } + for i := range a.Others { + other := &a.Others[i] + if other.UID != op.UID && other.Spec.DeviceRef.Name == device.Name && Running(other) { + return refuse(inventory.ReasonOperationInProgress, "operation "+other.Name+" on this Device is still running") + } + } + if device.Spec.Identity.SystemUUID == "" { + return refuse(inventory.ReasonSystemUUIDNotRecorded, "the Device has no system UUID on record") + } + if device.Spec.Identity.SystemUUID != op.Spec.ExpectedSystemUUID { + return refuse(inventory.ReasonSystemUUIDMismatch, "spec.expectedSystemUUID differs from the Device's recorded system UUID") + } + status := device.Status + discovery := status.Discovery + if device.Spec.BMC == nil || discovery == nil || discovery.Inventory == nil || discovery.TLS == nil || + discovery.Inventory.Endpoint != device.Spec.BMC.Endpoint || discovery.TLS.Endpoint != device.Spec.BMC.Endpoint || + a.Now.Sub(discovery.Inventory.ObservedAt.Time) > a.DiscoveryMaxAge || + !current(status, inventory.ConditionDiscovered, device.Generation) || !current(status, inventory.ConditionIdentityMatched, device.Generation) { + return refuse(inventory.ReasonDiscoveryNotCurrent, "discovery has not recently read this BMC and matched the Device's identity") + } + var systems []inventory.ObservedSystem + for _, s := range discovery.Inventory.Systems { + if s.UUID == op.Spec.ExpectedSystemUUID { + systems = append(systems, s) + } + } + if len(systems) != 1 { + return refuse(inventory.ReasonSystemNotObserved, "discovery did not see exactly one server with the expected UUID") + } + if c := meta.FindStatusCondition(status.Conditions, inventory.ConditionPublicKeyUnique); c == nil || c.Status != metav1.ConditionTrue { + if c != nil && c.Status == metav1.ConditionFalse { + return refuse(inventory.ReasonSharedPublicKey, "another BMC presents the same TLS key, so the key cannot tell them apart") + } + return refuse(inventory.ReasonDiscoveryNotCurrent, "discovery has not compared this BMC's TLS key with other BMCs") + } + if !slices.Contains(systems[0].ResetTypes, string(op.Spec.Action)) { + return refuse(inventory.ReasonResetTypeNotOffered, "the server does not offer "+string(op.Spec.Action)) + } + return nil +} + +// current reports whether a Device condition is True for the Device's +// current generation. +func current(status inventory.DeviceStatus, kind string, generation int64) bool { + c := meta.FindStatusCondition(status.Conditions, kind) + return c != nil && c.Status == metav1.ConditionTrue && c.ObservedGeneration == generation +} diff --git a/internal/devicepower/checks_test.go b/internal/devicepower/checks_test.go new file mode 100644 index 00000000..2cded872 --- /dev/null +++ b/internal/devicepower/checks_test.go @@ -0,0 +1,99 @@ +package devicepower + +import ( + "testing" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +func TestCheckRefusesEachUnsafeRequest(t *testing.T) { + base := func() Acceptance { + return Acceptance{Operation: operation("op", "device-a", inventory.PowerForceRestart), Device: discoveredDevice("device-a"), + DiscoveryMaxAge: time.Hour, Now: t0} + } + if r := Check(base()); r != nil { + t.Fatalf("a safe request was refused: %+v", r) + } + for _, tc := range []struct { + want string + mutate func(*Acceptance) + }{ + {inventory.ReasonExpired, func(a *Acceptance) { a.Operation.CreationTimestamp = metav1.NewTime(t0.Add(-6 * time.Minute)) }}, + {inventory.ReasonDeviceNotFound, func(a *Acceptance) { a.Device = nil }}, + {inventory.ReasonDeviceRetired, func(a *Acceptance) { a.Device.Spec.Lifecycle = inventory.DeviceRetired }}, + {inventory.ReasonCapacityBacked, func(a *Acceptance) { a.Capacities = []metal.MachineCapacity{*capacity("cap", "device-a")} }}, + {inventory.ReasonOperationInProgress, func(a *Acceptance) { + other := operation("other", "device-a", inventory.PowerOn) + meta.SetStatusCondition(&other.Status.Conditions, metav1.Condition{Type: inventory.ConditionPowerAccepted, Status: metav1.ConditionTrue, Reason: "Accepted"}) + a.Others = []inventory.DevicePowerOperation{*other} + }}, + {inventory.ReasonSystemUUIDNotRecorded, func(a *Acceptance) { a.Device.Spec.Identity.SystemUUID = "" }}, + {inventory.ReasonSystemUUIDMismatch, func(a *Acceptance) { a.Operation.Spec.ExpectedSystemUUID = uuidB }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { a.Device.Spec.BMC = nil }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { + a.Now = t0.Add(2 * time.Hour) + a.Operation.CreationTimestamp = metav1.NewTime(a.Now) + }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { a.Device.Status.Discovery.Inventory.Endpoint = "https://192.0.2.11:443" }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { a.Device.Generation = 2 }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { + meta.SetStatusCondition(&a.Device.Status.Conditions, metav1.Condition{Type: inventory.ConditionIdentityMatched, Status: metav1.ConditionFalse, Reason: "SystemUUIDMismatch", ObservedGeneration: 1}) + }}, + {inventory.ReasonDiscoveryNotCurrent, func(a *Acceptance) { + meta.RemoveStatusCondition(&a.Device.Status.Conditions, inventory.ConditionPublicKeyUnique) + }}, + {inventory.ReasonSystemNotObserved, func(a *Acceptance) { + inv := a.Device.Status.Discovery.Inventory + inv.Systems = append(inv.Systems, inv.Systems[0]) + }}, + {inventory.ReasonSystemNotObserved, func(a *Acceptance) { a.Device.Status.Discovery.Inventory.Systems[0].UUID = uuidB }}, + {inventory.ReasonSharedPublicKey, func(a *Acceptance) { + meta.SetStatusCondition(&a.Device.Status.Conditions, metav1.Condition{Type: inventory.ConditionPublicKeyUnique, Status: metav1.ConditionFalse, Reason: "SharedPublicKey", ObservedGeneration: 1}) + }}, + {inventory.ReasonResetTypeNotOffered, func(a *Acceptance) { a.Operation.Spec.Action = inventory.PowerCycle }}, + {inventory.ReasonResetTypeNotOffered, func(a *Acceptance) { a.Device.Status.Discovery.Inventory.Systems[0].ResetTypes = nil }}, + } { + t.Run(tc.want, func(t *testing.T) { + a := base() + tc.mutate(&a) + if r := Check(a); r == nil || r.Reason != tc.want { + t.Fatalf("refusal = %+v, want %s", r, tc.want) + } + }) + } +} + +func TestCheckIgnoresFinishedAndOtherDevicesOperations(t *testing.T) { + a := Acceptance{Operation: operation("op", "device-a", inventory.PowerOn), Device: discoveredDevice("device-a"), DiscoveryMaxAge: time.Hour, Now: t0, + Capacities: []metal.MachineCapacity{*capacity("cap", "device-b")}} + done := operation("done", "device-a", inventory.PowerOn) + meta.SetStatusCondition(&done.Status.Conditions, metav1.Condition{Type: inventory.ConditionPowerAccepted, Status: metav1.ConditionTrue, Reason: "Accepted"}) + done.Status.Result = inventory.PowerSucceeded + elsewhere := operation("elsewhere", "device-b", inventory.PowerOn) + meta.SetStatusCondition(&elsewhere.Status.Conditions, metav1.Condition{Type: inventory.ConditionPowerAccepted, Status: metav1.ConditionTrue, Reason: "Accepted"}) + a.Others = []inventory.DevicePowerOperation{*done, *elsewhere, *a.Operation} + if r := Check(a); r != nil { + t.Fatalf("refused: %+v", r) + } +} + +func TestNamesAreDerivedAndBounded(t *testing.T) { + if name, ok := CredentialSecretName("default", "device-a"); !ok || name != "bmc.default.device-a" { + t.Fatalf("credential name = %q %v", name, ok) + } + long := make([]byte, 250) + for i := range long { + long[i] = 'a' + } + if _, ok := CredentialSecretName("default", string(long)); ok { + t.Fatal("an over-long credential name was accepted") + } + if a, b := LockName(project, "a-b", "c"), LockName(project, "a", "b-c"); a == b || len(a) > 63 { + t.Fatalf("lock names %q %q", a, b) + } +} diff --git a/internal/devicepower/config.go b/internal/devicepower/config.go new file mode 100644 index 00000000..c49ab2fc --- /dev/null +++ b/internal/devicepower/config.go @@ -0,0 +1,98 @@ +package devicepower + +import ( + "errors" + "fmt" + "os" + "strings" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/yaml" +) + +// Config is the dispatcher configuration file, usually a mounted ConfigMap. +type Config struct { + // Project is the Milo project the kubeconfig addresses. It is the same + // project BMC discovery serves in this site. + Project string `json:"project"` + // MiloKubeconfig is the path of a kubeconfig for that one project. + MiloKubeconfig string `json:"miloKubeconfig"` + // DeviceNamespaces are the project namespaces whose operations are served. + DeviceNamespaces []string `json:"deviceNamespaces"` + // WorkerNamespace is the site namespace of the stage records, worker Jobs + // and the credential Secrets they mount. It defaults to $POD_NAMESPACE. + WorkerNamespace string `json:"workerNamespace,omitempty"` + // LocalKubeconfig reaches the site cluster. Empty uses the in-cluster + // service account. + LocalKubeconfig string `json:"localKubeconfig,omitempty"` + // WorkerImage is the image worker Jobs run. The site admission policy + // admits only this image. + WorkerImage string `json:"workerImage"` + // DiscoveryMaxAge bounds how old discovery's last inventory read of the + // BMC may be when an operation is accepted. + DiscoveryMaxAge metav1.Duration `json:"discoveryMaxAge,omitempty"` + // ObserveTimeout is how long a worker watches for the requested power + // state or a reset after its command. + ObserveTimeout metav1.Duration `json:"observeTimeout,omitempty"` + // RequestTimeout bounds each HTTP request a worker makes to a BMC. + RequestTimeout metav1.Duration `json:"requestTimeout,omitempty"` + // Retention is how long site objects of a finished operation are kept. + Retention metav1.Duration `json:"retention,omitempty"` + // HealthProbeAddress serves /healthz and /readyz; empty disables them. + HealthProbeAddress string `json:"healthProbeAddress,omitempty"` +} + +// LoadConfig reads, defaults and validates a configuration file. +func LoadConfig(path string) (Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return Config{}, fmt.Errorf("read dispatcher config: %w", err) + } + var c Config + if err := yaml.UnmarshalStrict(data, &c); err != nil { + return Config{}, fmt.Errorf("parse dispatcher config: %w", err) + } + c.Default() + return c, c.Validate() +} + +// Default fills unset values. +func (c *Config) Default() { + set := func(d *metav1.Duration, v time.Duration) { + if d.Duration == 0 { + d.Duration = v + } + } + set(&c.DiscoveryMaxAge, 2*time.Hour) + set(&c.ObserveTimeout, 3*time.Minute) + set(&c.RequestTimeout, 20*time.Second) + set(&c.Retention, 24*time.Hour) + if c.WorkerNamespace == "" { + c.WorkerNamespace = os.Getenv("POD_NAMESPACE") + } +} + +// Validate rejects an incomplete or out-of-range configuration. +func (c Config) Validate() error { + var errs []error + if c.Project == "" || c.MiloKubeconfig == "" || c.WorkerNamespace == "" || c.WorkerImage == "" || len(c.DeviceNamespaces) == 0 { + errs = append(errs, errors.New("project, miloKubeconfig, deviceNamespaces, workerImage and workerNamespace (or $POD_NAMESPACE) are required")) + } + for _, ns := range c.DeviceNamespaces { + if strings.TrimSpace(ns) == "" { + errs = append(errs, errors.New("deviceNamespaces must not contain an empty name")) + } + } + if c.DiscoveryMaxAge.Duration < time.Minute || c.ObserveTimeout.Duration < 10*time.Second || c.ObserveTimeout.Duration > 10*time.Minute || + c.RequestTimeout.Duration <= 0 || c.RequestTimeout.Duration > time.Minute || c.Retention.Duration < time.Minute { + errs = append(errs, errors.New("need discoveryMaxAge >= 1m, 10s <= observeTimeout <= 10m, 0 < requestTimeout <= 1m and retention >= 1m")) + } + return errors.Join(errs...) +} + +// jobDeadline bounds a worker Job: its start window, the command, the +// observation and its record writes. +func (c Config) jobDeadline() time.Duration { + return StaleAfter + 4*c.RequestTimeout.Duration + c.ObserveTimeout.Duration + time.Minute +} diff --git a/internal/devicepower/dispatcher.go b/internal/devicepower/dispatcher.go new file mode 100644 index 00000000..b7d54abb --- /dev/null +++ b/internal/devicepower/dispatcher.go @@ -0,0 +1,434 @@ +package devicepower + +import ( + "context" + "errors" + "fmt" + "time" + + batchv1 "k8s.io/api/batch/v1" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +// runningRequeue is how often a running operation is looked at even without +// an event. +const runningRequeue = 10 * time.Second + +// Reconciler is the site dispatcher. It accepts or refuses each operation, +// starts at most one worker for an accepted one, and publishes the worker's +// result. It is the only writer of operation status and holds no BMC +// credential: it reads Devices and capacity in Milo and writes stage records, +// worker Jobs and their RBAC in the site. +type Reconciler struct { + // Milo reads operations, Devices and capacity and writes only operation + // status. MiloReader bypasses the cache for the checks that must be + // fresh: the capacity re-check and a lock holder's state. + Milo client.Client + MiloReader client.Reader + // Site writes stage records, worker objects and per-Device Leases in + // Namespace; SiteReader reads them without a cache. + Site client.Client + SiteReader client.Reader + Namespace string + Config Config + Now func() time.Time +} + +func (r *Reconciler) now() time.Time { + if r.Now != nil { + return r.Now().UTC() + } + return time.Now().UTC() +} + +func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { + var op inventory.DevicePowerOperation + if err := r.Milo.Get(ctx, req.NamespacedName, &op); apierrors.IsNotFound(err) { + return reconcile.Result{}, r.collectOrphans(ctx, req.NamespacedName) + } else if err != nil { + return reconcile.Result{}, err + } + if op.Status.Result != "" { + return r.finished(ctx, &op) + } + rec, err := r.record(ctx, op.UID) + if err != nil { + return reconcile.Result{}, err + } + if rec == nil && !meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerAccepted) { + return r.accept(ctx, &op) + } + if rec == nil { + if meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerExecuting) { + // The record existed and is gone: a worker may have run. + return reconcile.Result{}, r.publish(ctx, &op, Progress{Result: inventory.PowerUnknown, Reason: ReasonRecordLost, + Message: "the site stage record of a started operation is missing; a command may have been sent", FinishedAt: ptrTime(r.now())}) + } + if rec, err = r.start(ctx, &op); err != nil || rec == nil { + return reconcile.Result{Requeue: err == nil && rec == nil}, err + } + } + return r.follow(ctx, &op, rec) +} + +// accept runs the acceptance checks and either refuses the operation or +// takes the Device's site lock and marks it Accepted. +func (r *Reconciler) accept(ctx context.Context, op *inventory.DevicePowerOperation) (reconcile.Result, error) { + a := Acceptance{Operation: op, DiscoveryMaxAge: r.Config.DiscoveryMaxAge.Duration, Now: r.now()} + var device inventory.Device + if err := r.Milo.Get(ctx, types.NamespacedName{Namespace: op.Namespace, Name: op.Spec.DeviceRef.Name}, &device); err == nil { + a.Device = &device + } else if !apierrors.IsNotFound(err) { + return reconcile.Result{}, err + } + var capacities metal.MachineCapacityList + if err := r.Milo.List(ctx, &capacities, client.InNamespace(op.Namespace)); err != nil { + return reconcile.Result{}, err + } + a.Capacities = capacities.Items + var others inventory.DevicePowerOperationList + if err := r.Milo.List(ctx, &others, client.InNamespace(op.Namespace)); err != nil { + return reconcile.Result{}, err + } + a.Others = others.Items + if refusal := Check(a); refusal != nil { + return reconcile.Result{}, r.refuse(ctx, op, *refusal) + } + held, err := r.lock(ctx, op) + if err != nil { + return reconcile.Result{}, err + } + if !held { + return reconcile.Result{}, r.refuse(ctx, op, Refusal{Reason: inventory.ReasonOperationInProgress, Message: "another operation on this Device is still running"}) + } + return reconcile.Result{Requeue: true}, r.writeStatus(ctx, op, func(s *inventory.DevicePowerOperationStatus) { + r.condition(op, s, inventory.ConditionPowerAccepted, metav1.ConditionTrue, "Accepted", "every acceptance check passed") + }) +} + +// start re-checks capacity against Milo itself, not the cache, and retains +// the operation's exact inputs in a new stage record. It returns nil when the +// operation was refused instead. +func (r *Reconciler) start(ctx context.Context, op *inventory.DevicePowerOperation) (*corev1.ConfigMap, error) { + var capacities metal.MachineCapacityList + if err := r.MiloReader.List(ctx, &capacities, client.InNamespace(op.Namespace)); err != nil { + return nil, err + } + checkedAt := r.now() + if BacksCapacity(capacities.Items, op.Spec.DeviceRef.Name) { + return nil, r.publish(ctx, op, Progress{Result: inventory.PowerFailed, Reason: inventory.ReasonCapacityBacked, + Message: "customer capacity was defined on the Device before the worker started; nothing was sent", FinishedAt: ptrTime(checkedAt)}) + } + var device inventory.Device + if err := r.MiloReader.Get(ctx, types.NamespacedName{Namespace: op.Namespace, Name: op.Spec.DeviceRef.Name}, &device); err != nil { + if apierrors.IsNotFound(err) { + return nil, r.publish(ctx, op, Progress{Result: inventory.PowerFailed, Reason: inventory.ReasonDeviceNotFound, + Message: "the Device was deleted before the worker started; nothing was sent", FinishedAt: ptrTime(checkedAt)}) + } + return nil, err + } + if _, ok := CredentialSecretName(op.Namespace, device.Name); !ok || device.Spec.BMC == nil || device.Status.Discovery == nil || device.Status.Discovery.TLS == nil { + return nil, r.publish(ctx, op, Progress{Result: inventory.PowerFailed, Reason: inventory.ReasonDiscoveryNotCurrent, + Message: "the Device lost its BMC endpoint or observed TLS key before the worker started; nothing was sent", FinishedAt: ptrTime(checkedAt)}) + } + in := Inputs{OperationUID: string(op.UID), Project: r.Config.Project, Namespace: op.Namespace, Operation: op.Name, Device: device.Name, + Endpoint: device.Spec.BMC.Endpoint, SystemUUID: op.Spec.ExpectedSystemUUID, PublicKeySHA256: device.Status.Discovery.TLS.PublicKeySHA256, + Action: op.Spec.Action, CapacityCheckedAt: metav1.NewTime(checkedAt), ObserveTimeout: r.Config.ObserveTimeout, RequestTimeout: r.Config.RequestTimeout} + rec := record(r.Namespace, in) + if err := r.Site.Create(ctx, rec); apierrors.IsAlreadyExists(err) { + // Another dispatcher, or this one before a restart, wrote it. + return r.record(ctx, op.UID) + } else if err != nil { + return nil, err + } + return rec, nil +} + +// follow starts the worker for a Pending record, and publishes the result +// once the worker recorded one or is gone. +func (r *Reconciler) follow(ctx context.Context, op *inventory.DevicePowerOperation, rec *corev1.ConfigMap) (reconcile.Result, error) { + in, p, err := decodeRecord(rec) + if err != nil { + return reconcile.Result{}, r.publish(ctx, op, Progress{Result: inventory.PowerUnknown, Reason: ReasonRecordLost, + Message: "the site stage record is unreadable; a command may have been sent", FinishedAt: ptrTime(r.now())}) + } + if p.Stage == StageFinished || p.Stage == StageAbandoned { + return reconcile.Result{}, r.publish(ctx, op, p) + } + var job batchv1.Job + err = r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: rec.Name}, &job) + if apierrors.IsNotFound(err) && p.Stage == StagePending { + if err := r.startWorker(ctx, rec, in); err != nil { + return reconcile.Result{}, err + } + return reconcile.Result{RequeueAfter: runningRequeue}, r.markExecuting(ctx, op) + } + if err != nil && !apierrors.IsNotFound(err) { + return reconcile.Result{}, err + } + if err == nil && !jobFinished(&job) { + return reconcile.Result{RequeueAfter: runningRequeue}, r.markExecuting(ctx, op) + } + // The worker is gone without a result. Fence the record so a lost worker + // process can no longer send, then publish what the record proves. + return reconcile.Result{}, r.fence(ctx, op, rec.Name) +} + +func jobFinished(job *batchv1.Job) bool { + for _, c := range job.Status.Conditions { + if (c.Type == batchv1.JobComplete || c.Type == batchv1.JobFailed) && c.Status == corev1.ConditionTrue { + return true + } + } + return false +} + +// fence moves an unfinished record to Abandoned with the optimistic lock and +// publishes the result. Nothing sent is Failed; a possible send is Unknown. +func (r *Reconciler) fence(ctx context.Context, op *inventory.DevicePowerOperation, name string) error { + var rec corev1.ConfigMap + if err := r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: name}, &rec); err != nil { + return err + } + _, p, err := decodeRecord(&rec) + if err != nil { + return err + } + if p.Stage == StageFinished || p.Stage == StageAbandoned { + return r.publish(ctx, op, p) + } + switch { + case p.Stage.mayHaveSent(): + p.Result, p.Reason, p.Message = inventory.PowerUnknown, ReasonWorkerLost, "the worker stopped after a command may have been sent; it was not resent" + case p.Stage == StageClaimed: + p.Result, p.Reason, p.Message = inventory.PowerFailed, ReasonWorkerLost, "the worker stopped before it sent a command; nothing was sent" + default: + p.Result, p.Reason, p.Message = inventory.PowerFailed, ReasonWorkerNotStarted, "the worker ended before it claimed the operation; nothing was sent" + } + p.Stage, p.FinishedAt = StageAbandoned, ptrTime(r.now()) + setProgress(&rec, p) + if err := r.Site.Update(ctx, &rec); err != nil { + // A conflict means the worker wrote first; the next pass reads it. + return err + } + return r.publish(ctx, op, p) +} + +func (r *Reconciler) startWorker(ctx context.Context, rec *corev1.ConfigMap, in Inputs) error { + secret, _ := CredentialSecretName(in.Namespace, in.Device) + sa, role, binding, job := workerObjects(rec, in, r.Config.WorkerImage, secret, int64(r.Config.jobDeadline()/time.Second)) + for _, obj := range []client.Object{sa, role, binding, job} { + if err := r.Site.Create(ctx, obj); err != nil && !apierrors.IsAlreadyExists(err) { + return fmt.Errorf("create worker %s: %w", obj.GetObjectKind().GroupVersionKind().Kind, err) + } + } + return nil +} + +func (r *Reconciler) markExecuting(ctx context.Context, op *inventory.DevicePowerOperation) error { + if meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerExecuting) { + return nil + } + return r.writeStatus(ctx, op, func(s *inventory.DevicePowerOperationStatus) { + r.condition(op, s, inventory.ConditionPowerExecuting, metav1.ConditionTrue, "WorkerStarted", "one worker was started for this operation") + }) +} + +// refuse ends an operation at acceptance: Failed, nothing sent. +func (r *Reconciler) refuse(ctx context.Context, op *inventory.DevicePowerOperation, refusal Refusal) error { + return r.writeStatus(ctx, op, func(s *inventory.DevicePowerOperationStatus) { + r.condition(op, s, inventory.ConditionPowerAccepted, metav1.ConditionFalse, refusal.Reason, refusal.Message+"; nothing was sent") + r.condition(op, s, inventory.ConditionPowerFinished, metav1.ConditionTrue, refusal.Reason, refusal.Message+"; nothing was sent") + s.Result, s.FinishedAt = inventory.PowerFailed, ptrTime(r.now()) + }) +} + +// publish copies a result into status. The CRD admits the result once. +func (r *Reconciler) publish(ctx context.Context, op *inventory.DevicePowerOperation, p Progress) error { + if err := r.writeStatus(ctx, op, func(s *inventory.DevicePowerOperationStatus) { + if meta.FindStatusCondition(s.Conditions, inventory.ConditionPowerExecuting) != nil { + r.condition(op, s, inventory.ConditionPowerExecuting, metav1.ConditionFalse, "Finished", "the operation finished") + } + r.condition(op, s, inventory.ConditionPowerFinished, metav1.ConditionTrue, p.Reason, p.Message) + s.Result, s.RequestSentAt, s.FinishedAt = p.Result, p.RequestSentAt, p.FinishedAt + if s.FinishedAt == nil { + s.FinishedAt = ptrTime(r.now()) + } + if p.Before != nil || p.After != nil { + s.Power = &inventory.PowerObservations{Before: p.Before, After: p.After} + } + }); err != nil { + return err + } + return r.unlock(ctx, op) +} + +func (r *Reconciler) condition(op *inventory.DevicePowerOperation, s *inventory.DevicePowerOperationStatus, kind string, status metav1.ConditionStatus, reason, message string) { + if len(message) > 1024 { + message = message[:1024] + } + meta.SetStatusCondition(&s.Conditions, metav1.Condition{Type: kind, Status: status, Reason: reason, Message: message, + ObservedGeneration: op.Generation, LastTransitionTime: metav1.NewTime(r.now().Truncate(time.Second))}) +} + +// writeStatus updates the status subresource with the object's +// resourceVersion, so a stale read conflicts instead of overwriting. +func (r *Reconciler) writeStatus(ctx context.Context, op *inventory.DevicePowerOperation, mutate func(*inventory.DevicePowerOperationStatus)) error { + updated := op.DeepCopyObject().(*inventory.DevicePowerOperation) + mutate(&updated.Status) + if err := r.Milo.Status().Update(ctx, updated); err != nil { + return err + } + *op = *updated + return nil +} + +// record reads an operation's stage record without the cache, or nil. +func (r *Reconciler) record(ctx context.Context, uid types.UID) (*corev1.ConfigMap, error) { + var rec corev1.ConfigMap + err := r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: WorkerName(uid)}, &rec) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &rec, nil +} + +// lock takes the Device's site Lease for the operation. Two dispatchers, or +// two operations on one Device, cannot both hold it: creation and takeover +// are optimistic writes. A holder that finished or no longer exists is +// replaced. +func (r *Reconciler) lock(ctx context.Context, op *inventory.DevicePowerOperation) (bool, error) { + name := LockName(r.Config.Project, op.Namespace, op.Spec.DeviceRef.Name) + lease := &coordinationv1.Lease{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: r.Namespace, Labels: objectLabels(string(op.UID), "lock"), + Annotations: map[string]string{DeviceNamespace: op.Namespace, DeviceName: op.Spec.DeviceRef.Name, OperationNamespace: op.Namespace, OperationName: op.Name}}, + Spec: coordinationv1.LeaseSpec{HolderIdentity: ptr.To(string(op.UID))}} + err := r.Site.Create(ctx, lease) + if err == nil { + return true, nil + } + if !apierrors.IsAlreadyExists(err) { + return false, err + } + var current coordinationv1.Lease + if err := r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: name}, ¤t); err != nil { + return false, err + } + holder := ptr.Deref(current.Spec.HolderIdentity, "") + if holder == string(op.UID) { + return true, nil + } + var ops inventory.DevicePowerOperationList + if err := r.MiloReader.List(ctx, &ops, client.InNamespace(op.Namespace)); err != nil { + return false, err + } + for _, other := range ops.Items { + if string(other.UID) == holder && other.Status.Result == "" { + return false, nil + } + } + current.Spec.HolderIdentity = ptr.To(string(op.UID)) + current.Labels = lease.Labels + current.Annotations = lease.Annotations + if err := r.Site.Update(ctx, ¤t); err != nil { + return false, err + } + return true, nil +} + +// unlock releases the Device's Lease if this operation holds it. +func (r *Reconciler) unlock(ctx context.Context, op *inventory.DevicePowerOperation) error { + var lease coordinationv1.Lease + err := r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: LockName(r.Config.Project, op.Namespace, op.Spec.DeviceRef.Name)}, &lease) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + return err + } + if ptr.Deref(lease.Spec.HolderIdentity, "") != string(op.UID) { + return nil + } + err = r.Site.Delete(ctx, &lease, client.Preconditions{UID: &lease.UID, ResourceVersion: &lease.ResourceVersion}) + if apierrors.IsNotFound(err) || apierrors.IsConflict(err) { + return nil + } + return err +} + +// finished releases the lock and, after the retention period, deletes the +// operation's stage record, which owns its worker objects. +func (r *Reconciler) finished(ctx context.Context, op *inventory.DevicePowerOperation) (reconcile.Result, error) { + if err := r.unlock(ctx, op); err != nil { + return reconcile.Result{}, err + } + rec, err := r.record(ctx, op.UID) + if err != nil || rec == nil { + return reconcile.Result{}, err + } + var job batchv1.Job + err = r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: rec.Name}, &job) + if err == nil && !jobFinished(&job) { + // A worker still runs; keep its record until it ends. + return reconcile.Result{RequeueAfter: runningRequeue}, nil + } + if err != nil && !apierrors.IsNotFound(err) { + return reconcile.Result{}, err + } + finishedAt := rec.CreationTimestamp.Time + if op.Status.FinishedAt != nil { + finishedAt = op.Status.FinishedAt.Time + } + if wait := finishedAt.Add(r.Config.Retention.Duration).Sub(r.now()); wait > 0 { + return reconcile.Result{RequeueAfter: wait}, nil + } + return reconcile.Result{}, r.deleteRecord(ctx, rec) +} + +// collectOrphans deletes the records of a deleted operation once their +// worker has ended. Deleting an operation never cancels a command. +func (r *Reconciler) collectOrphans(ctx context.Context, key types.NamespacedName) error { + var list corev1.ConfigMapList + if err := r.SiteReader.List(ctx, &list, client.InNamespace(r.Namespace), client.MatchingLabels{PartOfLabel: PartOf, ComponentLabel: "record"}); err != nil { + return err + } + var errs []error + for i := range list.Items { + rec := &list.Items[i] + if rec.Annotations[OperationNamespace] != key.Namespace || rec.Annotations[OperationName] != key.Name { + continue + } + var job batchv1.Job + err := r.SiteReader.Get(ctx, types.NamespacedName{Namespace: r.Namespace, Name: rec.Name}, &job) + if err == nil && !jobFinished(&job) { + continue + } + if err != nil && !apierrors.IsNotFound(err) { + errs = append(errs, err) + continue + } + errs = append(errs, r.deleteRecord(ctx, rec)) + } + return errors.Join(errs...) +} + +func (r *Reconciler) deleteRecord(ctx context.Context, rec *corev1.ConfigMap) error { + err := r.Site.Delete(ctx, rec, client.PropagationPolicy(metav1.DeletePropagationBackground), client.Preconditions{UID: &rec.UID}) + if apierrors.IsNotFound(err) { + return nil + } + return err +} diff --git a/internal/devicepower/dispatcher_test.go b/internal/devicepower/dispatcher_test.go new file mode 100644 index 00000000..38bbdf20 --- /dev/null +++ b/internal/devicepower/dispatcher_test.go @@ -0,0 +1,409 @@ +package devicepower + +import ( + "context" + "slices" + "sync" + "testing" + "time" + + batchv1 "k8s.io/api/batch/v1" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +const workerImage = "ghcr.io/datum-cloud/fleet@sha256:0000000000000000000000000000000000000000000000000000000000000000" + +type dispatchHarness struct { + milo, site client.Client + now time.Time + mu sync.Mutex +} + +func newDispatchHarness(t *testing.T, objs ...client.Object) *dispatchHarness { + t.Helper() + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + milo := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&inventory.DevicePowerOperation{}, &inventory.Device{}).Build() + site := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&batchv1.Job{}).Build() + return &dispatchHarness{milo: milo, site: site, now: t0} +} + +func (h *dispatchHarness) reconciler() *Reconciler { + c := Config{Project: project, MiloKubeconfig: "unused", DeviceNamespaces: []string{deviceNS}, WorkerNamespace: siteNS, WorkerImage: workerImage} + c.Default() + c.DiscoveryMaxAge.Duration = time.Hour + return &Reconciler{Milo: h.milo, MiloReader: h.milo, Site: h.site, SiteReader: h.site, Namespace: siteNS, Config: c, + Now: func() time.Time { h.mu.Lock(); defer h.mu.Unlock(); return h.now }} +} + +// settle reconciles one operation until it asks for no immediate requeue. +func (h *dispatchHarness) settle(t *testing.T, r *Reconciler, name string) { + t.Helper() + for range 10 { + result, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: deviceNS, Name: name}}) + if err != nil && !apierrors.IsConflict(err) { + t.Fatal(err) + } + if err == nil && !result.Requeue { + return + } + } + t.Fatal("reconcile did not settle") +} + +func (h *dispatchHarness) op(t *testing.T, name string) *inventory.DevicePowerOperation { + t.Helper() + var op inventory.DevicePowerOperation + if err := h.milo.Get(context.Background(), types.NamespacedName{Namespace: deviceNS, Name: name}, &op); err != nil { + t.Fatal(err) + } + return &op +} + +func (h *dispatchHarness) count(t *testing.T, list client.ObjectList) int { + t.Helper() + if err := h.site.List(context.Background(), list, client.InNamespace(siteNS)); err != nil { + t.Fatal(err) + } + return meta.LenList(list) +} + +// setProgressOf plays the worker's part on the stage record. +func (h *dispatchHarness) setProgressOf(t *testing.T, op *inventory.DevicePowerOperation, mutate func(*Progress)) { + t.Helper() + var cm corev1.ConfigMap + if err := h.site.Get(context.Background(), types.NamespacedName{Namespace: siteNS, Name: WorkerName(op.UID)}, &cm); err != nil { + t.Fatal(err) + } + _, p, err := decodeRecord(&cm) + if err != nil { + t.Fatal(err) + } + mutate(&p) + setProgress(&cm, p) + if err := h.site.Update(context.Background(), &cm); err != nil { + t.Fatal(err) + } +} + +func (h *dispatchHarness) failJob(t *testing.T, op *inventory.DevicePowerOperation) { + t.Helper() + var job batchv1.Job + if err := h.site.Get(context.Background(), types.NamespacedName{Namespace: siteNS, Name: WorkerName(op.UID)}, &job); err != nil { + t.Fatal(err) + } + job.Status.Conditions = append(job.Status.Conditions, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionTrue}) + if err := h.site.Status().Update(context.Background(), &job); err != nil { + t.Fatal(err) + } +} + +func finishedReason(op *inventory.DevicePowerOperation) string { + if c := meta.FindStatusCondition(op.Status.Conditions, inventory.ConditionPowerFinished); c != nil && c.Status == metav1.ConditionTrue { + return c.Reason + } + return "" +} + +func TestDispatcherStartsOneBoundedWorker(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerForceRestart)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + if !meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerAccepted) || !meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerExecuting) || op.Status.Result != "" { + t.Fatalf("status = %+v", op.Status) + } + name := types.NamespacedName{Namespace: siteNS, Name: WorkerName(op.UID)} + var rec corev1.ConfigMap + if err := h.site.Get(context.Background(), name, &rec); err != nil { + t.Fatal(err) + } + in, p, err := decodeRecord(&rec) + if err != nil || p.Stage != StagePending || in.Endpoint != endpoint || in.SystemUUID != uuidA || in.PublicKeySHA256 != keyA || in.Action != inventory.PowerForceRestart || !in.CapacityCheckedAt.Time.Equal(t0) { + t.Fatalf("record = %+v %+v %v", in, p, err) + } + var job batchv1.Job + if err := h.site.Get(context.Background(), name, &job); err != nil { + t.Fatal(err) + } + spec := job.Spec.Template.Spec + if *job.Spec.BackoffLimit != 0 || *job.Spec.PodReplacementPolicy != batchv1.Failed || spec.ServiceAccountName != name.Name || len(spec.Containers) != 1 || + spec.Containers[0].Image != workerImage || spec.HostNetwork || spec.HostPID || spec.HostIPC || len(spec.Volumes) != 1 || + spec.Volumes[0].Secret.SecretName != "bmc.default.device-a" || !*spec.Volumes[0].Secret.Optional || len(job.OwnerReferences) != 1 || job.OwnerReferences[0].UID != rec.UID { + t.Fatalf("job = %+v", job.Spec) + } + var role rbacv1.Role + if err := h.site.Get(context.Background(), name, &role); err != nil { + t.Fatal(err) + } + if len(role.Rules) != 1 || !slices.Equal(role.Rules[0].Resources, []string{"configmaps"}) || !slices.Equal(role.Rules[0].ResourceNames, []string{name.Name}) || + !slices.Equal(role.Rules[0].Verbs, []string{"get", "update"}) { + t.Fatalf("worker role = %+v", role.Rules) + } + // More passes while the worker runs start nothing new. + for range 3 { + h.settle(t, r, "op") + } + if n := h.count(t, &batchv1.JobList{}); n != 1 { + t.Fatalf("%d Jobs", n) + } +} + +func TestDispatcherRefusalsSendNothing(t *testing.T) { + retired := discoveredDevice("device-r") + retired.Spec.Lifecycle = inventory.DeviceRetired + for _, tc := range []struct { + op *inventory.DevicePowerOperation + objs []client.Object + reason string + }{ + {operation("op", "device-a", inventory.PowerOn), []client.Object{discoveredDevice("device-a"), capacity("cap", "device-a")}, inventory.ReasonCapacityBacked}, + {operation("op", "missing", inventory.PowerOn), nil, inventory.ReasonDeviceNotFound}, + {operation("op", "device-r", inventory.PowerOn), []client.Object{retired}, inventory.ReasonDeviceRetired}, + {operation("op", "device-a", inventory.PowerCycle), []client.Object{discoveredDevice("device-a")}, inventory.ReasonResetTypeNotOffered}, + } { + t.Run(tc.reason, func(t *testing.T) { + h := newDispatchHarness(t, append(tc.objs, tc.op)...) + h.settle(t, h.reconciler(), "op") + op := h.op(t, "op") + if op.Status.Result != inventory.PowerFailed || finishedReason(op) != tc.reason || meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerAccepted) { + t.Fatalf("status = %+v", op.Status) + } + if n := h.count(t, &corev1.ConfigMapList{}) + h.count(t, &batchv1.JobList{}) + h.count(t, &coordinationv1.LeaseList{}); n != 0 { + t.Fatalf("%d site objects for a refused operation", n) + } + }) + } +} + +func TestDispatcherRefusesAWrongSystemUUID(t *testing.T) { + op := operation("op", "device-a", inventory.PowerOn) + op.Spec.ExpectedSystemUUID = uuidB + h := newDispatchHarness(t, discoveredDevice("device-a"), op) + h.settle(t, h.reconciler(), "op") + if got := h.op(t, "op"); got.Status.Result != inventory.PowerFailed || finishedReason(got) != inventory.ReasonSystemUUIDMismatch { + t.Fatalf("status = %+v", got.Status) + } +} + +// Capacity defined after acceptance is caught by the re-check just before +// the worker starts. +func TestCapacityRecheckBeforeTheWorker(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerOn)) + r := h.reconciler() + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: deviceNS, Name: "op"}}); err != nil { + t.Fatal(err) + } + if !meta.IsStatusConditionTrue(h.op(t, "op").Status.Conditions, inventory.ConditionPowerAccepted) { + t.Fatal("not accepted") + } + if err := h.milo.Create(context.Background(), capacity("cap", "device-a")); err != nil { + t.Fatal(err) + } + h.settle(t, r, "op") + op := h.op(t, "op") + if op.Status.Result != inventory.PowerFailed || finishedReason(op) != inventory.ReasonCapacityBacked { + t.Fatalf("status = %+v", op.Status) + } + if n := h.count(t, &corev1.ConfigMapList{}) + h.count(t, &batchv1.JobList{}) + h.count(t, &coordinationv1.LeaseList{}); n != 0 { + t.Fatalf("%d site objects left", n) + } +} + +func TestDispatcherPublishesTheWorkersResult(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerForceOff)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + sent, done := metav1.NewTime(t0.Add(time.Second)), metav1.NewTime(t0.Add(20*time.Second)) + h.setProgressOf(t, op, func(p *Progress) { + *p = Progress{Stage: StageFinished, ClaimedBy: "pod", Result: inventory.PowerSucceeded, Reason: ReasonRequestedStateReached, Message: "the server reached Off", + RequestSentAt: &sent, FinishedAt: &done, Before: &inventory.PowerObservation{State: "On", ObservedAt: sent}, After: &inventory.PowerObservation{State: "Off", ObservedAt: done}} + }) + // A dispatcher restarted from nothing picks the operation up from the + // record. + h.settle(t, h.reconciler(), "op") + op = h.op(t, "op") + if op.Status.Result != inventory.PowerSucceeded || finishedReason(op) != ReasonRequestedStateReached || !op.Status.RequestSentAt.Equal(&sent) || + op.Status.Power.Before.State != "On" || op.Status.Power.After.State != "Off" || meta.IsStatusConditionTrue(op.Status.Conditions, inventory.ConditionPowerExecuting) { + t.Fatalf("status = %+v", op.Status) + } + if n := h.count(t, &coordinationv1.LeaseList{}); n != 0 { + t.Fatal("the Device lock was not released") + } +} + +func TestLostWorkerOutcomes(t *testing.T) { + for _, tc := range []struct { + stage Stage + result inventory.PowerResult + reason string + }{ + {StagePending, inventory.PowerFailed, ReasonWorkerNotStarted}, + {StageClaimed, inventory.PowerFailed, ReasonWorkerLost}, + {StageSending, inventory.PowerUnknown, ReasonWorkerLost}, + {StageSent, inventory.PowerUnknown, ReasonWorkerLost}, + } { + t.Run(string(tc.stage), func(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerForceRestart)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + h.setProgressOf(t, op, func(p *Progress) { p.Stage = tc.stage }) + h.failJob(t, op) + h.settle(t, r, "op") + op = h.op(t, "op") + if op.Status.Result != tc.result || finishedReason(op) != tc.reason { + t.Fatalf("status = %+v", op.Status) + } + var cm corev1.ConfigMap + _ = h.site.Get(context.Background(), types.NamespacedName{Namespace: siteNS, Name: WorkerName(op.UID)}, &cm) + if _, p, _ := decodeRecord(&cm); p.Stage != StageAbandoned || p.Result != tc.result { + t.Fatalf("record not fenced: %+v", p) + } + }) + } +} + +// A Job deleted mid-operation is not recreated once the record was claimed: +// the outcome follows the record. +func TestDeletedJobAfterTheClaimIsNotRestarted(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerOn)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + h.setProgressOf(t, op, func(p *Progress) { p.Stage = StageSent; p.SendOutcome = SendLost }) + if err := h.site.Delete(context.Background(), &batchv1.Job{ObjectMeta: metav1.ObjectMeta{Namespace: siteNS, Name: WorkerName(op.UID)}}); err != nil { + t.Fatal(err) + } + h.settle(t, r, "op") + if got := h.op(t, "op"); got.Status.Result != inventory.PowerUnknown || finishedReason(got) != ReasonWorkerLost { + t.Fatalf("status = %+v", got.Status) + } + if n := h.count(t, &batchv1.JobList{}); n != 0 { + t.Fatalf("%d Jobs were recreated", n) + } +} + +func TestStartedOperationWithoutARecordIsUnknown(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerOn)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + if err := h.site.Delete(context.Background(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: siteNS, Name: WorkerName(op.UID)}}); err != nil { + t.Fatal(err) + } + h.settle(t, r, "op") + if got := h.op(t, "op"); got.Status.Result != inventory.PowerUnknown || finishedReason(got) != ReasonRecordLost { + t.Fatalf("status = %+v", got.Status) + } +} + +func TestSecondOperationOnADeviceIsRefused(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("first", "device-a", inventory.PowerOn), operation("second", "device-a", inventory.PowerForceOff)) + r := h.reconciler() + h.settle(t, r, "first") + h.settle(t, r, "second") + if got := h.op(t, "second"); got.Status.Result != inventory.PowerFailed || finishedReason(got) != inventory.ReasonOperationInProgress { + t.Fatalf("second = %+v", got.Status) + } + if n := h.count(t, &batchv1.JobList{}); n != 1 { + t.Fatalf("%d Jobs", n) + } +} + +// Two dispatchers that both judge two operations on one Device acceptable +// cannot both start a worker: the site Lease admits one. +func TestDeviceLockAcrossDispatchers(t *testing.T) { + first, second := operation("first", "device-a", inventory.PowerOn), operation("second", "device-a", inventory.PowerOn) + h := newDispatchHarness(t, discoveredDevice("device-a"), first, second) + a, b := h.reconciler(), h.reconciler() + if held, err := a.lock(context.Background(), first); err != nil || !held { + t.Fatalf("first lock = %v %v", held, err) + } + if held, err := b.lock(context.Background(), second); err != nil || held { + t.Fatalf("second lock = %v %v", held, err) + } + // Once the holder has a result the lock is taken over. + done := h.op(t, "first") + done.Status.Result = inventory.PowerSucceeded + if err := h.milo.Status().Update(context.Background(), done); err != nil { + t.Fatal(err) + } + if held, err := b.lock(context.Background(), second); err != nil || !held { + t.Fatalf("takeover = %v %v", held, err) + } +} + +// Duplicate dispatch: several dispatchers reconciling the same operation at +// once write one record and one Job. +func TestDuplicateDispatchStartsOneWorker(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerForceRestart)) + var wg sync.WaitGroup + for range 6 { + r := h.reconciler() + wg.Add(1) + go func() { + defer wg.Done() + for range 10 { + _, _ = r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: deviceNS, Name: "op"}}) + } + }() + } + wg.Wait() + h.settle(t, h.reconciler(), "op") + if jobs, records, leases := h.count(t, &batchv1.JobList{}), h.count(t, &corev1.ConfigMapList{}), h.count(t, &coordinationv1.LeaseList{}); jobs != 1 || records != 1 || leases != 1 { + t.Fatalf("%d Jobs, %d records, %d leases", jobs, records, leases) + } + if !meta.IsStatusConditionTrue(h.op(t, "op").Status.Conditions, inventory.ConditionPowerExecuting) { + t.Fatal("not executing") + } +} + +func TestRetentionDeletesTheRecordAfterTheWorkerEnds(t *testing.T) { + h := newDispatchHarness(t, discoveredDevice("device-a"), operation("op", "device-a", inventory.PowerOn)) + r := h.reconciler() + h.settle(t, r, "op") + op := h.op(t, "op") + done := metav1.NewTime(t0) + h.setProgressOf(t, op, func(p *Progress) { + *p = Progress{Stage: StageFinished, ClaimedBy: "pod", Result: inventory.PowerSucceeded, Reason: ReasonAlreadyInState, FinishedAt: &done} + }) + var job batchv1.Job + _ = h.site.Get(context.Background(), types.NamespacedName{Namespace: siteNS, Name: WorkerName(op.UID)}, &job) + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + if err := h.site.Status().Update(context.Background(), &job); err != nil { + t.Fatal(err) + } + h.settle(t, r, "op") + h.settle(t, r, "op") + if n := h.count(t, &corev1.ConfigMapList{}); n != 1 { + t.Fatalf("record removed before retention: %d", n) + } + h.now = t0.Add(r.Config.Retention.Duration + time.Minute) + h.settle(t, r, "op") + if n := h.count(t, &corev1.ConfigMapList{}); n != 0 { + t.Fatalf("record kept after retention: %d", n) + } +} + +func TestShippedWorkerDeadlineCoversTheObservation(t *testing.T) { + c := Config{} + c.Default() + if d := c.jobDeadline(); d < StaleAfter+c.ObserveTimeout.Duration { + t.Fatalf("job deadline %s", d) + } +} diff --git a/internal/devicepower/fixtures_test.go b/internal/devicepower/fixtures_test.go new file mode 100644 index 00000000..c1dcab5e --- /dev/null +++ b/internal/devicepower/fixtures_test.go @@ -0,0 +1,84 @@ +package devicepower + +import ( + "strings" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +// Synthetic identifiers only. +const ( + project = "example-provider-project" + deviceNS = "default" + siteNS = "fleet-device-power" + uuidA = "00000000-0000-4000-8000-0000000000a1" + uuidB = "00000000-0000-4000-8000-0000000000b2" + endpoint = "https://192.0.2.10:443" +) + +var ( + t0 = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + keyA = strings.Repeat("a", 64) +) + +// discoveredDevice is a Device that discovery read recently and matched. +func discoveredDevice(name string) *inventory.Device { + at := metav1.NewTime(t0.Add(-10 * time.Minute)) + cond := func(kind, reason string) metav1.Condition { + return metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: reason, ObservedGeneration: 1, LastTransitionTime: at} + } + return &inventory.Device{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: deviceNS, Generation: 1, UID: types.UID("device-" + name)}, + Spec: inventory.DeviceSpec{ + ClaimRef: inventory.LocalReference{Name: "claim-" + name}, + Identity: inventory.DeviceIdentity{Model: "Example 1U", SystemUUID: uuidA}, + BMC: &inventory.BMC{Endpoint: endpoint}, + }, + Status: inventory.DeviceStatus{ + ObservedGeneration: 1, + Discovery: &inventory.DeviceDiscovery{ + LastAttemptAt: &at, LastAttemptEndpoint: endpoint, + TLS: &inventory.ObservedTLS{ObservedAt: at, Endpoint: endpoint, PublicKeySHA256: keyA}, + Inventory: &inventory.ObservedInventory{ObservedAt: at, Endpoint: endpoint, Systems: []inventory.ObservedSystem{ + {ID: "1", UUID: uuidA, Model: "Example 1U", PowerState: "Off", ResetTypes: []string{"On", "ForceOff", "ForceRestart"}}, + }}, + }, + Conditions: []metav1.Condition{ + cond(inventory.ConditionReachable, "ServiceRootRead"), + cond(inventory.ConditionAuthenticated, "CredentialAccepted"), + cond(inventory.ConditionDiscovered, "InventoryRead"), + cond(inventory.ConditionIdentityMatched, "Matched"), + cond(inventory.ConditionPublicKeyUnique, "Unique"), + }, + }, + } +} + +func operation(name, device string, action inventory.PowerAction) *inventory.DevicePowerOperation { + return &inventory.DevicePowerOperation{ + TypeMeta: metav1.TypeMeta{APIVersion: inventory.GroupVersion.String(), Kind: "DevicePowerOperation"}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: deviceNS, UID: types.UID("00000000-0000-4000-8000-00000000" + uidSuffix(name)), Generation: 1, CreationTimestamp: metav1.NewTime(t0.Add(-time.Minute))}, + Spec: inventory.DevicePowerOperationSpec{DeviceRef: inventory.LocalReference{Name: device}, Action: action, ExpectedSystemUUID: uuidA, + Requester: "staff@example.com", Reason: "synthetic test"}, + } +} + +// uidSuffix makes a stable four-hex-digit suffix per name. +func uidSuffix(name string) string { + var h uint16 + for _, r := range name { + h = h*31 + uint16(r) + } + const hex = "0123456789abcdef" + return string([]byte{hex[h>>12], hex[(h>>8)&15], hex[(h>>4)&15], hex[h&15]}) +} + +func capacity(name, device string) *metal.MachineCapacity { + return &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: deviceNS}, + Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device}}} +} diff --git a/internal/devicepower/manifest_test.go b/internal/devicepower/manifest_test.go new file mode 100644 index 00000000..bcadeb87 --- /dev/null +++ b/internal/devicepower/manifest_test.go @@ -0,0 +1,53 @@ +package devicepower + +import ( + "os" + "path/filepath" + "slices" + "testing" + + appsv1 "k8s.io/api/apps/v1" + rbacv1 "k8s.io/api/rbac/v1" + "sigs.k8s.io/yaml" +) + +func TestShippedConfigLoads(t *testing.T) { + t.Setenv("POD_NAMESPACE", siteNS) + c, err := LoadConfig(filepath.Join(siteRoot, "config.yaml")) + if err != nil { + t.Fatal(err) + } + if c.WorkerNamespace != siteNS || c.ObserveTimeout.Duration.Minutes() != 3 { + t.Fatalf("config = %+v", c) + } +} + +func TestDispatcherDeploymentAndRBAC(t *testing.T) { + data, err := os.ReadFile(filepath.Join(siteRoot, "deployment.yaml")) + if err != nil { + t.Fatal(err) + } + var d appsv1.Deployment + if err := yaml.UnmarshalStrict(data, &d); err != nil { + t.Fatal(err) + } + pod := d.Spec.Template.Spec + if d.Spec.Replicas == nil || *d.Spec.Replicas != 1 || pod.HostNetwork || pod.SecurityContext == nil || !*pod.SecurityContext.RunAsNonRoot || len(pod.Containers) != 1 { + t.Fatal("the dispatcher is one unprivileged replica") + } + for _, v := range pod.Volumes { + if v.Secret != nil && v.Secret.SecretName != "fleet-device-power-milo-kubeconfig" { + t.Fatalf("the dispatcher mounts Secret %s", v.Secret.SecretName) + } + } + // The dispatcher holds no Secret or Pod permission and cannot change a + // Job once created. + for _, r := range decodeFile[rbacv1.Role](t, filepath.Join(siteRoot, "rbac.yaml"))[1].Rules { + if slices.Contains(r.Resources, "secrets") || slices.Contains(r.Resources, "pods") || slices.Contains(r.Verbs, "*") || slices.Contains(r.Verbs, "escalate") || slices.Contains(r.Verbs, "bind") { + t.Fatalf("dispatcher rule %+v", r) + } + if slices.Contains(r.Resources, "jobs") && (slices.Contains(r.Verbs, "update") || slices.Contains(r.Verbs, "patch") || slices.Contains(r.Verbs, "delete")) { + t.Fatalf("dispatcher may change Jobs: %+v", r) + } + } +} diff --git a/internal/devicepower/objects.go b/internal/devicepower/objects.go new file mode 100644 index 00000000..e18544dc --- /dev/null +++ b/internal/devicepower/objects.go @@ -0,0 +1,95 @@ +package devicepower + +import ( + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" +) + +// Worker container contract. +const ( + WorkerCommand = "/fleet-device-power" + // CredentialMount holds the mounted credential Secret's username, + // password and tlsPublicKeySHA256 files. + CredentialMount = "/var/run/fleet/bmc" + // RecordEnv names the stage record; PodUIDEnv carries the worker Pod's + // UID as its claim identity. + RecordEnv = "FLEET_POWER_RECORD" + PodUIDEnv = "FLEET_POWER_POD_UID" +) + +func objectLabels(uid, component string) map[string]string { + return map[string]string{PartOfLabel: PartOf, ComponentLabel: component, OperationUIDLabel: uid} +} + +// record builds the stage record of an accepted operation. +func record(namespace string, in Inputs) *corev1.ConfigMap { + return &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Name: WorkerName(uidOf(in)), Namespace: namespace, Labels: objectLabels(in.OperationUID, "record"), + Annotations: map[string]string{OperationNamespace: in.Namespace, OperationName: in.Operation, DeviceNamespace: in.Namespace, DeviceName: in.Device}}, + Data: map[string]string{InputsKey: encode(in), ProgressKey: encode(Progress{Stage: StagePending})}, + } +} + +// owned makes a worker object a dependent of its stage record, so deleting +// the record after retention removes all of them. +func owned(rec *corev1.ConfigMap) []metav1.OwnerReference { + return []metav1.OwnerReference{{APIVersion: "v1", Kind: "ConfigMap", Name: rec.Name, UID: rec.UID}} +} + +// workerObjects builds the ServiceAccount, Role, RoleBinding and Job of one +// operation. The Role grants get and update on the stage record and nothing +// else; the Job mounts exactly the Device's credential Secret. +func workerObjects(rec *corev1.ConfigMap, in Inputs, image, secret string, deadline int64) (*corev1.ServiceAccount, *rbacv1.Role, *rbacv1.RoleBinding, *batchv1.Job) { + name, ns := rec.Name, rec.Namespace + meta := func(component string) metav1.ObjectMeta { + return metav1.ObjectMeta{Name: name, Namespace: ns, Labels: objectLabels(in.OperationUID, component), OwnerReferences: owned(rec), + Annotations: map[string]string{OperationNamespace: in.Namespace, OperationName: in.Operation, DeviceNamespace: in.Namespace, DeviceName: in.Device}} + } + sa := &corev1.ServiceAccount{ObjectMeta: meta("worker")} + role := &rbacv1.Role{ObjectMeta: meta("worker"), Rules: []rbacv1.PolicyRule{{ + APIGroups: []string{""}, Resources: []string{"configmaps"}, ResourceNames: []string{name}, Verbs: []string{"get", "update"}}}} + binding := &rbacv1.RoleBinding{ObjectMeta: meta("worker"), + RoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "Role", Name: name}, + Subjects: []rbacv1.Subject{{Kind: rbacv1.ServiceAccountKind, Name: name, Namespace: ns}}} + podLabels := objectLabels(in.OperationUID, "worker") + job := &batchv1.Job{ObjectMeta: meta("worker"), Spec: batchv1.JobSpec{ + // One Pod, never replaced: a second worker would stop at the claim, + // but none is started on purpose. + BackoffLimit: ptr.To[int32](0), + PodReplacementPolicy: ptr.To(batchv1.Failed), + ActiveDeadlineSeconds: ptr.To(deadline), + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{Labels: podLabels, Annotations: map[string]string{DeviceNamespace: in.Namespace, DeviceName: in.Device}}, + Spec: corev1.PodSpec{ + ServiceAccountName: name, + AutomountServiceAccountToken: ptr.To(true), + RestartPolicy: corev1.RestartPolicyNever, + EnableServiceLinks: ptr.To(false), + SecurityContext: &corev1.PodSecurityContext{RunAsNonRoot: ptr.To(true), RunAsUser: ptr.To[int64](65532), RunAsGroup: ptr.To[int64](65532), + FSGroup: ptr.To[int64](65532), SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}}, + Containers: []corev1.Container{{ + Name: "worker", + Image: image, + Command: []string{WorkerCommand, "worker"}, + Env: []corev1.EnvVar{{Name: RecordEnv, Value: name}, {Name: "POD_NAMESPACE", Value: ns}, + {Name: PodUIDEnv, ValueFrom: &corev1.EnvVarSource{FieldRef: &corev1.ObjectFieldSelector{FieldPath: "metadata.uid"}}}}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("10m"), corev1.ResourceMemory: resource.MustParse("32Mi")}, + Limits: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")}}, + SecurityContext: &corev1.SecurityContext{AllowPrivilegeEscalation: ptr.To(false), ReadOnlyRootFilesystem: ptr.To(true), + Capabilities: &corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}}, + VolumeMounts: []corev1.VolumeMount{{Name: "credential", MountPath: CredentialMount, ReadOnly: true}}, + }}, + // Optional, so a missing Secret ends the operation as Failed + // instead of a Pod that never starts. + Volumes: []corev1.Volume{{Name: "credential", VolumeSource: corev1.VolumeSource{Secret: &corev1.SecretVolumeSource{ + SecretName: secret, Optional: ptr.To(true), DefaultMode: ptr.To[int32](0o440)}}}}, + }, + }, + }} + return sa, role, binding, job +} diff --git a/internal/devicepower/record.go b/internal/devicepower/record.go new file mode 100644 index 00000000..f18afc3e --- /dev/null +++ b/internal/devicepower/record.go @@ -0,0 +1,173 @@ +// Package devicepower runs staff power operations on unallocated Devices. +// +// The site dispatcher (Reconciler) accepts or refuses each +// DevicePowerOperation in one Milo project, starts one worker Job per accepted +// operation and is the only writer of the operation's status. It holds no BMC +// credential. The worker (RunWorker) reads one mounted credential, re-checks +// the server's TLS key, identity and offered actions, sends at most one +// ComputerSystem.Reset and observes the result. It cannot reach Milo: it +// records its progress in a site-local stage record, which the dispatcher +// publishes. See docs/operations/device-power.md. +package devicepower + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +// Labels and annotations on site objects. Every object the dispatcher creates +// carries PartOfLabel and the operation's UID. +const ( + PartOfLabel = "app.kubernetes.io/part-of" + PartOf = "fleet-device-power" + ComponentLabel = "app.kubernetes.io/component" + OperationUIDLabel = "fleet.datumapis.com/power-operation-uid" + OperationNamespace = "fleet.datumapis.com/power-operation-namespace" + OperationName = "fleet.datumapis.com/power-operation-name" + DeviceNamespace = "fleet.datumapis.com/device-namespace" + DeviceName = "fleet.datumapis.com/device-name" + // InputsKey and ProgressKey are the stage record's two data keys. The + // dispatcher writes inputs once; the worker writes only progress. + InputsKey = "inputs" + ProgressKey = "progress" +) + +// Fixed time bounds from the design. +const ( + // AcceptanceWindow is how long an operation may wait to be accepted. + AcceptanceWindow = 5 * time.Minute + // StaleAfter is how long after the dispatcher's last capacity check a + // worker may still start. + StaleAfter = 2 * time.Minute +) + +// WorkerName is the name of the stage record, worker Job, ServiceAccount, +// Role and RoleBinding of one operation. +func WorkerName(uid types.UID) string { return "pwr-" + string(uid) } + +func uidOf(in Inputs) types.UID { return types.UID(in.OperationUID) } + +// CredentialSecretName is the one credential Secret a worker may mount: the +// Device's namespace and name joined by dots. Namespaces hold no dots, so the +// name is unambiguous. ok is false when the name would exceed 253 characters. +func CredentialSecretName(namespace, device string) (name string, ok bool) { + name = "bmc." + namespace + "." + device + return name, len(name) <= 253 +} + +// LockName is the site Lease that admits one running operation per Device. +func LockName(project, namespace, device string) string { + sum := sha256.Sum256([]byte(project + "/" + namespace + "/" + device)) + return "pwr-lock-" + hex.EncodeToString(sum[:10]) +} + +// Stage is how far a worker got. Only the worker moves a record from Pending +// through Finished; the dispatcher moves an unfinished record to Abandoned +// when its worker is gone, with the same optimistic lock, so a lost worker +// can no longer send. +type Stage string + +const ( + // StagePending: the worker has not claimed the operation. + StagePending Stage = "Pending" + // StageClaimed: one worker claimed it. Nothing has been sent. + StageClaimed Stage = "Claimed" + // StageSending is written before the one command. From here on a + // command may have been sent. + StageSending Stage = "Sending" + // StageSent: the command's response, or its loss, was recorded. + StageSent Stage = "Sent" + // StageFinished: the worker recorded a result. + StageFinished Stage = "Finished" + // StageAbandoned: the dispatcher fenced a record whose worker is gone. + StageAbandoned Stage = "Abandoned" +) + +// mayHaveSent reports whether a command may have reached the BMC. +func (s Stage) mayHaveSent() bool { return s == StageSending || s == StageSent } + +// Inputs are the exact inputs of one operation, retained before any effect. +type Inputs struct { + OperationUID string `json:"operationUID"` + Project string `json:"project"` + Namespace string `json:"namespace"` + Operation string `json:"operation"` + Device string `json:"device"` + Endpoint string `json:"endpoint"` + SystemUUID string `json:"systemUUID"` + // PublicKeySHA256 is the TLS key discovery last observed for this BMC. + // The mounted credential's approved pin must equal it. + PublicKeySHA256 string `json:"publicKeySHA256"` + Action inventory.PowerAction `json:"action"` + CapacityCheckedAt metav1.Time `json:"capacityCheckedAt"` + ObserveTimeout metav1.Duration `json:"observeTimeout"` + RequestTimeout metav1.Duration `json:"requestTimeout"` +} + +// Progress is the worker's record of one operation. +type Progress struct { + Stage Stage `json:"stage"` + ClaimedBy string `json:"claimedBy,omitempty"` + ClaimedAt *metav1.Time `json:"claimedAt,omitempty"` + // Before is the power state read just before the command. + Before *inventory.PowerObservation `json:"before,omitempty"` + RequestSentAt *metav1.Time `json:"requestSentAt,omitempty"` + // SendOutcome is Answered, Refused or Lost. A lost response is never + // resent. + SendOutcome string `json:"sendOutcome,omitempty"` + After *inventory.PowerObservation `json:"after,omitempty"` + Result inventory.PowerResult `json:"result,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + FinishedAt *metav1.Time `json:"finishedAt,omitempty"` +} + +// Send outcomes. +const ( + SendAnswered = "Answered" + SendRefused = "Refused" + SendLost = "Lost" +) + +var errRecordInvalid = errors.New("stage record is malformed") + +func decodeRecord(cm *corev1.ConfigMap) (Inputs, Progress, error) { + var in Inputs + var p Progress + if err := json.Unmarshal([]byte(cm.Data[InputsKey]), &in); err != nil { + return in, p, errRecordInvalid + } + if err := json.Unmarshal([]byte(cm.Data[ProgressKey]), &p); err != nil { + return in, p, errRecordInvalid + } + if in.OperationUID == "" || string(cm.Labels[OperationUIDLabel]) != in.OperationUID || cm.Name != WorkerName(types.UID(in.OperationUID)) || p.Stage == "" { + return in, p, errRecordInvalid + } + return in, p, nil +} + +func encode(v any) string { + b, err := json.Marshal(v) + if err != nil { + panic(fmt.Sprintf("encode stage record: %v", err)) + } + return string(b) +} + +// setProgress writes p into the record. +func setProgress(cm *corev1.ConfigMap, p Progress) { + if cm.Data == nil { + cm.Data = map[string]string{} + } + cm.Data[ProgressKey] = encode(p) +} diff --git a/internal/devicepower/runtime.go b/internal/devicepower/runtime.go new file mode 100644 index 00000000..52f63117 --- /dev/null +++ b/internal/devicepower/runtime.go @@ -0,0 +1,107 @@ +package devicepower + +import ( + "context" + "fmt" + + batchv1 "k8s.io/api/batch/v1" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/manager" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +// NewScheme registers the kinds the dispatcher and worker use. +func NewScheme() (*runtime.Scheme, error) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, batchv1.AddToScheme, coordinationv1.AddToScheme, rbacv1.AddToScheme, + inventory.AddToScheme, metal.AddToScheme} { + if err := add(scheme); err != nil { + return nil, err + } + } + return scheme, nil +} + +// NewManager builds the dispatcher. The manager's cluster is the Milo +// project; a second cluster is the site, where it reads and writes only its +// own labelled objects in the worker namespace. There is no leader election: +// run one replica. A second one is safe, because every acceptance, lock, +// record and Job write is optimistic or create-once, but it is not needed. +func NewManager(c Config, milo, local *rest.Config, scheme *runtime.Scheme) (manager.Manager, error) { + namespaces := map[string]cache.Config{} + for _, ns := range c.DeviceNamespaces { + namespaces[ns] = cache.Config{} + } + probe := c.HealthProbeAddress + if probe == "" { + probe = "0" + } + mgr, err := manager.New(milo, manager.Options{ + Scheme: scheme, + Cache: cache.Options{DefaultNamespaces: namespaces, DefaultTransform: cache.TransformStripManagedFields()}, + Metrics: metricsserver.Options{BindAddress: "0"}, + HealthProbeBindAddress: probe, + LeaderElection: false, + }) + if err != nil { + return nil, fmt.Errorf("build Milo project manager: %w", err) + } + selector := labels.SelectorFromSet(labels.Set{PartOfLabel: PartOf}) + site, err := cluster.New(local, func(o *cluster.Options) { + o.Scheme = scheme + o.Cache = cache.Options{DefaultNamespaces: map[string]cache.Config{c.WorkerNamespace: {}}, DefaultLabelSelector: selector, + DefaultTransform: cache.TransformStripManagedFields()} + }) + if err != nil { + return nil, fmt.Errorf("build site cache: %w", err) + } + if err := mgr.Add(site); err != nil { + return nil, err + } + r := &Reconciler{Milo: mgr.GetClient(), MiloReader: mgr.GetAPIReader(), Site: site.GetClient(), SiteReader: site.GetAPIReader(), + Namespace: c.WorkerNamespace, Config: c} + toOperation := handler.EnqueueRequestsFromMapFunc(func(_ context.Context, o client.Object) []reconcile.Request { + ns, name := o.GetAnnotations()[OperationNamespace], o.GetAnnotations()[OperationName] + if ns == "" || name == "" { + return nil + } + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: ns, Name: name}}} + }) + err = builder.ControllerManagedBy(mgr). + Named("device-power-dispatcher"). + For(&inventory.DevicePowerOperation{}). + WatchesRawSource(source.Kind(site.GetCache(), client.Object(&corev1.ConfigMap{}), toOperation)). + WatchesRawSource(source.Kind(site.GetCache(), client.Object(&batchv1.Job{}), toOperation)). + WithOptions(controller.Options{MaxConcurrentReconciles: 4}). + Complete(r) + if err != nil { + return nil, err + } + if c.HealthProbeAddress != "" { + if err := mgr.AddHealthzCheck("ping", healthz.Ping); err != nil { + return nil, err + } + if err := mgr.AddReadyzCheck("ping", healthz.Ping); err != nil { + return nil, err + } + } + return mgr, nil +} diff --git a/internal/devicepower/site_envtest_test.go b/internal/devicepower/site_envtest_test.go new file mode 100644 index 00000000..01272eab --- /dev/null +++ b/internal/devicepower/site_envtest_test.go @@ -0,0 +1,268 @@ +package devicepower + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + admissionv1 "k8s.io/api/admissionregistration/v1" + batchv1 "k8s.io/api/batch/v1" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/rest" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +var siteRoot = filepath.Join("..", "..", "config", "base", "device-power") + +// TestSitePoliciesAdmitOnlyTheWorkerShape applies the shipped dispatcher RBAC +// and site admission policies to a disposable API server, then acts as the +// dispatcher's and a worker's ServiceAccounts. +func TestSitePoliciesAdmitOnlyTheWorkerShape(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable API server validation") + } + environment := &envtest.Environment{} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + if err := admissionv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + for _, ns := range []*corev1.Namespace{{ObjectMeta: metav1.ObjectMeta{Name: siteNS, Labels: map[string]string{"fleet.datumapis.com/device-power-site": "true"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "elsewhere"}}} { + if err := admin.Create(ctx, ns); err != nil { + t.Fatal(err) + } + } + var objs []client.Object + for _, sa := range decodeFile[corev1.ServiceAccount](t, filepath.Join(siteRoot, "rbac.yaml"))[:1] { + objs = append(objs, &sa) + } + role := decodeFile[rbacv1.Role](t, filepath.Join(siteRoot, "rbac.yaml"))[1] + binding := decodeFile[rbacv1.RoleBinding](t, filepath.Join(siteRoot, "rbac.yaml"))[2] + params := decodeFile[corev1.ConfigMap](t, filepath.Join(siteRoot, "worker-policy-params.yaml"))[0] + params.Data["workerImage"] = workerImage + objs = append(objs, &role, &binding, ¶ms) + for _, obj := range objs { + obj.SetNamespace(siteNS) + } + policies := decodeFile[admissionv1.ValidatingAdmissionPolicy](t, filepath.Join(siteRoot, "worker-policy.yaml")) + bindings := decodeFile[admissionv1.ValidatingAdmissionPolicyBinding](t, filepath.Join(siteRoot, "worker-policy.yaml")) + objs = append(objs, &policies[0], &bindings[1], &policies[2], &bindings[3]) + for _, obj := range objs { + obj.GetObjectKind().SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind()) + if err := admin.Create(ctx, obj); err != nil { + t.Fatalf("create %s: %v", obj.GetName(), err) + } + } + as := func(user string) client.Client { + c := rest.CopyConfig(config) + c.Impersonate = rest.ImpersonationConfig{UserName: user} + out, err := client.New(c, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return out + } + dispatcher := as("system:serviceaccount:" + siteNS + ":fleet-device-power-dispatcher") + op := operation("op", "device-a", inventory.PowerForceRestart) + in := Inputs{OperationUID: string(op.UID), Project: project, Namespace: deviceNS, Operation: op.Name, Device: "device-a", Endpoint: endpoint, + SystemUUID: uuidA, PublicKeySHA256: keyA, Action: op.Spec.Action, CapacityCheckedAt: metav1.NewTime(t0)} + rec := record(siteNS, in) + // The policies take a moment to be enforced; until then a forbidden + // shape could slip through, so wait for one denial first. + waitDenied(t, func() error { + bad := record(siteNS, in) + bad.Name = "not-a-worker" + err := dispatcher.Create(ctx, bad) + if err == nil { + _ = admin.Delete(ctx, bad) + } + return err + }) + if err := dispatcher.Create(ctx, rec); err != nil { + t.Fatal(err) + } + sa, workerRole, workerBinding, job := workerObjects(rec, in, workerImage, "bmc.default.device-a", 600) + for _, obj := range []client.Object{sa, workerRole, workerBinding, job} { + if err := dispatcher.Create(ctx, obj); err != nil { + t.Fatalf("the worker shape was refused: %s: %v", obj.GetName(), err) + } + } + lease := &coordinationv1.Lease{ObjectMeta: metav1.ObjectMeta{Name: LockName(project, deviceNS, "device-a"), Namespace: siteNS, Labels: objectLabels(in.OperationUID, "lock")}, + Spec: coordinationv1.LeaseSpec{HolderIdentity: ptr.To(in.OperationUID)}} + if err := dispatcher.Create(ctx, lease); err != nil { + t.Fatal(err) + } + // Each deviation from the worker shape is denied. + clone := func(name string) (*corev1.ServiceAccount, *rbacv1.Role, *rbacv1.RoleBinding, *batchv1.Job) { + r := rec.DeepCopy() + r.Name = name + return workerObjects(r, in, workerImage, "bmc.default.device-a", 600) + } + for name, mutate := range map[string]func() client.Object{ + "another image": func() client.Object { + _, _, _, j := clone("pwr-image") + j.Spec.Template.Spec.Containers[0].Image = "example.invalid/other:1" + return j + }, + "another Device's credential": func() client.Object { + _, _, _, j := clone("pwr-secret") + j.Spec.Template.Spec.Volumes[0].Secret.SecretName = "bmc.default.device-b" + return j + }, + "a second volume": func() client.Object { + _, _, _, j := clone("pwr-volume") + j.Spec.Template.Spec.Volumes = append(j.Spec.Template.Spec.Volumes, corev1.Volume{Name: "extra", VolumeSource: corev1.VolumeSource{Secret: &corev1.SecretVolumeSource{SecretName: "fleet-bmc-discovery-milo-kubeconfig"}}}) + return j + }, + "a secret in the environment": func() client.Object { + _, _, _, j := clone("pwr-env") + j.Spec.Template.Spec.Containers[0].Env = append(j.Spec.Template.Spec.Containers[0].Env, corev1.EnvVar{Name: "X", ValueFrom: &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{LocalObjectReference: corev1.LocalObjectReference{Name: "bmc.default.device-b"}, Key: "password"}}}) + return j + }, + "privileged": func() client.Object { + _, _, _, j := clone("pwr-priv") + j.Spec.Template.Spec.Containers[0].SecurityContext.Privileged = ptr.To(true) + return j + }, + "host network": func() client.Object { + _, _, _, j := clone("pwr-host") + j.Spec.Template.Spec.HostNetwork = true + return j + }, + "retries": func() client.Object { + _, _, _, j := clone("pwr-retry") + j.Spec.BackoffLimit = ptr.To[int32](3) + return j + }, + "the dispatcher's identity": func() client.Object { + _, _, _, j := clone("pwr-identity") + j.Spec.Template.Spec.ServiceAccountName = "fleet-device-power-dispatcher" + return j + }, + "another command": func() client.Object { + _, _, _, j := clone("pwr-command") + j.Spec.Template.Spec.Containers[0].Command = []string{"/fleet-device-power", "dispatcher"} + return j + }, + "a Role reading Secrets": func() client.Object { + _, r, _, _ := clone("pwr-role") + r.Rules = append(r.Rules, rbacv1.PolicyRule{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}}) + return r + }, + "a Role on another record": func() client.Object { + _, r, _, _ := clone("pwr-role2") + r.Rules[0].ResourceNames = []string{rec.Name} + return r + }, + "a binding to another identity": func() client.Object { + _, r, b, _ := clone("pwr-bind") + // The Role exists, so only the policy can deny the binding. + if err := dispatcher.Create(ctx, r); err != nil { + t.Fatal(err) + } + b.Subjects[0].Name = "fleet-device-power-dispatcher" + return b + }, + "a non-worker object": func() client.Object { + return &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "fleet-bmc-discovery-2", Namespace: siteNS, Labels: map[string]string{PartOfLabel: PartOf}}} + }, + } { + t.Run(name, func(t *testing.T) { + if err := dispatcher.Create(ctx, mutate()); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("admitted: %v", err) + } + }) + } + // RBAC: the dispatcher cannot read Secrets or create Pods. + if err := dispatcher.Get(ctx, client.ObjectKey{Namespace: siteNS, Name: "bmc.default.device-a"}, &corev1.Secret{}); !apierrors.IsForbidden(err) { + t.Fatalf("the dispatcher read a Secret: %v", err) + } + if err := dispatcher.Create(ctx, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pwr-pod", Namespace: siteNS}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "c", Image: workerImage}}}}); !apierrors.IsForbidden(err) { + t.Fatalf("the dispatcher created a Pod: %v", err) + } + // The dispatcher changes a record's progress, not its inputs. + changed := rec.DeepCopy() + changed.Data[InputsKey] = encode(Inputs{OperationUID: in.OperationUID, Endpoint: "https://192.0.2.99:443"}) + if err := dispatcher.Update(ctx, changed); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("the dispatcher changed inputs: %v", err) + } + // A worker updates its own record's progress only. + worker := as("system:serviceaccount:" + siteNS + ":" + rec.Name) + var mine corev1.ConfigMap + if err := worker.Get(ctx, client.ObjectKeyFromObject(rec), &mine); err != nil { + t.Fatal(err) + } + setProgress(&mine, Progress{Stage: StageClaimed, ClaimedBy: "pod"}) + if err := worker.Update(ctx, &mine); err != nil { + t.Fatalf("the worker could not claim: %v", err) + } + mine.Data[InputsKey] = encode(Inputs{OperationUID: in.OperationUID, Endpoint: "https://192.0.2.99:443"}) + if err := worker.Update(ctx, &mine); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("the worker changed its inputs: %v", err) + } + for _, key := range []client.ObjectKey{{Namespace: siteNS, Name: "bmc.default.device-a"}, {Namespace: siteNS, Name: "fleet-device-power-worker-policy"}} { + var target client.Object = &corev1.ConfigMap{} + if key.Name[:4] == "bmc." { + target = &corev1.Secret{} + } + if err := worker.Get(ctx, key, target); !apierrors.IsForbidden(err) { + t.Fatalf("the worker read %s: %v", key.Name, err) + } + } + // Writes in other namespaces, which hold no policy parameter, are not + // touched by the policies: system leader election keeps working. + other := &coordinationv1.Lease{ObjectMeta: metav1.ObjectMeta{Name: "kube-controller-manager", Namespace: "elsewhere"}} + if err := admin.Create(ctx, other); err != nil { + t.Fatalf("a Lease outside the site namespace was denied: %v", err) + } + other.Spec.HolderIdentity = ptr.To("controller") + if err := admin.Update(ctx, other); err != nil { + t.Fatalf("a Lease update outside the site namespace was denied: %v", err) + } + // Deletes are limited to records and locks. + if err := dispatcher.Delete(ctx, lease); err != nil { + t.Fatal(err) + } + if err := dispatcher.Delete(ctx, ¶ms); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("the dispatcher deleted the policy parameter: %v", err) + } +} + +func waitDenied(t *testing.T, try func() error) { + t.Helper() + var err error + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { + if err = try(); apierrors.IsForbidden(err) || apierrors.IsInvalid(err) { + return + } + } + t.Fatalf("policy not enforced: %v", err) +} diff --git a/internal/devicepower/worker.go b/internal/devicepower/worker.go new file mode 100644 index 00000000..1b536993 --- /dev/null +++ b/internal/devicepower/worker.go @@ -0,0 +1,373 @@ +package devicepower + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/redfish" +) + +// BMC is the Redfish surface a worker uses. It is built only after the +// credential's pin is known, and every connection checks that pin. +type BMC interface { + FindPowerSystem(ctx context.Context, uuid string) (redfish.PowerSystem, error) + ObservePower(ctx context.Context, sys redfish.PowerSystem) (redfish.PowerState, error) + ResetPower(ctx context.Context, sys redfish.PowerSystem, kind string) error +} + +// NewBMC builds a pinned BMC client. +type NewBMC func(endpoint, user, password, pin string, timeout time.Duration) (BMC, error) + +// PinnedBMC is NewBMC over redfish.NewPinnedClient. +func PinnedBMC(endpoint, user, password, pin string, timeout time.Duration) (BMC, error) { + return redfish.NewPinnedClient(endpoint, user, password, pin, timeout) +} + +// Worker reasons, in addition to the acceptance reasons in the API. +const ( + ReasonStale = "Stale" + ReasonCredentialNotFound = "CredentialNotFound" + ReasonCredentialInvalid = "CredentialInvalid" + ReasonPinNotApproved = "PinNotApproved" + ReasonCredentialMismatch = "CredentialMismatch" + ReasonPinMismatch = "PinMismatch" + ReasonCredentialRejected = "CredentialRejected" + ReasonBMCUnreachable = "BMCUnreachable" + ReasonPowerStateChanging = "PowerStateChanging" + ReasonSystemOff = "SystemOff" + ReasonAlreadyInState = "AlreadyInState" + ReasonRequestedStateReached = "RequestedStateObserved" + ReasonResetObserved = "ResetObserved" + ReasonCommandRefused = "CommandRefused" + ReasonPowerChangedAnyway = "PowerChangedAfterRefusal" + ReasonNotObserved = "OutcomeNotObserved" + ReasonIdentityChanged = "IdentityChanged" + ReasonWorkerLost = "WorkerLost" + ReasonWorkerNotStarted = "WorkerNotStarted" + ReasonRecordLost = "RecordLost" +) + +// Worker runs one operation from its stage record. +type Worker struct { + // Records reads and updates exactly one stage record. + Records client.Client + Record types.NamespacedName + // PodUID is this worker's claim identity. + PodUID string + // CredentialDir holds the mounted credential Secret's files. + CredentialDir string + NewBMC NewBMC + Now func() time.Time + // Poll is the observation interval; Sleep waits for it. + Poll time.Duration + Sleep func(context.Context, time.Duration) + Log func(format string, args ...any) +} + +func (w *Worker) now() time.Time { + if w.Now != nil { + return w.Now().UTC() + } + return time.Now().UTC() +} + +func (w *Worker) sleep(ctx context.Context, d time.Duration) { + if w.Sleep != nil { + w.Sleep(ctx, d) + return + } + select { + case <-ctx.Done(): + case <-time.After(d): + } +} + +func (w *Worker) logf(format string, args ...any) { + if w.Log != nil { + w.Log(format, args...) + } +} + +// ErrNotClaimed means another worker, or the dispatcher's fence, holds the +// record. This worker contacted no BMC. +var ErrNotClaimed = errors.New("the operation was already claimed; no BMC was contacted") + +// run state of one worker. +type run struct { + w *Worker + cm *corev1.ConfigMap + in Inputs + p Progress + ctx context.Context +} + +// save writes progress with the record's optimistic lock. A conflict means +// the dispatcher fenced the record, or another writer changed it: the worker +// then stops without any further BMC request. +func (r *run) save(p Progress) error { + cm := r.cm.DeepCopy() + setProgress(cm, p) + if err := r.w.Records.Update(r.ctx, cm); err != nil { + return err + } + r.cm, r.p = cm, p + return nil +} + +// finish records the result. On a conflict it re-reads once and gives up +// if the record is no longer this worker's. +func (r *run) finish(result inventory.PowerResult, reason, message string) error { + p := r.p + p.Stage, p.Result, p.Reason, p.Message = StageFinished, result, reason, message + p.FinishedAt = ptrTime(r.w.now()) + r.w.logf("result %s reason %s", result, reason) + err := r.save(p) + for attempt := 0; err != nil && attempt < 5; attempt++ { + if !apierrors.IsConflict(err) { + r.w.sleep(r.ctx, time.Second) + } else { + var cm corev1.ConfigMap + if err := r.w.Records.Get(r.ctx, r.w.Record, &cm); err != nil { + continue + } + _, current, decodeErr := decodeRecord(&cm) + if decodeErr != nil || current.ClaimedBy != r.w.PodUID || current.Stage == StageAbandoned || current.Stage == StageFinished { + return fmt.Errorf("record taken over before the result was saved: %w", err) + } + r.cm = &cm + } + err = r.save(p) + } + return err +} + +func ptrTime(t time.Time) *metav1.Time { + v := metav1.NewTime(t.Truncate(time.Second)) + return &v +} + +// Run claims the operation, re-checks the server, sends at most one command +// and records the outcome. It returns ErrNotClaimed, without contacting a BMC, +// when the record is not Pending. +func (w *Worker) Run(ctx context.Context) error { + var cm corev1.ConfigMap + if err := w.Records.Get(ctx, w.Record, &cm); err != nil { + return fmt.Errorf("read stage record: %w", err) + } + in, p, err := decodeRecord(&cm) + if err != nil { + return err + } + if p.Stage != StagePending || w.PodUID == "" { + return ErrNotClaimed + } + r := &run{w: w, cm: &cm, in: in, p: p, ctx: ctx} + // The claim. Of two workers for one operation, at most one wins this + // update; the other stops here. + if err := r.save(Progress{Stage: StageClaimed, ClaimedBy: w.PodUID, ClaimedAt: ptrTime(w.now())}); err != nil { + if apierrors.IsConflict(err) { + return ErrNotClaimed + } + return fmt.Errorf("claim the operation: %w", err) + } + w.logf("claimed operation %s/%s action %s", in.Namespace, in.Operation, in.Action) + return r.execute() +} + +func (r *run) execute() error { + in, w := r.in, r.w + if w.now().Sub(in.CapacityCheckedAt.Time) > StaleAfter { + return r.finish(inventory.PowerFailed, ReasonStale, "the worker started more than two minutes after the dispatcher's last capacity check; nothing was sent") + } + user, password, pin, reason := readCredential(w.CredentialDir) + switch { + case reason != "": + return r.finish(inventory.PowerFailed, reason, "the worker has no usable credential for this Device; nothing was sent") + case pin == "": + return r.finish(inventory.PowerFailed, ReasonPinNotApproved, "the credential has no approved TLS key; nothing was sent") + case pin != in.PublicKeySHA256: + return r.finish(inventory.PowerFailed, ReasonCredentialMismatch, "the credential's approved TLS key is not the key discovery observed for this Device; nothing was sent") + } + bmc, err := w.NewBMC(in.Endpoint, user, password, pin, in.RequestTimeout.Duration) + if err != nil { + return r.finish(inventory.PowerFailed, ReasonCredentialInvalid, "the credential or endpoint is not usable; nothing was sent") + } + sys, err := bmc.FindPowerSystem(r.ctx, in.SystemUUID) + if err != nil { + reason, message := refusal(err) + return r.finish(inventory.PowerFailed, reason, message+"; nothing was sent") + } + action := string(in.Action) + if !slices.Contains(sys.ResetTypes, action) { + return r.finish(inventory.PowerFailed, inventory.ReasonResetTypeNotOffered, "the server no longer offers "+action+"; nothing was sent") + } + before, err := bmc.ObservePower(r.ctx, sys) + if err != nil { + reason, message := refusal(err) + return r.finish(inventory.PowerFailed, reason, message+"; nothing was sent") + } + r.p.Before = observation(before) + switch { + case before.State != "On" && before.State != "Off": + return r.finish(inventory.PowerFailed, ReasonPowerStateChanging, "the power state is "+safeState(before.State)+", not On or Off; nothing was sent") + case (in.Action == inventory.PowerOn && before.State == "On") || (in.Action == inventory.PowerForceOff && before.State == "Off"): + r.p.After = r.p.Before + return r.finish(inventory.PowerSucceeded, ReasonAlreadyInState, "the server was already "+before.State+"; nothing was sent") + case (in.Action == inventory.PowerForceRestart || in.Action == inventory.PowerCycle) && before.State == "Off": + return r.finish(inventory.PowerFailed, ReasonSystemOff, "the server is off; a restart or power cycle is refused; nothing was sent") + } + // Write ahead: from this record on, the outcome is Unknown unless + // proven. If it cannot be written, nothing is sent. + sending := r.p + sending.Stage, sending.RequestSentAt = StageSending, ptrTime(w.now()) + if err := r.save(sending); err != nil { + return fmt.Errorf("record the send before sending; nothing was sent: %w", err) + } + outcome := sendOutcome(bmc.ResetPower(r.ctx, sys, action)) + w.logf("command %s %s", action, outcome) + sent := r.p + sent.Stage, sent.SendOutcome = StageSent, outcome + if err := r.save(sent); err != nil { + // Keep observing: the result write below is what matters. + w.logf("record the send outcome: %v", err) + r.p = sent + } + return r.observe(bmc, sys, before, outcome) +} + +// observe decides the result from what the BMC shows after the command. +func (r *run) observe(bmc BMC, sys redfish.PowerSystem, before redfish.PowerState, outcome string) error { + in, w := r.in, r.w + if outcome == SendRefused { + w.sleep(r.ctx, w.Poll) + after, err := bmc.ObservePower(r.ctx, sys) + if err != nil { + return r.finish(inventory.PowerUnknown, ReasonNotObserved, "the BMC refused the command and the power state could not be read afterwards") + } + r.p.After = observation(after) + if after.State == before.State && after.LastResetTime.Equal(before.LastResetTime) { + return r.finish(inventory.PowerFailed, ReasonCommandRefused, "the BMC refused the command and the power did not change") + } + return r.finish(inventory.PowerUnknown, ReasonPowerChangedAnyway, "the BMC refused the command but the power changed") + } + lost := "" + if outcome == SendLost { + lost = " after the BMC's response was lost; the command was not resent" + } + deadline := r.p.RequestSentAt.Add(in.ObserveTimeout.Duration) + for { + after, err := bmc.ObservePower(r.ctx, sys) + if errors.Is(err, redfish.ErrIdentity) { + return r.finish(inventory.PowerUnknown, ReasonIdentityChanged, "the server behind the BMC changed identity after the command") + } + if err == nil { + r.p.After = observation(after) + switch in.Action { + case inventory.PowerOn, inventory.PowerForceOff: + if want := map[inventory.PowerAction]string{inventory.PowerOn: "On", inventory.PowerForceOff: "Off"}[in.Action]; after.State == want { + return r.finish(inventory.PowerSucceeded, ReasonRequestedStateReached, "the server reached "+want+lost) + } + default: + if after.State == "On" && !after.LastResetTime.IsZero() && after.LastResetTime.After(before.LastResetTime) { + return r.finish(inventory.PowerSucceeded, ReasonResetObserved, "the BMC reports a reset after the command and the server is on"+lost) + } + } + } + if !w.now().Before(deadline) || r.ctx.Err() != nil { + return r.finish(inventory.PowerUnknown, ReasonNotObserved, "the expected result was not observed within "+in.ObserveTimeout.Duration.String()+lost) + } + w.sleep(r.ctx, w.Poll) + } +} + +// sendOutcome classifies the one Reset's response. A definite client-side +// refusal is Refused; a 5xx, a timeout or a broken connection may have been +// applied and is Lost. +func sendOutcome(err error) string { + var status redfish.Status + switch { + case err == nil: + return SendAnswered + case errors.Is(err, redfish.ErrUnauthorized), errors.Is(err, redfish.ErrPrecondition), errors.Is(err, redfish.ErrUnsupported): + return SendRefused + case errors.As(err, &status) && status.Code >= 400 && status.Code < 500: + return SendRefused + default: + return SendLost + } +} + +// refusal maps an error before any command to a Failed reason. +func refusal(err error) (reason, message string) { + switch { + case errors.Is(err, redfish.ErrPinMismatch): + return ReasonPinMismatch, "the BMC presented a TLS key other than the approved pin, so the credential was not sent" + case errors.Is(err, redfish.ErrUnauthorized): + return ReasonCredentialRejected, "the BMC rejected the credential" + case errors.Is(err, redfish.ErrIdentity): + return inventory.ReasonSystemUUIDMismatch, "the BMC does not report exactly one server with the expected UUID" + case errors.Is(err, redfish.ErrUnsupported): + return inventory.ReasonResetTypeNotOffered, "the server offers no reset action on itself" + default: + return ReasonBMCUnreachable, "the BMC could not be read" + } +} + +func observation(p redfish.PowerState) *inventory.PowerObservation { + return &inventory.PowerObservation{State: safeState(p.State), ObservedAt: metav1.NewTime(p.ObservedAt.Truncate(time.Second))} +} + +// safeState keeps a reported power state short and printable. +func safeState(s string) string { + s = strings.Map(func(r rune) rune { + if r < 0x20 || r > 0x7e { + return -1 + } + return r + }, s) + if len(s) > 63 { + s = s[:63] + } + if s == "" { + return "Unreported" + } + return s +} + +// readCredential reads the mounted credential Secret. A missing Secret has +// no files, because the volume is optional. +func readCredential(dir string) (user, password, pin, reason string) { + read := func(key string) (string, bool) { + b, err := os.ReadFile(filepath.Join(dir, key)) + return strings.TrimSpace(string(b)), err == nil + } + user, okUser := read("username") + password, okPassword := read("password") + if !okUser && !okPassword { + return "", "", "", ReasonCredentialNotFound + } + if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { + return "", "", "", ReasonCredentialInvalid + } + if raw, ok := read("tlsPublicKeySHA256"); ok && raw != "" { + parsed, err := redfish.ParsePin(raw) + if err != nil { + return "", "", "", ReasonCredentialInvalid + } + pin = parsed + } + return user, password, pin, "" +} diff --git a/internal/devicepower/worker_test.go b/internal/devicepower/worker_test.go new file mode 100644 index 00000000..e425d53c --- /dev/null +++ b/internal/devicepower/worker_test.go @@ -0,0 +1,444 @@ +package devicepower + +import ( + "context" + "errors" + "os" + "path/filepath" + "sync" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/redfish" +) + +// fakeServer is one emulated System. Every Reset is counted, whatever its +// response. +type fakeServer struct { + mu sync.Mutex + state string + lastReset time.Time + resetTypes []string + uuid string + resets []string + findErr error + observeErr error + resetErr error // the response the worker sees + applyEffect bool // whether the reset takes effect despite resetErr + noResetTime bool + onReset func() + clock func() time.Time +} + +func newServer(state string) *fakeServer { + return &fakeServer{state: state, uuid: uuidA, resetTypes: []string{"On", "ForceOff", "ForceRestart"}, applyEffect: true, + lastReset: t0.Add(-time.Hour), clock: func() time.Time { return t0 }} +} + +func (f *fakeServer) FindPowerSystem(_ context.Context, uuid string) (redfish.PowerSystem, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.findErr != nil { + return redfish.PowerSystem{}, f.findErr + } + if uuid != f.uuid { + return redfish.PowerSystem{}, redfish.ErrIdentity + } + return redfish.PowerSystem{Path: "/redfish/v1/Systems/1", ID: "1", UUID: uuid, ResetTarget: "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", ResetTypes: f.resetTypes}, nil +} + +func (f *fakeServer) ObservePower(_ context.Context, _ redfish.PowerSystem) (redfish.PowerState, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.observeErr != nil { + return redfish.PowerState{}, f.observeErr + } + p := redfish.PowerState{State: f.state, ObservedAt: f.clock()} + if !f.noResetTime { + p.LastResetTime = f.lastReset + } + return p, nil +} + +func (f *fakeServer) ResetPower(_ context.Context, _ redfish.PowerSystem, kind string) error { + f.mu.Lock() + f.resets = append(f.resets, kind) + if f.applyEffect { + switch kind { + case "On": + f.state = "On" + case "ForceOff": + f.state = "Off" + case "ForceRestart", "PowerCycle": + f.state = "On" + } + if kind != "ForceOff" { + f.lastReset = f.clock().Add(time.Second) + } + } + hook := f.onReset + f.mu.Unlock() + if hook != nil { + hook() + } + return f.resetErr +} + +func (f *fakeServer) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.resets) +} + +// workerHarness is one stage record and the credential files a worker sees. +type workerHarness struct { + client client.Client + key types.NamespacedName + dir string + server *fakeServer + now time.Time + bmcMade int + mu sync.Mutex +} + +func newWorkerHarness(t *testing.T, action inventory.PowerAction, server *fakeServer, funcs *interceptor.Funcs) *workerHarness { + t.Helper() + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + op := operation("op", "device-a", action) + in := Inputs{OperationUID: string(op.UID), Project: project, Namespace: deviceNS, Operation: op.Name, Device: "device-a", Endpoint: endpoint, + SystemUUID: uuidA, PublicKeySHA256: keyA, Action: action, CapacityCheckedAt: metav1.NewTime(t0), + ObserveTimeout: metav1.Duration{Duration: 30 * time.Second}, RequestTimeout: metav1.Duration{Duration: 5 * time.Second}} + rec := record(siteNS, in) + builder := fake.NewClientBuilder().WithScheme(scheme).WithObjects(rec) + if funcs != nil { + builder = builder.WithInterceptorFuncs(*funcs) + } + h := &workerHarness{client: builder.Build(), key: types.NamespacedName{Namespace: siteNS, Name: rec.Name}, dir: t.TempDir(), server: server, now: t0.Add(10 * time.Second)} + server.clock = h.clock + h.writeCredential(t, "operator", "synthetic-secret", keyA) + return h +} + +func (h *workerHarness) clock() time.Time { + h.mu.Lock() + defer h.mu.Unlock() + return h.now +} + +func (h *workerHarness) writeCredential(t *testing.T, user, password, pin string) { + t.Helper() + for k, v := range map[string]string{"username": user, "password": password, "tlsPublicKeySHA256": pin} { + if err := os.WriteFile(filepath.Join(h.dir, k), []byte(v), 0o600); err != nil { + t.Fatal(err) + } + } +} + +func (h *workerHarness) worker(pod string) *Worker { + return &Worker{Records: h.client, Record: h.key, PodUID: pod, CredentialDir: h.dir, Poll: 2 * time.Second, + NewBMC: func(endpoint, user, password, pin string, _ time.Duration) (BMC, error) { + h.mu.Lock() + h.bmcMade++ + h.mu.Unlock() + if endpoint != "https://192.0.2.10:443" || user != "operator" || pin != keyA { + return nil, errors.New("unexpected BMC inputs") + } + return h.server, nil + }, + Now: h.clock, + Sleep: func(_ context.Context, d time.Duration) { + h.mu.Lock() + h.now = h.now.Add(d) + h.mu.Unlock() + }} +} + +func (h *workerHarness) progress(t *testing.T) Progress { + t.Helper() + var cm corev1.ConfigMap + if err := h.client.Get(context.Background(), h.key, &cm); err != nil { + t.Fatal(err) + } + _, p, err := decodeRecord(&cm) + if err != nil { + t.Fatal(err) + } + return p +} + +func TestWorkerOutcomes(t *testing.T) { + refused := redfish.Status{Code: 400} + lost := errors.New("redfish: transport failure or unreadable response") + for _, tc := range []struct { + name string + action inventory.PowerAction + server func() *fakeServer + result inventory.PowerResult + reason string + resets int + sentAt bool + before string + after string + message string + }{ + {name: "on", action: inventory.PowerOn, server: func() *fakeServer { return newServer("Off") }, + result: inventory.PowerSucceeded, reason: ReasonRequestedStateReached, resets: 1, sentAt: true, before: "Off", after: "On"}, + {name: "force off", action: inventory.PowerForceOff, server: func() *fakeServer { return newServer("On") }, + result: inventory.PowerSucceeded, reason: ReasonRequestedStateReached, resets: 1, sentAt: true, before: "On", after: "Off"}, + {name: "restart", action: inventory.PowerForceRestart, server: func() *fakeServer { return newServer("On") }, + result: inventory.PowerSucceeded, reason: ReasonResetObserved, resets: 1, sentAt: true, before: "On", after: "On"}, + {name: "already on", action: inventory.PowerOn, server: func() *fakeServer { return newServer("On") }, + result: inventory.PowerSucceeded, reason: ReasonAlreadyInState, before: "On", after: "On"}, + {name: "restart while off", action: inventory.PowerForceRestart, server: func() *fakeServer { return newServer("Off") }, + result: inventory.PowerFailed, reason: ReasonSystemOff, before: "Off"}, + {name: "power changing", action: inventory.PowerOn, server: func() *fakeServer { return newServer("PoweringOn") }, + result: inventory.PowerFailed, reason: ReasonPowerStateChanging, before: "PoweringOn"}, + {name: "replaced server", action: inventory.PowerOn, server: func() *fakeServer { s := newServer("Off"); s.uuid = uuidB; return s }, + result: inventory.PowerFailed, reason: inventory.ReasonSystemUUIDMismatch}, + {name: "action no longer offered", action: inventory.PowerForceRestart, server: func() *fakeServer { s := newServer("On"); s.resetTypes = []string{"On"}; return s }, + result: inventory.PowerFailed, reason: inventory.ReasonResetTypeNotOffered}, + {name: "wrong TLS key", action: inventory.PowerOn, server: func() *fakeServer { s := newServer("Off"); s.findErr = redfish.ErrPinMismatch; return s }, + result: inventory.PowerFailed, reason: ReasonPinMismatch}, + {name: "credential rejected", action: inventory.PowerOn, server: func() *fakeServer { s := newServer("Off"); s.findErr = redfish.ErrUnauthorized; return s }, + result: inventory.PowerFailed, reason: ReasonCredentialRejected}, + {name: "unreachable", action: inventory.PowerOn, server: func() *fakeServer { s := newServer("Off"); s.findErr = lost; return s }, + result: inventory.PowerFailed, reason: ReasonBMCUnreachable}, + {name: "refused", action: inventory.PowerOn, server: func() *fakeServer { + s := newServer("Off") + s.resetErr, s.applyEffect = refused, false + return s + }, result: inventory.PowerFailed, reason: ReasonCommandRefused, resets: 1, sentAt: true, before: "Off", after: "Off"}, + {name: "refused but changed", action: inventory.PowerOn, server: func() *fakeServer { + s := newServer("Off") + s.resetErr = refused + return s + }, result: inventory.PowerUnknown, reason: ReasonPowerChangedAnyway, resets: 1, sentAt: true, before: "Off", after: "On"}, + {name: "lost response then on", action: inventory.PowerOn, server: func() *fakeServer { + s := newServer("Off") + s.resetErr = lost + return s + }, result: inventory.PowerSucceeded, reason: ReasonRequestedStateReached, resets: 1, sentAt: true, before: "Off", after: "On", + message: "the server reached On after the BMC's response was lost; the command was not resent"}, + {name: "lost response no effect", action: inventory.PowerOn, server: func() *fakeServer { + s := newServer("Off") + s.resetErr, s.applyEffect = lost, false + return s + }, result: inventory.PowerUnknown, reason: ReasonNotObserved, resets: 1, sentAt: true, before: "Off", after: "Off"}, + {name: "lost response after force off", action: inventory.PowerForceOff, server: func() *fakeServer { + s := newServer("On") + s.resetErr, s.applyEffect = lost, false + return s + }, result: inventory.PowerUnknown, reason: ReasonNotObserved, resets: 1, sentAt: true, before: "On", after: "On"}, + {name: "restart without reset time", action: inventory.PowerForceRestart, server: func() *fakeServer { + s := newServer("On") + s.noResetTime = true + return s + }, result: inventory.PowerUnknown, reason: ReasonNotObserved, resets: 1, sentAt: true, before: "On", after: "On"}, + {name: "lost restart response", action: inventory.PowerForceRestart, server: func() *fakeServer { + s := newServer("On") + s.resetErr, s.applyEffect = lost, false + return s + }, result: inventory.PowerUnknown, reason: ReasonNotObserved, resets: 1, sentAt: true, before: "On", after: "On"}, + {name: "server swapped after the command", action: inventory.PowerOn, server: func() *fakeServer { + s := newServer("Off") + s.applyEffect = false + s.onReset = func() { s.mu.Lock(); s.observeErr = redfish.ErrIdentity; s.mu.Unlock() } + return s + }, result: inventory.PowerUnknown, reason: ReasonIdentityChanged, resets: 1, sentAt: true, before: "Off"}, + } { + t.Run(tc.name, func(t *testing.T) { + server := tc.server() + h := newWorkerHarness(t, tc.action, server, nil) + if err := h.worker("pod-1").Run(context.Background()); err != nil { + t.Fatal(err) + } + p := h.progress(t) + if p.Stage != StageFinished || p.Result != tc.result || p.Reason != tc.reason || p.ClaimedBy != "pod-1" { + t.Fatalf("progress = %+v", p) + } + if server.count() != tc.resets { + t.Fatalf("%d resets reached the BMC, want %d", server.count(), tc.resets) + } + if (p.RequestSentAt != nil) != tc.sentAt { + t.Fatalf("requestSentAt = %v", p.RequestSentAt) + } + if tc.before != "" && (p.Before == nil || p.Before.State != tc.before) { + t.Fatalf("before = %+v", p.Before) + } + if tc.after != "" && (p.After == nil || p.After.State != tc.after) { + t.Fatalf("after = %+v", p.After) + } + if tc.message != "" && p.Message != tc.message { + t.Fatalf("message = %q", p.Message) + } + }) + } +} + +func TestWorkerRefusesBeforeContactingTheBMC(t *testing.T) { + for _, tc := range []struct { + name string + setup func(*testing.T, *workerHarness) + reason string + }{ + {"stale start", func(_ *testing.T, h *workerHarness) { h.now = t0.Add(StaleAfter + time.Second) }, ReasonStale}, + {"no credential", func(t *testing.T, h *workerHarness) { + for _, f := range []string{"username", "password", "tlsPublicKeySHA256"} { + os.Remove(filepath.Join(h.dir, f)) + } + }, ReasonCredentialNotFound}, + {"pin not approved", func(t *testing.T, h *workerHarness) { h.writeCredential(t, "operator", "synthetic-secret", "") }, ReasonPinNotApproved}, + {"credential for another key", func(t *testing.T, h *workerHarness) { + h.writeCredential(t, "operator", "synthetic-secret", "bb"+keyA[2:]) + }, ReasonCredentialMismatch}, + {"malformed credential", func(t *testing.T, h *workerHarness) { h.writeCredential(t, "oper:ator", "synthetic-secret", keyA) }, ReasonCredentialInvalid}, + } { + t.Run(tc.name, func(t *testing.T) { + h := newWorkerHarness(t, inventory.PowerOn, newServer("Off"), nil) + tc.setup(t, h) + if err := h.worker("pod-1").Run(context.Background()); err != nil { + t.Fatal(err) + } + if p := h.progress(t); p.Result != inventory.PowerFailed || p.Reason != tc.reason || p.RequestSentAt != nil { + t.Fatalf("progress = %+v", p) + } + if h.bmcMade != 0 || h.server.count() != 0 { + t.Fatalf("the BMC was contacted: clients %d, resets %d", h.bmcMade, h.server.count()) + } + }) + } +} + +// A second worker for one operation, started by mistake or by a recreated +// Job, stops before it contacts the BMC and leaves the first result alone. +func TestSecondWorkerStopsAtTheClaim(t *testing.T) { + h := newWorkerHarness(t, inventory.PowerForceRestart, newServer("On"), nil) + if err := h.worker("pod-1").Run(context.Background()); err != nil { + t.Fatal(err) + } + first := h.progress(t) + made := h.bmcMade + if err := h.worker("pod-2").Run(context.Background()); !errors.Is(err, ErrNotClaimed) { + t.Fatalf("second worker: %v", err) + } + if h.bmcMade != made || h.server.count() != 1 { + t.Fatalf("second worker contacted the BMC: clients %d, resets %d", h.bmcMade, h.server.count()) + } + if got := h.progress(t); got.ClaimedBy != "pod-1" || got.Result != first.Result || got.FinishedAt.Time != first.FinishedAt.Time { + t.Fatalf("first result changed: %+v", got) + } +} + +// Workers started at once race only on the claim: exactly one sends. +func TestConcurrentWorkersSendOnce(t *testing.T) { + h := newWorkerHarness(t, inventory.PowerForceRestart, newServer("On"), nil) + var wg sync.WaitGroup + errs := make([]error, 8) + for i := range errs { + wg.Add(1) + go func() { + defer wg.Done() + errs[i] = h.worker("pod-" + string(rune('a'+i))).Run(context.Background()) + }() + } + wg.Wait() + won := 0 + for _, err := range errs { + switch { + case err == nil: + won++ + case !errors.Is(err, ErrNotClaimed): + t.Fatal(err) + } + } + if won != 1 || h.server.count() != 1 || h.progress(t).Result != inventory.PowerSucceeded { + t.Fatalf("%d workers ran, %d resets, result %s", won, h.server.count(), h.progress(t).Result) + } +} + +// When the dispatcher fences a record (its worker looked lost), the worker's +// write-ahead conflicts and it sends nothing. +func TestFencedWorkerSendsNothing(t *testing.T) { + server := newServer("Off") + h := newWorkerHarness(t, inventory.PowerOn, server, nil) + fenced := false + server.findErr = nil + w := h.worker("pod-1") + inner := w.NewBMC + w.NewBMC = func(endpoint, user, password, pin string, timeout time.Duration) (BMC, error) { + // The dispatcher fences between the claim and the send. + var cm corev1.ConfigMap + if err := h.client.Get(context.Background(), h.key, &cm); err != nil { + return nil, err + } + _, p, _ := decodeRecord(&cm) + p.Stage, p.Result, p.Reason = StageAbandoned, inventory.PowerFailed, ReasonWorkerLost + setProgress(&cm, p) + if err := h.client.Update(context.Background(), &cm); err != nil { + return nil, err + } + fenced = true + return inner(endpoint, user, password, pin, timeout) + } + if err := w.Run(context.Background()); err == nil { + t.Fatal("a fenced worker reported success") + } + if !fenced || server.count() != 0 { + t.Fatalf("fenced %v, resets %d", fenced, server.count()) + } + if p := h.progress(t); p.Stage != StageAbandoned || p.Reason != ReasonWorkerLost { + t.Fatalf("fenced record changed: %+v", p) + } +} + +// If the write-ahead record cannot be saved, nothing is sent. +func TestUnrecordableSendIsNotSent(t *testing.T) { + server := newServer("Off") + updates := 0 + funcs := &interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + updates++ + if updates == 2 { // the claim succeeds; the write-ahead fails + return errors.New("site API unavailable") + } + return c.Update(ctx, obj, opts...) + }} + h := newWorkerHarness(t, inventory.PowerOn, server, funcs) + if err := h.worker("pod-1").Run(context.Background()); err == nil { + t.Fatal("worker succeeded without recording the send") + } + if server.count() != 0 { + t.Fatalf("%d resets were sent without a write-ahead record", server.count()) + } + if p := h.progress(t); p.Stage != StageClaimed { + t.Fatalf("stage = %s", p.Stage) + } +} + +func TestSendOutcomeClassification(t *testing.T) { + for err, want := range map[error]string{ + nil: SendAnswered, + redfish.ErrUnauthorized: SendRefused, + redfish.ErrPrecondition: SendRefused, + redfish.Status{Code: 400}: SendRefused, + redfish.Status{Code: 409}: SendRefused, + redfish.Status{Code: 500}: SendLost, + redfish.Status{Code: 503}: SendLost, + errors.New("timeout"): SendLost, + context.DeadlineExceeded: SendLost, + } { + if got := sendOutcome(err); got != want { + t.Errorf("sendOutcome(%v) = %s, want %s", err, got, want) + } + } +} From 1b402b313a6651cdb7448fb5ed2825383a1aabb3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 16:39:41 -0600 Subject: [PATCH 3/3] test: Run power operations against lab BMCs The design needs proof against emulated BMCs and the real control plane, not unit tests alone. task device-power:acceptance builds a kind cluster with a Milo project API, BMC discovery, the dispatcher and two lab BMCs serving TLS, and drives every operation as a staff identity through Milo. Each scenario records the result staff see and the number of resets in the BMC's own audit log: success, refusals, a lost response with and without effect, a cloned worker, a deleted worker, two dispatchers, and a restart that cannot be proven. The lab adapter gains what these scenarios need: TLS from a mounted certificate, LastResetTime, and drop-request, swap-identity and hide-reset-time faults. The docs record what is implemented and verified, the choices made where the proposal left a question open, and where the prototype differs from it. Co-Authored-By: Claude Opus 5.5 --- Taskfile.yaml | 5 + config/README.md | 10 + docs/development/README.md | 7 + docs/operations/README.md | 1 + docs/operations/device-power.md | 419 +++++++++++++ docs/operations/redfish-lab.md | 3 + hack/device-power/e2e.py | 819 ++++++++++++++++++++++++++ hack/device-power/run.sh | 8 + hack/redfish-lab/fleet_lab_adapter.py | 48 +- hack/redfish-lab/test_adapter.py | 32 +- 10 files changed, 1346 insertions(+), 6 deletions(-) create mode 100644 docs/operations/device-power.md create mode 100755 hack/device-power/e2e.py create mode 100755 hack/device-power/run.sh diff --git a/Taskfile.yaml b/Taskfile.yaml index 6b55c0d2..ca7bf92f 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -48,6 +48,11 @@ tasks: cmds: - bash hack/local-vm/run.sh + device-power:acceptance: + desc: "DevicePowerOperation end to end: Milo project API, BMC discovery, the dispatcher and worker Jobs against two TLS lab BMCs in a disposable kind cluster (exit 0 pass, 1 fail)." + cmds: + - ./hack/device-power/run.sh {{.CLI_ARGS}} + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/config/README.md b/config/README.md index f28af822..64a887b6 100644 --- a/config/README.md +++ b/config/README.md @@ -68,6 +68,16 @@ its namespace, image digest, Milo kubeconfig Secret and configuration. `examples/` holds a synthetic credential Secret and a sidecar container snippet. See [BMC discovery](../docs/operations/bmc-discovery.md). +`config/components/device-power` registers `DevicePowerOperation` in Milo: its +CRD, ProtectedResource, power operator and dispatcher roles, and an admission +policy that binds the requester to the creating user. Milo v0.32.5 does not +enforce that policy in a project. No root includes the component. +`config/base/device-power` runs the power dispatcher for one Milo project in +the site namespace that holds BMC credential Secrets, with the site admission +policies that pin every worker Job to one image, one credential and no +privilege. It is in no root either. See +[Device power operations](../docs/operations/device-power.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/docs/development/README.md b/docs/development/README.md index 33eccf8b..2984137f 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -47,6 +47,13 @@ cleanup. [Redfish-mode acceptance](../operations/redfish-lab.md) Interface Emulator and a lab-only libvirt adapter. It is not qualified against a physical BMC or server, and the production manager does not use it. +`internal/devicepower` is a prototype of staff power operations on unallocated +Devices: the `DevicePowerOperation` API, a site dispatcher, and one worker Job +per operation that sends at most one Redfish reset. It runs end to end against +a Milo project API and TLS lab BMCs with `task device-power:acceptance`. It is +in no deployment root and has not run on real hardware; see +[Device power operations](../operations/device-power.md). + Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/operations/README.md b/docs/operations/README.md index 0a6f9ac6..a9412fd3 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -19,6 +19,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | +| Power an unallocated Device on, off or restart it | [Device power operations](device-power.md) (`task device-power:acceptance`) | `DevicePowerOperation` acceptance checks, a site dispatcher and one worker Job per operation sending at most one Redfish reset; end to end against a Milo project API and two TLS lab BMCs with simulated power; not run on real hardware | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/device-power.md b/docs/operations/device-power.md new file mode 100644 index 00000000..27ca8fb6 --- /dev/null +++ b/docs/operations/device-power.md @@ -0,0 +1,419 @@ +# Device power operations + +[Operations guide](README.md) · [BMC discovery](bmc-discovery.md) · +[Redfish lab](redfish-lab.md) + +Staff can power an unallocated Device on or off, or restart it, by creating a +`DevicePowerOperation` in the provider project. A dispatcher in the site +checks the request and starts one short-lived worker. The worker sends at most +one Redfish `ComputerSystem.Reset` to the exact server named. The operation +then ends as `Succeeded`, `Failed` or `Unknown`, and nothing retries it. + +This is a prototype of the +[device power proposal](https://github.com/datum-cloud/fleet/pull/173), which +is not yet merged into this branch. It has run end to +end against emulated BMCs only. No real server or vendor BMC has received a +command. + +## Implementation status + +| Proposal part | State | +| --- | --- | +| Phase 1: discovery records offered actions | **Implemented and verified** against the lab BMCs. `status.discovery.inventory.systems[].resetTypes`, read with `GET`s only. | +| Phase 2: API and roles | **Implemented.** Opt-in component `config/components/device-power`; no root includes it. The CRD rules and role split are verified in a Milo v0.32.5 project API. The requester check is verified only on a standard API server: [Milo does not enforce it](#the-requester-check-is-not-enforced-in-milo). | +| Phase 3: dispatcher and worker | **Implemented and verified** against the lab BMCs ([run record](#end-to-end-run-record)). | +| Phase 4: staff UI | **Not built.** Staff use the API. | +| Phase 4: one real server | **Not done.** Restart and power cycle stay unqualified on real hardware. | +| Phase 5: allocator gate | **Not built.** The window between the dispatcher's last capacity check and the command is still open; see [known gaps](#known-gaps). | +| Production readiness: monitoring | **Not built.** There are no metrics or alerts yet. | + +## Who writes what + +| Surface | Writer | Content | +| --- | --- | --- | +| `DevicePowerOperation.spec` | Staff with the power operator role | The request. Fixed at creation. | +| `DevicePowerOperation.status` | The site dispatcher only | Conditions, the result, the time the one command was sent, power before and after. | +| Stage record, ConfigMap `pwr-` in the site | Inputs: the dispatcher, once. Progress: the operation's worker. | The exact inputs and how far the worker got. | +| Device lock, Lease `pwr-lock-` in the site | The dispatcher | Which operation holds the Device. | +| `Device.status` | BMC discovery only, unchanged | What the BMC reports, now including offered reset types. | + +The worker holds no Milo credential. The dispatcher holds no BMC credential. + +## How one operation runs + +1. Staff create the operation. The CRD fixes the spec. An admission policy + requires `spec.requester` to be the creating user, but Milo does not yet + enforce it; see [known gaps](#the-requester-check-is-not-enforced-in-milo). +2. The dispatcher runs the [acceptance checks](#acceptance-checks). A refusal + ends the operation as `Failed`, and nothing reaches the site or the BMC. +3. The dispatcher takes the Device's site Lease and marks the operation + `Accepted`. A second operation on the Device is refused while the first + holds the Lease. +4. The dispatcher re-reads capacity from Milo, bypassing its cache. It writes + the stage record with the exact inputs and the time of that check, then + creates the worker's ServiceAccount, Role, RoleBinding and Job, and marks + the operation `Executing`. +5. The worker claims the record: it moves the stage from `Pending` to + `Claimed` with an optimistic update. A second worker for the same + operation loses that update and exits without contacting the BMC. +6. The worker refuses with `Stale` if it started more than two minutes after + the capacity check. It then checks its mounted credential, connects with + the approved TLS key, finds the one System with the expected UUID, checks + the action is offered, and reads the power state. +7. The worker records stage `Sending`, then sends one `ComputerSystem.Reset`. + If it cannot record `Sending`, it sends nothing. +8. The worker observes the System and records the result. The dispatcher + copies it to the operation's status and releases the Lease. + +If the worker Job ends without a result, the dispatcher fences the record: +it moves the stage to `Abandoned` with the same optimistic lock. A lost worker +process can then no longer record `Sending`, so it cannot send. A record that +reached `Sending` or `Sent` ends as `Unknown`; an earlier stage ends as +`Failed`. + +### Acceptance checks + +The dispatcher refuses with `result: Failed` and sends nothing when any of +these holds, checked in this order: + +| Reason | When | +| --- | --- | +| `Expired` | The operation is more than five minutes old and was never accepted. | +| `DeviceNotFound` | The Device does not exist in the namespace. | +| `DeviceRetired` | `spec.lifecycle` is `Retired`. | +| `CapacityBacked` | A MachineCapacity in the namespace names the Device. Checked again just before the worker starts. | +| `OperationInProgress` | Another accepted operation on the Device has no result, or holds the Device's Lease. | +| `SystemUUIDNotRecorded` | The Device has no `spec.identity.systemUUID`. | +| `SystemUUIDMismatch` | `spec.expectedSystemUUID` differs from the Device's system UUID. | +| `DiscoveryNotCurrent` | Discovery has no TLS and inventory observation of the current `spec.bmc.endpoint`, the inventory is older than `discoveryMaxAge`, `Discovered` or `IdentityMatched` is not `True` for the current generation, or `PublicKeyUnique` is not yet known. | +| `SystemNotObserved` | Discovery did not see exactly one System with the expected UUID. | +| `SharedPublicKey` | `PublicKeyUnique` is `False`. | +| `ResetTypeNotOffered` | The observed System does not list the action in `resetTypes`. | + +### Worker reasons + +| Result | Reason | Meaning | +| --- | --- | --- | +| `Succeeded` | `RequestedStateObserved` | `On` or `Off` was observed within `observeTimeout`. The message says when the BMC's response was lost first. | +| `Succeeded` | `ResetObserved` | The System is `On` and its `LastResetTime` is later than before the command. | +| `Succeeded` | `AlreadyInState` | The System was already in the requested state. Nothing was sent. | +| `Failed` | `Stale`, `CredentialNotFound`, `CredentialInvalid`, `PinNotApproved`, `CredentialMismatch`, `PinMismatch`, `CredentialRejected`, `BMCUnreachable`, `SystemUUIDMismatch`, `ResetTypeNotOffered`, `PowerStateChanging`, `SystemOff` | Refused before any command. Nothing was sent. | +| `Failed` | `CommandRefused` | The BMC answered the command with a 4xx and the power did not change. | +| `Unknown` | `PowerChangedAfterRefusal` | The BMC refused the command, but the power changed. | +| `Unknown` | `OutcomeNotObserved` | A command may have been sent, and the expected state or reset was not observed in time. | +| `Unknown` | `IdentityChanged` | The BMC reported another server after the command. | +| `Failed` | `WorkerNotStarted`, `WorkerLost` | The worker ended before it recorded `Sending`. Nothing was sent. | +| `Unknown` | `WorkerLost` | The worker ended after it recorded `Sending`. | +| `Unknown` | `RecordLost` | The stage record of a started operation is missing or unreadable. | + +A 5xx, a timeout or a broken connection on the command counts as a lost +response, because the BMC may have applied it. A command is never resent. + +## Authorization + +### Milo + +`config/components/device-power` adds two IAM roles: + +| Role | Grants | +| --- | --- | +| `fleet.datumapis.com-device-power-operator` | Create, get, list and watch operations; get, list and watch Devices. No update, patch, delete or status write. | +| `fleet.datumapis.com-device-power-dispatcher` | Get, list and watch operations, Devices and MachineCapacities; write operation status. No create, update or delete. | + +The `fleet-device-power-requester` ValidatingAdmissionPolicy denies a create +whose `spec.requester` differs from the request's username. A standard API +server enforces it. Milo v0.32.5 does not; see +[known gaps](#the-requester-check-is-not-enforced-in-milo). + +### Site + +`config/base/device-power` runs the dispatcher with this Role in its +namespace: + +| Resource | Verbs | +| --- | --- | +| ConfigMaps, Leases | get, list, watch, create, update, delete | +| Jobs | get, list, watch, create | +| ServiceAccounts, Roles, RoleBindings | get, create | + +It has no Secret or Pod permission. RBAC still lets it create a Job that +mounts any Secret in the namespace, so two ValidatingAdmissionPolicies pin its +writes. Their bindings select namespaces labelled +`fleet.datumapis.com/device-power-site=true`. Without the label the +dispatcher's writes are unchecked. The selector is required: the +dispatcher policy's parameter is looked up before its match conditions, so an +unscoped binding denies every write in a namespace without the parameter, +including system leader election. + +- `fleet-device-power-dispatcher-writes` matches only the dispatcher's + ServiceAccount. Every object is named `pwr-` and labelled + `app.kubernetes.io/part-of=fleet-device-power`. A worker Job runs one Pod with + `backoffLimit: 0`, as its own ServiceAccount, without host namespaces, as + non-root and unprivileged, with the image in the + `fleet-device-power-worker-policy` ConfigMap and the command + `/fleet-device-power worker`. It mounts exactly one volume: the Secret + `bmc..` named by its own annotations. A worker + Role grants only get and update on its own stage record. A RoleBinding binds + only its own Role to its own ServiceAccount. A stage record's inputs cannot + change. Deletes are limited to stage records and Leases. +- `fleet-device-power-worker-writes` matches the per-operation worker + ServiceAccounts. A worker may only update its own stage record, and only its + progress. + +The worker reads its credential from the mounted volume, not the API, so its +token cannot read any Secret. Deleting a stage record removes the worker +objects it owns. + +## Credentials + +A worker mounts one Secret, named after the Device: +`bmc..`, in the namespace where discovery and +the dispatcher run. It is the same Secret discovery reads, with the same +labels, annotations and keys; see [credential Secrets](bmc-discovery.md#credential-secrets). +Discovery still selects Secrets by annotation, so this name is required for +power operations only. A name longer than 253 characters cannot be used. + +The worker requires the Secret's approved `tlsPublicKeySHA256` to equal the +key discovery last observed for the Device. A missing Secret ends the +operation as `Failed` with `CredentialNotFound`. + +## Deployment + +Apply `config/components/device-power` to the Milo control plane that serves +the provider project, next to `config/milo`. Without a dispatcher, operations +are never accepted and have no effect. + +Apply `config/base/device-power` in the site namespace that holds discovery's +credential Secrets. The deploying repository supplies: + +| Input | Where | +| --- | --- | +| Namespace | Kustomize `namespace:`. Label it `fleet.datumapis.com/device-power-site=true`; the site policies apply only in labelled namespaces. | +| Image digest | Kustomize `images:` for `ghcr.io/datum-cloud/fleet`, `workerImage` in `config.yaml`, and `workerImage` in the `fleet-device-power-worker-policy` ConfigMap. All three must match. | +| Milo kubeconfig | Secret `fleet-device-power-milo-kubeconfig`, key `kubeconfig`, bound to the dispatcher role. | +| Configuration | A patch of `config.yaml`. | + +`config.yaml`, read with strict decoding: + +| Field | Default | Meaning | +| --- | --- | --- | +| `project` | required | The Milo project the kubeconfig addresses. | +| `miloKubeconfig` | required | Path of the Milo project kubeconfig. | +| `deviceNamespaces` | required | Project namespaces whose operations are served. | +| `workerImage` | required | The image worker Jobs run. | +| `workerNamespace` | `$POD_NAMESPACE` | Site namespace of records, workers and credential Secrets. | +| `localKubeconfig` | in-cluster | Kubeconfig of the site cluster. | +| `discoveryMaxAge` | `2h` | Oldest discovery inventory read that acceptance allows. Keep it above discovery's `interval`. | +| `observeTimeout` | `3m` | How long a worker watches for the result after its command (10s to 10m). | +| `requestTimeout` | `20s` | Each HTTP request a worker makes to the BMC. | +| `retention` | `24h` | How long a finished operation's site objects are kept. | +| `healthProbeAddress` | off | Serves `/healthz` and `/readyz`; the base sets `:8081`. | + +The dispatcher runs as one replica without leader election. A second replica +is safe: acceptance, the Lease, the stage record and the Job are each written +once or with an optimistic lock. The run record shows two dispatchers starting +one worker. + +## End-to-end acceptance + +```sh +task device-power:acceptance +# equivalent: +hack/device-power/run.sh +``` + +The harness needs Go, Python 3, Docker, kind, kubectl, kustomize, OpenSSL and +curl, the running task-owned Colima profile `fleet-acceptance-tcg`, and +network access to GitHub, PyPI, Docker Hub, `ghcr.io` and `registry.k8s.io`. +It refuses to start while another `fleet-mp-`, `fleet-local-` or `fleet-dp-` +container runs. `--keep` leaves the cluster running after a pass, and a failed +run always keeps it. `--skip-unit-tests` skips the test gate, for diagnosis +only. + +Exit 0 means every phase passed. The harness then deletes its kind cluster, +image tags, tokens, passwords, keys and kubeconfigs. Exit 1 means a phase +failed; the cluster and the private state are kept. Only the state +directory's `evidence/` subdirectory is shareable. + +### What runs + +One kind cluster (node v1.35.0) holds: + +- A Milo v0.32.5 project API with its own etcd. The harness installs the + inventory, metal and `DevicePowerOperation` CRDs and the requester policy + in project `provider`. Static tokens identify staff, a viewer, the + dispatcher and discovery. Kubernetes RBAC with the same grants stands in + for the Milo IAM roles. +- Site namespace `fleet-power-site`, which enforces the `restricted` Pod + Security profile. It runs discovery from `config/base/bmc-discovery`, the + dispatcher and its admission policies from `config/base/device-power`, and + holds one credential Secret per Device. +- Two lab BMCs: the unmodified DMTF Redfish Interface Emulator 1.2.2 with the + [lab adapter](redfish-lab.md), each serving one System over TLS with its own + key. Power is the adapter's simulated libvirt (`fake_virsh.py`). No guest + boots. + +Device A backs no capacity. Device B backs a MachineCapacity. + +### Phases + +| Phase | What it proves | +| --- | --- | +| `preflight` | Tools present; no other Fleet runtime in the profile. | +| `unit-tests` | `go test -race` of the power, Redfish, discovery and inventory API packages, including the envtest API-server tests. | +| `images` | Binaries built from the checkout; the lab BMC image built from the verified DMTF archive; the adapter self-test passes. | +| `cluster`, `milo`, `site` | The topology above, applied from the shipped manifests with only namespace, image and config overlays. | +| `inventory` | Discovery reads both BMCs over pinned TLS, matches identity, and records `resetTypes` `[On, ForceOff, ForceRestart]`, with `GET`s only. | +| `admission` | In Milo: a user without the operator role is forbidden; a spec change is rejected; staff cannot write status or delete. A forged requester is **admitted** and recorded as the known gap. The probe targets the capacity-backed Device, so the dispatcher refuses it. | +| `power` | The scenarios in the run record, each with the result staff see and the number of `ComputerSystem.Reset` requests in the BMC's own audit log. | +| `security` | `kubectl auth can-i` as each site identity: the dispatcher cannot read Secrets or create Pods; a worker cannot get or list Secrets and can update its own record. | +| `evidence-scan` | No token, password or private key appears in `evidence/`. | + +The harness sets `observeTimeout: 45s` and `requestTimeout: 10s` to keep the +run short. Lab faults withhold a response for 25 seconds, past the request +timeout. + +### End-to-end run record + +`hack/device-power/run.sh` (the command behind `task device-power:acceptance`) +exited 0 on 2026-11-24, on a fresh cluster in the `fleet-acceptance-tcg` +profile. All 11 phases passed in 541 seconds; the `power` phase took 368. The +Fleet image held `fleet-device-power` with SHA-256 `bc042c1f…` and +`fleet-bmc-discovery` with `0a1eea91…`, built from this branch. + +Discovery read both lab BMCs over pinned TLS, matched their identity, and +recorded `[On, ForceOff, ForceRestart]`, with `GET`s only. + +| Scenario | Result | Reason | Resets at the BMC | Worker Jobs | +| --- | --- | --- | --- | --- | +| `On`, with the dispatcher Pod deleted right after the request | `Succeeded` | `RequestedStateObserved` | 1 | 1 | +| `ForceRestart` | `Succeeded` | `ResetObserved` | 1 | 1 | +| `ForceOff` | `Succeeded` | `RequestedStateObserved` | 1 | 1 | +| `PowerCycle`, which the BMC does not offer | `Failed` | `ResetTypeNotOffered` | 0 | 0 | +| `On` with another Device's system UUID | `Failed` | `SystemUUIDMismatch` | 0 | 0 | +| `ForceRestart` of the capacity-backed Device | `Failed` | `CapacityBacked` | 0 | 0 | +| `On` after the BMC starts reporting another server (`swap-identity`) | `Failed` | `SystemUUIDMismatch` | 0 | 1 | +| `On`, response withheld 25s after the effect | `Succeeded` | `RequestedStateObserved`, "after the BMC's response was lost; the command was not resent" | 1 | 1 | +| `ForceOff`, request withheld 25s and never applied; a cloned worker Job started mid-observation | `Unknown` | `OutcomeNotObserved` | 1 | 1, and the clone exited without claiming | +| `On` while the next operation on the Device runs | `Failed` | `OperationInProgress` | 0 | 0 | +| `ForceOff`, request withheld; the worker Pod force-deleted after it recorded `Sending` | `Unknown` | `WorkerLost` | 1 | 1, never replaced | +| `ForceRestart` with a second dispatcher Deployment running | `Succeeded` | `ResetObserved` | 1 | 1 | +| `ForceRestart` on a BMC that hides `LastResetTime` | `Unknown` | `OutcomeNotObserved` | 1 | 1 | + +The capacity-backed Device's BMC received no reset in the whole run. In +`admission`, the viewer was forbidden, the spec change was rejected and staff +could neither write status nor delete. The forged requester was admitted, +which is the [known gap](#the-requester-check-is-not-enforced-in-milo). In +`security`, the dispatcher could not get Secrets, create Pods or delete Jobs, +and in Milo could neither create operations nor patch Devices. No worker could +get or list Secrets through the API, and each could update its own record. +Nine evidence files held no token, password or private key. Teardown removed +the cluster, both image tags and every private credential file. + +Earlier attempts on the same day found these, each fixed before the pass: + +- The site policy binding denied every Lease update in namespaces without its + parameter, including kube-controller-manager's leader election. The + bindings now select the labelled site namespace, and an envtest covers it. +- Milo does not enforce the requester policy, as described in known gaps. +- Harness defects: client-side validation against Milo's OpenAPI document, + binaries copied without the execute bit, counting resets before the lab + wrote a withheld request's audit line, and reading a terminating lab Pod. + +## Decisions where the proposal left a choice + +| Open question | Prototype choice | +| --- | --- | +| Override for capacity-backed Devices | None. `CapacityBacked` has no exception. | +| Lost response, then the right state | `Succeeded`, as the proposal proposes. The message records that the response was lost. The stricter `Unknown` remains a one-line change. | +| Restart evidence | Restart and power cycle are built and run only against the emulator. `ResetObserved` needs a `LastResetTime` later than before the command, on the BMC's own clock. A BMC that reports none ends as `Unknown`. Real hardware stays unqualified until the phase 4 test. | +| Graceful actions | Excluded. The CRD admits only `On`, `ForceOff`, `ForceRestart` and `PowerCycle`. | +| Retention | Operations in Milo are kept; nothing deletes them, and staff cannot. Site records and worker objects are deleted `retention` after the result. | +| Unserved operations | Not expired. An operation no dispatcher serves stays without status. A dispatcher that starts later refuses it as `Expired` if it is more than five minutes old. | +| Credential naming | Derived from the Device: `bmc..`, mounted as a volume. No dispatcher credential read and no broker. | +| Installation server list | Unchanged. The prototype checks MachineCapacity only. | +| Requester source | `spec.requester`, checked by a ValidatingAdmissionPolicy. Milo does not enforce that policy, so this choice is open again; see [known gaps](#the-requester-check-is-not-enforced-in-milo). | + +## Where the prototype differs from the proposal + +- **Executing comes after the record.** The proposal's sequence marks the + operation `Executing` before the capacity re-check. The prototype marks it + after it writes the stage record. A started operation whose record then + disappears ends as `Unknown` (`RecordLost`). +- **The acceptance order** starts with `Expired`, `DeviceNotFound`, + `DeviceRetired` and `CapacityBacked`. The proposal's table lists reasons + without an order. +- **Extra refusal reasons.** The worker has reasons the proposal does not + name, listed in [worker reasons](#worker-reasons). `DiscoveryNotCurrent` also + covers a TLS key that discovery has not yet compared with other BMCs. +- **The worker also checks the credential's pin** against the key discovery + observed (`CredentialMismatch`), before it connects. +- **The Device lock is a site Lease**, in addition to the proposal's check of + other running operations. It stops two dispatchers from accepting two + operations on one Device at once. +- **Worker deadline.** The Job's `activeDeadlineSeconds` is the two-minute + start window plus four request timeouts, `observeTimeout` and one minute. + +## Known gaps + +### The requester check is not enforced in Milo + +The proposal says admission requires `spec.requester` to equal the creating +user. The prototype ships that check as a ValidatingAdmissionPolicy. In the +end-to-end run, Milo v0.32.5 loads the policy plugin but does not evaluate a +policy stored in a project: a staff user created an operation naming another +requester. A copy of the policy at Milo's root is evaluated, but it resolves +the request's namespace in root storage and rejects every create in a project +namespace with `namespaces "inventory" not found`. Do not apply the policy at +the root. + +Until this is decided, `spec.requester` is what the creator wrote, and the +audit record of who asked comes only from Milo's own audit log. The choices +are a validating webhook at Milo's root, as capacity registration already +uses, or taking the requester from Milo's audit record, as the proposal's +open question suggests. Milo versions after v0.32.5 have not been tested. + +### Other gaps + +- **Capacity window.** Capacity defined after the dispatcher's last check and + before the command is not caught. The allocator gate in phase 5 is not built. +- **No staff UI.** +- **No real hardware.** The command path has run only against the emulator + and its simulated power. Vendor `LastResetTime`, `PoweringOn` and + `PoweringOff`, and reset semantics are unqualified. +- **Milo IAM.** The roles are checked by tests of their shape. The e2e run + uses Kubernetes RBAC with the same grants, not Milo's IAM authorizer. +- **Monitoring.** No metrics for unaccepted operations, `Unknown` results, + duplicate workers or dispatcher restarts. +- **Deployed Milo.** The component has not been applied to any deployed Milo, + and it is in no root. + +## Tests + +`go test -race ./internal/devicepower ./internal/redfish ./internal/bmcdiscovery` +covers, with `KUBEBUILDER_ASSETS` set for the API-server tests: + +- every acceptance refusal, and that refusals create no site object; +- the capacity re-check after acceptance; +- each worker outcome, with the number of resets the BMC received: success, + already in state, refused, refused but changed, lost response with and + without effect, restart without a reset time, identity change after the + command, and every refusal before the command; +- a second worker and eight concurrent workers sending once; +- a fenced worker and a failed write-ahead sending nothing; +- a lost worker at each stage, a deleted Job and a missing record; +- two dispatchers and six concurrent reconcilers starting one worker; +- the Device Lease and its takeover after the holder finishes; +- retention; +- on a real API server: the requester policy, spec immutability, the + result set once, and the staff and dispatcher permissions; +- on a real API server: the site policies admit the worker shape and deny + another image, another Device's credential, a second volume, a Secret in + the environment, a privileged or host-network Pod, retries, the + dispatcher's identity, another command, a Role reading Secrets or another + record, a binding to another identity, a non-worker object, an input change + and a delete of the policy parameter; +- the Redfish client finding one System by UUID, refusing a replaced or + duplicated server and a foreign reset target, re-checking identity, and + sending a lost reset once; +- discovery recording reset types with `GET`s only. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index a96498ff..df8fc2c7 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -76,7 +76,10 @@ does not fork or patch upstream files. | 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, 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 | +| `LastResetTime` on each System, set when a reset starts its domain | Adapter | +| Optional TLS from a mounted lab certificate (`FLEET_BMC_TLS_CERT`, `FLEET_BMC_TLS_KEY`), TLS 1.2 or later | Adapter, used by the [device power acceptance](device-power.md#end-to-end-acceptance) | | Bounded, one-shot lab faults (`reject-auth`, `hide-reset`, `drop-response`) from a fault file | Adapter, lab only | +| Power-operation lab faults: `drop-request` (accepted, never applied, response withheld), `swap-identity` (the System reports another UUID), `hide-reset-time` (no `LastResetTime`). `drop-response` now also applies after a power-off. | 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. diff --git a/hack/device-power/e2e.py b/hack/device-power/e2e.py new file mode 100755 index 00000000..f52042a4 --- /dev/null +++ b/hack/device-power/e2e.py @@ -0,0 +1,819 @@ +#!/usr/bin/env python3 +"""End-to-end acceptance of staff power operations against emulated BMCs. + +One disposable kind cluster in the task-owned Colima profile holds: + + * a Milo v0.32.5 project API (its own etcd) with the inventory, metal and + DevicePowerOperation CRDs and the requester admission policy, reached + through Milo's native project route with per-identity static tokens; + * the site namespace with read-only BMC discovery, the power dispatcher, + its admission policies and the BMC credential Secrets; + * two lab BMCs: the unmodified DMTF Redfish Interface Emulator 1.2.2 with + the Fleet lab adapter over TLS, each serving one System. Power is the + adapter's simulated libvirt (fake_virsh.py); no guest boots. + +Every operation is created by a staff identity through the Milo API, accepted +or refused by the deployed dispatcher, and run by a real worker Job against a +lab BMC. Each scenario records the result staff see and the number of +ComputerSystem.Reset requests in the BMC's own audit log. + +Synthetic data only. Credentials, tokens and kubeconfigs stay in the private +state directory; only evidence/ is shareable. See docs/operations/device-power.md. +""" +import argparse +import base64 +import datetime +import hashlib +import json +import os +import pathlib +import re +import secrets +import shutil +import socket +import subprocess +import sys +import time + +ROOT = pathlib.Path(__file__).resolve().parents[2] +CONTEXT = 'colima-fleet-acceptance-tcg' +NODE = 'kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f' +PROJECT = 'provider' +INVENTORY_NS = 'inventory' +SITE_NS = 'fleet-power-site' +LAB_NS = 'fleet-lab-bmc' +MILO_NS = 'milo-provider' +MILO_NODE_PORT = 30441 +STAFF = 'staff@example.com' +# Synthetic lab servers. Device A has no capacity; Device B backs capacity. +BMCS = { + 'a': {'ip': '10.96.0.91', 'device': 'device-a', 'uuid': '00000000-0000-4000-8000-0000000000a1'}, + 'b': {'ip': '10.96.0.92', 'device': 'device-b', 'uuid': '00000000-0000-4000-8000-0000000000b2'}, +} +OBSERVE_TIMEOUT = '45s' +REQUEST_TIMEOUT = '10s' + +os.environ['DOCKER_CONTEXT'] = CONTEXT +os.environ['KIND_EXPERIMENTAL_PROVIDER'] = 'docker' + + +class Failed(Exception): + pass + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + + +def run(*args, input=None, check=True, timeout=600, quiet=False): + r = subprocess.run([str(a) for a in args], input=input, text=True, capture_output=True, timeout=timeout, cwd=ROOT) + if check and r.returncode: + raise Failed('%s failed (%d): %s' % (' '.join(str(a) for a in args[:4]), r.returncode, (r.stderr or r.stdout).strip()[-800:])) + return r + + +class Env: + def __init__(self, state, prefix): + self.state, self.prefix = state, prefix + self.evidence = state / 'evidence' + self.admin = state / 'kind-admin.yaml' + self.image = prefix + '-fleet:e2e' + self.bmc_image = prefix + '-bmc:e2e' + self.records = [] + + # The kind cluster, as cluster admin (fixtures and lab faults only). + def kube(self, *args, input=None, check=True, timeout=120): + return run('kubectl', '--kubeconfig', self.admin, '--request-timeout=30s', *args, input=input, check=check, timeout=timeout) + + # The Milo project, as one identity. + def milo(self, who, *args, input=None, check=True): + # Milo's OpenAPI document fails kubectl's client-side schema check; + # the server still validates every write. + if args and args[0] in ('apply', 'create', 'replace'): + args = (args[0], '--validate=false') + args[1:] + return run('kubectl', '--kubeconfig', self.state / 'milo' / (who + '-project.json'), '--request-timeout=30s', *args, input=input, check=check) + + def apply(self, obj, who=None, namespace=None): + args = ['apply', '-f', '-'] + (['-n', namespace] if namespace else []) + data = json.dumps(obj) if not isinstance(obj, str) else obj + return self.milo(who, *args, input=data) if who else self.kube(*args, input=data) + + def write(self, name, value): + path = self.evidence / name + path.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + return path + + +def phase(name): + def wrap(fn): + fn.phase = name + return fn + return wrap + + +def wait(fn, seconds, what, interval=2): + deadline = time.time() + seconds + last = None + while time.time() < deadline: + try: + last = fn() + except Failed: + last = None + if last: + return last + time.sleep(interval) + raise Failed('timed out waiting for ' + what) + + +def free_port(): + s = socket.socket() + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + +def kubeconfig(path, server, token, ca): + path.write_text(json.dumps({'apiVersion': 'v1', 'kind': 'Config', + 'clusters': [{'name': 'milo', 'cluster': {'server': server, 'certificate-authority-data': base64.b64encode(ca).decode()}}], + 'users': [{'name': 'u', 'user': {'token': token}}], + 'contexts': [{'name': 'c', 'context': {'cluster': 'milo', 'user': 'u'}}], 'current-context': 'c'})) + path.chmod(0o600) + + +def pin_of(cert): + der = run('sh', '-c', 'openssl x509 -in "$1" -pubkey -noout | openssl pkey -pubin -outform der | shasum -a 256', 'sh', cert).stdout.split()[0] + return der + + +# --- phases --------------------------------------------------------------- + +@phase('preflight') +def preflight(e): + for tool in ('docker', 'kind', 'kubectl', 'kustomize', 'go', 'openssl', 'curl'): + if not shutil.which(tool): + raise Failed('missing tool ' + tool) + run('docker', 'info', timeout=30) + running = run('docker', 'ps', '--format', '{{.Names}}').stdout.split() + busy = [n for n in running if n.startswith(('fleet-mp-', 'fleet-local-', 'fleet-dp-'))] + if busy: + raise Failed('another Fleet runtime is running in %s: %s' % (CONTEXT, ', '.join(busy))) + print('preflight: tools present; %s reachable; no other Fleet runtime running' % CONTEXT) + + +@phase('unit-tests') +def unit_tests(e): + env = dict(os.environ) + assets = run('go', 'run', 'sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2', 'use', '1.37.0', '-p', 'path', timeout=900).stdout.strip() + env['KUBEBUILDER_ASSETS'] = assets + r = subprocess.run(['go', 'test', '-race', '-count=1', './internal/devicepower', './internal/redfish', './internal/bmcdiscovery', './internal/api/inventory/...'], + cwd=ROOT, env=env, text=True, capture_output=True, timeout=1200) + (e.state / 'logs' / 'unit-tests.log').write_text(r.stdout + r.stderr) + if r.returncode: + raise Failed('go test failed; see logs/unit-tests.log') + print('unit-tests: devicepower, redfish, bmcdiscovery and inventory API tests passed, including envtest') + + +@phase('images') +def images(e): + bin_dir = e.state / 'bin' + bin_dir.mkdir(exist_ok=True) + arch = run('docker', 'info', '--format', '{{.Architecture}}').stdout.strip() + goarch = {'aarch64': 'arm64', 'x86_64': 'amd64'}.get(arch, arch) + env = dict(os.environ, CGO_ENABLED='0', GOOS='linux', GOARCH=goarch) + for cmd in ('fleet-device-power', 'fleet-bmc-discovery'): + r = subprocess.run(['go', 'build', '-trimpath', '-o', str(bin_dir / cmd), './cmd/' + cmd], cwd=ROOT, env=env, text=True, capture_output=True, timeout=900) + if r.returncode: + raise Failed('build %s: %s' % (cmd, r.stderr[-500:])) + (bin_dir / 'Containerfile').write_text('FROM scratch\nCOPY --chmod=0755 fleet-device-power fleet-bmc-discovery /\nUSER 65532:65532\n') + run('docker', 'build', '-q', '-t', e.image, '-f', bin_dir / 'Containerfile', bin_dir, timeout=600) + upstream = e.state / 'redfish-upstream' + provenance = run('bash', 'hack/redfish-lab/upstream.sh', upstream, timeout=300).stdout + (e.evidence / 'redfish-upstream.json').write_text(provenance) + run('docker', 'build', '-q', '--build-context', 'upstream=%s' % (upstream / 'src' / 'Redfish-Interface-Emulator-1.2.2'), '-t', e.bmc_image, + '-f', 'hack/redfish-lab/Containerfile', 'hack/redfish-lab', timeout=1800) + run('docker', 'run', '--rm', '--network', 'none', '--entrypoint', 'python3', e.bmc_image, '/opt/fleet-lab/test_adapter.py', timeout=300) + ids = {name: run('docker', 'image', 'inspect', name, '--format', '{{.Id}}').stdout.strip() for name in (e.image, e.bmc_image)} + e.write('images.json', {'fleet': ids[e.image], 'labBMC': ids[e.bmc_image], 'binaries': { + b: hashlib.sha256((bin_dir / b).read_bytes()).hexdigest() for b in ('fleet-device-power', 'fleet-bmc-discovery')}}) + print('images: fleet binaries built from the checkout; lab BMC image built from the verified DMTF 1.2.2 archive; adapter self-test passed') + + +@phase('cluster') +def cluster(e): + port = free_port() + (e.state / 'milo-port').write_text(str(port)) + config = e.state / 'kind.yaml' + config.write_text('kind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\nnodes:\n - role: control-plane\n extraPortMappings:\n' + ' - {containerPort: %d, hostPort: %d, listenAddress: 127.0.0.1}\n' % (MILO_NODE_PORT, port)) + run('kind', 'create', 'cluster', '--name', e.prefix, '--config', config, '--kubeconfig', e.admin, '--image', NODE, '--wait', '180s', timeout=600) + e.admin.chmod(0o600) + for image in (e.image, e.bmc_image): + run('kind', 'load', 'docker-image', '--name', e.prefix, image, timeout=600) + print('cluster: kind node %s; images loaded' % NODE.split('@')[0]) + + +@phase('milo') +def milo(e): + d = e.state / 'milo' + d.mkdir(mode=0o700, exist_ok=True) + identities = {'bootstrap': 'system:masters', STAFF: 'staff', 'viewer@example.com': 'staff', 'fleet-device-power-dispatcher': 'fleet', 'fleet-bmc-discovery': 'fleet'} + tokens = {who: secrets.token_hex(32) for who in identities} + (d / 'tokens.csv').write_text(''.join('%s,%s,%s,%s\n' % (tokens[w], w, w, g) for w, g in identities.items())) + (d / 'tokens.json').write_text(json.dumps(tokens)) + run('openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', d / 'tls.key', '-out', d / 'tls.crt', '-days', '2', '-subj', '/CN=fleet-e2e-milo', + '-addext', 'subjectAltName=DNS:milo-apiserver.%s.svc,IP:127.0.0.1' % MILO_NS) + for f in ('tokens.csv', 'tokens.json', 'tls.key', 'tls.crt'): + (d / f).chmod(0o600) + e.apply(run('kustomize', 'build', 'config/multiplane/milo/provider').stdout) + secret = e.kube('-n', MILO_NS, 'create', 'secret', 'generic', 'milo-apiserver-private', '--from-file=tokens.csv=%s' % (d / 'tokens.csv'), + '--from-file=tls.crt=%s' % (d / 'tls.crt'), '--from-file=tls.key=%s' % (d / 'tls.key'), '--dry-run=client', '-o', 'json').stdout + e.apply(secret) + e.kube('-n', MILO_NS, 'rollout', 'status', 'deployment/milo-apiserver', '--timeout=600s', timeout=660) + ca = (d / 'tls.crt').read_bytes() + root = 'https://127.0.0.1:%s' % (e.state / 'milo-port').read_text() + route = '/apis/resourcemanager.miloapis.com/v1alpha1/projects/%s/control-plane' % PROJECT + kubeconfig(d / 'bootstrap-root.json', root, tokens['bootstrap'], ca) + wait(lambda: run('kubectl', '--kubeconfig', d / 'bootstrap-root.json', 'get', 'crd', 'projects.resourcemanager.miloapis.com', check=False).returncode == 0, 300, 'Milo API') + run('kubectl', '--kubeconfig', d / 'bootstrap-root.json', 'wait', '--for=condition=Established', 'crd/projects.resourcemanager.miloapis.com', '--timeout=90s') + run('kubectl', '--kubeconfig', d / 'bootstrap-root.json', 'apply', '--validate=false', '-f', '-', input=json.dumps( + {'apiVersion': 'resourcemanager.miloapis.com/v1alpha1', 'kind': 'Project', 'metadata': {'name': PROJECT}, 'spec': {'ownerRef': {'kind': 'Organization', 'name': 'e2e-fixture'}}})) + names = {'bootstrap': 'bootstrap', STAFF: 'staff', 'viewer@example.com': 'viewer', 'fleet-device-power-dispatcher': 'dispatcher', 'fleet-bmc-discovery': 'discovery'} + for who, short in names.items(): + kubeconfig(d / (short + '-project.json'), root + route, tokens[who], ca) + for who in ('fleet-device-power-dispatcher', 'fleet-bmc-discovery'): + kubeconfig(d / (names[who] + '-incluster.json'), 'https://milo-apiserver.%s.svc:6443%s' % (MILO_NS, route), tokens[who], ca) + # The project's APIs: inventory, capacity and power operations. + def project_apply(path): + wait(lambda: e.milo('bootstrap', 'apply', '-f', '-', input=run('kustomize', 'build', path).stdout, check=False).returncode == 0, 120, 'apply ' + path) + e.milo('bootstrap', 'apply', '-f', 'config/base/crd/metal.datumapis.com.yaml') + project_apply('config/components/inventory/crds') + project_apply('config/components/device-power/crds') + e.milo('bootstrap', 'wait', '--for=condition=Established', 'crd', '--all', '--timeout=120s') + project_apply('config/components/device-power/admission') + e.apply({'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': {'name': INVENTORY_NS}}, who='bootstrap') + # Kubernetes RBAC stands in for the Milo IAM roles of the same names + # (config/components/device-power/roles, inventory discoverer). This is + # the local static-token seam, as in the multi-plane harness. + rules = { + 'staff': [{'apiGroups': ['fleet.datumapis.com'], 'resources': ['devicepoweroperations'], 'verbs': ['create', 'get', 'list', 'watch']}, + {'apiGroups': ['fleet.datumapis.com'], 'resources': ['devices'], 'verbs': ['get', 'list', 'watch']}], + 'viewer': [{'apiGroups': ['fleet.datumapis.com'], 'resources': ['devices', 'devicepoweroperations'], 'verbs': ['get', 'list', 'watch']}], + 'dispatcher': [{'apiGroups': ['fleet.datumapis.com'], 'resources': ['devicepoweroperations', 'devices'], 'verbs': ['get', 'list', 'watch']}, + {'apiGroups': ['fleet.datumapis.com'], 'resources': ['devicepoweroperations/status'], 'verbs': ['update', 'patch']}, + {'apiGroups': ['metal.datumapis.com'], 'resources': ['machinecapacities'], 'verbs': ['get', 'list', 'watch']}], + 'discovery': [{'apiGroups': ['fleet.datumapis.com'], 'resources': ['devices'], 'verbs': ['get', 'list', 'watch']}, + {'apiGroups': ['fleet.datumapis.com'], 'resources': ['devices/status'], 'verbs': ['update', 'patch']}], + } + users = {'staff': STAFF, 'viewer': 'viewer@example.com', 'dispatcher': 'fleet-device-power-dispatcher', 'discovery': 'fleet-bmc-discovery'} + for role, rule in rules.items(): + for config in ('bootstrap-root.json',): + run('kubectl', '--kubeconfig', d / config, 'apply', '--validate=false', '-f', '-', input=json.dumps({'apiVersion': 'v1', 'kind': 'List', 'items': [ + {'apiVersion': 'rbac.authorization.k8s.io/v1', 'kind': 'ClusterRole', 'metadata': {'name': 'e2e-' + role}, 'rules': rule}, + {'apiVersion': 'rbac.authorization.k8s.io/v1', 'kind': 'ClusterRoleBinding', 'metadata': {'name': 'e2e-' + role}, + 'roleRef': {'apiGroup': 'rbac.authorization.k8s.io', 'kind': 'ClusterRole', 'name': 'e2e-' + role}, + 'subjects': [{'apiGroup': 'rbac.authorization.k8s.io', 'kind': 'User', 'name': users[role]}]}]})) + wait(lambda: e.milo('staff', 'auth', 'can-i', 'create', 'devicepoweroperations.fleet.datumapis.com', '-n', INVENTORY_NS, check=False).stdout.strip() == 'yes', 60, 'staff RBAC') + print('milo: Milo v0.32.5 project API ready; inventory, metal and DevicePowerOperation CRDs and the requester policy applied in project %s' % PROJECT) + + +def bmc_manifests(e, key, spec): + d = e.state / 'lab' / key + d.mkdir(parents=True, exist_ok=True) + run('openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', d / 'tls.key', '-out', d / 'tls.crt', + '-days', '2', '-subj', '/CN=fleet-lab-bmc', '-addext', 'subjectAltName=IP:' + spec['ip']) + password = secrets.token_hex(24) + (d / 'password').write_text(password) + for f in ('tls.key', 'password'): + (d / f).chmod(0o600) + spec['pin'] = pin_of(d / 'tls.crt') + spec['password'] = password + targets = [{'system': 'System-1', 'name': 'fleet-lab-' + key, 'domain': 'fleet-lab-' + key, 'uuid': spec['uuid'], 'mac': '52:54:00:77:02:0' + ('a' if key == 'a' else 'b'), + 'ip': '192.168.78.1' + ('0' if key == 'a' else '1'), 'disk': '/var/lib/fleet-bmc/disk.raw', 'console': '/var/lib/fleet-bmc/console.log'}] + populate = json.loads((ROOT / 'hack/redfish-lab/populate-config.json').read_text()) + populate['POPULATE']['Chassis'][0]['Links']['ComputerSystems'][0]['Count'] = 1 + name = 'lab-bmc-' + key + return [ + {'apiVersion': 'v1', 'kind': 'ConfigMap', 'metadata': {'name': name, 'namespace': LAB_NS}, 'data': { + 'emulator-config.json': (ROOT / 'hack/redfish-lab/emulator-config.json').read_text(), 'populate-config.json': json.dumps(populate), + 'targets.json': json.dumps(targets)}}, + {'apiVersion': 'v1', 'kind': 'Secret', 'metadata': {'name': name, 'namespace': LAB_NS}, 'type': 'Opaque', 'data': { + 'username': base64.b64encode(b'lab-operator').decode(), 'password': base64.b64encode(password.encode()).decode(), + 'tls.crt': base64.b64encode((d / 'tls.crt').read_bytes()).decode(), 'tls.key': base64.b64encode((d / 'tls.key').read_bytes()).decode()}}, + {'apiVersion': 'v1', 'kind': 'Service', 'metadata': {'name': name, 'namespace': LAB_NS}, 'spec': { + 'clusterIP': spec['ip'], 'selector': {'app': name}, 'ports': [{'name': 'https', 'port': 443, 'targetPort': 8443}]}}, + {'apiVersion': 'apps/v1', 'kind': 'Deployment', 'metadata': {'name': name, 'namespace': LAB_NS}, 'spec': { + 'replicas': 1, 'strategy': {'type': 'Recreate'}, 'selector': {'matchLabels': {'app': name}}, 'template': { + 'metadata': {'labels': {'app': name}}, 'spec': {'automountServiceAccountToken': False, 'enableServiceLinks': False, 'containers': [{ + 'name': 'bmc', 'image': e.bmc_image, 'imagePullPolicy': 'Never', 'args': ['serve'], + 'env': [{'name': 'FLEET_BMC_CONFIG', 'value': '/etc/fleet-bmc'}, {'name': 'FLEET_BMC_STATE', 'value': '/var/lib/fleet-bmc'}, + {'name': 'FLEET_BMC_CREDENTIALS', 'value': '/etc/fleet-bmc-credentials'}, {'name': 'FLEET_BMC_PORT', 'value': '8443'}, + {'name': 'FLEET_BMC_TLS_CERT', 'value': '/etc/fleet-bmc-credentials/tls.crt'}, {'name': 'FLEET_BMC_TLS_KEY', 'value': '/etc/fleet-bmc-credentials/tls.key'}, + {'name': 'FLEET_VIRSH', 'value': '/opt/fleet-lab/fake_virsh.py'}, {'name': 'FAKE_VIRSH_STATE', 'value': '/var/lib/fleet-bmc/virsh.json'}, + {'name': 'FLEET_BOOT_IP', 'value': '10.96.0.80'}], + 'ports': [{'containerPort': 8443}], + 'readinessProbe': {'tcpSocket': {'port': 8443}, 'periodSeconds': 2}, + 'volumeMounts': [{'name': 'config', 'mountPath': '/etc/fleet-bmc', 'readOnly': True}, + {'name': 'credentials', 'mountPath': '/etc/fleet-bmc-credentials', 'readOnly': True}, + {'name': 'state', 'mountPath': '/var/lib/fleet-bmc'}]}], + 'volumes': [{'name': 'config', 'configMap': {'name': name}}, {'name': 'credentials', 'secret': {'secretName': name}}, + {'name': 'state', 'emptyDir': {}}]}}}}, + ] + + +@phase('site') +def site(e): + e.apply({'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': {'name': LAB_NS}}) + # The site namespace enforces the restricted Pod Security profile, which + # every discovery, dispatcher and worker Pod must meet. + e.apply({'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': {'name': SITE_NS, 'labels': { + 'pod-security.kubernetes.io/enforce': 'restricted', 'pod-security.kubernetes.io/enforce-version': 'latest', + 'fleet.datumapis.com/device-power-site': 'true'}}}) + for key, spec in BMCS.items(): + e.apply({'apiVersion': 'v1', 'kind': 'List', 'items': bmc_manifests(e, key, spec)}) + for key in BMCS: + # A lab BMC reads its TLS key at start; a resumed run regenerated it. + e.kube('-n', LAB_NS, 'rollout', 'restart', 'deployment/lab-bmc-' + key) + e.kube('-n', LAB_NS, 'rollout', 'status', 'deployment/lab-bmc-' + key, '--timeout=300s', timeout=330) + lab = {k: {kk: v for kk, v in spec.items() if kk not in ('password',)} for k, spec in BMCS.items()} + e.write('lab.json', lab) + d = e.state / 'milo' + for who, secret in (('dispatcher', 'fleet-device-power-milo-kubeconfig'), ('discovery', 'fleet-bmc-discovery-milo-kubeconfig')): + e.apply(e.kube('-n', SITE_NS, 'create', 'secret', 'generic', secret, '--from-file=kubeconfig=%s' % (d / (who + '-incluster.json')), '--dry-run=client', '-o', 'json').stdout) + # One credential Secret per Device, named bmc.., with + # the approved pin. The harness generated each lab key, which stands in + # for the out-of-band verification. + for key, spec in BMCS.items(): + e.apply({'apiVersion': 'v1', 'kind': 'Secret', 'metadata': {'name': 'bmc.%s.%s' % (INVENTORY_NS, spec['device']), 'namespace': SITE_NS, + 'labels': {'fleet.datumapis.com/bmc-credential': 'true'}, + 'annotations': {'fleet.datumapis.com/device-project': PROJECT, 'fleet.datumapis.com/device-namespace': INVENTORY_NS, 'fleet.datumapis.com/device-name': spec['device']}}, + 'type': 'Opaque', 'stringData': {'username': 'lab-operator', 'password': spec['password'], 'tlsPublicKeySHA256': spec['pin']}}) + overlay = e.state / 'overlay' + for name, base, config in (('discovery', 'config/base/bmc-discovery', {'project': PROJECT, 'miloKubeconfig': '/var/run/fleet/milo/kubeconfig', + 'deviceNamespaces': [INVENTORY_NS], 'interval': '1h', 'retryBase': '10s', 'minContactInterval': '1m', 'requestTimeout': '10s', + 'concurrency': 4, 'healthProbeAddress': ':8081'}), + ('dispatcher', 'config/base/device-power', {'project': PROJECT, 'miloKubeconfig': '/var/run/fleet/milo/kubeconfig', + 'deviceNamespaces': [INVENTORY_NS], 'workerImage': e.image, 'discoveryMaxAge': '2h', 'observeTimeout': OBSERVE_TIMEOUT, + 'requestTimeout': REQUEST_TIMEOUT, 'retention': '1h', 'healthProbeAddress': ':8081'})): + o = overlay / name + o.mkdir(parents=True, exist_ok=True) + o = o.resolve() + (o / 'config.yaml').write_text(json.dumps(config)) + rel = os.path.relpath(ROOT / base, o) + patches = '' + if name == 'dispatcher': + (o / 'params.json').write_text(json.dumps([{'op': 'replace', 'path': '/data/workerImage', 'value': e.image}])) + patches = 'patches:\n - target: {kind: ConfigMap, name: fleet-device-power-worker-policy}\n path: params.json\n' + cm = 'fleet-device-power-config' if name == 'dispatcher' else 'fleet-bmc-discovery-config' + (o / 'kustomization.yaml').write_text( + 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nnamespace: %s\nresources:\n - %s\n' + 'images:\n - {name: ghcr.io/datum-cloud/fleet, newName: %s, newTag: e2e}\n' + 'configMapGenerator:\n - {name: %s, behavior: replace, files: [config.yaml]}\n%s' % (SITE_NS, rel, e.image.split(':')[0], cm, patches)) + rendered = run('kustomize', 'build', o).stdout + (e.evidence / ('rendered-' + name + '.yaml')).write_text(rendered) + e.apply(rendered) + for deploy in ('fleet-bmc-discovery', 'fleet-device-power-dispatcher'): + e.kube('-n', SITE_NS, 'patch', 'deployment', deploy, '--type=json', '-p', json.dumps([{'op': 'add', 'path': '/spec/template/spec/containers/0/imagePullPolicy', 'value': 'Never'}])) + print('site: two TLS lab BMCs, credential Secrets with approved pins, BMC discovery and the dispatcher applied from config/base') + + +@phase('inventory') +def inventory(e): + for key, spec in BMCS.items(): + e.apply({'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'Device', 'metadata': {'name': spec['device'], 'namespace': INVENTORY_NS}, + 'spec': {'claimRef': {'name': 'claim-' + key}, 'identity': {'model': 'libvirt/QEMU lab target', 'systemUUID': spec['uuid']}, + 'bmc': {'endpoint': 'https://%s:443' % spec['ip']}}}, who='bootstrap') + # Device B backs customer capacity. + e.apply({'apiVersion': 'metal.datumapis.com/v1alpha1', 'kind': 'MachineCapacity', 'metadata': {'name': 'capacity-b', 'namespace': INVENTORY_NS}, + 'spec': {'deviceRef': {'name': BMCS['b']['device']}, 'allocationPolicy': 'Disabled', 'cleaningPolicyRef': {'name': ''}, 'reclaimPolicy': 'Retain'}}, who='bootstrap') + for deploy in ('fleet-bmc-discovery', 'fleet-device-power-dispatcher'): + e.kube('-n', SITE_NS, 'rollout', 'status', 'deployment/' + deploy, '--timeout=300s', timeout=330) + + def discovered(): + out = {} + for spec in BMCS.values(): + d = json.loads(e.milo('bootstrap', 'get', 'device', spec['device'], '-n', INVENTORY_NS, '-o', 'json').stdout) + conds = {c['type']: c['status'] for c in d.get('status', {}).get('conditions', [])} + systems = (d.get('status', {}).get('discovery') or {}).get('inventory', {}).get('systems', []) + if not (conds.get('Discovered') == conds.get('IdentityMatched') == conds.get('PublicKeyUnique') == 'True') or not systems: + return None + out[spec['device']] = {'conditions': conds, 'systems': [{k: s.get(k) for k in ('id', 'uuid', 'powerState', 'resetTypes')} for s in systems], + 'publicKeySHA256': d['status']['discovery']['tls']['publicKeySHA256']} + return out + seen = wait(discovered, 240, 'discovery of both Devices') + for key, spec in BMCS.items(): + if seen[spec['device']]['publicKeySHA256'] != spec['pin'] or seen[spec['device']]['systems'][0]['resetTypes'] != ['On', 'ForceOff', 'ForceRestart']: + raise Failed('discovery recorded unexpected TLS key or reset types: %s' % seen) + posts = {k: [x for x in audit(e, k) if x['method'] != 'GET'] for k in BMCS} + if any(posts.values()): + raise Failed('discovery issued a non-GET request: %s' % posts) + e.write('discovery.json', {'observedAt': now(), 'devices': seen, 'nonGetRequests': 0}) + print('inventory: discovery matched both Devices over pinned TLS and recorded resetTypes [On, ForceOff, ForceRestart] with GETs only') + + +def lab_pod(e, key): + pods = json.loads(e.kube('-n', LAB_NS, 'get', 'pod', '-l', 'app=lab-bmc-' + key, '-o', 'json').stdout)['items'] + live = [p['metadata']['name'] for p in pods if not p['metadata'].get('deletionTimestamp') and p['status'].get('phase') == 'Running'] + if len(live) != 1: + raise Failed('expected one running lab BMC %s, found %d' % (key, len(live))) + return live[0] + + +def audit(e, key): + pod = lab_pod(e, key) + text = e.kube('-n', LAB_NS, 'exec', pod, '--', 'cat', '/var/lib/fleet-bmc/audit.log', check=False).stdout + return [json.loads(l) for l in text.splitlines() if l.strip()] + + +def resets(e, key): + return [x for x in audit(e, key) if x['method'] == 'POST' and x['path'].endswith('/Actions/ComputerSystem.Reset')] + + +def fault(e, key, *args): + pod = lab_pod(e, key) + return e.kube('-n', LAB_NS, 'exec', pod, '--', 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', *args).stdout.strip() + + +def power_state(e, key): + pod = lab_pod(e, key) + r = e.kube('-n', LAB_NS, 'exec', pod, '--', 'cat', '/var/lib/fleet-bmc/virsh.json', check=False) + if r.returncode: + return 'Off' # no lab domain defined yet: never powered + state = json.loads(r.stdout) + return 'On' if state['domains'].get('fleet-lab-' + key, {}).get('running') else 'Off' + + +SEQ = [0] +# Distinguishes operations of a resumed run from earlier ones. +RUN_ID = secrets.token_hex(2) + + +def operation(e, device, action, uuid=None, requester=STAFF, who='staff'): + SEQ[0] += 1 + name = 'op-%s-%02d-%s' % (RUN_ID, SEQ[0], action.lower()) + key = next(k for k, s in BMCS.items() if s['device'] == device) + obj = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DevicePowerOperation', 'metadata': {'name': name, 'namespace': INVENTORY_NS}, + 'spec': {'deviceRef': {'name': device}, 'action': action, 'expectedSystemUUID': uuid or BMCS[key]['uuid'], 'requester': requester, + 'reason': 'synthetic end-to-end scenario'}} + r = e.milo(who, 'create', '-f', '-', input=json.dumps(obj), check=False) + return name, r + + +def get_op(e, name): + return json.loads(e.milo('staff', 'get', 'devicepoweroperation', name, '-n', INVENTORY_NS, '-o', 'json').stdout) + + +def finished(e, name, seconds=240): + def done(): + op = get_op(e, name) + return op if op.get('status', {}).get('result') else None + return wait(done, seconds, 'operation %s to finish' % name) + + +def jobs_for(e, uid): + out = json.loads(e.kube('-n', SITE_NS, 'get', 'jobs', '-l', 'fleet.datumapis.com/power-operation-uid=' + uid, '-o', 'json').stdout) + return out['items'] + + +def summary(op): + s = op.get('status', {}) + reason = next((c['reason'] for c in s.get('conditions', []) if c['type'] == 'Finished'), None) + message = next((c['message'] for c in s.get('conditions', []) if c['type'] == 'Finished'), None) + accepted = next((c['status'] for c in s.get('conditions', []) if c['type'] == 'Accepted'), None) + return {'operation': op['metadata']['name'], 'action': op['spec']['action'], 'device': op['spec']['deviceRef']['name'], 'requester': op['spec']['requester'], + 'accepted': accepted, 'result': s.get('result'), 'reason': reason, 'message': message, 'requestSentAt': s.get('requestSentAt'), + 'power': s.get('power'), 'finishedAt': s.get('finishedAt')} + + +def scenario(e, title, name, key, before_resets, want_result, want_reason, want_resets, extra=None, want_jobs=None): + op = get_op(e, name) + # The lab audits a request when its response is written, which a + # withheld response delays by up to 25 seconds. Wait out that window + # before counting, so a late second request would be counted too. + if op.get('status', {}).get('requestSentAt'): + time.sleep(30) + after = resets(e, key) + sent = after[len(before_resets):] + record = summary(op) + record.update({'scenario': title, 'resetRequestsAtBMC': len(sent), 'resetRequests': [{k: x.get(k) for k in ('resetType', 'status', 'effect', 'fault')} for x in sent], + 'workerJobs': len(jobs_for(e, op['metadata']['uid']))}) + if extra: + record.update(extra) + e.records.append(record) + ok = record['result'] == want_result and record['reason'] == want_reason and len(sent) == want_resets and (want_jobs is None or record['workerJobs'] == want_jobs) + status = 'passed' if ok else 'FAILED' + print(' %-58s %-9s %-26s resets=%d jobs=%d %s' % (title, record['result'], record['reason'], len(sent), record['workerJobs'], status)) + if not ok: + raise Failed('%s: got %s/%s with %d resets, want %s/%s with %d' % (title, record['result'], record['reason'], len(sent), want_result, want_reason, want_resets)) + return op + + +@phase('admission') +def admission(e): + results = {} + # Device B backs capacity, so a probe that is admitted is still refused + # by the dispatcher and reaches no BMC. + _, r = operation(e, 'device-b', 'On', requester='someone-else@example.com') + # Known gap: Milo v0.32.5 does not evaluate ValidatingAdmissionPolicies + # stored in a project, so the requester policy is applied but not + # enforced. Recorded as observed; see docs/operations/device-power.md. + results['forgedRequester'] = 'denied' if r.returncode and 'spec.requester must be' in r.stderr else r.stderr.strip() or 'admitted' + _, r = operation(e, 'device-b', 'On', requester='viewer@example.com', who='viewer') + results['withoutOperatorRole'] = 'forbidden' if r.returncode and 'forbidden' in r.stderr.lower() else r.stderr.strip() or 'admitted' + name, r = operation(e, 'device-b', 'On', uuid='00000000-0000-4000-8000-0000000000ff') + if r.returncode: + raise Failed('staff could not create an operation: ' + r.stderr) + op = finished(e, name) + op['spec']['action'] = 'ForceOff' + r = e.milo('bootstrap', 'replace', '-f', '-', input=json.dumps(op), check=False) + results['specChange'] = 'rejected' if r.returncode and 'spec is immutable' in r.stderr else r.stderr.strip() or 'accepted' + status = {'apiVersion': op['apiVersion'], 'kind': op['kind'], 'metadata': {'name': name, 'namespace': INVENTORY_NS, 'resourceVersion': op['metadata']['resourceVersion']}, + 'spec': get_op(e, name)['spec'], 'status': dict(op['status'], result='Succeeded')} + r = e.milo('staff', 'replace', '--subresource=status', '-f', '-', input=json.dumps(status), check=False) + results['staffStatusWrite'] = 'forbidden' if r.returncode and 'forbidden' in r.stderr.lower() else r.stderr.strip() or 'allowed' + r = e.milo('staff', 'delete', 'devicepoweroperation', name, '-n', INVENTORY_NS, check=False) + results['staffDelete'] = 'forbidden' if r.returncode and 'forbidden' in r.stderr.lower() else r.stderr.strip() or 'allowed' + results['requesterPolicyStoredInProject'] = e.milo('bootstrap', 'get', 'validatingadmissionpolicy', 'fleet-device-power-requester', check=False).returncode == 0 + e.write('admission.json', results) + want = {'forgedRequester': 'admitted', 'requesterPolicyStoredInProject': True, 'withoutOperatorRole': 'forbidden', 'specChange': 'rejected', 'staffStatusWrite': 'forbidden', 'staffDelete': 'forbidden'} + if results != want: + raise Failed('admission: %s' % results) + print('admission: KNOWN GAP forged requester admitted (Milo v0.32.5 does not enforce project-stored admission policies); viewer forbidden; spec change rejected; staff status write and delete forbidden') + + +@phase('power') +def power(e): + print('power: scenario result reason resets jobs') + a, b = 'a', 'b' + if power_state(e, a) != 'Off': + raise Failed('device A did not start Off') + + # 1. On, with the dispatcher restarted while the operation is new. + before = resets(e, a) + name, _ = operation(e, 'device-a', 'On') + e.kube('-n', SITE_NS, 'delete', 'pod', '-l', 'app.kubernetes.io/name=fleet-device-power-dispatcher', '--wait=false') + finished(e, name) + scenario(e, 'On (dispatcher restarted after the request)', name, a, before, 'Succeeded', 'RequestedStateObserved', 1, want_jobs=1) + + # 2. ForceRestart, proven by the BMC's LastResetTime. + before = resets(e, a) + name, _ = operation(e, 'device-a', 'ForceRestart') + finished(e, name) + scenario(e, 'ForceRestart', name, a, before, 'Succeeded', 'ResetObserved', 1) + + # 3. ForceOff. + before = resets(e, a) + name, _ = operation(e, 'device-a', 'ForceOff') + finished(e, name) + scenario(e, 'ForceOff', name, a, before, 'Succeeded', 'RequestedStateObserved', 1) + if power_state(e, a) != 'Off': + raise Failed('device A is not Off after ForceOff') + + # 4. Refusals at acceptance: nothing reaches the BMC and no worker starts. + before_a, before_b = resets(e, a), resets(e, b) + name, _ = operation(e, 'device-a', 'PowerCycle') + finished(e, name) + scenario(e, 'PowerCycle, not offered by the BMC', name, a, before_a, 'Failed', 'ResetTypeNotOffered', 0, want_jobs=0) + name, _ = operation(e, 'device-a', 'On', uuid=BMCS['b']['uuid']) + finished(e, name) + scenario(e, 'On with the wrong expected system UUID', name, a, before_a, 'Failed', 'SystemUUIDMismatch', 0, want_jobs=0) + name, _ = operation(e, 'device-b', 'ForceRestart') + finished(e, name) + scenario(e, 'ForceRestart of a capacity-backed Device', name, b, before_b, 'Failed', 'CapacityBacked', 0, want_jobs=0) + + # 5. A replaced server behind the same BMC: the worker's identity check + # refuses before any command. + fault(e, a, 'swap-identity', 'System-1', '00000000-0000-4000-8000-0000000000cc') + before = resets(e, a) + name, _ = operation(e, 'device-a', 'On') + finished(e, name) + scenario(e, 'On after the BMC reports another server', name, a, before, 'Failed', 'SystemUUIDMismatch', 0, want_jobs=1) + fault(e, a, 'clear') + + # 6. Lost response, effect applied: the requested state proves it. + fault(e, a, 'drop-response', 'System-1', 'On', '25') + before = resets(e, a) + name, _ = operation(e, 'device-a', 'On') + finished(e, name) + scenario(e, 'On, response lost after the effect', name, a, before, 'Succeeded', 'RequestedStateObserved', 1) + + # 7. Lost BMC response with no effect: Unknown, never resent. A cloned + # worker for the same operation starts mid-observation and stops at the + # claim without contacting the BMC. + fault(e, a, 'drop-request', 'System-1', 'ForceOff', '25') + before = resets(e, a) + name, _ = operation(e, 'device-a', 'ForceOff') + uid = get_op(e, name)['metadata']['uid'] + wait(lambda: record_stage(e, uid) in ('Sending', 'Sent'), 60, 'the worker to send') + clone = clone_worker(e, uid) + op = finished(e, name) + logs = e.kube('-n', SITE_NS, 'logs', 'job/' + clone, check=False).stdout + scenario(e, 'ForceOff, request lost (no effect); cloned worker', name, a, before, 'Unknown', 'OutcomeNotObserved', 1, + extra={'clonedWorker': {'job': clone, 'exitedWithoutClaim': 'already claimed' in logs}}) + if 'already claimed' not in logs: + raise Failed('the cloned worker did not stop at the claim: ' + logs[-400:]) + + # 8. Two requests at once for one Device, and a worker lost after its + # command: the second request is refused; the first ends Unknown with + # one command and no retry. + fault(e, a, 'drop-request', 'System-1', 'ForceOff', '25') + before = resets(e, a) + first, _ = operation(e, 'device-a', 'ForceOff') + uid = get_op(e, first)['metadata']['uid'] + wait(lambda: record_stage(e, uid) in ('Sending', 'Sent'), 60, 'the first worker to send') + second, _ = operation(e, 'device-a', 'On') + finished(e, second) + scenario(e, 'On while another operation on the Device runs', second, a, resets(e, a), 'Failed', 'OperationInProgress', 0, want_jobs=0) + e.kube('-n', SITE_NS, 'delete', 'pod', '-l', 'fleet.datumapis.com/power-operation-uid=' + uid, '--grace-period=0', '--force') + finished(e, first) + scenario(e, 'ForceOff, worker deleted after its command', first, a, before, 'Unknown', 'WorkerLost', 1, want_jobs=1) + pods = json.loads(e.kube('-n', SITE_NS, 'get', 'pods', '-l', 'fleet.datumapis.com/power-operation-uid=' + uid, '-o', 'json').stdout)['items'] + if pods: + raise Failed('a replacement worker Pod was started: %s' % [p['metadata']['name'] for p in pods]) + fault(e, a, 'clear') + + # 9. Duplicate dispatch: a second dispatcher Deployment runs against the + # same project and site. One worker, one command. + deploy = json.loads(e.kube('-n', SITE_NS, 'get', 'deployment', 'fleet-device-power-dispatcher', '-o', 'json').stdout) + for k in ('resourceVersion', 'uid', 'creationTimestamp', 'generation', 'managedFields', 'annotations'): + deploy['metadata'].pop(k, None) + deploy.pop('status', None) + deploy['metadata']['name'] = 'fleet-device-power-dispatcher-duplicate' + labels = {'app.kubernetes.io/name': 'fleet-device-power-dispatcher-duplicate'} + deploy['metadata']['labels'] = labels + deploy['spec']['selector'] = {'matchLabels': labels} + deploy['spec']['template']['metadata']['labels'] = labels + e.apply(deploy) + e.kube('-n', SITE_NS, 'rollout', 'status', 'deployment/fleet-device-power-dispatcher-duplicate', '--timeout=180s', timeout=200) + # Device A is On after scenario 8's lost ForceOff had no effect. + state = power_state(e, a) + action = 'ForceRestart' if state == 'On' else 'On' + before = resets(e, a) + name, _ = operation(e, 'device-a', action) + finished(e, name) + scenario(e, '%s with two dispatchers running' % action, name, a, before, 'Succeeded', 'ResetObserved' if action == 'ForceRestart' else 'RequestedStateObserved', 1, want_jobs=1) + e.kube('-n', SITE_NS, 'delete', 'deployment', 'fleet-device-power-dispatcher-duplicate') + + # 10. A restart on a BMC that does not report a reset time cannot be + # proven: Unknown, one command. + fault(e, a, 'hide-reset-time') + before = resets(e, a) + name, _ = operation(e, 'device-a', 'ForceRestart') + finished(e, name) + scenario(e, 'ForceRestart on a BMC without LastResetTime', name, a, before, 'Unknown', 'OutcomeNotObserved', 1) + fault(e, a, 'clear') + + if resets(e, b): + raise Failed('the capacity-backed Device received a command') + e.write('scenarios.json', {'observedAt': now(), 'observeTimeout': OBSERVE_TIMEOUT, 'requestTimeout': REQUEST_TIMEOUT, 'scenarios': e.records}) + print('power: all scenarios matched; the capacity-backed Device received no command') + + +def record_stage(e, uid): + r = e.kube('-n', SITE_NS, 'get', 'configmap', 'pwr-' + uid, '-o', 'jsonpath={.data.progress}', check=False) + try: + return json.loads(r.stdout).get('stage') + except ValueError: + return None + + +def clone_worker(e, uid): + """As cluster admin (outside the dispatcher's policy), start a second Job + with the first worker's exact Pod template.""" + job = wait(lambda: (jobs_for(e, uid) or [None])[0], 60, 'the worker Job') + template = job['spec']['template'] + template['metadata'].pop('labels', None) + template['metadata']['labels'] = {'fleet.datumapis.com/e2e-clone': uid} + clone = {'apiVersion': 'batch/v1', 'kind': 'Job', 'metadata': {'name': 'clone-' + uid[:8], 'namespace': SITE_NS}, + 'spec': {'backoffLimit': 0, 'template': template}} + e.apply(clone) + e.kube('-n', SITE_NS, 'wait', '--for=condition=Complete', 'job/clone-' + uid[:8], '--timeout=120s', timeout=150) + return 'clone-' + uid[:8] + + +@phase('security') +def security(e): + """Facts about who can do what, as each identity.""" + can = lambda who, *a: e.kube('auth', 'can-i', *a, '-n', SITE_NS, '--as', who, check=False).stdout.strip() + dispatcher = 'system:serviceaccount:%s:fleet-device-power-dispatcher' % SITE_NS + facts = { + 'dispatcherCanGetSecrets': can(dispatcher, 'get', 'secrets'), + 'dispatcherCanCreatePods': can(dispatcher, 'create', 'pods'), + 'dispatcherCanCreateJobs': can(dispatcher, 'create', 'jobs'), + 'dispatcherCanDeleteJobs': can(dispatcher, 'delete', 'jobs'), + } + jobs = json.loads(e.kube('-n', SITE_NS, 'get', 'jobs', '-l', 'app.kubernetes.io/part-of=fleet-device-power', '-o', 'json').stdout)['items'] + shapes = [] + for job in jobs: + spec = job['spec']['template']['spec'] + sa = spec['serviceAccountName'] + shapes.append({'job': job['metadata']['name'], 'image': spec['containers'][0]['image'], 'secretVolumes': [v['secret']['secretName'] for v in spec['volumes'] if 'secret' in v], + 'backoffLimit': job['spec']['backoffLimit'], 'workerCanGetItsCredential': can('system:serviceaccount:%s:%s' % (SITE_NS, sa), 'get', 'secret/' + spec['volumes'][0]['secret']['secretName']), + 'workerCanListSecrets': can('system:serviceaccount:%s:%s' % (SITE_NS, sa), 'list', 'secrets'), + 'workerCanUpdateItsRecord': can('system:serviceaccount:%s:%s' % (SITE_NS, sa), 'update', 'configmap/' + job['metadata']['name'])}) + facts['workers'] = shapes + # The worker holds no Milo credential: its Pod mounts only the Device's + # credential Secret and its own ServiceAccount token. + dispatcher_rbac = e.milo('dispatcher', 'auth', 'can-i', '--list', '-n', INVENTORY_NS, check=False).stdout + facts['dispatcherMiloCanCreateOperations'] = e.milo('dispatcher', 'auth', 'can-i', 'create', 'devicepoweroperations.fleet.datumapis.com', '-n', INVENTORY_NS, check=False).stdout.strip() + facts['dispatcherMiloCanPatchDevices'] = e.milo('dispatcher', 'auth', 'can-i', 'patch', 'devices.fleet.datumapis.com', '-n', INVENTORY_NS, check=False).stdout.strip() + e.write('security.json', facts) + bad = [k for k, v in facts.items() if isinstance(v, str) and v == 'yes' and k != 'dispatcherCanCreateJobs'] + bad += ['%s:%s' % (w['job'], k) for w in shapes for k in ('workerCanGetItsCredential', 'workerCanListSecrets') if w[k] == 'yes'] + bad += ['%s:record' % w['job'] for w in shapes if w['workerCanUpdateItsRecord'] != 'yes'] + if facts['dispatcherCanCreateJobs'] != 'yes' or bad or len({w['image'] for w in shapes}) != 1: + raise Failed('security facts: %s' % bad) + del dispatcher_rbac + print('security: the dispatcher cannot read Secrets or create Pods; each worker reads no Secret through the API and updates only its own record') + + +@phase('evidence-scan') +def evidence_scan(e): + tokens = json.loads((e.state / 'milo' / 'tokens.json').read_text()).values() + needles = list(tokens) + [s['password'] for s in BMCS.values()] + [(e.state / 'milo' / 'tls.key').read_text().splitlines()[1]] + for key in BMCS: + needles.append((e.state / 'lab' / key / 'tls.key').read_text().splitlines()[1]) + for path in e.evidence.iterdir(): + text = path.read_text() + for n in needles: + if n and n in text: + raise Failed('secret material in evidence/%s' % path.name) + print('evidence-scan: %d evidence files contain no token, password or private key' % len(list(e.evidence.iterdir()))) + + +PHASES = [preflight, unit_tests, images, cluster, milo, site, inventory, admission, power, security, evidence_scan] + + +def teardown(e, keep): + if keep: + print('teardown: --keep; cluster %s left running (delete with: kind delete cluster --name %s)' % (e.prefix, e.prefix)) + return + run('kind', 'delete', 'cluster', '--name', e.prefix, check=False, timeout=300) + for image in (e.image, e.bmc_image): + run('docker', 'image', 'rm', image, check=False) + for p in ('milo', 'lab', 'kind-admin.yaml', 'overlay'): + path = e.state / p + if path.is_dir(): + shutil.rmtree(path, ignore_errors=True) + elif path.exists(): + path.unlink() + print('teardown: cluster and image tags removed; tokens, passwords, keys and kubeconfigs deleted') + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--keep', action='store_true', help='leave the cluster running after the run') + p.add_argument('--skip-unit-tests', action='store_true') + p.add_argument('--resume', metavar='STATE', help='diagnosis only: continue a kept run from --from-phase') + p.add_argument('--from-phase', default='preflight') + a = p.parse_args() + if a.resume: + state = pathlib.Path(a.resume).resolve() + prefix = (state / 'prefix').read_text().strip() + else: + state = pathlib.Path(run('mktemp', '-d', '/tmp/fleet-device-power.XXXXXX').stdout.strip()).resolve() + prefix = 'fleet-dp-' + secrets.token_hex(4) + state.chmod(0o700) + (state / 'evidence').mkdir(exist_ok=True) + (state / 'logs').mkdir(exist_ok=True) + (state / 'prefix').write_text(prefix) + e = Env(state, prefix) + names = [fn.phase for fn in PHASES] + if a.from_phase not in names: + raise SystemExit('unknown phase ' + a.from_phase) + if a.resume: + # Rebuild in-memory lab facts the site phase records. + for key, spec in BMCS.items(): + d = state / 'lab' / key + if (d / 'tls.crt').exists(): + spec['pin'], spec['password'] = pin_of(d / 'tls.crt'), (d / 'password').read_text() + print('state %s prefix %s' % (state, prefix), flush=True) + phases, status, failed = [], 'passed', None + try: + for fn in PHASES[names.index(a.from_phase):]: + if fn is unit_tests and a.skip_unit_tests: + continue + start = time.time() + try: + fn(e) + except (Failed, subprocess.TimeoutExpired) as err: + phases.append({'phase': fn.phase, 'status': 'failed', 'seconds': round(time.time() - start)}) + status, failed = 'failed', fn.phase + print('%s: FAILED: %s' % (fn.phase, err), file=sys.stderr) + break + phases.append({'phase': fn.phase, 'status': 'passed', 'seconds': round(time.time() - start)}) + sys.stdout.flush() + finally: + if status == 'failed' and e.admin.exists(): + for cmd in (['-n', SITE_NS, 'get', 'all,configmaps,leases', '-o', 'wide'], ['-n', SITE_NS, 'logs', 'deployment/fleet-device-power-dispatcher', '--tail=200']): + r = e.kube(*cmd, check=False) + (state / 'logs' / ('failure-' + cmd[2] + '.log')).write_text(r.stdout + r.stderr) + e.write('result.json', {'status': status, 'failedPhase': failed, 'phases': phases, 'finishedAt': now(), 'prefix': prefix, + 'physicalHardware': False, 'vendorBMC': False, 'bmcTLS': True, 'powerPlane': 'lab adapter fake_virsh (simulated)'}) + teardown(e, a.keep or status == 'failed') + print('result: %s; evidence in %s' % (status, e.evidence)) + sys.exit(0 if status == 'passed' else 1) + + +if __name__ == '__main__': + main() diff --git a/hack/device-power/run.sh b/hack/device-power/run.sh new file mode 100755 index 00000000..a61f8b17 --- /dev/null +++ b/hack/device-power/run.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# End-to-end acceptance of DevicePowerOperation against emulated BMCs in a +# disposable kind cluster in the task-owned Colima profile. Exit 0 pass, 1 +# fail (the cluster is kept for inspection). See docs/operations/device-power.md. +set -euo pipefail +umask 077 +cd "$(dirname "$0")/../.." +exec python3 hack/device-power/e2e.py "$@" diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 3798d5e1..88b71052 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -12,6 +12,8 @@ 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; + * LastResetTime on each System, recorded when a reset starts its domain; + * optional TLS from a mounted lab certificate (FLEET_BMC_TLS_CERT/KEY); * an append-only request audit log (no bodies, no credentials); * bounded, one-shot lab fault injection driven by a state file. @@ -135,6 +137,10 @@ def __init__(self, targets, state, boot_ip): self.targets, self.state, self.boot_ip = targets, state, boot_ip self.nvram_path = os.path.join(state, 'nvram.json') self.nvram = read_json(self.nvram_path, {}) + # When each System last came out of a reset, like a BMC's + # ComputerSystem.LastResetTime. Persisted with the NVRAM. + self.resets_path = os.path.join(state, 'last-reset.json') + self.resets = read_json(self.resets_path, {}) for sid in targets: self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'}) atomic_write(self.nvram_path, self.nvram) @@ -178,6 +184,8 @@ def power_on(self, sid): self.save() virsh('define', '/dev/stdin', input=domain_xml(t, boot)) virsh('start', t['domain']) + self.resets[sid] = now() + atomic_write(self.resets_path, self.resets) return boot @@ -207,7 +215,14 @@ 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() + # swap-identity: the BMC now reports another server, as after a + # board or BMC replacement behind the same address. + m['UUID'] = current.get('swapIdentity', {}).get(sid, targets[sid]['uuid']) + if sid in lab.resets and not current.get('hideResetTime'): + m['LastResetTime'] = lab.resets[sid] + else: + m.pop('LastResetTime', None) m['Name'] = targets[sid]['name'] m['Manufacturer'] = 'DMTF Redfish Interface Emulator (Fleet lab adapter)' m['Model'] = 'libvirt/QEMU lab target' @@ -216,7 +231,7 @@ def publish(sid, power=None): 'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)}) if power: m['PowerState'] = power - hidden = set(faults.read().get('hideResetTypes', [])) + 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: @@ -314,6 +329,13 @@ def reset(sid): if kind not in allowed: return error(400, 'unsupported ResetType') domain = targets[sid]['domain'] + lost = take('dropRequest', lambda f: f.get('system') == sid and f.get('resetType') == kind) + if lost: + # Lab fault: the request is accepted but never applied, and the + # response is withheld past the client timeout. + request_context.detail = {'resetType': kind, 'effect': 'none', 'fault': 'drop-request-before-effect'} + time.sleep(min(int(lost.get('seconds', 45)), 120)) + return '', 204 try: with LOCK: power = lab.power(sid) @@ -327,7 +349,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' @@ -362,12 +384,19 @@ 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) == 4: + faults.update(lambda v: v.setdefault('dropRequest', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3])})) + elif args[:1] == ['swap-identity'] and len(args) == 3: + faults.update(lambda v: v.setdefault('swapIdentity', {}).__setitem__(args[1], args[2].lower())) + elif args == ['hide-reset-time']: + faults.update(lambda v: v.__setitem__('hideResetTime', True)) 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 | reject-auth COUNT | ' + 'hide-reset TYPE | hide-reset-time | swap-identity SYSTEM UUID | clear | show') print(json.dumps(faults.read(), sort_keys=True)) @@ -376,7 +405,16 @@ def main(): boot_ip = os.environ.get('FLEET_BOOT_IP', '') if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', boot_ip): raise SystemExit('FLEET_BOOT_IP must be the boot Service IPv4 address') - create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True) + cert, key = os.environ.get('FLEET_BMC_TLS_CERT', ''), os.environ.get('FLEET_BMC_TLS_KEY', '') + if bool(cert) != bool(key): + raise SystemExit('set both FLEET_BMC_TLS_CERT and FLEET_BMC_TLS_KEY, or neither') + tls = None + if cert: + import ssl + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.minimum_version = ssl.TLSVersion.TLSv1_2 + tls.load_cert_chain(cert, key) + create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True, ssl_context=tls) elif sys.argv[1:2] == ['fault']: fault_cli(sys.argv[2:]) else: diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index e44926a6..c3ead0f7 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -99,7 +99,37 @@ def test_5_faults_are_bounded_and_audited(self): self.assertNotIn('synthetic-test-password', text) self.assertNotIn('Authorization', text) - def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): + def test_6_power_operation_lab_features(self): + reset = '/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset' + system = '/redfish/v1/Systems/System-1' + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + before = self.app.get(system, headers=AUTH).json.get('LastResetTime') + self.assertIsNotNone(before) # set by the earlier power-ons + self.app.post(reset, headers=AUTH, json={'ResetType': 'On'}) + after = self.app.get(system, headers=AUTH).json['LastResetTime'] + self.assertGreaterEqual(after, before) + starts = len(virsh_state()['domains']['fleet-lab-target-a']['starts']) + self.assertEqual(self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceRestart'}).status_code, 204) + self.assertEqual(len(virsh_state()['domains']['fleet-lab-target-a']['starts']), starts + 1) + self.assertGreaterEqual(self.app.get(system, headers=AUTH).json['LastResetTime'], after) + adapter.fault_cli(['hide-reset-time']) + self.assertNotIn('LastResetTime', self.app.get(system, headers=AUTH).json) + adapter.fault_cli(['swap-identity', 'System-1', '00000000-0000-4000-8000-0000000000ff']) + self.assertEqual(self.app.get(system, headers=AUTH).json['UUID'], '00000000-0000-4000-8000-0000000000ff') + adapter.fault_cli(['clear']) + self.assertEqual(self.app.get(system, headers=AUTH).json['UUID'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') + # A dropped request is audited and has no effect. + adapter.fault_cli(['drop-request', 'System-1', 'ForceOff', '0']) + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + self.assertEqual(self.audit()[-1]['fault'], 'drop-request-before-effect') + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'On') + # A dropped response after a power-off: the effect is applied. + adapter.fault_cli(['drop-response', 'System-1', 'ForceOff', '0']) + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + self.assertEqual(self.audit()[-1]['fault'], 'drop-response-after-effect') + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'Off') + + def test_7_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): s = virsh_state() s['domains'].pop('fleet-lab-target-a') s['networks'].clear()