From b063aebb9ce3e85cd018ac53dd1c5ac2dc8f1fdf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 14:43:32 -0600 Subject: [PATCH 1/4] feat(bmc-discovery): Tell a failed reset type read from none offered An omitted resetTypes meant both "the BMC offers none" and "the read failed". The field now uses omitzero, so an empty advertised list, inline or from the ActionInfo, is stored as []. The previous omitempty tag dropped it on every marshal, including the Device's JSON deep copy. An omitted list now always means unknown. A new ResetTypesRead condition reports why the list is unknown: ResetActionMalformed, ActionInfoNotFound, ActionInfoUnreadable, ActionInfoMalformed or TooManyResetTypes. More than 16 distinct types is now unknown instead of a truncated list, which would refuse a type the BMC offers. Discovered and the rest of the inventory are unchanged, and a rejected credential still fails the whole read. Co-Authored-By: Claude Opus 5.5 --- docs/operations/bmc-discovery.md | 41 +++- .../inventory/v1alpha1/reset_types_test.go | 131 ++++++++++++ internal/api/inventory/v1alpha1/types.go | 11 +- internal/bmcdiscovery/reset_types_test.go | 196 ++++++++++++++++++ internal/bmcdiscovery/status.go | 64 +++++- internal/bmcdiscovery/status_test.go | 42 +++- internal/redfish/inventory.go | 23 +- internal/redfish/reset.go | 48 ++++- internal/redfish/reset_test.go | 75 ++++++- 9 files changed, 579 insertions(+), 52 deletions(-) create mode 100644 internal/api/inventory/v1alpha1/reset_types_test.go create mode 100644 internal/bmcdiscovery/reset_types_test.go diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 49a45f7f..3b5fe081 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -296,6 +296,7 @@ lowercase canonical. Power state is an observation; discovery never changes it. | `Discovered` | `InventoryRead`; False for a definite refusal (the reason above); Unknown `Unreachable`, `ReadFailed` | | `IdentityMatched` | `Matched`; False `SystemUUIDMismatch`, `SerialMismatch`, `ModelMismatch`; Unknown `NotObserved`, `StaleObservation`, `AmbiguousSystem` | | `PublicKeyUnique` | `Unique`; False `SharedPublicKey`; Unknown `NotObserved` | +| `ResetTypesRead` | `ResetTypesRead`; False `ResetActionMalformed`, `ActionInfoNotFound`, `ActionInfoUnreadable`, `ActionInfoMalformed`, `TooManyResetTypes`. Set with each recorded inventory; see [What is read](#what-is-read) | Messages never carry a URL, credential, header or response body. @@ -329,14 +330,34 @@ Service root, then every Manager and every ComputerSystem (up to 16 of each), 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`. It reads the action's description -and never invokes it. It keeps at most 16 distinct values. Malformed actions, -a reset target off the System, an ActionInfo off the System or under its -Actions, or an ActionInfo that cannot be read (missing, malformed, a server -error or a timeout) records none and keeps the rest of the inventory. A -rejected credential (401 or 403), a pin mismatch or an unexpected resource -path on the ActionInfo fails the read. Nothing reads `resetTypes` yet: it is -recorded for planned Device power operations, which will refuse an action the -server does not offer. +and never invokes it. + +| `resetTypes` | Meaning | +| --- | --- | +| Omitted (no key) | Unknown. The System advertises no list (no reset action, or one without allowable values), or the list could not be read. | +| `[]` | The BMC advertises an empty list: it offers no reset type. | +| `["On", ForceOff]` | The reset types offered. Any type not listed is not offered. | + +`ResetTypesRead` tells a failed read from an unadvertised list. It is False, +and `resetTypes` omitted, when the reset action is malformed or not on the +System (`ResetActionMalformed`), the ActionInfo is missing +(`ActionInfoNotFound`), a server error or timeout stops the read +(`ActionInfoUnreadable`), the response is not an ActionInfo +(`ActionInfoMalformed`), or the BMC advertises more than 16 distinct types +(`TooManyResetTypes`), since a partial list would refuse a type the BMC +offers. The message names each affected System. The rest of the inventory is +kept and `Discovered` stays True. A rejected credential (401 or 403), a pin +mismatch or an unexpected resource path on the ActionInfo fails the whole read, +as for any other document. + +A separate condition, rather than a reason on `Discovered` or an event, keeps +`Discovered` meaning the inventory was read, and puts the outcome in status +next to the list it qualifies, where a reader finds it after events expire. +It changes only when a new inventory is recorded. + +Nothing reads `resetTypes` yet. Planned Device power operations will admit an +action when the list is omitted and check the live BMC, and refuse it when the +list is empty or does not contain it. Collections follow `Members@odata.nextLink` for up to 8 pages. Every member must sit under its collection. Documents are decoded leniently: only the @@ -367,6 +388,10 @@ sessions. Basic authentication is used; no Redfish session is created. - end to end against an `httptest` TLS service: first contact records the pin with no credential sent, then approval yields inventory and `IdentityMatched=True`; +- each `resetTypes` outcome as stored through the status patch: a list, an + empty list, or omitted with the `ResetTypesRead` reason, and a status + round trip through a disposable API server that keeps `[]` apart from + omitted; - the Device status schema, the discoverer role, and the shipped Deployment's single unprivileged replica. diff --git a/internal/api/inventory/v1alpha1/reset_types_test.go b/internal/api/inventory/v1alpha1/reset_types_test.go new file mode 100644 index 00000000..d039ad22 --- /dev/null +++ b/internal/api/inventory/v1alpha1/reset_types_test.go @@ -0,0 +1,131 @@ +package v1alpha1 + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// resetTypesJSON is the serialized resetTypes of the first System, or "" when +// the field is omitted. +func resetTypesJSON(t *testing.T, d *Device) string { + t.Helper() + b, err := json.Marshal(d.Status.Discovery.Inventory.Systems[0]) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(b, &fields); err != nil { + t.Fatal(err) + } + return string(fields["resetTypes"]) +} + +// An empty resetTypes (the BMC offers none) is serialized, admitted, kept by +// pruning and kept by DeepCopy; an unset one (unknown) is omitted. +func TestResetTypesKeepEmptyApartFromOmitted(t *testing.T) { + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + types []string + want string + }{{nil, ""}, {[]string{}, "[]"}, {[]string{"On"}, `["On"]`}} { + device := discoveredDevice() + device.Status.Discovery.Inventory.Systems[0].ResetTypes = tc.types + if got := resetTypesJSON(t, &device); got != tc.want { + t.Fatalf("serialized %#v as %q, want %q", tc.types, got, tc.want) + } + if got := resetTypesJSON(t, device.DeepCopyObject().(*Device)); got != tc.want { + t.Fatalf("DeepCopy of %#v serialized as %q, want %q", tc.types, got, tc.want) + } + if errs := admit(t, "Device", object(t, device), nil); len(errs) > 0 { + t.Fatalf("resetTypes %#v rejected: %v", tc.types, errs) + } + pruned := object(t, device) + pruning.Prune(pruned, structural, true) + system := pruned["status"].(map[string]any)["discovery"].(map[string]any)["inventory"].(map[string]any)["systems"].([]any)[0].(map[string]any) + if got, ok := system["resetTypes"]; ok != (tc.want != "") || ok && len(got.([]any)) != len(tc.types) { + t.Fatalf("pruned resetTypes %#v to %#v", tc.types, got) + } + } +} + +// A status merge patch through the API server stores a list, an empty list +// and an omitted list distinctly, and moves between them. +func TestResetTypesRoundTripThroughTheAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable Device status validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system"}}); err != nil { + t.Fatal(err) + } + device := syntheticDevice() + if err := api.Create(ctx, &device); err != nil { + t.Fatal(err) + } + status := discoveredDevice().Status + for _, types := range [][]string{{"On", "ForceOff"}, {}, nil, {}, {"On"}} { + var stored Device + if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &stored); err != nil { + t.Fatal(err) + } + patch := client.MergeFromWithOptions(stored.DeepCopyObject().(*Device), client.MergeFromWithOptimisticLock{}) + deepCopy(&status, &stored.Status) + stored.Status.Discovery.Inventory.Systems[0].ResetTypes = types + want := resetTypesJSON(t, &stored) + if err := api.Status().Patch(ctx, &stored, patch); err != nil { + t.Fatalf("patch resetTypes %#v: %v", types, err) + } + var read Device + if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &read); err != nil { + t.Fatal(err) + } + if got := resetTypesJSON(t, &read); got != want || (types == nil) != (read.Status.Discovery.Inventory.Systems[0].ResetTypes == nil) { + t.Fatalf("stored resetTypes %#v as %q, want %q", types, got, want) + } + if types != nil && !strings.HasPrefix(want, "[") { + t.Fatalf("resetTypes %#v serialized as %q", types, want) + } + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 562a23f9..3e13ab3f 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -190,8 +190,8 @@ type DeviceStatus struct { // Discovery holds the latest observations. A failed attempt never clears // them: each keeps its own time and endpoint. Discovery *DeviceDiscovery `json:"discovery,omitempty"` - // Conditions are Reachable, Authenticated, Discovered, IdentityMatched and - // PublicKeyUnique. + // Conditions are Reachable, Authenticated, Discovered, IdentityMatched, + // PublicKeyUnique and ResetTypesRead. Conditions []metav1.Condition `json:"conditions,omitempty"` } @@ -202,6 +202,7 @@ const ( ConditionDiscovered = "Discovered" ConditionIdentityMatched = "IdentityMatched" ConditionPublicKeyUnique = "PublicKeyUnique" + ConditionResetTypesRead = "ResetTypesRead" ) // DeviceDiscovery is the retained BMC observation of a Device. @@ -257,7 +258,9 @@ type ObservedManager struct { // ObservedSystem is one Redfish ComputerSystem. PowerState is an observation // only; discovery never changes power. ResetTypes are the ComputerSystem.Reset -// types the BMC advertises for the System, read but never invoked. +// types the BMC advertises for the System, read but never invoked: omitted +// (nil) when they are unknown, an empty list when the BMC offers none. Use +// omitzero, not omitempty, so an empty list is kept. type ObservedSystem struct { ID string `json:"id"` UUID string `json:"uuid,omitempty"` @@ -267,7 +270,7 @@ type ObservedSystem struct { SKU string `json:"sku,omitempty"` PowerState string `json:"powerState,omitempty"` NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` - ResetTypes []string `json:"resetTypes,omitempty"` + ResetTypes []string `json:"resetTypes,omitzero"` } // ObservedNetworkInterface is one Redfish EthernetInterface. diff --git a/internal/bmcdiscovery/reset_types_test.go b/internal/bmcdiscovery/reset_types_test.go new file mode 100644 index 00000000..dec4492c --- /dev/null +++ b/internal/bmcdiscovery/reset_types_test.go @@ -0,0 +1,196 @@ +package bmcdiscovery + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/redfish" +) + +// resetBMC serves one System whose reset action and ActionInfo a test sets. +type resetBMC struct { + mu sync.Mutex + actions string // the System's Actions JSON; empty for none + info func(w http.ResponseWriter, r *http.Request) + requests []string +} + +func (b *resetBMC) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + b.requests = append(b.requests, r.Method+" "+r.URL.Path) + actions, info := b.actions, b.info + b.mu.Unlock() + if user, pass, _ := r.BasicAuth(); r.URL.Path != "/redfish/v1/" && (user != "operator" || pass != "synthetic-secret") { + w.WriteHeader(http.StatusUnauthorized) + return + } + if actions != "" { + actions = `,"Actions":` + actions + } + docs := map[string]string{ + "/redfish/v1/": `{"RedfishVersion":"1.15.0","Systems":{"@odata.id":"/redfish/v1/Systems"},"Managers":{"@odata.id":"/redfish/v1/Managers"}}`, + "/redfish/v1/Managers": `{"Members":[]}`, + "/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"` + actions + `}`, + } + if r.URL.Path == "/redfish/v1/Systems/1/ResetActionInfo" && info != nil && r.Method == http.MethodGet { + info(w, r) + return + } + doc, ok := docs[r.URL.Path] + if !ok || r.Method != http.MethodGet { + w.WriteHeader(http.StatusNotFound) + return + } + w.Write([]byte(doc)) +} + +const ( + inlineReset = `{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","ResetType@Redfish.AllowableValues":%s}}` + infoReset = `{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","@Redfish.ActionInfo":"/redfish/v1/Systems/1/ResetActionInfo"}}` +) + +func actionInfo(values string) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { + w.Write([]byte(`{"Parameters":[{"Name":"ResetType","Required":"true","DataType":"String","AllowableValues":` + values + `}]}`)) + } +} + +func replyStatus(code int) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(code) } +} + +// resetHarness reconciles one Device against bmc over TLS with an approved +// pin, through the real Redfish client and a status merge patch. +func resetHarness(t *testing.T, bmc *resetBMC) (*harness, func() *inventory.Device) { + t.Helper() + server := httptest.NewTLSServer(bmc) + t.Cleanup(server.Close) + h := newHarness(t, device("example-device-01", server.URL), secret("example-device-01", redfish.PublicKeySHA256(server.Certificate()))) + h.r.BMC = RedfishBMC{Timeout: time.Second} + return h, func() *inventory.Device { + h.reconcile(t, "example-device-01") + h.now = h.now.Add(2 * time.Hour) + return h.get(t, "example-device-01") + } +} + +// systemJSON is the stored System as the API serializes it. +func systemJSON(t *testing.T, d *inventory.Device) string { + t.Helper() + if d.Status.Discovery == nil || d.Status.Discovery.Inventory == nil || len(d.Status.Discovery.Inventory.Systems) != 1 { + t.Fatalf("no recorded System: %+v", d.Status) + } + b, err := json.Marshal(d.Status.Discovery.Inventory.Systems[0]) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// Each way the BMC can describe its reset action is stored distinctly: +// a list, an empty list (offers none), or omitted (unknown) with +// ResetTypesRead False and the reason. None of them changes Discovered. +func TestResetTypesStatus(t *testing.T) { + for name, tc := range map[string]struct { + actions string + info func(http.ResponseWriter, *http.Request) + want string // the stored resetTypes JSON; empty for omitted + status metav1.ConditionStatus + reason string + }{ + "inline values": {strings.Replace(inlineReset, "%s", `["On","ForceOff"]`, 1), nil, `"resetTypes":["On","ForceOff"]`, metav1.ConditionTrue, ReasonResetTypesRead}, + "inline empty": {strings.Replace(inlineReset, "%s", `[]`, 1), nil, `"resetTypes":[]`, metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo": {infoReset, actionInfo(`["On","ForceOff","ForceRestart"]`), `"resetTypes":["On","ForceOff","ForceRestart"]`, metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo empty": {infoReset, actionInfo(`[]`), `"resetTypes":[]`, metav1.ConditionTrue, ReasonResetTypesRead}, + "no actions": {"", nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, + "no reset action": {`{"#ComputerSystem.Other":{}}`, nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, + "no list": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset"}}`, nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo 404": {infoReset, replyStatus(http.StatusNotFound), "", metav1.ConditionFalse, ReasonActionInfoNotFound}, + "actioninfo 500": {infoReset, replyStatus(http.StatusInternalServerError), "", metav1.ConditionFalse, ReasonActionInfoUnreadable}, + "actioninfo timeout": {infoReset, func(_ http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(5 * time.Second): + } + }, "", metav1.ConditionFalse, ReasonActionInfoUnreadable}, + "actioninfo malformed": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":"none"}`)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "actioninfo not json": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(``)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "actions malformed": {`"not actions"`, nil, "", metav1.ConditionFalse, ReasonResetActionMalformed}, + } { + t.Run(name, func(t *testing.T) { + bmc := &resetBMC{actions: tc.actions, info: tc.info} + _, reconcile := resetHarness(t, bmc) + got := reconcile() + stored := systemJSON(t, got) + if tc.want == "" && strings.Contains(stored, "resetTypes") || tc.want != "" && !strings.Contains(stored, tc.want) { + t.Fatalf("stored System = %s, want %s", stored, tc.want) + } + if c := condition(t, got.Status, inventory.ConditionResetTypesRead); c.Status != tc.status || c.Reason != tc.reason || c.ObservedGeneration != 1 { + t.Fatalf("ResetTypesRead = %+v", c) + } + if c := condition(t, got.Status, inventory.ConditionDiscovered); c.Status != metav1.ConditionTrue || c.Reason != ReasonInventoryRead { + t.Fatalf("Discovered = %+v", c) + } + for _, r := range bmc.requests { + if !strings.HasPrefix(r, "GET ") || strings.Contains(r, "/Actions") { + t.Fatalf("discovery issued %s", r) + } + } + }) + } +} + +// A rejected credential on the ActionInfo still fails the whole read, as for +// any other document, and records no inventory or ResetTypesRead. +func TestResetTypesRejectedCredentialFailsTheRead(t *testing.T) { + for _, code := range []int{http.StatusUnauthorized, http.StatusForbidden} { + _, reconcile := resetHarness(t, &resetBMC{actions: infoReset, info: replyStatus(code)}) + got := reconcile() + if got.Status.Discovery.Inventory != nil { + t.Fatalf("%d: inventory recorded: %+v", code, got.Status.Discovery.Inventory) + } + if c := condition(t, got.Status, inventory.ConditionDiscovered); c.Status != metav1.ConditionFalse || c.Reason != ReasonCredentialRejected { + t.Fatalf("%d: Discovered = %+v", code, c) + } + for _, c := range got.Status.Conditions { + if c.Type == inventory.ConditionResetTypesRead { + t.Fatalf("%d: ResetTypesRead set without an inventory: %+v", code, c) + } + } + } +} + +// The stored list moves between present, empty and omitted across reads: the +// status patch carries an empty list and removes an omitted one. A failed +// read clears a previously recorded list rather than keeping a stale one. +func TestResetTypesTransitionsThroughTheStatusPatch(t *testing.T) { + bmc := &resetBMC{actions: infoReset, info: actionInfo(`["On","ForceOff"]`)} + _, reconcile := resetHarness(t, bmc) + for _, step := range []struct { + info func(http.ResponseWriter, *http.Request) + want string + }{ + {actionInfo(`["On","ForceOff"]`), `"resetTypes":["On","ForceOff"]`}, + {actionInfo(`[]`), `"resetTypes":[]`}, + {replyStatus(http.StatusNotFound), ""}, + {actionInfo(`[]`), `"resetTypes":[]`}, + {actionInfo(`["On"]`), `"resetTypes":["On"]`}, + } { + bmc.mu.Lock() + bmc.info = step.info + bmc.mu.Unlock() + stored := systemJSON(t, reconcile()) + if step.want == "" && strings.Contains(stored, "resetTypes") || step.want != "" && !strings.Contains(stored, step.want) { + t.Fatalf("stored System = %s, want %s", stored, step.want) + } + } +} diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go index 954e6e93..7ccc84ff 100644 --- a/internal/bmcdiscovery/status.go +++ b/internal/bmcdiscovery/status.go @@ -66,6 +66,12 @@ const ( ReasonModelMismatch = "ModelMismatch" ReasonUnique = "Unique" ReasonSharedPublicKey = "SharedPublicKey" + ReasonResetTypesRead = "ResetTypesRead" + ReasonResetActionMalformed = "ResetActionMalformed" + ReasonActionInfoNotFound = "ActionInfoNotFound" + ReasonActionInfoUnreadable = "ActionInfoUnreadable" + ReasonActionInfoMalformed = "ActionInfoMalformed" + ReasonTooManyResetTypes = "TooManyResetTypes" ) // attempt is the outcome of contacting one BMC once. @@ -75,7 +81,8 @@ type attempt struct { cert *redfish.Certificate root *redfish.ServiceRoot inv *redfish.Inventory - // conditions set by the attempt: Reachable, Authenticated, Discovered. + // conditions set by the attempt: Reachable, Authenticated, Discovered, + // and ResetTypesRead when an inventory is recorded. conditions []metav1.Condition // uncertain attempts are retried with backoff; definite refusals wait for // the interval or a credential change. A rejected credential is never @@ -186,7 +193,9 @@ func apply(status *inventory.DeviceStatus, a attempt, generation int64) { UUID: canonicalUUIDOrEmpty(a.root.UUID), Vendor: clip(a.root.Vendor, 253), Product: clip(a.root.Product, 253)} } if a.inv != nil { - d.Inventory = observedInventory(*a.inv, a.at, a.endpoint) + var read metav1.Condition + d.Inventory, read = observedInventory(*a.inv, a.at, a.endpoint) + a.conditions = append(a.conditions, read) } for _, c := range a.conditions { setCondition(status, c, generation, a.at) @@ -198,7 +207,9 @@ func setCondition(status *inventory.DeviceStatus, c metav1.Condition, generation meta.SetStatusCondition(&status.Conditions, c) } -func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) *inventory.ObservedInventory { +// observedInventory also returns ResetTypesRead for the recorded Systems. It +// describes the retained inventory, so it changes only with a new one. +func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) (*inventory.ObservedInventory, metav1.Condition) { nics := func(in []redfish.NetworkInterface) []inventory.ObservedNetworkInterface { var out []inventory.ObservedNetworkInterface for _, n := range in { @@ -215,26 +226,57 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) * out.Managers = append(out.Managers, inventory.ObservedManager{ID: clip(m.ID, 253), Model: clip(m.Model, 253), FirmwareVersion: clip(m.FirmwareVersion, 253), NetworkInterfaces: nics(m.NetworkInterfaces)}) } } + read := cond(inventory.ConditionResetTypesRead, metav1.ConditionTrue, ReasonResetTypesRead, "every System's reset types were read") + var unread []string for _, s := range inv.Systems { if s.ID != "" && len(out.Systems) < 16 { + types, reason, why := resetTypes(s.ResetTypes, s.ResetTypesUnread) 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), - ResetTypes: resetTypes(s.ResetTypes)}) + ResetTypes: types}) + if reason != "" { + if len(unread) == 0 { + read.Reason = reason + } + unread = append(unread, "System "+clip(s.ID, 63)+": "+why) + } } } - return out + if len(unread) > 0 { + read.Status, read.Message = metav1.ConditionFalse, "resetTypes is omitted, so unknown, for "+strings.Join(unread, "; ") + } + return out, read } -// resetTypes keeps up to 16 distinct, nonempty advertised reset types. -func resetTypes(in []string) []string { - var out []string +// resetTypes keeps the advertised reset types, distinct and nonempty: nil +// when they are unknown, empty when the BMC offers none. A read that failed, +// or more than 16 distinct values, leaves them unknown with a reason, because +// a partial list would refuse an action the BMC offers. +func resetTypes(in []string, unread error) (types []string, reason, why string) { + var status redfish.Status + switch { + case errors.Is(unread, redfish.ErrUnsupported): + return nil, ReasonResetActionMalformed, "the ComputerSystem.Reset action is malformed or not on the System" + case errors.As(unread, &status) && status.Code == 404: + return nil, ReasonActionInfoNotFound, "the reset ActionInfo returned HTTP 404" + case errors.Is(unread, redfish.ErrMalformed): + return nil, ReasonActionInfoMalformed, "the reset ActionInfo is not an ActionInfo document" + case unread != nil: + return nil, ReasonActionInfoUnreadable, "the reset ActionInfo read failed: " + safe(unread) + case in == nil: + return nil, "", "" + } + types = []string{} for _, v := range in { v = clip(v, 63) - if v != "" && !slices.Contains(out, v) && len(out) < 16 { - out = append(out, v) + if v != "" && !slices.Contains(types, v) { + if len(types) == 16 { + return nil, ReasonTooManyResetTypes, "the BMC advertises more than 16 reset types" + } + types = append(types, v) } } - return out + return types, "", "" } func clip(s string, n int) string { diff --git a/internal/bmcdiscovery/status_test.go b/internal/bmcdiscovery/status_test.go index 2893ae01..32ea6e96 100644 --- a/internal/bmcdiscovery/status_test.go +++ b/internal/bmcdiscovery/status_test.go @@ -5,17 +5,47 @@ import ( "slices" "strings" "testing" + + "go.datum.net/fleet/internal/redfish" ) -// Recorded reset types stay within the Device schema: at most 16 distinct, -// nonempty values of at most 63 characters each. +// Recorded reset types stay within the Device schema: distinct, nonempty +// values of at most 63 characters. More than 16 distinct values are unknown, +// not a partial list, because a partial list would refuse an offered action. func TestResetTypesStayWithinTheSchema(t *testing.T) { in := []string{"On", " On ", "", " ", strings.Repeat("x", 80)} - for i := range 20 { + for i := range 14 { in = append(in, fmt.Sprintf("Vendor%d", i)) } - got := resetTypes(in) - if len(got) != 16 || !slices.Equal(got[:2], []string{"On", strings.Repeat("x", 63)}) || got[15] != "Vendor13" { - t.Fatalf("resetTypes = %v", got) + got, reason, _ := resetTypes(in, nil) + if len(got) != 16 || !slices.Equal(got[:2], []string{"On", strings.Repeat("x", 63)}) || got[15] != "Vendor13" || reason != "" { + t.Fatalf("resetTypes = %v, %s", got, reason) + } + got, reason, _ = resetTypes(append(in, "Vendor14"), nil) + if got != nil || reason != ReasonTooManyResetTypes { + t.Fatalf("17 values = %v, %s", got, reason) + } +} + +// Unknown stays nil and offers-none stays empty, including a list of blanks. +func TestResetTypesKeepUnknownApartFromNone(t *testing.T) { + if got, reason, _ := resetTypes(nil, nil); got != nil || reason != "" { + t.Fatalf("no list = %#v, %s", got, reason) + } + for _, in := range [][]string{{}, {"", " "}} { + if got, reason, _ := resetTypes(in, nil); got == nil || len(got) != 0 || reason != "" { + t.Fatalf("%q = %#v, %s", in, got, reason) + } + } + for err, want := range map[error]string{ + redfish.ErrUnsupported: ReasonResetActionMalformed, + redfish.Status{Code: 404}: ReasonActionInfoNotFound, + redfish.ErrMalformed: ReasonActionInfoMalformed, + redfish.Status{Code: 503}: ReasonActionInfoUnreadable, + fmt.Errorf("timeout"): ReasonActionInfoUnreadable, + } { + if got, reason, _ := resetTypes([]string{"On"}, err); got != nil || reason != want { + t.Fatalf("%v = %#v, %s; want %s", err, got, reason, want) + } } } diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index ecc79294..5e136066 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -44,9 +44,13 @@ type InventorySystem struct { PowerState string // NetworkInterfaces are the System's EthernetInterfaces. NetworkInterfaces []NetworkInterface - // ResetTypes are the ComputerSystem.Reset types the System advertises. + // ResetTypes are the ComputerSystem.Reset types the System advertises: + // nil when it advertises no list, empty when it advertises an empty one. // Discovery reads them and never invokes the action. ResetTypes []string + // ResetTypesUnread is why the reset types could not be read, with + // ResetTypes nil. The rest of the System is still read. + ResetTypesUnread error } // NetworkInterface is one Redfish EthernetInterface. @@ -63,7 +67,9 @@ type NetworkInterface struct { // decoded leniently: only the named properties are read, and a vendor // property with an off-schema type elsewhere in a document is ignored. Any // failed read fails the whole observation; nothing partial is returned. The -// optional reset types are the exception: see below. +// optional reset types are the exception: an unreadable reset action is +// recorded per System, and only a rejected credential, pin or identity fails +// the read. func (c *Client) Inventory(ctx context.Context) (Inventory, error) { api, err := c.connect(ctx) if err != nil { @@ -126,17 +132,8 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { } 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} - // Reset types are optional. Malformed actions, a reset target or - // ActionInfo off the System, or an ActionInfo that cannot be read - // records none and keeps the rest of the inventory. Only a - // rejected credential, pin or identity fails the read. - var raw resetAction - if json.Unmarshal(doc.Actions, &raw.Actions) == nil && raw.Actions.Reset.Target != "" { - if _, types, err := resetTypes(api, p, raw); err == nil { - system.ResetTypes = types - } else if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { - return Inventory{}, err - } + if system.ResetTypes, system.ResetTypesUnread, err = systemResetTypes(api, p, doc.Actions); err != nil { + return Inventory{}, err } inv.Systems = append(inv.Systems, system) } diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go index f3ff6000..8a053d78 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -1,16 +1,26 @@ package redfish import ( + "encoding/json" + "errors" "fmt" + "io" "strings" "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" ) +// ErrMalformed means a document the BMC returned is not of the expected +// shape. +var ErrMalformed = errors.New("redfish: malformed document") + // 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, and the ActionInfo must not sit under its Actions. It // issues at most one GET, of the ActionInfo, and never invokes the action. +// Types are nil when the BMC advertises no list, and empty but not nil when it +// advertises an empty one. func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, err error) { reset := raw.Actions.Reset target, err = cleanPath(reset.Target) @@ -33,8 +43,19 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target AllowableValues []string } } - if err := getJSON(api, info, &ai); err != nil { - return "", nil, err + resp, err := api.Get(info) + if err == nil { + var syntax *json.SyntaxError + var typed *json.UnmarshalTypeError + if err = json.NewDecoder(resp.Body).Decode(&ai); errors.As(err, &syntax) || errors.As(err, &typed) || errors.Is(err, io.EOF) { + err = ErrMalformed + } + } + schemas.DeferredCleanupHTTPResponse(resp) + if errors.Is(err, ErrMalformed) { + return "", nil, ErrMalformed + } else if err != nil { + return "", nil, classify(err) } for _, p := range ai.Parameters { if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { @@ -43,3 +64,26 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target } return target, types, nil } + +// systemResetTypes reads the reset types of the System at sysPath from its +// Actions for the inventory. A System without a reset action advertises no +// list. unread is why the types could not be read; the inventory keeps the +// System. Only a rejected credential, pin or identity is fatal and fails the +// whole read. +func systemResetTypes(api *gofish.APIClient, sysPath string, actions json.RawMessage) (types []string, unread, fatal error) { + if len(actions) == 0 { + return nil, nil, nil + } + var raw resetAction + if err := json.Unmarshal(actions, &raw.Actions); err != nil { + return nil, fmt.Errorf("%w: ComputerSystem.Reset action malformed", ErrUnsupported), nil + } + if r := raw.Actions.Reset; r.Target == "" && r.Info == "" && r.Allowed == nil { + return nil, nil, nil + } + _, types, err := resetTypes(api, sysPath, raw) + if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { + return nil, nil, err + } + return types, err, nil +} diff --git a/internal/redfish/reset_test.go b/internal/redfish/reset_test.go index f8a2a63f..e2b131b0 100644 --- a/internal/redfish/reset_test.go +++ b/internal/redfish/reset_test.go @@ -13,13 +13,18 @@ import ( ) // Discovery reads offered reset types inline or from the System's own -// ActionInfo, with GETs only. A reset target off the System records none. +// ActionInfo, with GETs only. An empty advertised list stays empty, a reset +// action without a list records none, and a reset target off the System +// records none with the reason. func TestInventoryRecordsResetTypes(t *testing.T) { bmc := newInventoryBMC() bmc.docs["/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"}, map[string]string{"@odata.id": "/redfish/v1/Systems/3"}, + map[string]string{"@odata.id": "/redfish/v1/Systems/4"}, + map[string]string{"@odata.id": "/redfish/v1/Systems/5"}, + map[string]string{"@odata.id": "/redfish/v1/Systems/6"}, }} bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}} @@ -29,6 +34,13 @@ func TestInventoryRecordsResetTypes(t *testing.T) { "target": "/redfish/v1/Systems/2/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "PowerCycle"}}}} bmc.docs["/redfish/v1/Systems/3"] = map[string]any{"Id": "3", "UUID": "00000000-0000-4000-8000-0000000000c3", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On"}}}} + bmc.docs["/redfish/v1/Systems/4"] = map[string]any{"Id": "4", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/4/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{}}}} + bmc.docs["/redfish/v1/Systems/5"] = map[string]any{"Id": "5", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/5/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/5/ResetActionInfo"}}} + bmc.docs["/redfish/v1/Systems/5/ResetActionInfo"] = map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "DataType": "String", "AllowableValues": []string{}}}} + bmc.docs["/redfish/v1/Systems/6"] = map[string]any{"Id": "6", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/6/Actions/ComputerSystem.Reset"}}} server := httptest.NewTLSServer(bmc) t.Cleanup(server.Close) client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), 5*time.Second) @@ -39,10 +51,20 @@ func TestInventoryRecordsResetTypes(t *testing.T) { if err != nil { t.Fatal(err) } - if len(inv.Systems) != 3 || !slices.Equal(inv.Systems[0].ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) || - !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) || inv.Systems[2].ResetTypes != nil { + if len(inv.Systems) != 6 || !slices.Equal(inv.Systems[0].ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) || + !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) || inv.Systems[2].ResetTypes != nil || !errors.Is(inv.Systems[2].ResetTypesUnread, ErrUnsupported) { t.Fatalf("systems = %+v", inv.Systems) } + for _, i := range []int{3, 4} { + if s := inv.Systems[i]; s.ResetTypes == nil || len(s.ResetTypes) != 0 || s.ResetTypesUnread != nil { + t.Fatalf("System %s offers none: %#v, %v", s.ID, s.ResetTypes, s.ResetTypesUnread) + } + } + for _, i := range []int{0, 1, 5} { + if s := inv.Systems[i]; s.ResetTypesUnread != nil || (i == 5 && s.ResetTypes != nil) { + t.Fatalf("System %s: %#v, %v", s.ID, s.ResetTypes, s.ResetTypesUnread) + } + } requests, _ := bmc.seen() for _, request := range requests { if !strings.HasPrefix(request, "GET ") || strings.Contains(request, "/Actions/") { @@ -51,8 +73,8 @@ func TestInventoryRecordsResetTypes(t *testing.T) { } } -// An ActionInfo that cannot be read records no reset types and keeps the -// rest of the inventory. +// An ActionInfo that cannot be read records no reset types, keeps the rest of +// the inventory, and says why. func TestInventoryKeepsTheSystemWhenActionInfoFails(t *testing.T) { for name, info := range map[string]any{"missing": nil, "malformed": "not an ActionInfo"} { t.Run(name, func(t *testing.T) { @@ -75,6 +97,10 @@ func TestInventoryKeepsTheSystemWhenActionInfoFails(t *testing.T) { if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { t.Fatalf("systems = %+v", inv.Systems) } + unread := inv.Systems[0].ResetTypesUnread + if name == "missing" && unread != (Status{http.StatusNotFound}) || name == "malformed" && !errors.Is(unread, ErrMalformed) { + t.Fatalf("unread = %v", unread) + } }) } } @@ -93,7 +119,8 @@ func TestInventoryKeepsTheSystemWhenActionsAreMalformed(t *testing.T) { bmc := newInventoryBMC() bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = actions inv := inventoryOf(t, bmc) - if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 || + !errors.Is(inv.Systems[0].ResetTypesUnread, ErrUnsupported) { t.Fatalf("systems = %+v", inv.Systems) } }) @@ -121,7 +148,7 @@ func TestInventoryNeverReadsAGuardedActionInfo(t *testing.T) { bmc.docs[p] = offered } inv := inventoryOf(t, bmc) - if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 || inv.Systems[0].ResetTypesUnread == nil { t.Fatalf("systems = %+v", inv.Systems) } requests, _ := bmc.seen() @@ -164,13 +191,45 @@ func TestInventoryActionInfoStatus(t *testing.T) { } return } - if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 || + inv.Systems[0].ResetTypesUnread != (Status{tc.status}) { t.Fatalf("inventory = %+v, err = %v", inv, err) } }) } } +// An ActionInfo read that times out records no reset types and keeps the +// inventory, as unreadable rather than missing or malformed. +func TestInventoryActionInfoTimeout(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}} + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/redfish/v1/Systems/1/ResetActionInfo" { + select { + case <-r.Context().Done(): + case <-time.After(5 * time.Second): + } + return + } + bmc.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := client.Inventory(context.Background()) + if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + t.Fatalf("inventory = %+v, err = %v", inv, err) + } + var status Status + if unread := inv.Systems[0].ResetTypesUnread; unread == nil || errors.As(unread, &status) || errors.Is(unread, ErrMalformed) { + t.Fatalf("unread = %v", unread) + } +} + func inventoryOf(t *testing.T, bmc *inventoryBMC) Inventory { t.Helper() server := httptest.NewTLSServer(bmc) From dbbeb96a9bb6db6223f328c388403230143d30fc Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 14:49:54 -0600 Subject: [PATCH 2/4] fix(bmc-discovery): Treat a blank reset list as unknown A reset type list of only blank or null values was stored as an empty list, which reads as "offers none" and would refuse every action. It is now unknown with ResetActionMalformed. A truncated ActionInfo body is ActionInfoMalformed rather than unreadable. The True ResetTypesRead message and the docs now say it means no read failed, not that a list was recorded. Co-Authored-By: Claude Opus 5.5 --- docs/operations/bmc-discovery.md | 5 +++-- internal/bmcdiscovery/reset_types_test.go | 2 ++ internal/bmcdiscovery/status.go | 12 ++++++++---- internal/bmcdiscovery/status_test.go | 12 +++++++----- internal/redfish/reset.go | 2 +- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 3b5fe081..428927d8 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -340,7 +340,7 @@ and never invokes it. `ResetTypesRead` tells a failed read from an unadvertised list. It is False, and `resetTypes` omitted, when the reset action is malformed or not on the -System (`ResetActionMalformed`), the ActionInfo is missing +System, or the list holds only blank values (`ResetActionMalformed`), the ActionInfo is missing (`ActionInfoNotFound`), a server error or timeout stops the read (`ActionInfoUnreadable`), the response is not an ActionInfo (`ActionInfoMalformed`), or the BMC advertises more than 16 distinct types @@ -348,7 +348,8 @@ System (`ResetActionMalformed`), the ActionInfo is missing offers. The message names each affected System. The rest of the inventory is kept and `Discovered` stays True. A rejected credential (401 or 403), a pin mismatch or an unexpected resource path on the ActionInfo fails the whole read, -as for any other document. +as for any other document. True means no read failed. It does not mean a list +was recorded: an omitted list with True means the System advertises no list. A separate condition, rather than a reason on `Discovered` or an event, keeps `Discovered` meaning the inventory was read, and puts the outcome in status diff --git a/internal/bmcdiscovery/reset_types_test.go b/internal/bmcdiscovery/reset_types_test.go index dec4492c..1f936771 100644 --- a/internal/bmcdiscovery/reset_types_test.go +++ b/internal/bmcdiscovery/reset_types_test.go @@ -124,6 +124,8 @@ func TestResetTypesStatus(t *testing.T) { }, "", metav1.ConditionFalse, ReasonActionInfoUnreadable}, "actioninfo malformed": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":"none"}`)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, "actioninfo not json": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(``)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "actioninfo truncated": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":[{"Name":"ResetType"`)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "inline blanks": {strings.Replace(inlineReset, "%s", `[null,""]`, 1), nil, "", metav1.ConditionFalse, ReasonResetActionMalformed}, "actions malformed": {`"not actions"`, nil, "", metav1.ConditionFalse, ReasonResetActionMalformed}, } { t.Run(name, func(t *testing.T) { diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go index 7ccc84ff..28af3907 100644 --- a/internal/bmcdiscovery/status.go +++ b/internal/bmcdiscovery/status.go @@ -226,7 +226,7 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) ( out.Managers = append(out.Managers, inventory.ObservedManager{ID: clip(m.ID, 253), Model: clip(m.Model, 253), FirmwareVersion: clip(m.FirmwareVersion, 253), NetworkInterfaces: nics(m.NetworkInterfaces)}) } } - read := cond(inventory.ConditionResetTypesRead, metav1.ConditionTrue, ReasonResetTypesRead, "every System's reset types were read") + read := cond(inventory.ConditionResetTypesRead, metav1.ConditionTrue, ReasonResetTypesRead, "no System's reset type read failed; an omitted list means the System advertises no list") var unread []string for _, s := range inv.Systems { if s.ID != "" && len(out.Systems) < 16 { @@ -249,9 +249,10 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) ( } // resetTypes keeps the advertised reset types, distinct and nonempty: nil -// when they are unknown, empty when the BMC offers none. A read that failed, -// or more than 16 distinct values, leaves them unknown with a reason, because -// a partial list would refuse an action the BMC offers. +// when they are unknown, empty when the BMC advertises an empty list. A read +// that failed, a list of only blank values, or more than 16 distinct values +// leaves them unknown with a reason, because a partial list would refuse an +// action the BMC offers. func resetTypes(in []string, unread error) (types []string, reason, why string) { var status redfish.Status switch { @@ -276,6 +277,9 @@ func resetTypes(in []string, unread error) (types []string, reason, why string) types = append(types, v) } } + if len(types) == 0 && len(in) != 0 { + return nil, ReasonResetActionMalformed, "the BMC advertises only blank reset types" + } return types, "", "" } diff --git a/internal/bmcdiscovery/status_test.go b/internal/bmcdiscovery/status_test.go index 32ea6e96..105183fb 100644 --- a/internal/bmcdiscovery/status_test.go +++ b/internal/bmcdiscovery/status_test.go @@ -27,15 +27,17 @@ func TestResetTypesStayWithinTheSchema(t *testing.T) { } } -// Unknown stays nil and offers-none stays empty, including a list of blanks. +// Unknown stays nil and offers-none stays empty. A list of only blanks was +// advertised but is unusable, so it is unknown rather than offers-none. func TestResetTypesKeepUnknownApartFromNone(t *testing.T) { if got, reason, _ := resetTypes(nil, nil); got != nil || reason != "" { t.Fatalf("no list = %#v, %s", got, reason) } - for _, in := range [][]string{{}, {"", " "}} { - if got, reason, _ := resetTypes(in, nil); got == nil || len(got) != 0 || reason != "" { - t.Fatalf("%q = %#v, %s", in, got, reason) - } + if got, reason, _ := resetTypes([]string{}, nil); got == nil || len(got) != 0 || reason != "" { + t.Fatalf("empty list = %#v, %s", got, reason) + } + if got, reason, _ := resetTypes([]string{"", " "}, nil); got != nil || reason != ReasonResetActionMalformed { + t.Fatalf("blank list = %#v, %s", got, reason) } for err, want := range map[error]string{ redfish.ErrUnsupported: ReasonResetActionMalformed, diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go index 8a053d78..c1c680cf 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -47,7 +47,7 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target if err == nil { var syntax *json.SyntaxError var typed *json.UnmarshalTypeError - if err = json.NewDecoder(resp.Body).Decode(&ai); errors.As(err, &syntax) || errors.As(err, &typed) || errors.Is(err, io.EOF) { + if err = json.NewDecoder(resp.Body).Decode(&ai); errors.As(err, &syntax) || errors.As(err, &typed) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { err = ErrMalformed } } From 35cd6f2c9edfdd4c2c9d85a28aee30972d60fda6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 14:55:34 -0600 Subject: [PATCH 3/4] feat(bmc-discovery): Record whether a System's reset types were observed An empty resetTypes list cannot be told from an omitted one: the field is omitempty, and pruning, apply and other clients do not keep an empty list reliably. resetTypes goes back to #181's tag unchanged. A per-System resetTypesObserved boolean is now true only when this read got an advertised list, inline or from the ActionInfo, even an empty one. A failed read, a System that advertises no list, a list of only blanks or more than 16 types leaves it absent, so the types are unknown. ResetTypesRead keeps explaining failures for operators. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 1 + docs/operations/bmc-discovery.md | 56 +++++++------ .../inventory/v1alpha1/reset_types_test.go | 69 +++++++++------- internal/api/inventory/v1alpha1/types.go | 26 +++--- internal/bmcdiscovery/reset_types_test.go | 80 +++++++++++-------- internal/bmcdiscovery/status.go | 40 +++++----- internal/bmcdiscovery/status_test.go | 32 ++++---- internal/redfish/client.go | 2 +- internal/redfish/inventory.go | 8 +- internal/redfish/reset.go | 37 ++++----- internal/redfish/reset_test.go | 22 ++--- 11 files changed, 203 insertions(+), 170 deletions(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index c6534990..9f4f44be 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -645,6 +645,7 @@ spec: type: array maxItems: 16 items: {type: string, minLength: 1, maxLength: 63} + resetTypesObserved: {type: boolean} networkInterfaces: type: array maxItems: 32 diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 428927d8..49cc6d08 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -275,6 +275,7 @@ status: sku: TAG0001 powerState: "On" resetTypes: ["On", ForceOff, ForceRestart] + resetTypesObserved: true networkInterfaces: - {id: NIC.1, macAddress: "00:00:5e:00:53:01", linkStatus: LinkUp, speedMbps: 25000} conditions: [...] @@ -332,33 +333,38 @@ the `ComputerSystem.Reset` types the BMC advertises, inline or from the System's own ActionInfo, as `resetTypes`. It reads the action's description and never invokes it. -| `resetTypes` | Meaning | -| --- | --- | -| Omitted (no key) | Unknown. The System advertises no list (no reset action, or one without allowable values), or the list could not be read. | -| `[]` | The BMC advertises an empty list: it offers no reset type. | -| `["On", ForceOff]` | The reset types offered. Any type not listed is not offered. | - -`ResetTypesRead` tells a failed read from an unadvertised list. It is False, -and `resetTypes` omitted, when the reset action is malformed or not on the -System, or the list holds only blank values (`ResetActionMalformed`), the ActionInfo is missing -(`ActionInfoNotFound`), a server error or timeout stops the read +| `resetTypesObserved` | `resetTypes` | Meaning | +| --- | --- | --- | +| `true` | `["On", ForceOff]` | The BMC advertised these types. Any type not listed is not offered. | +| `true` | omitted | The BMC advertised an empty list. It offers no reset type. | +| omitted | omitted | Unknown. The System advertises no list (no reset action, or one without allowable values), or the list could not be read. | + +Readers use `resetTypesObserved`, never whether `resetTypes` is empty: an +empty list is not serialized, so it is indistinguishable from an omitted one. +`resetTypesObserved` is per System and true only when this read succeeded. + +`ResetTypesRead` explains, for operators, why a System's types are unknown. +It is False when the reset action is malformed or not on the System, or the +list holds only blank values (`ResetActionMalformed`), the ActionInfo is +missing (`ActionInfoNotFound`), a server error or timeout stops the read (`ActionInfoUnreadable`), the response is not an ActionInfo (`ActionInfoMalformed`), or the BMC advertises more than 16 distinct types (`TooManyResetTypes`), since a partial list would refuse a type the BMC -offers. The message names each affected System. The rest of the inventory is -kept and `Discovered` stays True. A rejected credential (401 or 403), a pin -mismatch or an unexpected resource path on the ActionInfo fails the whole read, -as for any other document. True means no read failed. It does not mean a list -was recorded: an omitted list with True means the System advertises no list. +offers. The message names each affected System. True means no read failed, +not that a list was observed. The rest of the inventory is kept and +`Discovered` stays True. A rejected credential (401 or 403), a pin mismatch +or an unexpected resource path on the ActionInfo fails the whole read, as for +any other document. A separate condition, rather than a reason on `Discovered` or an event, keeps -`Discovered` meaning the inventory was read, and puts the outcome in status -next to the list it qualifies, where a reader finds it after events expire. -It changes only when a new inventory is recorded. +`Discovered` meaning the inventory was read, and keeps the explanation in +status after events expire. It is per Device, so the per-System field carries +the signal. It changes only when a new inventory is recorded. -Nothing reads `resetTypes` yet. Planned Device power operations will admit an -action when the list is omitted and check the live BMC, and refuse it when the -list is empty or does not contain it. +Nothing reads these fields yet. Planned Device power operations will refuse +an action with `ResetTypeNotOffered` when `resetTypesObserved` is true and +`resetTypes` lacks it. When `resetTypesObserved` is omitted they will admit +it, and the worker's live BMC check decides. Collections follow `Members@odata.nextLink` for up to 8 pages. Every member must sit under its collection. Documents are decoded leniently: only the @@ -389,10 +395,10 @@ sessions. Basic authentication is used; no Redfish session is created. - end to end against an `httptest` TLS service: first contact records the pin with no credential sent, then approval yields inventory and `IdentityMatched=True`; -- each `resetTypes` outcome as stored through the status patch: a list, an - empty list, or omitted with the `ResetTypesRead` reason, and a status - round trip through a disposable API server that keeps `[]` apart from - omitted; +- each reset type outcome as stored through the status patch: observed with a + list, observed with an empty list, or unobserved with the `ResetTypesRead` + reason, and a status round trip of `resetTypesObserved` through a disposable + API server; - the Device status schema, the discoverer role, and the shipped Deployment's single unprivileged replica. diff --git a/internal/api/inventory/v1alpha1/reset_types_test.go b/internal/api/inventory/v1alpha1/reset_types_test.go index d039ad22..86d21174 100644 --- a/internal/api/inventory/v1alpha1/reset_types_test.go +++ b/internal/api/inventory/v1alpha1/reset_types_test.go @@ -5,7 +5,7 @@ import ( "encoding/json" "os" "path/filepath" - "strings" + "slices" "testing" corev1 "k8s.io/api/core/v1" @@ -19,9 +19,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/envtest" ) -// resetTypesJSON is the serialized resetTypes of the first System, or "" when -// the field is omitted. -func resetTypesJSON(t *testing.T, d *Device) string { +// resetFields is the serialized resetTypes and resetTypesObserved of the +// first System, each "" when omitted. +func resetFields(t *testing.T, d *Device) (types, observed string) { t.Helper() b, err := json.Marshal(d.Status.Discovery.Inventory.Systems[0]) if err != nil { @@ -31,12 +31,13 @@ func resetTypesJSON(t *testing.T, d *Device) string { if err := json.Unmarshal(b, &fields); err != nil { t.Fatal(err) } - return string(fields["resetTypes"]) + return string(fields["resetTypes"]), string(fields["resetTypesObserved"]) } -// An empty resetTypes (the BMC offers none) is serialized, admitted, kept by -// pruning and kept by DeepCopy; an unset one (unknown) is omitted. -func TestResetTypesKeepEmptyApartFromOmitted(t *testing.T) { +// resetTypesObserved is admitted as a boolean and kept by pruning and +// DeepCopy, so an observed empty list survives although resetTypes is then +// omitted. +func TestResetTypesObservedIsKept(t *testing.T) { var schema apiextensions.JSONSchemaProps if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { t.Fatal(err) @@ -46,32 +47,38 @@ func TestResetTypesKeepEmptyApartFromOmitted(t *testing.T) { t.Fatal(err) } for _, tc := range []struct { - types []string - want string - }{{nil, ""}, {[]string{}, "[]"}, {[]string{"On"}, `["On"]`}} { + types []string + observed bool + wantTypes, wantSeen string + }{{nil, false, "", ""}, {[]string{}, true, "", "true"}, {[]string{"On"}, true, `["On"]`, "true"}} { device := discoveredDevice() device.Status.Discovery.Inventory.Systems[0].ResetTypes = tc.types - if got := resetTypesJSON(t, &device); got != tc.want { - t.Fatalf("serialized %#v as %q, want %q", tc.types, got, tc.want) - } - if got := resetTypesJSON(t, device.DeepCopyObject().(*Device)); got != tc.want { - t.Fatalf("DeepCopy of %#v serialized as %q, want %q", tc.types, got, tc.want) + device.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = tc.observed + for _, d := range []*Device{&device, device.DeepCopyObject().(*Device)} { + if types, seen := resetFields(t, d); types != tc.wantTypes || seen != tc.wantSeen { + t.Fatalf("%v/%v serialized as %q/%q", tc.types, tc.observed, types, seen) + } } if errs := admit(t, "Device", object(t, device), nil); len(errs) > 0 { - t.Fatalf("resetTypes %#v rejected: %v", tc.types, errs) + t.Fatalf("%v/%v rejected: %v", tc.types, tc.observed, errs) } pruned := object(t, device) pruning.Prune(pruned, structural, true) system := pruned["status"].(map[string]any)["discovery"].(map[string]any)["inventory"].(map[string]any)["systems"].([]any)[0].(map[string]any) - if got, ok := system["resetTypes"]; ok != (tc.want != "") || ok && len(got.([]any)) != len(tc.types) { - t.Fatalf("pruned resetTypes %#v to %#v", tc.types, got) + if got, ok := system["resetTypesObserved"]; ok != tc.observed || ok && got != true { + t.Fatalf("pruned resetTypesObserved %v to %#v", tc.observed, got) } } + device := object(t, discoveredDevice()) + device["status"].(map[string]any)["discovery"].(map[string]any)["inventory"].(map[string]any)["systems"].([]any)[0].(map[string]any)["resetTypesObserved"] = "true" + if errs := admit(t, "Device", device, nil); len(errs) == 0 { + t.Fatal("string resetTypesObserved accepted") + } } -// A status merge patch through the API server stores a list, an empty list -// and an omitted list distinctly, and moves between them. -func TestResetTypesRoundTripThroughTheAPIServer(t *testing.T) { +// A status merge patch through the API server stores and clears +// resetTypesObserved, with or without a list. +func TestResetTypesObservedRoundTripThroughTheAPIServer(t *testing.T) { if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS required for disposable Device status validation") } @@ -105,27 +112,27 @@ func TestResetTypesRoundTripThroughTheAPIServer(t *testing.T) { t.Fatal(err) } status := discoveredDevice().Status - for _, types := range [][]string{{"On", "ForceOff"}, {}, nil, {}, {"On"}} { + for _, step := range []struct { + types []string + observed bool + }{{[]string{"On", "ForceOff"}, true}, {nil, true}, {nil, false}, {nil, true}, {[]string{"On"}, true}} { var stored Device if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &stored); err != nil { t.Fatal(err) } patch := client.MergeFromWithOptions(stored.DeepCopyObject().(*Device), client.MergeFromWithOptimisticLock{}) deepCopy(&status, &stored.Status) - stored.Status.Discovery.Inventory.Systems[0].ResetTypes = types - want := resetTypesJSON(t, &stored) + stored.Status.Discovery.Inventory.Systems[0].ResetTypes = step.types + stored.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = step.observed if err := api.Status().Patch(ctx, &stored, patch); err != nil { - t.Fatalf("patch resetTypes %#v: %v", types, err) + t.Fatalf("patch %v/%v: %v", step.types, step.observed, err) } var read Device if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &read); err != nil { t.Fatal(err) } - if got := resetTypesJSON(t, &read); got != want || (types == nil) != (read.Status.Discovery.Inventory.Systems[0].ResetTypes == nil) { - t.Fatalf("stored resetTypes %#v as %q, want %q", types, got, want) - } - if types != nil && !strings.HasPrefix(want, "[") { - t.Fatalf("resetTypes %#v serialized as %q", types, want) + if got := read.Status.Discovery.Inventory.Systems[0]; got.ResetTypesObserved != step.observed || !slices.Equal(got.ResetTypes, step.types) { + t.Fatalf("stored %v/%v as %v/%v", step.types, step.observed, got.ResetTypes, got.ResetTypesObserved) } } } diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 3e13ab3f..cdf3d11f 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -258,19 +258,21 @@ type ObservedManager struct { // ObservedSystem is one Redfish ComputerSystem. PowerState is an observation // only; discovery never changes power. ResetTypes are the ComputerSystem.Reset -// types the BMC advertises for the System, read but never invoked: omitted -// (nil) when they are unknown, an empty list when the BMC offers none. Use -// omitzero, not omitempty, so an empty list is kept. +// types the BMC advertises for the System, read but never invoked. +// ResetTypesObserved is true only when discovery read an advertised list of +// them, which may be empty; otherwise the offered types are unknown. Readers +// use it rather than whether ResetTypes is empty, which is not serialized. type ObservedSystem struct { - ID string `json:"id"` - UUID string `json:"uuid,omitempty"` - Manufacturer string `json:"manufacturer,omitempty"` - Model string `json:"model,omitempty"` - SerialNumber string `json:"serialNumber,omitempty"` - SKU string `json:"sku,omitempty"` - PowerState string `json:"powerState,omitempty"` - NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` - ResetTypes []string `json:"resetTypes,omitzero"` + ID string `json:"id"` + UUID string `json:"uuid,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model,omitempty"` + SerialNumber string `json:"serialNumber,omitempty"` + SKU string `json:"sku,omitempty"` + PowerState string `json:"powerState,omitempty"` + NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` + ResetTypes []string `json:"resetTypes,omitempty"` + ResetTypesObserved bool `json:"resetTypesObserved,omitempty"` } // ObservedNetworkInterface is one Redfish EthernetInterface. diff --git a/internal/bmcdiscovery/reset_types_test.go b/internal/bmcdiscovery/reset_types_test.go index 1f936771..48b5da8c 100644 --- a/internal/bmcdiscovery/reset_types_test.go +++ b/internal/bmcdiscovery/reset_types_test.go @@ -96,45 +96,60 @@ func systemJSON(t *testing.T, d *inventory.Device) string { return string(b) } -// Each way the BMC can describe its reset action is stored distinctly: -// a list, an empty list (offers none), or omitted (unknown) with -// ResetTypesRead False and the reason. None of them changes Discovered. +// afterPowerState is the stored System's JSON after powerState: the reset +// type fields, as the API serializes them. +func afterPowerState(t *testing.T, d *inventory.Device) string { + t.Helper() + stored := systemJSON(t, d) + i := strings.Index(stored, `"powerState":"Off"`) + if i < 0 { + t.Fatalf("stored System = %s", stored) + } + return stored[i+len(`"powerState":"Off"`):] +} + +// Each way the BMC can describe its reset action is stored distinctly. +// resetTypesObserved is true for an advertised list read without error, even +// an empty one; otherwise it is absent, and a failed read sets ResetTypesRead +// False with the reason. None of them changes Discovered. func TestResetTypesStatus(t *testing.T) { for name, tc := range map[string]struct { actions string info func(http.ResponseWriter, *http.Request) - want string // the stored resetTypes JSON; empty for omitted + want string // the stored System JSON after powerState status metav1.ConditionStatus reason string }{ - "inline values": {strings.Replace(inlineReset, "%s", `["On","ForceOff"]`, 1), nil, `"resetTypes":["On","ForceOff"]`, metav1.ConditionTrue, ReasonResetTypesRead}, - "inline empty": {strings.Replace(inlineReset, "%s", `[]`, 1), nil, `"resetTypes":[]`, metav1.ConditionTrue, ReasonResetTypesRead}, - "actioninfo": {infoReset, actionInfo(`["On","ForceOff","ForceRestart"]`), `"resetTypes":["On","ForceOff","ForceRestart"]`, metav1.ConditionTrue, ReasonResetTypesRead}, - "actioninfo empty": {infoReset, actionInfo(`[]`), `"resetTypes":[]`, metav1.ConditionTrue, ReasonResetTypesRead}, - "no actions": {"", nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, - "no reset action": {`{"#ComputerSystem.Other":{}}`, nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, - "no list": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset"}}`, nil, "", metav1.ConditionTrue, ReasonResetTypesRead}, - "actioninfo 404": {infoReset, replyStatus(http.StatusNotFound), "", metav1.ConditionFalse, ReasonActionInfoNotFound}, - "actioninfo 500": {infoReset, replyStatus(http.StatusInternalServerError), "", metav1.ConditionFalse, ReasonActionInfoUnreadable}, + "inline values": {strings.Replace(inlineReset, "%s", `["On","ForceOff"]`, 1), nil, `,"resetTypes":["On","ForceOff"],"resetTypesObserved":true}`, metav1.ConditionTrue, ReasonResetTypesRead}, + "inline empty": {strings.Replace(inlineReset, "%s", `[]`, 1), nil, `,"resetTypesObserved":true}`, metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo": {infoReset, actionInfo(`["On","ForceOff","ForceRestart"]`), `,"resetTypes":["On","ForceOff","ForceRestart"],"resetTypesObserved":true}`, metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo empty": {infoReset, actionInfo(`[]`), `,"resetTypesObserved":true}`, metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo without values": {infoReset, func(w http.ResponseWriter, _ *http.Request) { + w.Write([]byte(`{"Parameters":[{"Name":"ResetType","DataType":"String"}]}`)) + }, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "no actions": {"", nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "no reset action": {`{"#ComputerSystem.Other":{}}`, nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "no list": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset"}}`, nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "actioninfo 404": {infoReset, replyStatus(http.StatusNotFound), "}", metav1.ConditionFalse, ReasonActionInfoNotFound}, + "actioninfo 500": {infoReset, replyStatus(http.StatusInternalServerError), "}", metav1.ConditionFalse, ReasonActionInfoUnreadable}, "actioninfo timeout": {infoReset, func(_ http.ResponseWriter, r *http.Request) { select { case <-r.Context().Done(): case <-time.After(5 * time.Second): } - }, "", metav1.ConditionFalse, ReasonActionInfoUnreadable}, - "actioninfo malformed": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":"none"}`)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, - "actioninfo not json": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(``)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, - "actioninfo truncated": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":[{"Name":"ResetType"`)) }, "", metav1.ConditionFalse, ReasonActionInfoMalformed}, - "inline blanks": {strings.Replace(inlineReset, "%s", `[null,""]`, 1), nil, "", metav1.ConditionFalse, ReasonResetActionMalformed}, - "actions malformed": {`"not actions"`, nil, "", metav1.ConditionFalse, ReasonResetActionMalformed}, + }, "}", metav1.ConditionFalse, ReasonActionInfoUnreadable}, + "actioninfo malformed": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":"none"}`)) }, "}", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "actioninfo not json": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(``)) }, "}", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "actioninfo truncated": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":[{"Name":"ResetType"`)) }, "}", metav1.ConditionFalse, ReasonActionInfoMalformed}, + "inline blanks": {strings.Replace(inlineReset, "%s", `[null,""]`, 1), nil, "}", metav1.ConditionFalse, ReasonResetActionMalformed}, + "actions malformed": {`"not actions"`, nil, "}", metav1.ConditionFalse, ReasonResetActionMalformed}, } { t.Run(name, func(t *testing.T) { bmc := &resetBMC{actions: tc.actions, info: tc.info} _, reconcile := resetHarness(t, bmc) got := reconcile() - stored := systemJSON(t, got) - if tc.want == "" && strings.Contains(stored, "resetTypes") || tc.want != "" && !strings.Contains(stored, tc.want) { - t.Fatalf("stored System = %s, want %s", stored, tc.want) + if tail := afterPowerState(t, got); tail != tc.want { + t.Fatalf("stored System ends %s, want %s", tail, tc.want) } if c := condition(t, got.Status, inventory.ConditionResetTypesRead); c.Status != tc.status || c.Reason != tc.reason || c.ObservedGeneration != 1 { t.Fatalf("ResetTypesRead = %+v", c) @@ -171,9 +186,9 @@ func TestResetTypesRejectedCredentialFailsTheRead(t *testing.T) { } } -// The stored list moves between present, empty and omitted across reads: the -// status patch carries an empty list and removes an omitted one. A failed -// read clears a previously recorded list rather than keeping a stale one. +// The stored fields move between observed with a list, observed empty and +// unobserved across reads, through the status patch. A failed read clears a +// previously observed list rather than keeping a stale one. func TestResetTypesTransitionsThroughTheStatusPatch(t *testing.T) { bmc := &resetBMC{actions: infoReset, info: actionInfo(`["On","ForceOff"]`)} _, reconcile := resetHarness(t, bmc) @@ -181,18 +196,17 @@ func TestResetTypesTransitionsThroughTheStatusPatch(t *testing.T) { info func(http.ResponseWriter, *http.Request) want string }{ - {actionInfo(`["On","ForceOff"]`), `"resetTypes":["On","ForceOff"]`}, - {actionInfo(`[]`), `"resetTypes":[]`}, - {replyStatus(http.StatusNotFound), ""}, - {actionInfo(`[]`), `"resetTypes":[]`}, - {actionInfo(`["On"]`), `"resetTypes":["On"]`}, + {actionInfo(`["On","ForceOff"]`), `,"resetTypes":["On","ForceOff"],"resetTypesObserved":true}`}, + {actionInfo(`[]`), `,"resetTypesObserved":true}`}, + {replyStatus(http.StatusNotFound), `}`}, + {actionInfo(`[]`), `,"resetTypesObserved":true}`}, + {actionInfo(`["On"]`), `,"resetTypes":["On"],"resetTypesObserved":true}`}, } { bmc.mu.Lock() bmc.info = step.info bmc.mu.Unlock() - stored := systemJSON(t, reconcile()) - if step.want == "" && strings.Contains(stored, "resetTypes") || step.want != "" && !strings.Contains(stored, step.want) { - t.Fatalf("stored System = %s, want %s", stored, step.want) + if tail := afterPowerState(t, reconcile()); tail != step.want { + t.Fatalf("stored System ends %s, want %s", tail, step.want) } } } diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go index 28af3907..961756a2 100644 --- a/internal/bmcdiscovery/status.go +++ b/internal/bmcdiscovery/status.go @@ -226,14 +226,14 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) ( out.Managers = append(out.Managers, inventory.ObservedManager{ID: clip(m.ID, 253), Model: clip(m.Model, 253), FirmwareVersion: clip(m.FirmwareVersion, 253), NetworkInterfaces: nics(m.NetworkInterfaces)}) } } - read := cond(inventory.ConditionResetTypesRead, metav1.ConditionTrue, ReasonResetTypesRead, "no System's reset type read failed; an omitted list means the System advertises no list") + read := cond(inventory.ConditionResetTypesRead, metav1.ConditionTrue, ReasonResetTypesRead, "no System's reset type read failed") var unread []string for _, s := range inv.Systems { if s.ID != "" && len(out.Systems) < 16 { - types, reason, why := resetTypes(s.ResetTypes, s.ResetTypesUnread) + types, observed, reason, why := resetTypes(s.ResetTypes, s.ResetTypesAdvertised, s.ResetTypesUnread) 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), - ResetTypes: types}) + ResetTypes: types, ResetTypesObserved: observed}) if reason != "" { if len(unread) == 0 { read.Reason = reason @@ -243,44 +243,44 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) ( } } if len(unread) > 0 { - read.Status, read.Message = metav1.ConditionFalse, "resetTypes is omitted, so unknown, for "+strings.Join(unread, "; ") + read.Status, read.Message = metav1.ConditionFalse, "reset types are unknown for "+strings.Join(unread, "; ") } return out, read } -// resetTypes keeps the advertised reset types, distinct and nonempty: nil -// when they are unknown, empty when the BMC advertises an empty list. A read -// that failed, a list of only blank values, or more than 16 distinct values -// leaves them unknown with a reason, because a partial list would refuse an -// action the BMC offers. -func resetTypes(in []string, unread error) (types []string, reason, why string) { +// resetTypes keeps the advertised reset types, distinct and nonempty, and +// reports whether they were observed: true only for an advertised list read +// without error, which may be empty. A failed read, a list of only blank +// values, or more than 16 distinct values is unobserved with a reason, +// because a partial list would refuse an action the BMC offers. A System that +// advertises no list is unobserved without one. +func resetTypes(in []string, advertised bool, unread error) (types []string, observed bool, reason, why string) { var status redfish.Status switch { case errors.Is(unread, redfish.ErrUnsupported): - return nil, ReasonResetActionMalformed, "the ComputerSystem.Reset action is malformed or not on the System" + return nil, false, ReasonResetActionMalformed, "the ComputerSystem.Reset action is malformed or not on the System" case errors.As(unread, &status) && status.Code == 404: - return nil, ReasonActionInfoNotFound, "the reset ActionInfo returned HTTP 404" + return nil, false, ReasonActionInfoNotFound, "the reset ActionInfo returned HTTP 404" case errors.Is(unread, redfish.ErrMalformed): - return nil, ReasonActionInfoMalformed, "the reset ActionInfo is not an ActionInfo document" + return nil, false, ReasonActionInfoMalformed, "the reset ActionInfo is not an ActionInfo document" case unread != nil: - return nil, ReasonActionInfoUnreadable, "the reset ActionInfo read failed: " + safe(unread) - case in == nil: - return nil, "", "" + return nil, false, ReasonActionInfoUnreadable, "the reset ActionInfo read failed: " + safe(unread) + case !advertised: + return nil, false, "", "" } - types = []string{} for _, v := range in { v = clip(v, 63) if v != "" && !slices.Contains(types, v) { if len(types) == 16 { - return nil, ReasonTooManyResetTypes, "the BMC advertises more than 16 reset types" + return nil, false, ReasonTooManyResetTypes, "the BMC advertises more than 16 reset types" } types = append(types, v) } } if len(types) == 0 && len(in) != 0 { - return nil, ReasonResetActionMalformed, "the BMC advertises only blank reset types" + return nil, false, ReasonResetActionMalformed, "the BMC advertises only blank reset types" } - return types, "", "" + return types, true, "", "" } func clip(s string, n int) string { diff --git a/internal/bmcdiscovery/status_test.go b/internal/bmcdiscovery/status_test.go index 105183fb..20c56e2d 100644 --- a/internal/bmcdiscovery/status_test.go +++ b/internal/bmcdiscovery/status_test.go @@ -10,34 +10,34 @@ import ( ) // Recorded reset types stay within the Device schema: distinct, nonempty -// values of at most 63 characters. More than 16 distinct values are unknown, +// values of at most 63 characters. More than 16 distinct values are unobserved, // not a partial list, because a partial list would refuse an offered action. func TestResetTypesStayWithinTheSchema(t *testing.T) { in := []string{"On", " On ", "", " ", strings.Repeat("x", 80)} for i := range 14 { in = append(in, fmt.Sprintf("Vendor%d", i)) } - got, reason, _ := resetTypes(in, nil) - if len(got) != 16 || !slices.Equal(got[:2], []string{"On", strings.Repeat("x", 63)}) || got[15] != "Vendor13" || reason != "" { + got, observed, reason, _ := resetTypes(in, true, nil) + if len(got) != 16 || !slices.Equal(got[:2], []string{"On", strings.Repeat("x", 63)}) || got[15] != "Vendor13" || !observed || reason != "" { t.Fatalf("resetTypes = %v, %s", got, reason) } - got, reason, _ = resetTypes(append(in, "Vendor14"), nil) - if got != nil || reason != ReasonTooManyResetTypes { + got, observed, reason, _ = resetTypes(append(in, "Vendor14"), true, nil) + if got != nil || observed || reason != ReasonTooManyResetTypes { t.Fatalf("17 values = %v, %s", got, reason) } } -// Unknown stays nil and offers-none stays empty. A list of only blanks was -// advertised but is unusable, so it is unknown rather than offers-none. -func TestResetTypesKeepUnknownApartFromNone(t *testing.T) { - if got, reason, _ := resetTypes(nil, nil); got != nil || reason != "" { - t.Fatalf("no list = %#v, %s", got, reason) +// Only an advertised list read without error is observed, even when empty. +// A list of only blanks was advertised but is unusable, so it is unobserved. +func TestResetTypesObservedOnlyForAnAdvertisedList(t *testing.T) { + if got, observed, reason, _ := resetTypes(nil, false, nil); got != nil || observed || reason != "" { + t.Fatalf("no list = %v, %v, %s", got, observed, reason) } - if got, reason, _ := resetTypes([]string{}, nil); got == nil || len(got) != 0 || reason != "" { - t.Fatalf("empty list = %#v, %s", got, reason) + if got, observed, reason, _ := resetTypes(nil, true, nil); len(got) != 0 || !observed || reason != "" { + t.Fatalf("empty list = %v, %v, %s", got, observed, reason) } - if got, reason, _ := resetTypes([]string{"", " "}, nil); got != nil || reason != ReasonResetActionMalformed { - t.Fatalf("blank list = %#v, %s", got, reason) + if got, observed, reason, _ := resetTypes([]string{"", " "}, true, nil); got != nil || observed || reason != ReasonResetActionMalformed { + t.Fatalf("blank list = %v, %v, %s", got, observed, reason) } for err, want := range map[error]string{ redfish.ErrUnsupported: ReasonResetActionMalformed, @@ -46,8 +46,8 @@ func TestResetTypesKeepUnknownApartFromNone(t *testing.T) { redfish.Status{Code: 503}: ReasonActionInfoUnreadable, fmt.Errorf("timeout"): ReasonActionInfoUnreadable, } { - if got, reason, _ := resetTypes([]string{"On"}, err); got != nil || reason != want { - t.Fatalf("%v = %#v, %s; want %s", err, got, reason, want) + if got, observed, reason, _ := resetTypes([]string{"On"}, true, err); got != nil || observed || reason != want { + t.Fatalf("%v = %v, %v, %s; want %s", err, got, observed, reason, want) } } } diff --git a/internal/redfish/client.go b/internal/redfish/client.go index 11f6f2b5..487029e7 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -365,7 +365,7 @@ func (c *Client) Identify(ctx context.Context, t Target) (System, error) { if err := json.Unmarshal(s.RawData, &raw); err != nil { return System{}, classify(err) } - if sys.ResetTarget, sys.ResetTypes, err = resetTypes(api, sys.Path, raw); err != nil { + if sys.ResetTarget, sys.ResetTypes, _, err = resetTypes(api, sys.Path, raw); err != nil { return System{}, err } for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index 5e136066..d364f582 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -44,10 +44,12 @@ type InventorySystem struct { PowerState string // NetworkInterfaces are the System's EthernetInterfaces. NetworkInterfaces []NetworkInterface - // ResetTypes are the ComputerSystem.Reset types the System advertises: - // nil when it advertises no list, empty when it advertises an empty one. + // ResetTypes are the ComputerSystem.Reset types the System advertises. // Discovery reads them and never invokes the action. ResetTypes []string + // ResetTypesAdvertised reports whether the System advertised a list of + // reset types, which may be empty. + ResetTypesAdvertised bool // ResetTypesUnread is why the reset types could not be read, with // ResetTypes nil. The rest of the System is still read. ResetTypesUnread error @@ -132,7 +134,7 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { } 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 system.ResetTypes, system.ResetTypesUnread, err = systemResetTypes(api, p, doc.Actions); err != nil { + if system.ResetTypes, system.ResetTypesAdvertised, system.ResetTypesUnread, err = systemResetTypes(api, p, doc.Actions); err != nil { return Inventory{}, err } inv.Systems = append(inv.Systems, system) diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go index c1c680cf..d63fc374 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -19,20 +19,20 @@ var ErrMalformed = errors.New("redfish: malformed document") // inline or through its ActionInfo, and the action target. Both must belong to // the System at sysPath, and the ActionInfo must not sit under its Actions. It // issues at most one GET, of the ActionInfo, and never invokes the action. -// Types are nil when the BMC advertises no list, and empty but not nil when it -// advertises an empty one. -func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, err error) { +// advertised reports whether the BMC advertised a list, which may be empty. +func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, advertised bool, 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) + return "", nil, false, fmt.Errorf("%w: ComputerSystem.Reset target not on the System", ErrUnsupported) } + // An inline AllowableValues that is present, even empty, is advertised. if len(reset.Allowed) != 0 || reset.Info == "" { - return target, reset.Allowed, nil + return target, reset.Allowed, reset.Allowed != nil, nil } info, err := cleanPath(reset.Info) if err != nil || !strings.HasPrefix(info, sysPath+"/") || strings.Contains(info+"/", "/Actions/") { - return "", nil, fmt.Errorf("%w: ActionInfo not on the System", ErrUnsupported) + return "", nil, false, 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 @@ -53,16 +53,17 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target } schemas.DeferredCleanupHTTPResponse(resp) if errors.Is(err, ErrMalformed) { - return "", nil, ErrMalformed + return "", nil, false, ErrMalformed } else if err != nil { - return "", nil, classify(err) + return "", nil, false, classify(err) } + types, advertised = reset.Allowed, reset.Allowed != nil for _, p := range ai.Parameters { - if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { - types = p.AllowableValues + if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") && p.AllowableValues != nil { + types, advertised = p.AllowableValues, true } } - return target, types, nil + return target, types, advertised, nil } // systemResetTypes reads the reset types of the System at sysPath from its @@ -70,20 +71,20 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target // list. unread is why the types could not be read; the inventory keeps the // System. Only a rejected credential, pin or identity is fatal and fails the // whole read. -func systemResetTypes(api *gofish.APIClient, sysPath string, actions json.RawMessage) (types []string, unread, fatal error) { +func systemResetTypes(api *gofish.APIClient, sysPath string, actions json.RawMessage) (types []string, advertised bool, unread, fatal error) { if len(actions) == 0 { - return nil, nil, nil + return nil, false, nil, nil } var raw resetAction if err := json.Unmarshal(actions, &raw.Actions); err != nil { - return nil, fmt.Errorf("%w: ComputerSystem.Reset action malformed", ErrUnsupported), nil + return nil, false, fmt.Errorf("%w: ComputerSystem.Reset action malformed", ErrUnsupported), nil } if r := raw.Actions.Reset; r.Target == "" && r.Info == "" && r.Allowed == nil { - return nil, nil, nil + return nil, false, nil, nil } - _, types, err := resetTypes(api, sysPath, raw) + _, types, advertised, err := resetTypes(api, sysPath, raw) if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { - return nil, nil, err + return nil, false, nil, err } - return types, err, nil + return types, advertised, err, nil } diff --git a/internal/redfish/reset_test.go b/internal/redfish/reset_test.go index e2b131b0..89f06f9d 100644 --- a/internal/redfish/reset_test.go +++ b/internal/redfish/reset_test.go @@ -13,9 +13,9 @@ import ( ) // Discovery reads offered reset types inline or from the System's own -// ActionInfo, with GETs only. An empty advertised list stays empty, a reset -// action without a list records none, and a reset target off the System -// records none with the reason. +// ActionInfo, with GETs only. An empty list is advertised, a reset action +// without a list is not, and a reset target off the System records none with +// the reason. func TestInventoryRecordsResetTypes(t *testing.T) { bmc := newInventoryBMC() bmc.docs["/redfish/v1/Systems"] = map[string]any{"Members": []any{ @@ -52,16 +52,16 @@ func TestInventoryRecordsResetTypes(t *testing.T) { t.Fatal(err) } if len(inv.Systems) != 6 || !slices.Equal(inv.Systems[0].ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) || - !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) || inv.Systems[2].ResetTypes != nil || !errors.Is(inv.Systems[2].ResetTypesUnread, ErrUnsupported) { + !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) || inv.Systems[2].ResetTypes != nil || inv.Systems[2].ResetTypesAdvertised || !errors.Is(inv.Systems[2].ResetTypesUnread, ErrUnsupported) { t.Fatalf("systems = %+v", inv.Systems) } for _, i := range []int{3, 4} { - if s := inv.Systems[i]; s.ResetTypes == nil || len(s.ResetTypes) != 0 || s.ResetTypesUnread != nil { + if s := inv.Systems[i]; !s.ResetTypesAdvertised || len(s.ResetTypes) != 0 || s.ResetTypesUnread != nil { t.Fatalf("System %s offers none: %#v, %v", s.ID, s.ResetTypes, s.ResetTypesUnread) } } for _, i := range []int{0, 1, 5} { - if s := inv.Systems[i]; s.ResetTypesUnread != nil || (i == 5 && s.ResetTypes != nil) { + if s := inv.Systems[i]; s.ResetTypesUnread != nil || s.ResetTypesAdvertised != (i != 5) || (i == 5 && s.ResetTypes != nil) { t.Fatalf("System %s: %#v, %v", s.ID, s.ResetTypes, s.ResetTypesUnread) } } @@ -94,7 +94,7 @@ func TestInventoryKeepsTheSystemWhenActionInfoFails(t *testing.T) { if err != nil { t.Fatal(err) } - if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].ResetTypesAdvertised || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { t.Fatalf("systems = %+v", inv.Systems) } unread := inv.Systems[0].ResetTypesUnread @@ -119,7 +119,7 @@ func TestInventoryKeepsTheSystemWhenActionsAreMalformed(t *testing.T) { bmc := newInventoryBMC() bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = actions inv := inventoryOf(t, bmc) - if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 || + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].ResetTypesAdvertised || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 || !errors.Is(inv.Systems[0].ResetTypesUnread, ErrUnsupported) { t.Fatalf("systems = %+v", inv.Systems) } @@ -148,7 +148,7 @@ func TestInventoryNeverReadsAGuardedActionInfo(t *testing.T) { bmc.docs[p] = offered } inv := inventoryOf(t, bmc) - if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 || inv.Systems[0].ResetTypesUnread == nil { + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].ResetTypesAdvertised || len(inv.Systems[0].NetworkInterfaces) != 1 || inv.Systems[0].ResetTypesUnread == nil { t.Fatalf("systems = %+v", inv.Systems) } requests, _ := bmc.seen() @@ -191,7 +191,7 @@ func TestInventoryActionInfoStatus(t *testing.T) { } return } - if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 || + if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].ResetTypesAdvertised || len(inv.Systems[0].NetworkInterfaces) != 1 || inv.Systems[0].ResetTypesUnread != (Status{tc.status}) { t.Fatalf("inventory = %+v, err = %v", inv, err) } @@ -221,7 +221,7 @@ func TestInventoryActionInfoTimeout(t *testing.T) { t.Fatal(err) } inv, err := client.Inventory(context.Background()) - if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].ResetTypesAdvertised || len(inv.Systems[0].NetworkInterfaces) != 1 { t.Fatalf("inventory = %+v, err = %v", inv, err) } var status Status From 11e04238f8f1a21f5eeffeee49673138245d4578 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 15:00:01 -0600 Subject: [PATCH 4/4] fix(bmc-discovery): Ignore an empty inline list beside an ActionInfo An empty inline reset list next to an ActionInfo without ResetType values was observed as an empty list, which power reads as offers none and would refuse every action. With an ActionInfo, only its values now count, so that case is unknown and the live BMC check decides. Co-Authored-By: Claude Opus 5.5 --- internal/bmcdiscovery/reset_types_test.go | 6 ++++++ internal/redfish/reset.go | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/internal/bmcdiscovery/reset_types_test.go b/internal/bmcdiscovery/reset_types_test.go index 48b5da8c..ecb935d9 100644 --- a/internal/bmcdiscovery/reset_types_test.go +++ b/internal/bmcdiscovery/reset_types_test.go @@ -127,6 +127,12 @@ func TestResetTypesStatus(t *testing.T) { "actioninfo without values": {infoReset, func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"Parameters":[{"Name":"ResetType","DataType":"String"}]}`)) }, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "inline empty beside actioninfo without values": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","ResetType@Redfish.AllowableValues":[],"@Redfish.ActionInfo":"/redfish/v1/Systems/1/ResetActionInfo"}}`, + func(w http.ResponseWriter, _ *http.Request) { + w.Write([]byte(`{"Parameters":[{"Name":"ResetType","DataType":"String"}]}`)) + }, "}", metav1.ConditionTrue, ReasonResetTypesRead}, + "inline empty beside actioninfo empty": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","ResetType@Redfish.AllowableValues":[],"@Redfish.ActionInfo":"/redfish/v1/Systems/1/ResetActionInfo"}}`, + actionInfo(`[]`), `,"resetTypesObserved":true}`, metav1.ConditionTrue, ReasonResetTypesRead}, "no actions": {"", nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, "no reset action": {`{"#ComputerSystem.Other":{}}`, nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, "no list": {`{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset"}}`, nil, "}", metav1.ConditionTrue, ReasonResetTypesRead}, diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go index d63fc374..e312f906 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -57,7 +57,8 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target } else if err != nil { return "", nil, false, classify(err) } - types, advertised = reset.Allowed, reset.Allowed != nil + // With an ActionInfo, only its ResetType values count: an empty inline + // list beside an ActionInfo without values is unknown, not offers-none. for _, p := range ai.Parameters { if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") && p.AllowableValues != nil { types, advertised = p.AllowableValues, true