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 49a45f7f..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: [...] @@ -296,6 +297,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 +331,40 @@ 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. + +| `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. 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 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 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 @@ -367,6 +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 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 new file mode 100644 index 00000000..86d21174 --- /dev/null +++ b/internal/api/inventory/v1alpha1/reset_types_test.go @@ -0,0 +1,138 @@ +package v1alpha1 + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "slices" + "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" +) + +// 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 { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(b, &fields); err != nil { + t.Fatal(err) + } + return string(fields["resetTypes"]), string(fields["resetTypesObserved"]) +} + +// 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) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + 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 + 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("%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["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 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") + } + 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 _, 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 = step.types + stored.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = step.observed + if err := api.Status().Patch(ctx, &stored, patch); err != nil { + 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 := 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 562a23f9..cdf3d11f 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. @@ -258,16 +259,20 @@ 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. +// 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,omitempty"` + 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 new file mode 100644 index 00000000..ecb935d9 --- /dev/null +++ b/internal/bmcdiscovery/reset_types_test.go @@ -0,0 +1,218 @@ +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) +} + +// 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 System JSON after powerState + status metav1.ConditionStatus + reason string + }{ + "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}, + "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}, + "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}, + } { + t.Run(name, func(t *testing.T) { + bmc := &resetBMC{actions: tc.actions, info: tc.info} + _, reconcile := resetHarness(t, bmc) + got := reconcile() + 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) + } + 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 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) + for _, step := range []struct { + info func(http.ResponseWriter, *http.Request) + want string + }{ + {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() + 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 954e6e93..961756a2 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,61 @@ 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") + var unread []string for _, s := range inv.Systems { if s.ID != "" && len(out.Systems) < 16 { + 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: resetTypes(s.ResetTypes)}) + ResetTypes: types, ResetTypesObserved: observed}) + 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, "reset types are 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, 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, false, ReasonResetActionMalformed, "the ComputerSystem.Reset action is malformed or not on the System" + case errors.As(unread, &status) && status.Code == 404: + return nil, false, ReasonActionInfoNotFound, "the reset ActionInfo returned HTTP 404" + case errors.Is(unread, redfish.ErrMalformed): + return nil, false, ReasonActionInfoMalformed, "the reset ActionInfo is not an ActionInfo document" + case unread != nil: + return nil, false, ReasonActionInfoUnreadable, "the reset ActionInfo read failed: " + safe(unread) + case !advertised: + return nil, false, "", "" + } 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, false, ReasonTooManyResetTypes, "the BMC advertises more than 16 reset types" + } + types = append(types, v) } } - return out + if len(types) == 0 && len(in) != 0 { + return nil, false, ReasonResetActionMalformed, "the BMC advertises only blank reset 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 2893ae01..20c56e2d 100644 --- a/internal/bmcdiscovery/status_test.go +++ b/internal/bmcdiscovery/status_test.go @@ -5,17 +5,49 @@ 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 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 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, 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, observed, reason, _ = resetTypes(append(in, "Vendor14"), true, nil) + if got != nil || observed || reason != ReasonTooManyResetTypes { + t.Fatalf("17 values = %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, observed, reason, _ := resetTypes(nil, true, nil); len(got) != 0 || !observed || reason != "" { + t.Fatalf("empty list = %v, %v, %s", got, observed, 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, + redfish.Status{Code: 404}: ReasonActionInfoNotFound, + redfish.ErrMalformed: ReasonActionInfoMalformed, + redfish.Status{Code: 503}: ReasonActionInfoUnreadable, + fmt.Errorf("timeout"): ReasonActionInfoUnreadable, + } { + 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 ecc79294..d364f582 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -47,6 +47,12 @@ type InventorySystem struct { // 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 } // NetworkInterface is one Redfish EthernetInterface. @@ -63,7 +69,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 +134,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.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 f3ff6000..e312f906 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -1,28 +1,38 @@ 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. -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 @@ -33,13 +43,49 @@ 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) || errors.Is(err, io.ErrUnexpectedEOF) { + err = ErrMalformed + } + } + schemas.DeferredCleanupHTTPResponse(resp) + if errors.Is(err, ErrMalformed) { + return "", nil, false, ErrMalformed + } else if err != nil { + return "", nil, false, classify(err) } + // 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") { - 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 +// 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, advertised bool, unread, fatal error) { + if len(actions) == 0 { + return nil, false, nil, nil + } + var raw resetAction + if err := json.Unmarshal(actions, &raw.Actions); err != 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, false, nil, nil + } + _, types, advertised, err := resetTypes(api, sysPath, raw) + if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { + return nil, false, nil, err + } + return types, advertised, err, nil } diff --git a/internal/redfish/reset_test.go b/internal/redfish/reset_test.go index f8a2a63f..89f06f9d 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 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{ 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 || 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.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 || s.ResetTypesAdvertised != (i != 5) || (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) { @@ -72,9 +94,13 @@ 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 + 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].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) } }) @@ -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 || inv.Systems[0].ResetTypesAdvertised || 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 || 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) } }) } } +// 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 || inv.Systems[0].ResetTypesAdvertised || 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)